use std::{
env,
ffi::OsString,
fs,
fs::OpenOptions,
io::Write as _,
path::{Path, PathBuf},
};
use serde_json::{Value, json};
use crate::{
args::{InitArgs, NewArgs, ScaffoldOptions},
error::CliError,
output::Reporter,
process::{Cancellation, CommandSpec, run_command},
vite_path,
};
const KAYRO_VERSION: &str = "0.5.0";
const VITE_VERSION: &str = "8.2.0";
const TYPESCRIPT_VERSION: &str = "5.9.3";
struct Identity {
package_name: String,
app_name: String,
identifier: String,
}
struct ScaffoldFile {
relative_path: PathBuf,
contents: String,
}
pub fn create_new(
arguments: &NewArgs,
reporter: &Reporter,
cancellation: &Cancellation,
dry_run: bool,
) -> Result<(), CliError> {
let current_dir = current_dir()?;
let root = absolute_from(
¤t_dir,
arguments
.directory
.as_deref()
.unwrap_or_else(|| Path::new(&arguments.name)),
);
vite_path::validate(&root)?;
if root.exists() {
return Err(CliError::ScaffoldTargetExists { path: root });
}
let identity = identity(&arguments.name, &arguments.scaffold)?;
scaffold(
&root,
&identity,
&arguments.scaffold,
false,
reporter,
cancellation,
dry_run,
)
}
pub fn initialize(
arguments: &InitArgs,
reporter: &Reporter,
cancellation: &Cancellation,
dry_run: bool,
) -> Result<(), CliError> {
let current_dir = current_dir()?;
let unresolved_root = absolute_from(¤t_dir, &arguments.directory);
if unresolved_root.exists() && !unresolved_root.is_dir() {
return Err(CliError::ScaffoldTargetNotDirectory {
path: unresolved_root,
});
}
let root = if unresolved_root.exists() {
unresolved_root
.canonicalize()
.map_err(|source| CliError::InvalidProjectPath {
path: unresolved_root,
source,
})?
} else {
unresolved_root
};
vite_path::validate(&root)?;
let inferred_name = arguments
.name
.as_deref()
.map(str::to_owned)
.or_else(|| {
root.file_name()
.and_then(|name| name.to_str())
.map(str::to_owned)
})
.ok_or_else(|| CliError::InvalidArguments {
message: "--name is required when the directory has no usable name".to_owned(),
})?;
let identity = identity(&inferred_name, &arguments.scaffold)?;
preflight_native_files(&root)?;
let package_json = root.join("package.json");
let has_package = if package_json.is_file() {
validate_package_scripts(&package_json)?;
true
} else {
false
};
scaffold(
&root,
&identity,
&arguments.scaffold,
has_package,
reporter,
cancellation,
dry_run,
)
}
fn scaffold(
root: &Path,
identity: &Identity,
options: &ScaffoldOptions,
has_package: bool,
reporter: &Reporter,
cancellation: &Cancellation,
dry_run: bool,
) -> Result<(), CliError> {
preflight_native_files(root)?;
let root_existed = root.exists();
let (files, skipped) = files(root, identity, has_package);
for path in &skipped {
reporter.scaffold_skipped(path);
}
if dry_run {
for file in &files {
reporter.scaffold_file(&root.join(&file.relative_path), true);
}
} else {
write_files(root, &files, root_existed)?;
for file in &files {
reporter.scaffold_file(&root.join(&file.relative_path), false);
}
}
reporter.scaffold_created(root, root_existed, dry_run);
if !options.no_install {
run_command(cargo_lock_command(root), reporter, cancellation, dry_run)?;
run_command(bun_install_command(root), reporter, cancellation, dry_run)?;
}
Ok(())
}
fn files(root: &Path, identity: &Identity, has_package: bool) -> (Vec<ScaffoldFile>, Vec<PathBuf>) {
let mut files = vec![
generated("kayro.toml", kayro_config(identity)),
generated("src-kayro/Cargo.toml", native_manifest(identity)),
static_file("src-kayro/build.rs", include_str!("../templates/build.rs")),
static_file(
"src-kayro/src/main.rs",
include_str!("../templates/native-main.rs"),
),
static_file(
"src-kayro/src/commands.rs",
include_str!("../templates/commands.rs"),
),
];
let mut skipped = Vec::new();
if has_package {
skipped.push(root.join("package.json"));
} else {
files.push(generated("package.json", package_json(identity)));
}
let vite_configs = [
"vite.config.ts",
"vite.config.js",
"vite.config.mts",
"vite.config.mjs",
"vite.config.cts",
"vite.config.cjs",
];
if let Some(existing) = vite_configs
.iter()
.map(|path| root.join(path))
.find(|path| path.exists())
{
skipped.push(existing);
} else {
files.push(static_file(
"vite.config.ts",
include_str!("../templates/vite.config.ts"),
));
}
push_if_missing(
root,
&mut files,
&mut skipped,
static_file("tsconfig.json", include_str!("../templates/tsconfig.json")),
);
push_if_missing(
root,
&mut files,
&mut skipped,
generated("index.html", index_html(identity)),
);
let frontend_entries = ["src/main.ts", "src/main.tsx", "src/main.js", "src/main.jsx"];
if let Some(existing) = frontend_entries
.iter()
.map(|path| root.join(path))
.find(|path| path.exists())
{
skipped.push(existing);
} else {
files.push(static_file(
"src/main.ts",
include_str!("../templates/frontend-main.ts"),
));
push_if_missing(
root,
&mut files,
&mut skipped,
static_file("src/style.css", include_str!("../templates/style.css")),
);
}
push_if_missing(
root,
&mut files,
&mut skipped,
static_file(".gitignore", include_str!("../templates/gitignore")),
);
push_if_missing(
root,
&mut files,
&mut skipped,
generated("README.md", project_readme(identity)),
);
(files, skipped)
}
fn preflight_native_files(root: &Path) -> Result<(), CliError> {
for relative in [
"kayro.toml",
"src-kayro/Cargo.toml",
"src-kayro/build.rs",
"src-kayro/src/main.rs",
"src-kayro/src/commands.rs",
] {
let path = root.join(relative);
if path.exists() {
return Err(CliError::ScaffoldConflict { path });
}
}
Ok(())
}
fn validate_package_scripts(path: &Path) -> Result<(), CliError> {
let source = fs::read_to_string(path).map_err(|source| CliError::ReadConfig {
path: path.to_path_buf(),
source,
})?;
let package: Value =
serde_json::from_str(&source).map_err(|error| CliError::InvalidPackageJson {
path: path.to_path_buf(),
message: error.to_string(),
})?;
let scripts = package
.get("scripts")
.and_then(Value::as_object)
.ok_or(CliError::MissingPackageScript { script: "dev" })?;
let _ = select_script(scripts, "dev:web", "dev")?;
let _ = select_script(scripts, "build:web", "build")?;
Ok(())
}
fn select_script(
scripts: &serde_json::Map<String, Value>,
preferred: &'static str,
fallback: &'static str,
) -> Result<String, CliError> {
for name in [preferred, fallback] {
if let Some(command) = scripts.get(name).and_then(Value::as_str) {
if command.split_whitespace().any(|part| part == "kayro") {
continue;
}
return Ok(name.to_owned());
}
}
Err(CliError::MissingPackageScript { script: fallback })
}
fn identity(name: &str, options: &ScaffoldOptions) -> Result<Identity, CliError> {
let package_name = slugify(name).ok_or_else(|| CliError::InvalidArguments {
message: format!("`{name}` does not contain a usable project name"),
})?;
let app_name = options
.app_name
.clone()
.unwrap_or_else(|| humanize(&package_name));
if app_name.trim().is_empty() {
return Err(CliError::InvalidArguments {
message: "--app-name cannot be empty".to_owned(),
});
}
let identifier = options
.identifier
.clone()
.unwrap_or_else(|| format!("dev.kayro.{package_name}"));
if !valid_identifier(&identifier) {
return Err(CliError::InvalidArguments {
message: format!("`{identifier}` is not a valid reverse-DNS identifier"),
});
}
Ok(Identity {
package_name,
app_name,
identifier,
})
}
fn slugify(value: &str) -> Option<String> {
let mut output = String::new();
let mut separator = false;
for character in value.chars().flat_map(char::to_lowercase) {
if character.is_ascii_alphanumeric() {
if separator && !output.is_empty() {
output.push('-');
}
separator = false;
output.push(character);
} else {
separator = true;
}
}
if output.is_empty() {
return None;
}
if output.starts_with(|character: char| character.is_ascii_digit()) {
output.insert_str(0, "app-");
}
Some(output)
}
fn humanize(value: &str) -> String {
value
.split('-')
.filter(|part| !part.is_empty())
.map(|part| {
let mut characters = part.chars();
characters.next().map_or_else(String::new, |first| {
first.to_uppercase().collect::<String>() + characters.as_str()
})
})
.collect::<Vec<_>>()
.join(" ")
}
fn valid_identifier(value: &str) -> bool {
let parts = value.split('.').collect::<Vec<_>>();
parts.len() >= 2
&& parts.iter().all(|part| {
!part.is_empty()
&& part
.chars()
.all(|character| character.is_ascii_alphanumeric() || character == '-')
})
}
fn kayro_config(identity: &Identity) -> String {
format!(
"[app]\nname = {}\nidentifier = {}\n\n[window]\nwidth = 1080\nheight = 720\nmin_width = 720\nmin_height = 520\n\n[permissions]\ndefault_profile = \"main\"\n\n[permissions.profiles.main]\nnative = [\"os\"]\ncommands = [\"greet\"]\n\n[permissions.filesystem]\nread = [\"data\", \"config\", \"cache\"]\nwrite = [\"data\", \"config\", \"cache\"]\nremove = [\"data\", \"config\", \"cache\"]\nwatch = [\"data\", \"config\", \"cache\"]\nmax_file_size = 67108864\nmax_watchers = 32\n\n[security]\nmax_ipc_message_bytes = 1048576\nmax_ipc_requests_per_second = 120\n\n[shell]\nmax_concurrent = 4\n\n[bundle]\nactive = true\n",
quoted(&identity.app_name),
quoted(&identity.identifier),
)
}
fn native_manifest(identity: &Identity) -> String {
format!(
"[package]\nname = {}\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"1.96\"\n\n[workspace]\n\n[dependencies]\nkayro = \"{KAYRO_VERSION}\"\nrust-embed = {{ version = \"8\", features = [\"debug-embed\", \"deterministic-timestamps\"] }}\n",
quoted(&identity.package_name),
)
}
fn package_json(identity: &Identity) -> String {
serde_json::to_string_pretty(&json!({
"name": identity.package_name,
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "kayro dev",
"build": "kayro build",
"types": "KAYRO_TYPES_ONLY=1 cargo run --manifest-path src-kayro/Cargo.toml --quiet",
"dev:web": "vite",
"build:web": "tsc --noEmit && vite build",
"check": "bun run types && tsc --noEmit"
},
"devDependencies": {
"typescript": TYPESCRIPT_VERSION,
"vite": VITE_VERSION
}
}))
.expect("project package JSON serializes")
+ "\n"
}
fn index_html(identity: &Identity) -> String {
let name = escape_html(&identity.app_name);
format!(
"<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self' kayro: http://127.0.0.1:* http://localhost:*; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' kayro: http://127.0.0.1:* http://localhost:* ws://127.0.0.1:* ws://localhost:*\" />\n <meta name=\"color-scheme\" content=\"dark light\" />\n <title>{name}</title>\n </head>\n <body>\n <main id=\"app\"></main>\n <script type=\"module\" src=\"/src/main.ts\"></script>\n </body>\n</html>\n"
)
}
fn project_readme(identity: &Identity) -> String {
format!(
"# {}\n\nA Kayro desktop app with a GPUI native shell and Vite frontend.\n\n```sh\nbun install\nkayro dev\n```\n\n`kayro build` creates the native installer for your OS: a macOS DMG, Windows\nsetup EXE, or Linux AppImage. Pass `--no-bundle` for only the executable. Rust\ncommands live in `src-kayro/src/commands.rs`; Kayro generates their TypeScript\nclient at `src/kayro.gen.ts`. Tools granted by the profile in `kayro.toml` are\navailable directly on `window.kayro`; the starter grants `os` and `greet`.\n",
identity.app_name
)
}
fn quoted(value: &str) -> String {
serde_json::to_string(value).expect("strings serialize")
}
fn escape_html(value: &str) -> String {
value
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
fn generated(path: &str, contents: String) -> ScaffoldFile {
ScaffoldFile {
relative_path: PathBuf::from(path),
contents,
}
}
fn static_file(path: &str, contents: &str) -> ScaffoldFile {
generated(path, contents.to_owned())
}
fn push_if_missing(
root: &Path,
files: &mut Vec<ScaffoldFile>,
skipped: &mut Vec<PathBuf>,
file: ScaffoldFile,
) {
let path = root.join(&file.relative_path);
if path.exists() {
skipped.push(path);
} else {
files.push(file);
}
}
fn write_files(root: &Path, files: &[ScaffoldFile], root_existed: bool) -> Result<(), CliError> {
if root_existed {
if !root.is_dir() {
return Err(CliError::ScaffoldTargetNotDirectory {
path: root.to_path_buf(),
});
}
} else {
if let Some(parent) = root.parent() {
fs::create_dir_all(parent).map_err(|source| CliError::WriteScaffold {
path: parent.to_path_buf(),
source,
})?;
}
fs::create_dir(root).map_err(|source| {
if source.kind() == std::io::ErrorKind::AlreadyExists {
CliError::ScaffoldTargetExists {
path: root.to_path_buf(),
}
} else {
CliError::WriteScaffold {
path: root.to_path_buf(),
source,
}
}
})?;
}
let mut created = Vec::new();
for file in files {
let path = root.join(&file.relative_path);
let result = (|| {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let mut output = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)?;
output.write_all(file.contents.as_bytes())?;
output.sync_all()
})();
if let Err(source) = result {
for created_path in created.iter().rev() {
let _ = fs::remove_file(created_path);
}
if !root_existed {
let _ = fs::remove_dir_all(root);
}
return if source.kind() == std::io::ErrorKind::AlreadyExists {
Err(CliError::ScaffoldConflict { path })
} else {
Err(CliError::WriteScaffold { path, source })
};
}
created.push(path);
}
Ok(())
}
fn cargo_lock_command(root: &Path) -> CommandSpec {
let mut command = CommandSpec::new(
"lockfile",
env::var_os("CARGO").unwrap_or_else(|| OsString::from("cargo")),
root.to_path_buf(),
);
command
.arg("generate-lockfile")
.arg("--manifest-path")
.arg(root.join("src-kayro/Cargo.toml"));
command
}
fn bun_install_command(root: &Path) -> CommandSpec {
let mut command = CommandSpec::new("dependencies", "bun", root.to_path_buf());
command.arg("install");
command
}
fn current_dir() -> Result<PathBuf, CliError> {
env::current_dir().map_err(|source| CliError::Io {
action: "reading the current directory",
source,
})
}
fn absolute_from(current_dir: &Path, path: &Path) -> PathBuf {
if path.is_absolute() {
path.to_path_buf()
} else {
current_dir.join(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_human_names_for_packages() {
assert_eq!(slugify("My Cool_App"), Some("my-cool-app".to_owned()));
assert_eq!(slugify("42"), Some("app-42".to_owned()));
assert_eq!(humanize("my-cool-app"), "My Cool App");
}
#[test]
fn validates_reverse_dns_identifiers() {
assert!(valid_identifier("dev.kayro.my-app"));
assert!(!valid_identifier("not an id"));
assert!(!valid_identifier("single"));
}
#[test]
fn generated_fallible_command_returns_ok() {
let commands = include_str!("../templates/commands.rs");
assert!(commands.contains("Ok(Greeting {\n message,\n count,\n })"));
}
}