diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs index 72da961..59d9533 100644 --- a/src/cmd_plugin.rs +++ b/src/cmd_plugin.rs @@ -121,10 +121,104 @@ fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> crate::cmd_create::maybe_check(opts.check) } +const EMPTY_DIR: &str = "a plugin package needs an empty directory, so the package stays self-contained — pass --package or run it in an empty folder"; +const NPM_CONVENTION: &str = + "green-tea- is the naming convention; the plugin listing uses it to find green-tea plugins."; + +/// JSR's scope rule: lowercase letters, digits and hyphens. +fn valid_scope(s: &str) -> bool { + !s.is_empty() + && s.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// npm's package name rule, closely enough to catch a typo: optional `@scope/`, lowercase. +fn valid_npm_name(s: &str) -> bool { + let part = |p: &str| { + !p.is_empty() + && !p.starts_with(['.', '_']) + && p.chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "-._~".contains(c)) + }; + match s.strip_prefix('@').and_then(|rest| rest.split_once('/')) { + Some((scope, name)) => part(scope) && part(name), + None => !s.starts_with('@') && part(s), + } +} + fn package_mode( - _opts: Opts, - _ask: &mut Ask, - _root: &Path, + opts: Opts, + ask: &mut Ask, + root: &Path, ) -> io::Result<()> { - Err(invalid("package mode is not built yet".into())) + // The directory is checked before any question: a person should not answer + // four questions to be told the folder was never going to work. + let dir = match &opts.package { + Some(Some(d)) => root.join(d), + _ => root.to_path_buf(), + }; + if dir.exists() && std::fs::read_dir(&dir)?.next().is_some() { + return Err(invalid(EMPTY_DIR.into())); + } + + let slug = resolve_slug(opts.name, ask)?; + let scope = match opts.scope { + Some(s) => s, + None => ask.text("JSR scope?", None, "--scope")?, + }; + let scope = scope.trim_start_matches('@').to_string(); + if !valid_scope(&scope) { + return Err(invalid(format!( + "'{scope}' is not a JSR scope: use lowercase letters, digits and hyphens" + ))); + } + + let registry = match opts.registry { + Some(r) => r, + None => { + ask.say(&format!("\n{}\n", plugin_files::JSR_BANNER))?; + match ask + .text( + "Publish to: (1) JSR only (2) JSR + npm", + Some("1"), + "--registry", + )? + .as_str() + { + "2" | "both" => "both".to_string(), + _ => "jsr".to_string(), + } + } + }; + + let npm = if registry == "both" { + let suggested = format!("@{scope}/green-tea-{slug}"); + let name = match opts.npm_name { + Some(n) => n, + // The default in parentheses is the suggestion; Enter takes it. + None => ask.text("npm package name?", Some(&suggested), "--npm-name")?, + }; + if !valid_npm_name(&name) { + return Err(invalid(format!("'{name}' is not a valid npm name"))); + } + let unscoped = name.rsplit('/').next().unwrap_or(&name); + if !unscoped.starts_with("green-tea-") { + println!("note: {NPM_CONVENTION}"); + } + Some(name) + } else { + None + }; + + let package = plugin_files::Package { slug, scope, npm }; + for (rel, content) in plugin_files::package(&package) { + let path = dir.join(&rel); + std::fs::create_dir_all(path.parent().unwrap())?; + std::fs::write(&path, content)?; + println!("✓ {}", path.strip_prefix(root).unwrap_or(&path).display()); + } + println!( + "→ next: fill in the Runtimes table in README.md, then `deno test` and `deno publish`" + ); + Ok(()) } diff --git a/src/plugin_files.rs b/src/plugin_files.rs index ba9df21..0f6dc05 100644 --- a/src/plugin_files.rs +++ b/src/plugin_files.rs @@ -2,6 +2,7 @@ //! options in, file content out, so the shapes are tested without a disk. use crate::naming::{camel, pascal}; +use crate::template::CORE_VERSION; /// The plugin itself, the same in both modes. It follows the official /// plugins' convention: one string is the plugin name, the node name and the @@ -36,3 +37,209 @@ export function {fun}(options: {opts} = {{}}): Plugin {{ " ) } + +pub const JSR_BANNER: &str = "JSR is recommended. It records which runtimes a package supports (Node, Deno, Bun, workerd), and the green-tea plugin listing shows that for every plugin."; + +pub struct Package { + pub slug: String, + pub scope: String, + /// `Some(name)` when it also publishes to npm. + pub npm: Option, +} + +impl Package { + fn jsr_name(&self) -> String { + format!("@{}/{}", self.scope, self.slug) + } +} + +/// Every file of a package, as (path relative to the package root, content). +pub fn package(p: &Package) -> Vec<(String, String)> { + let mut files = vec![ + ("deno.json".to_string(), deno_json(p)), + ("package.json".to_string(), package_json(p)), + ("src/index.ts".to_string(), factory(&p.slug)), + (format!("test/{}.test.ts", p.slug), test_ts(p)), + ("README.md".to_string(), readme(p)), + ( + "CHANGELOG.md".to_string(), + "# Changelog\n\n## [Unreleased]\n\n- First version.\n".to_string(), + ), + ( + ".gitignore".to_string(), + "node_modules\ndist\n.DS_Store\n".to_string(), + ), + ]; + if p.npm.is_some() { + files.push(("tsconfig.json".to_string(), TSCONFIG.to_string())); + } + files +} + +fn deno_json(p: &Package) -> String { + format!( + r#"{{ + "name": "{name}", + "version": "0.1.0", + "license": "MIT", + "exports": "./src/index.ts", + "imports": {{ + "@green-tea/core": "npm:@green-tea/core@{CORE_VERSION}" + }}, + "tasks": {{ + "test": "deno test --allow-env --allow-read" + }}, + "publish": {{ + "include": ["src", "README.md", "CHANGELOG.md", "deno.json"] + }} +}} +"#, + name = p.jsr_name() + ) +} + +const ENGINES: &str = r#" "engines": { + "node": ">=22", + "deno": ">=2", + "bun": ">=1.3" + },"#; + +fn package_json(p: &Package) -> String { + match &p.npm { + None => format!( + r#"{{ + "name": "{name}", + "version": "0.1.0", + "private": true, + "type": "module", +{ENGINES} + "scripts": {{ + "test": "node --test test/*.test.ts" + }}, + "devDependencies": {{ + "@green-tea/core": "{CORE_VERSION}" + }} +}} +"#, + name = p.jsr_name() + ), + Some(npm) => format!( + r#"{{ + "name": "{npm}", + "version": "0.1.0", + "license": "MIT", + "type": "module", + "exports": {{ + ".": {{ + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }} + }}, + "files": ["dist"], +{ENGINES} + "scripts": {{ + "build": "tsc", + "prepublishOnly": "npm run build", + "test": "node --test test/*.test.ts" + }}, + "devDependencies": {{ + "@green-tea/core": "{CORE_VERSION}", + "typescript": "^5" + }} +}} +"# + ), + } +} + +const TSCONFIG: &str = r#"{ + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "declaration": true, + "outDir": "dist", + "rootDir": "src", + "strict": true, + "skipLibCheck": true + }, + "include": ["src"] +} +"#; + +fn test_ts(p: &Package) -> String { + let fun = camel(&p.slug); + let slug = &p.slug; + format!( + "import {{ strict as assert }} from 'node:assert'; +import {{ test }} from 'node:test'; + +import {{ createApp }} from '@green-tea/core'; + +import {{ {fun} }} from '../src/index.ts'; + +test('mounts into an app, and the app boots', async () => {{ + const app = createApp({{ modules: [], plugins: [{fun}()] }}); + await app.boot(); +}}); + +test('two instances mount side by side under different tokens', async () => {{ + const app = createApp({{ modules: [], plugins: [{fun}(), {fun}({{ provides: '{slug}-2' }})] }}); + await app.boot(); +}}); + +test('two instances under one name are refused', () => {{ + assert.throws(() => createApp({{ modules: [], plugins: [{fun}(), {fun}()] }}), /two plugins are named/); +}}); +" + ) +} + +fn readme(p: &Package) -> String { + let jsr = p.jsr_name(); + let fun = camel(&p.slug); + let npm_install = match &p.npm { + Some(npm) => format!("\nOr from npm:\n\n```bash\nnpm i {npm}\n```\n"), + None => String::new(), + }; + format!( + "# {jsr} + +> {JSR_BANNER} + +What this plugin adds to a green-tea app, in one or two sentences. + +## Runtimes + +| Runtime | Supported | Why not | +|---|---|---| +| Node | | | +| Deno | | | +| Bun | | | +| workerd (edge) | | | + +Fill in every row. The green-tea plugin listing asks for a reason beside each runtime this does not support. + +## Install + +```bash +npx jsr add {jsr} +``` +{npm_install} +Needs `@green-tea/core@{CORE_VERSION}` or newer. + +## Usage + +```ts +import {{ createApp }} from '@green-tea/core'; +import {{ {fun} }} from '{jsr}'; + +const app = createApp({{ modules: [AppModule], plugins: [{fun}()] }}); +``` + +## List it + +Once it is published, add it to the green-tea plugin listing: https://green-tea.expressive-tea.io/plugins/#contribute +" + ) +} diff --git a/tests/plugin.rs b/tests/plugin.rs index 02d73bf..4dc36e8 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -143,3 +143,210 @@ fn other_kinds_still_require_a_name() { .failure() .stderr(contains("needs a name")); } + +fn files_under(dir: &std::path::Path) -> Vec { + fn walk(base: &std::path::Path, dir: &std::path::Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(base, &p, out) + } else { + out.push(p.strip_prefix(base).unwrap().display().to_string()) + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn package_jsr_writes_the_tree_into_dir() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "Plugin Algo", + "--package", + "algo-pkg", + "--scope", + "@acme", + ]) + .assert() + .success(); + let pkg = d.path().join("algo-pkg"); + assert_eq!( + files_under(&pkg), + [ + ".gitignore", + "CHANGELOG.md", + "README.md", + "deno.json", + "package.json", + "src/index.ts", + "test/plugin-algo.test.ts" + ] + ); + let deno = std::fs::read_to_string(pkg.join("deno.json")).unwrap(); + assert!(deno.contains("\"name\": \"@acme/plugin-algo\""), "{deno}"); + assert!(deno.contains("npm:@green-tea/core@26.9.0-beta.2"), "{deno}"); + let pj = std::fs::read_to_string(pkg.join("package.json")).unwrap(); + assert!(pj.contains("\"private\": true"), "{pj}"); + assert!(pj.contains("\"devDependencies\""), "{pj}"); + assert!( + !pj.contains("\"dependencies\""), + "core is a type-only dependency: {pj}" + ); + let readme = std::fs::read_to_string(pkg.join("README.md")).unwrap(); + assert!(readme.contains("JSR is recommended"), "banner"); + for runtime in ["| Node |", "| Deno |", "| Bun |", "| workerd (edge) |"] { + assert!(readme.contains(runtime), "{runtime} row"); + } +} + +#[test] +fn package_both_adds_the_npm_build() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "acme", + "--registry", + "both", + ]) + .assert() + .success(); + let pkg = d.path().join("p"); + assert!(pkg.join("tsconfig.json").exists()); + let pj = std::fs::read_to_string(pkg.join("package.json")).unwrap(); + assert!( + pj.contains("\"name\": \"@acme/green-tea-algo\""), + "suggested name is the default: {pj}" + ); + assert!(!pj.contains("\"private\""), "{pj}"); + assert!(pj.contains("\"prepublishOnly\": \"npm run build\""), "{pj}"); + let readme = std::fs::read_to_string(pkg.join("README.md")).unwrap(); + assert!(readme.contains("npm i @acme/green-tea-algo"), "{readme}"); +} + +#[test] +fn both_package_json_is_esm_only() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "acme", + "--registry", + "both", + ]) + .assert() + .success(); + let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap(); + assert!(pj.contains("\"type\": \"module\""), "{pj}"); + assert!(!pj.contains("require"), "{pj}"); + assert!(!pj.contains(".cjs"), "{pj}"); +} + +#[test] +fn package_accepts_any_npm_name_and_notes_the_convention() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "acme", + "--registry", + "both", + "--npm-name", + "algo-plugin", + ]) + .assert() + .success() + .stdout(contains("green-tea- is the naming convention")); + let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap(); + assert!(pj.contains("\"name\": \"algo-plugin\""), "{pj}"); +} + +#[test] +fn package_refuses_a_non_empty_directory_and_writes_nothing() { + let d = tempdir().unwrap(); + std::fs::write(d.path().join("keep.txt"), "x").unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo", "--package", "--scope", "acme"]) + .assert() + .failure() + .stderr(contains("a plugin package needs an empty directory")); + assert_eq!(files_under(d.path()), ["keep.txt"]); +} + +#[test] +fn package_in_an_empty_current_directory() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo", "--package", "--scope", "acme"]) + .assert() + .success(); + assert!(d.path().join("deno.json").exists()); +} + +#[test] +fn package_off_a_tty_needs_a_scope() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo", "--package", "p"]) + .assert() + .failure() + .stderr(contains("--scope")); + assert!(!d.path().join("p").exists()); +} + +#[test] +fn package_rejects_a_bad_scope_or_npm_name() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "Ac Me", + ]) + .assert() + .failure() + .stderr(contains("scope")); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "q", + "--scope", + "acme", + "--registry", + "both", + "--npm-name", + "Not Valid", + ]) + .assert() + .failure() + .stderr(contains("npm name")); +}