From 82d6b809daa103391fd65d21e5a9718f437b0f87 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 5 Sep 2026 17:12:58 -0500 Subject: [PATCH 01/14] chore(release): 26.9.0-beta.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the changelog section the merged work has been accumulating in and moves the crate onto the version its scaffolds already pin core against. Everything in it is a fix for something users hit today — a scaffold frozen on 26.7.0-beta.0 with no way forward, a bun template that never type-checked, a published crate declaring MIT with no licence text, an installer that refused Linux arm64 — and none of it reaches anyone until this ships. Verified as the artifact rather than as the working tree: `cargo publish --dry-run --locked` packages 56 files and compiles the *packaged* crate, which is what proves `include_dir!` still finds `template/`. All 22 template files are included, `template/runtimes/edge/.npmrc` among them — a dotfile cargo could have dropped, and without it a `cargo install`ed matcha would scaffold edge against npm instead of JSR and produce a project that cannot boot on workerd. Signed-off-by: Diego Resendez --- CHANGELOG.md | 4 ++-- Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67a0e14..e806740 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8 mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved. -## [Unreleased] +## [26.9.0-beta.0] - 2026-09-05 ### Added @@ -182,6 +182,6 @@ First tagged release. A single native binary, no JS runtime needed to install it - **A `curl | sh` installer** with sha256 verification, and cross-platform binaries attached to each release. -[Unreleased]: https://github.com/Expressive-Tea/matcha/compare/v26.8.0-beta.0...HEAD +[26.9.0-beta.0]: https://github.com/Expressive-Tea/matcha/compare/v26.8.0-beta.0...v26.9.0-beta.0 [26.8.0-beta.0]: https://github.com/Expressive-Tea/matcha/compare/v26.7.0...v26.8.0-beta.0 [26.7.0]: https://github.com/Expressive-Tea/matcha/releases/tag/v26.7.0 diff --git a/Cargo.lock b/Cargo.lock index 19f951b..1274d2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,7 +254,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "matcha-cli" -version = "26.8.0-beta.0" +version = "26.9.0-beta.0" dependencies = [ "assert_cmd", "clap", diff --git a/Cargo.toml b/Cargo.toml index 6e5bb4c..c42dbcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "matcha-cli" -version = "26.8.0-beta.0" +version = "26.9.0-beta.0" edition = "2021" description = "The green-tea CLI: scaffold a project, generate controllers, steps and providers already wired into their module, and run with your runtime detected. One native binary, no JS runtime needed to install it." license = "MIT" -- 2.54.1 From 483cc23deac21352ca8ef47c34265122c8fc7387 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 5 Sep 2026 17:32:30 -0500 Subject: [PATCH 02/14] ci: make this forge the gate it was meant to be, and stop pushing every tag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two problems in one place, one of them latent since before this release. `promote.yml` and `release.yml` both fired on the same `v*` tag push, so Gitea started building and handed the tag to GitHub at the same moment — and the tag arriving there is what starts GitHub's build and its crates.io publish. The local build was therefore a parallel opinion rather than a check: by the time it could have said no, the crate was already going out, and crates.io has no unpublish, only yank. Tag promotion moves into `release.yml` behind `needs: build`, so the sequence is what it was always described as — Gitea builds all four targets and runs every artifact it can, and only then does GitHub hear about the tag. `promote.yml` also ran `git push github --tags` on every push to `main`, which has been failing every time. The tags diverged before this: `v26.7.0` points at `371c5f7` here and `2a3dae9` there, and `v26.8.0-beta.0` is annotated here and lightweight there — so the push is a non-fast-forward on refs that already exist. `main` itself was pushed by the line above and always succeeded, so the job went red while its actual work had already been done, which is the worst shape a CI failure can take: permanent, and therefore ignored on the day it means something. Dropped rather than forced, because reconciling the divergence rewrites what a published tag points at — a decision, not a fix. New tags are unaffected; they go through `release.yml` now. Branched from `main` rather than `develop` so it is active for the v26.9.0-beta.0 tag, and so merging it back carries the release's version bump to `develop` with it. Signed-off-by: Diego Resendez --- .github/workflows/promote.yml | 27 ++++++++++++++++++--------- .github/workflows/release.yml | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index 386c005..3d01201 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -1,10 +1,16 @@ name: Promote → GitHub -# Runs on GITEA ONLY. Mirrors only main + version tags to the public GitHub repo. +# Runs on GITEA ONLY. Mirrors `main` to the public GitHub repo. +# +# Tags are NOT promoted here. They are promoted by release.yml's `promote-tag` +# job, which waits for this forge's builds to pass first — pushing a tag is what +# starts GitHub's release and its crates.io publish, and crates.io cannot be +# unpublished, only yanked. Both workflows used to fire on the same tag push, so +# Gitea built and GitHub published at the same time and this forge was never the +# check it was meant to be. on: push: branches: [main] - tags: ['v*'] jobs: push-github: @@ -14,14 +20,17 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - name: Push main + tags to GitHub + - name: Push main to GitHub env: GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }} run: | git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/matcha.git" - if [ "${{ github.ref_type }}" = "tag" ]; then - git push github "refs/tags/${{ github.ref_name }}" - else - git push github "HEAD:refs/heads/main" - git push github --tags - fi + # Deliberately not `--tags`. v26.7.0 points at a different commit on + # each forge and v26.8.0-beta.0 is annotated here and lightweight + # there, so pushing every tag is a non-fast-forward that fails — which + # it has been doing on every push to main, reddening a job whose real + # work (the line above) had already succeeded. Reconciling that + # divergence means rewriting what a published tag points at, which is + # a decision rather than a fix; new tags are unaffected and go through + # release.yml. + git push github "HEAD:refs/heads/main" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e06ba7e..82ba2ed 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -172,6 +172,29 @@ jobs: "$PWD/.bin/matcha" --version "$PWD/.bin/matcha" --help > /dev/null + # Gitea only: hand the tag to GitHub, but only once this forge has built all + # four targets and run every artifact it can. + # + # This is the gate. Pushing the tag is what starts GitHub's release and, with + # it, the crates.io publish — and crates.io has no unpublish, only yank. So the + # local build is not a parallel opinion, it is the thing that has to pass + # first. `needs: build` is what makes the two sequential; when both workflows + # fired on the same tag push they were not. + promote-tag: + needs: build + if: ${{ github.server_url != 'https://github.com' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Push the tag to GitHub + env: + GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }} + run: | + git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/matcha.git" + git push github "refs/tags/$GITHUB_REF_NAME" + # crates.io = production only. # crates.io = production only, via OIDC Trusted Publishing (no CARGO_TOKEN). # Requires a trusted publisher configured on crates.io (Expressive-Tea/matcha, release.yml). -- 2.54.1 From 6304ad7e24ecda02c194e70e7d4101f47577fca8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 5 Sep 2026 17:37:16 -0500 Subject: [PATCH 03/14] ci: use the expression form for the tag ref, not the env var MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit promote.yml handed v26.8.0-beta.0 to GitHub with `${{ github.ref_name }}`, so that form is proven on this act_runner. `$GITHUB_REF_NAME` is not — act_runner 0.2.13 may or may not export it, and the failure mode is silent in the worst way: `git push github "refs/tags/"` with an empty name, a tag that never leaves this forge, and a release that simply never happens on GitHub. Signed-off-by: Diego Resendez --- .github/workflows/release.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 82ba2ed..8646665 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -193,7 +193,12 @@ jobs: GH_TOKEN: ${{ secrets.GH_PROMOTE_TOKEN }} run: | git remote add github "https://x-access-token:${GH_TOKEN}@github.com/Expressive-Tea/matcha.git" - git push github "refs/tags/$GITHUB_REF_NAME" + # `${{ github.ref_name }}` rather than $GITHUB_REF_NAME: the expression + # is what promote.yml used to hand v26.8.0-beta.0 to GitHub, so it is + # proven on this act_runner. Whether the env var is exported here is + # not, and getting it wrong would push an empty ref and leave the tag + # on this forge alone. + git push github "refs/tags/${{ github.ref_name }}" # crates.io = production only. # crates.io = production only, via OIDC Trusted Publishing (no CARGO_TOKEN). -- 2.54.1 From c5b4a56ccd919b2db2b712de20106de7cbb0dfa5 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:53:17 -0500 Subject: [PATCH 04/14] feat(plugin): derive a plugin's slug and identifiers from what was typed Signed-off-by: Diego Resendez --- src/main.rs | 1 + src/naming.rs | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/naming.rs diff --git a/src/main.rs b/src/main.rs index b0b9fb8..5067fab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod cmd_graph; mod cmd_new; mod cmd_run; mod entry; +mod naming; mod runtime; mod template; mod wire; diff --git a/src/naming.rs b/src/naming.rs new file mode 100644 index 0000000..82dddcc --- /dev/null +++ b/src/naming.rs @@ -0,0 +1,85 @@ +//! Names for a plugin: the slug a person types their way into, and the +//! TypeScript identifiers derived from it. +//! +//! The slug is one string on purpose. It is the folder, the plugin's `name`, +//! its node name and the token it provides — the same rule the official +//! plugins follow — so a plugin never has two names to keep in step. + +/// `Plugin Algo` → `plugin-algo`. Letters and digits are kept (lowercased); +/// spaces, `-` and `_` separate words; anything else rejects the name, because +/// quietly dropping a `.` or an emoji would hand back a name nobody typed. +/// `None` when nothing usable is left or the result does not start with a letter. +pub fn slug(name: &str) -> Option { + let mut out = String::new(); + for ch in name.trim().chars() { + if ch.is_ascii_alphanumeric() { + out.push(ch.to_ascii_lowercase()); + } else if ch.is_whitespace() || ch == '-' || ch == '_' { + if !out.is_empty() && !out.ends_with('-') { + out.push('-'); + } + } else { + return None; + } + } + let out = out.trim_end_matches('-').to_string(); + out.starts_with(|c: char| c.is_ascii_lowercase()) + .then_some(out) +} + +fn words(slug: &str) -> impl Iterator { + slug.split('-').filter(|w| !w.is_empty()) +} + +fn capitalised(word: &str) -> String { + let mut chars = word.chars(); + match chars.next() { + Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(), + None => String::new(), + } +} + +/// `plugin-algo` → `PluginAlgo`, for the options interface. +pub fn pascal(slug: &str) -> String { + words(slug).map(capitalised).collect() +} + +/// `plugin-algo` → `pluginAlgo`, for the factory. +pub fn camel(slug: &str) -> String { + let mut words = words(slug); + let first = words.next().unwrap_or_default().to_string(); + first + &words.map(capitalised).collect::() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn slug_kebab_cases_what_was_typed() { + assert_eq!(slug("Plugin Algo").as_deref(), Some("plugin-algo")); + assert_eq!(slug("algo").as_deref(), Some("algo")); + assert_eq!(slug(" Rate Limit ").as_deref(), Some("rate-limit")); + assert_eq!(slug("rate_limit").as_deref(), Some("rate-limit")); + assert_eq!(slug("already-kebab").as_deref(), Some("already-kebab")); + assert_eq!(slug("v2 cache").as_deref(), Some("v2-cache")); + } + + #[test] + fn slug_rejects_what_cannot_be_a_name() { + assert_eq!(slug(""), None); + assert_eq!(slug(" "), None); + assert_eq!(slug("--"), None); + assert_eq!(slug("🍵"), None); + assert_eq!(slug("2fa"), None); + assert_eq!(slug("rate.limit"), None); + } + + #[test] + fn identifiers_follow_the_slug() { + assert_eq!(camel("plugin-algo"), "pluginAlgo"); + assert_eq!(pascal("plugin-algo"), "PluginAlgo"); + assert_eq!(camel("algo"), "algo"); + assert_eq!(pascal("v2-cache"), "V2Cache"); + } +} -- 2.54.1 From f2a3c16023276afafd0454f3dee413d497e43244 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:53:44 -0500 Subject: [PATCH 05/14] feat(plugin): ask questions at a terminal and take defaults everywhere else Signed-off-by: Diego Resendez --- src/ask.rs | 163 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 1 + 2 files changed, 164 insertions(+) create mode 100644 src/ask.rs diff --git a/src/ask.rs b/src/ask.rs new file mode 100644 index 0000000..e28942b --- /dev/null +++ b/src/ask.rs @@ -0,0 +1,163 @@ +//! Questions for a person at a terminal, and defaults for everyone else. +//! +//! Off a TTY (CI, a pipe, a script) nothing is asked: each question takes its +//! default, and one without a default is an error naming the flag to pass. +//! Blocking on a read that nobody will ever answer is the one thing this must +//! never do. + +use std::io::{self, BufRead, IsTerminal, Write}; + +pub struct Ask { + interactive: bool, + input: R, + output: W, +} + +impl Ask, io::Stderr> { + /// Prompts go to stderr, so stdout stays the report of what was written. + pub fn stdio() -> Self { + Ask::new(io::stdin().is_terminal(), io::stdin().lock(), io::stderr()) + } +} + +impl Ask { + pub fn new(interactive: bool, input: R, output: W) -> Self { + Ask { + interactive, + input, + output, + } + } + + /// A line for the person answering; silent off a TTY. + pub fn say(&mut self, text: &str) -> io::Result<()> { + if self.interactive { + writeln!(self.output, "{text}")?; + } + Ok(()) + } + + fn line(&mut self, prompt: &str) -> io::Result { + write!(self.output, "{prompt} ")?; + self.output.flush()?; + let mut answer = String::new(); + if self.input.read_line(&mut answer)? == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "no answer (end of input)", + )); + } + Ok(answer.trim().to_string()) + } + + pub fn yes_no(&mut self, question: &str, default: bool) -> io::Result { + if !self.interactive { + return Ok(default); + } + let hint = if default { "(Y/n)" } else { "(y/N)" }; + let answer = self.line(&format!("{question} {hint}"))?.to_lowercase(); + Ok(match answer.as_str() { + "" => default, + "y" | "yes" => true, + _ => false, + }) + } + + /// `flag` names what to pass instead, for the error off a TTY. + pub fn text( + &mut self, + question: &str, + default: Option<&str>, + flag: &str, + ) -> io::Result { + if !self.interactive { + return default.map(str::to_string).ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("no terminal to ask on; pass {flag}"), + ) + }); + } + let prompt = match default { + Some(d) => format!("{question} ({d})"), + None => question.to_string(), + }; + loop { + let answer = self.line(&prompt)?; + if !answer.is_empty() { + return Ok(answer); + } + if let Some(d) = default { + return Ok(d.to_string()); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn scripted(answers: &str) -> Ask>, Vec> { + Ask::new(true, Cursor::new(answers.as_bytes().to_vec()), Vec::new()) + } + + fn piped() -> Ask>, Vec> { + Ask::new(false, Cursor::new(Vec::new()), Vec::new()) + } + + #[test] + fn yes_no_takes_the_default_on_enter_and_reads_y() { + assert!(!scripted("\n").yes_no("Package?", false).unwrap()); + assert!(scripted("y\n").yes_no("Package?", false).unwrap()); + assert!(scripted("YES\n").yes_no("Package?", false).unwrap()); + assert!(!scripted("nope\n").yes_no("Package?", false).unwrap()); + } + + #[test] + fn text_takes_the_default_on_enter() { + assert_eq!( + scripted("\n") + .text("Folder?", Some("plugins"), "--folder") + .unwrap(), + "plugins" + ); + assert_eq!( + scripted("lib\n") + .text("Folder?", Some("plugins"), "--folder") + .unwrap(), + "lib" + ); + } + + #[test] + fn text_without_a_default_asks_again_until_answered() { + assert_eq!( + scripted("\n\nalgo\n").text("Name?", None, "NAME").unwrap(), + "algo" + ); + } + + #[test] + fn text_errors_on_eof() { + let err = scripted("").text("Name?", None, "NAME").unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof); + } + + #[test] + fn off_a_tty_nothing_is_asked() { + let mut ask = piped(); + assert!(!ask.yes_no("Package?", false).unwrap()); + assert_eq!( + ask.text("Folder?", Some("plugins"), "--folder").unwrap(), + "plugins" + ); + let err = ask.text("Name?", None, "the NAME argument").unwrap_err(); + assert!(err.to_string().contains("the NAME argument"), "{err}"); + assert!( + ask.output.is_empty(), + "nothing is printed when nobody is there to answer" + ); + } +} diff --git a/src/main.rs b/src/main.rs index 5067fab..3a30a50 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +mod ask; mod check; mod cli; mod cmd_add; -- 2.54.1 From 3c3b7aaf8e2e99574b3a4d088fdf21df25d8b7bc Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:54:51 -0500 Subject: [PATCH 06/14] feat(plugin): matcha create plugin scaffolds an in-app plugin and wires it In-app is the default. Each plugin gets its own folder under plugins/ (or --folder), so it can be exported as a package later, and the factory is registered in createApp({ plugins }). A plugins value that is not an array literal is left alone with a hint, as modules already is. Signed-off-by: Diego Resendez --- src/cli.rs | 18 +++++- src/cmd_create.rs | 6 +- src/cmd_plugin.rs | 130 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 34 ++++++++++- src/plugin_files.rs | 38 ++++++++++++ src/wire.rs | 19 ++++-- tests/cli.rs | 5 +- tests/plugin.rs | 145 ++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 383 insertions(+), 12 deletions(-) create mode 100644 src/cmd_plugin.rs create mode 100644 src/plugin_files.rs create mode 100644 tests/plugin.rs diff --git a/src/cli.rs b/src/cli.rs index 83e9d80..e03153f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -26,9 +26,25 @@ pub enum Command { Create { #[arg(value_parser = PossibleValuesParser::new(cmd_create::kinds()))] kind: String, - name: String, + /// Required for every kind but `plugin`, which asks for it + name: Option, #[arg(long)] check: bool, + /// plugin: a package of its own, in DIR (default: the current directory, which must be empty) + #[arg(long, num_args = 0..=1, value_name = "DIR")] + package: Option>, + /// plugin, in-app: folder relative to the project root (default: plugins) + #[arg(long)] + folder: Option, + /// plugin, package: the JSR scope + #[arg(long)] + scope: Option, + /// plugin, package: where it publishes (default: jsr) + #[arg(long, value_parser = ["jsr", "both"])] + registry: Option, + /// plugin, package, both: the npm name (default: @/green-tea-) + #[arg(long)] + npm_name: Option, }, /// Check the project for the misconfigurations that fail confusingly Doctor, diff --git a/src/cmd_create.rs b/src/cmd_create.rs index 0e1050f..d4a6bc1 100644 --- a/src/cmd_create.rs +++ b/src/cmd_create.rs @@ -53,8 +53,10 @@ const PIECES: &[Piece] = &[ /// list, so a new kind cannot be accepted by the parser and rejected by `run` /// (or the reverse). pub fn kinds() -> Vec<&'static str> { - std::iter::once("module") + ["module"] + .into_iter() .chain(PIECES.iter().map(|p| p.kind)) + .chain(["plugin"]) .collect() } @@ -143,7 +145,7 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> { maybe_check(check) } -fn maybe_check(check: bool) -> std::io::Result<()> { +pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> { if check { match crate::check::run(Path::new(".")) { Ok(true) => println!("✓ type-check passed"), diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs new file mode 100644 index 0000000..72da961 --- /dev/null +++ b/src/cmd_plugin.rs @@ -0,0 +1,130 @@ +//! `matcha create plugin`: an in-app plugin folder by default, or, with +//! `--package` or a yes, a package of its own. + +use std::io::{self, BufRead, Error, ErrorKind, Write}; +use std::path::{Component, Path}; + +use crate::ask::Ask; +use crate::{entry, naming, plugin_files, wire}; + +pub struct Opts { + pub name: Option, + /// `None`: not asked for. `Some(None)`: `--package` with no directory. + pub package: Option>, + pub folder: Option, + pub scope: Option, + pub registry: Option, + pub npm_name: Option, + pub check: bool, +} + +pub fn run(opts: Opts) -> io::Result<()> { + run_with(opts, &mut Ask::stdio(), Path::new(".")) +} + +pub fn run_with( + opts: Opts, + ask: &mut Ask, + root: &Path, +) -> io::Result<()> { + let package = match opts.package { + Some(_) => true, + None => ask.yes_no("Separate it as a package?", false)?, + }; + if package { + package_mode(opts, ask, root) + } else { + in_app(opts, ask, root) + } +} + +fn invalid(msg: String) -> Error { + Error::new(ErrorKind::InvalidInput, msg) +} + +fn resolve_slug( + name: Option, + ask: &mut Ask, +) -> io::Result { + let raw = match name { + Some(n) => n, + None => ask.text("Plugin name?", None, "the NAME argument")?, + }; + naming::slug(&raw).ok_or_else(|| { + invalid(format!( + "'{raw}' does not make a plugin name: start with a letter, and use letters, digits, spaces or hyphens" + )) + }) +} + +/// Relative, and never climbing out: `..` or an absolute path would put the +/// plugin outside the project it is being wired into. +fn inside_project(folder: &str) -> bool { + !folder.is_empty() + && Path::new(folder) + .components() + .all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) +} + +fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> io::Result<()> { + let Some(entry_path) = entry::find(root) else { + return Err(invalid(format!( + "an in-app plugin is wired into createApp, and there is no {} here; run this in a project, or pass --package for a package of its own", + entry::candidates() + ))); + }; + let folder = match opts.folder { + Some(f) => f, + None => ask.text("Folder?", Some("plugins"), "--folder")?, + }; + let folder = folder.trim_end_matches('/').to_string(); + if !inside_project(&folder) { + return Err(invalid(format!( + "the plugin folder has to be inside the project, got '{folder}'" + ))); + } + let slug = resolve_slug(opts.name, ask)?; + + let dir = root.join(&folder).join(&slug); + if dir.exists() { + return Err(Error::new( + ErrorKind::AlreadyExists, + format!( + "{} already exists", + Path::new(&folder).join(&slug).display() + ), + )); + } + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?; + println!( + "✓ {}", + Path::new(&folder).join(&slug).join("index.ts").display() + ); + + let fun = naming::camel(&slug); + let call = format!("{fun}()"); + // Both entry candidates live in src/, so the plugin folder is one level up. + let from = format!("../{folder}/{slug}/index"); + let src = std::fs::read_to_string(&entry_path)?; + let imported = wire::add_import(&src, &fun, &from); + match wire::add_to_createapp(&imported, "plugins", &call) { + Some(wired) => { + std::fs::write(&entry_path, wired)?; + println!("✓ registered {call} in createApp"); + } + None => println!( + "→ could not auto-register; add {call} to createApp plugins[] in {}, and import {{ {fun} }} from '{from}'", + entry_path.strip_prefix(root).unwrap_or(&entry_path).display() + ), + } + crate::cmd_create::maybe_check(opts.check) +} + +fn package_mode( + _opts: Opts, + _ask: &mut Ask, + _root: &Path, +) -> io::Result<()> { + Err(invalid("package mode is not built yet".into())) +} diff --git a/src/main.rs b/src/main.rs index 3a30a50..2bb1686 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,11 @@ mod cmd_create; mod cmd_doctor; mod cmd_graph; mod cmd_new; +mod cmd_plugin; mod cmd_run; mod entry; mod naming; +mod plugin_files; mod runtime; mod template; mod wire; @@ -35,8 +37,36 @@ fn main() { std::process::exit(1); } } - Command::Create { kind, name, check } => { - if let Err(e) = cmd_create::run(&kind, &name, check) { + Command::Create { + kind, + name, + check, + package, + folder, + scope, + registry, + npm_name, + } => { + let result = if kind == "plugin" { + cmd_plugin::run(cmd_plugin::Opts { + name, + package, + folder, + scope, + registry, + npm_name, + check, + }) + } else { + match name { + Some(name) => cmd_create::run(&kind, &name, check), + None => Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("create {kind} needs a name"), + )), + } + }; + if let Err(e) = result { eprintln!("error: {e}"); std::process::exit(1); } diff --git a/src/plugin_files.rs b/src/plugin_files.rs new file mode 100644 index 0000000..ba9df21 --- /dev/null +++ b/src/plugin_files.rs @@ -0,0 +1,38 @@ +//! The text of every file `matcha create plugin` writes. Pure: slug and +//! options in, file content out, so the shapes are tested without a disk. + +use crate::naming::{camel, pascal}; + +/// 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 +/// token, and `provides` renames it, so two instances can sit side by side. +pub fn factory(slug: &str) -> String { + let fun = camel(slug); + let opts = format!("{}Options", pascal(slug)); + format!( + "import type {{ Plugin }} from '@green-tea/core'; + +export interface {opts} {{ + /** The token this plugin provides. Change it to mount two instances side by side. */ + provides?: string; +}} + +export function {fun}(options: {opts} = {{}}): Plugin {{ + const provides = options.provides ?? '{slug}'; + + return {{ + name: provides, + mount({{ scope }}) {{ + scope.add({{ + kind: 'provider', + name: provides, + needs: [], + provides: [provides], + run: () => ({{ [provides]: null }}), + }}); + }}, + }}; +}} +" + ) +} diff --git a/src/wire.rs b/src/wire.rs index 21c2209..e44e012 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -215,15 +215,22 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option insert_into_object_array(src, object, key, symbol) } -/// Inserts `symbol` into the `modules` array of the first `createApp(...)` -/// call's argument object (creating the `modules` key if absent). Idempotent; -/// reverts (returns `None`) on parse breakage or when no `createApp(...)` call -/// with an object argument is found. -pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { +/// Inserts `item` into the `key: [...]` array of the first `createApp(...)` +/// call's argument object, creating the key if absent. `item` is any array +/// element: a symbol for `modules`, a call like `algo()` for `plugins`. +/// Idempotent; returns `None` on parse breakage, when there is no +/// `createApp({...})`, or when `key` holds something other than an array +/// literal. +pub fn add_to_createapp(src: &str, key: &str, item: &str) -> Option { let tree = parser().parse(src, None).unwrap(); let root = tree.root_node(); let object = find_createapp_object(&root, src)?; - insert_into_object_array(src, object, "modules", symbol) + insert_into_object_array(src, object, key, item) +} + +/// `add_to_createapp` for `modules`, kept as the name `create module` reads. +pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { + add_to_createapp(src, "modules", symbol) } /// Inserts `symbol` into the `key: [...]` array directly inside `object` diff --git a/tests/cli.rs b/tests/cli.rs index 620118c..b098072 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -25,7 +25,10 @@ fn help_lists_all_subcommands() { #[test] fn create_and_add_advertise_every_value_they_accept() { for (command, values) in [ - ("create", vec!["module", "controller", "step", "provider"]), + ( + "create", + vec!["module", "controller", "step", "provider", "plugin"], + ), ("add", vec!["sse", "stream", "buffer", "ws", "upload"]), ] { let mut assertion = Command::cargo_bin("matcha") diff --git a/tests/plugin.rs b/tests/plugin.rs new file mode 100644 index 0000000..02d73bf --- /dev/null +++ b/tests/plugin.rs @@ -0,0 +1,145 @@ +use assert_cmd::Command; +use predicates::str::contains; +use tempfile::tempdir; + +const APP: &str = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nexport const app = createApp({ modules: [AppModule] });\n"; + +fn project(app_ts: &str) -> tempfile::TempDir { + let d = tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("src")).unwrap(); + std::fs::write(d.path().join("src/app.ts"), app_ts).unwrap(); + d +} + +fn matcha(dir: &std::path::Path) -> Command { + let mut c = Command::cargo_bin("matcha").unwrap(); + c.current_dir(dir); + c +} + +#[test] +fn in_app_is_the_default_and_wires_into_create_app() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "Plugin Algo"]) + .assert() + .success(); + + let index = std::fs::read_to_string(d.path().join("plugins/plugin-algo/index.ts")).unwrap(); + assert!(index.contains("export function pluginAlgo(")); + assert!(index.contains("options.provides ?? 'plugin-algo'")); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!( + app.contains("import { pluginAlgo } from '../plugins/plugin-algo/index';"), + "{app}" + ); + assert!(app.contains("plugins: [pluginAlgo()]"), "{app}"); +} + +#[test] +fn in_app_appends_to_an_existing_plugins_array() { + let d = project("import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: [other()] });\n"); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .success(); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("plugins: [other(), algo()]"), "{app}"); +} + +#[test] +fn in_app_honours_folder() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", "lib/plugins"]) + .assert() + .success(); + assert!(d.path().join("lib/plugins/algo/index.ts").exists()); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("'../lib/plugins/algo/index'"), "{app}"); +} + +#[test] +fn in_app_leaves_a_non_array_plugins_alone_and_says_what_to_add() { + let original = "import { createApp } from '@green-tea/core';\n\nexport const app = createApp({ modules: [], plugins: PLUGINS });\n"; + let d = project(original); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .success() + .stdout(contains("add algo() to createApp plugins[]")); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + original + ); + assert!(d.path().join("plugins/algo/index.ts").exists()); +} + +#[test] +fn in_app_refuses_an_existing_folder() { + let d = project(APP); + std::fs::create_dir_all(d.path().join("plugins/algo")).unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .failure() + .stderr(contains("already exists")); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + APP + ); +} + +#[test] +fn in_app_refuses_a_folder_outside_the_project() { + let d = project(APP); + for folder in ["../outside", "/tmp/elsewhere"] { + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", folder]) + .assert() + .failure() + .stderr(contains("inside the project")); + } +} + +#[test] +fn in_app_needs_a_project() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .failure() + .stderr(contains("src/app.ts")); +} + +#[test] +fn a_bad_name_writes_nothing() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "🍵"]) + .assert() + .failure() + .stderr(contains("does not make a plugin name")); + assert!(!d.path().join("plugins").exists()); +} + +#[test] +fn off_a_tty_a_missing_name_is_an_error_not_a_hang() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin"]) + .timeout(std::time::Duration::from_secs(10)) + .assert() + .failure() + .stderr(contains("NAME")); +} + +#[test] +fn other_kinds_still_require_a_name() { + let d = project(APP); + matcha(d.path()) + .args(["create", "controller"]) + .assert() + .failure() + .stderr(contains("needs a name")); +} -- 2.54.1 From 42c1148903ee5cf5ecb8e0c19c86a999725f8141 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:57:32 -0500 Subject: [PATCH 07/14] feat(plugin): --package scaffolds a JSR-first plugin package The directory must be empty, so a package never mixes into another project. JSR is the default and the README says why; JSR + npm adds an ESM-only tsc build, since npm consumers need compiled output, and suggests the green-tea- name without enforcing it. Signed-off-by: Diego Resendez --- src/cmd_plugin.rs | 102 +++++++++++++++++++++- src/plugin_files.rs | 207 ++++++++++++++++++++++++++++++++++++++++++++ tests/plugin.rs | 207 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 512 insertions(+), 4 deletions(-) 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")); +} -- 2.54.1 From efe7ad6027c1b8063dfc315767c3d29b44a90fb2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 12:58:16 -0500 Subject: [PATCH 08/14] feat(new): scaffold core 26.9.0-beta.2, and boot before binding on Deno and Bun beta.2 made serveDeno and serveBun boot the app before they bind. The starters called Deno.serve and Bun.serve with app.fetch directly, so a provider that failed left an open port answering 500 to everything. Signed-off-by: Diego Resendez --- src/template.rs | 11 ++++++++--- template/runtimes/bun/src/main.ts | 6 +++++- template/runtimes/deno/src/main.ts | 6 +++++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/template.rs b/src/template.rs index 03d28e2..a5b3e08 100644 --- a/src/template.rs +++ b/src/template.rs @@ -14,7 +14,7 @@ use crate::runtime::Runtime; /// reaches a stable major this becomes a range (`^27`) and the exactness stops /// mattering; until then the `core-freshness` CI job fails when this falls /// behind the `beta` dist-tag, which is what keeps it current. -pub const CORE_VERSION: &str = "26.9.0-beta.1"; +pub const CORE_VERSION: &str = "26.9.0-beta.2"; pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared"); pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno"); @@ -137,7 +137,10 @@ mod tests { assert!(d.path().join("deno.json").exists()); assert!(d.path().join("matcha.toml").exists()); let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); - assert!(main.contains("Deno.serve")); + // serveDeno boots before it binds; Deno.serve(app.fetch) bound first and + // left a port answering 500 when a provider failed. + assert!(main.contains("await serveDeno(app")); + assert!(!main.contains("Deno.serve(")); assert!(!d.path().join("package.json").exists()); let deno_json = std::fs::read_to_string(d.path().join("deno.json")).unwrap(); @@ -177,7 +180,9 @@ mod tests { assert!(pkg.contains("\"name\": \"my-api\"")); assert!(!pkg.contains("{{project_name}}")); let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap(); - assert!(main.contains("Bun.serve")); + // Same reason as Deno: serveBun boots first. + assert!(main.contains("await serveBun(app")); + assert!(!main.contains("Bun.serve(")); assert!(!d.path().join("deno.json").exists()); } } diff --git a/template/runtimes/bun/src/main.ts b/template/runtimes/bun/src/main.ts index af63cac..d4c9594 100644 --- a/template/runtimes/bun/src/main.ts +++ b/template/runtimes/bun/src/main.ts @@ -1,4 +1,8 @@ +import { serveBun } from '@green-tea/core/bun'; + import { app } from './app'; -Bun.serve({ port: 8000, fetch: app.fetch }); +// Boots before it binds: a provider that fails stops the process here, instead +// of leaving an open port that answers 500 to everything. +await serveBun(app, { port: 8000 }); console.log('🍵 green-tea running on http://localhost:8000'); diff --git a/template/runtimes/deno/src/main.ts b/template/runtimes/deno/src/main.ts index a2c938f..1991082 100644 --- a/template/runtimes/deno/src/main.ts +++ b/template/runtimes/deno/src/main.ts @@ -1,4 +1,8 @@ +import { serveDeno } from '@green-tea/core/deno'; + import { app } from './app'; -Deno.serve({ port: 8000 }, app.fetch); +// Boots before it binds: a provider that fails stops the process here, instead +// of leaving an open port that answers 500 to everything. +await serveDeno(app, { port: 8000 }); console.log('🍵 green-tea running on http://localhost:8000'); -- 2.54.1 From 52241cc9a6dc0565f3b3378c7ac00a3da4405ddf Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:00:43 -0500 Subject: [PATCH 09/14] fix(plugin): let a generated package run deno test straight away With a package.json beside deno.json, Deno expects node_modules to be installed, so deno test failed until a deno install, and then failed to type-check node:assert without @types/node. nodeModulesDir "auto" installs on demand, and the package now passes deno test, node --test and bun test as generated. Signed-off-by: Diego Resendez --- src/plugin_files.rs | 1 + tests/plugin.rs | 3 +++ 2 files changed, 4 insertions(+) diff --git a/src/plugin_files.rs b/src/plugin_files.rs index 0f6dc05..8867162 100644 --- a/src/plugin_files.rs +++ b/src/plugin_files.rs @@ -83,6 +83,7 @@ fn deno_json(p: &Package) -> String { "version": "0.1.0", "license": "MIT", "exports": "./src/index.ts", + "nodeModulesDir": "auto", "imports": {{ "@green-tea/core": "npm:@green-tea/core@{CORE_VERSION}" }}, diff --git a/tests/plugin.rs b/tests/plugin.rs index 4dc36e8..e26c726 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -192,6 +192,9 @@ fn package_jsr_writes_the_tree_into_dir() { 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}"); + // Without it `deno test` needs a `deno install` first, and then fails to + // type-check `node:assert` for want of @types/node. + assert!(deno.contains("\"nodeModulesDir\": \"auto\""), "{deno}"); let pj = std::fs::read_to_string(pkg.join("package.json")).unwrap(); assert!(pj.contains("\"private\": true"), "{pj}"); assert!(pj.contains("\"devDependencies\""), "{pj}"); -- 2.54.1 From 70b51e5de4608a28814913b9c80c3bb2bccd3cfe Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:02:40 -0500 Subject: [PATCH 10/14] docs: document create plugin, and version 26.9.0-beta.1 Signed-off-by: Diego Resendez --- CHANGELOG.md | 23 +++++++++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 25 +++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e806740..83463c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,29 @@ green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8 mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says when it moved. +## [26.9.0-beta.1] - 2026-09-24 + +### Added + +- **`matcha create plugin`.** By default it scaffolds an in-app plugin in a folder of its own, + `plugins//`, and registers it in `createApp({ plugins })`. With `--package [DIR]` it writes + a package instead. JSR is the default, and `--registry both` adds an ESM-only npm build. The + package passes `deno test`, `node --test`, `bun test` and `deno publish --dry-run` as generated. + At a terminal it asks for what the flags leave out. Without one it takes the defaults, and fails + with the flag to pass instead of waiting for an answer. + +### Changed + +- **Scaffolds `@green-tea/core` 26.9.0-beta.2** (`CORE_VERSION` moved from beta.1). That is the + release where a plugin became `{ name, mount }` and `app.boot()` became public, so a project + made with the previous version could not use plugins in their current form. + +### Fixed + +- **The Deno and Bun starters bound the port before booting.** They passed `app.fetch` straight to + `Deno.serve` and `Bun.serve`, so a provider that failed left the port open and answering 500 to + every request. They now `await serveDeno(app)` and `await serveBun(app)`, which boot first. + ## [26.9.0-beta.0] - 2026-09-05 ### Added diff --git a/Cargo.lock b/Cargo.lock index 1274d2a..362dda0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,7 +254,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "matcha-cli" -version = "26.9.0-beta.0" +version = "26.9.0-beta.1" dependencies = [ "assert_cmd", "clap", diff --git a/Cargo.toml b/Cargo.toml index c42dbcb..48ecf77 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "matcha-cli" -version = "26.9.0-beta.0" +version = "26.9.0-beta.1" edition = "2021" description = "The green-tea CLI: scaffold a project, generate controllers, steps and providers already wired into their module, and run with your runtime detected. One native binary, no JS runtime needed to install it." license = "MIT" diff --git a/README.md b/README.md index f53e80b..16678d0 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ matcha new my-api # scaffold from the official starter matcha new my-api --template-url gh:owner/repo # scaffold from any git template matcha run # detect node/deno/bun and run in watch matcha create controller Users # generate + auto-wire into @Module +matcha create plugin "Plugin Algo" # an in-app plugin, or --package for its own package matcha add sse # add a capability to your controller matcha graph # draw the dependency graph matcha explain /users/:id # one route's chain, in execution order @@ -111,6 +112,30 @@ and wire pieces into the right `@Module` array or controller. Edits are idempotent and revert themselves if they would break the file's syntax. Pass `--check` to `create` to type-check with your project's runtime afterward. +### `matcha create plugin` + +An in-app plugin by default, or a package of its own. + +```sh +matcha create plugin "Plugin Algo" # plugins/plugin-algo/, registered in createApp +matcha create plugin algo --folder lib/plugins +matcha create plugin algo --package ./algo --scope acme # a JSR package +matcha create plugin algo --package ./algo --scope acme --registry both # JSR + npm, ESM only +``` + +In-app, each plugin gets a folder of its own under `plugins/` (or `--folder`, relative to the +project root) and is registered in `createApp({ plugins })`. It lives in a folder so it can become +a package later without being pulled out of the app. + +`--package [DIR]` writes a package into `DIR`, or into the current directory, and either one has to +be empty. JSR is the default, because it records which runtimes a package supports. +`--registry both` adds npm with a `tsc` build to ESM only, and suggests the +`@scope/green-tea-` name without requiring it. The package passes `deno test`, `node --test`, +`bun test` and `deno publish --dry-run` as generated. + +At a terminal it asks for whatever the flags leave out. Without a terminal (CI, a pipe) it takes the +defaults, and for anything that has no default it stops and names the flag to pass. + ### `matcha doctor` The checks whose failures are confusing rather than loud: `experimentalDecorators` -- 2.54.1 From e4a350fcbf0dc430c2209cd4145d54fe26fcd345 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:05:46 -0500 Subject: [PATCH 11/14] fix(plugin): refuse names whose factory would not compile `delete`, `class` or `default` made `export function delete(...)`, which is not TypeScript. `create app` and `app` made a factory named after something the entry already binds, so the import broke src/app.ts, and the command still reported the wiring as a success. Both are now refused before anything is written. Signed-off-by: Diego Resendez --- src/cmd_plugin.rs | 24 +++++++++++--- src/naming.rs | 81 +++++++++++++++++++++++++++++++++++++++++++++++ tests/plugin.rs | 56 ++++++++++++++++++++++++++++++++ 3 files changed, 157 insertions(+), 4 deletions(-) diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs index 59d9533..bbd86e6 100644 --- a/src/cmd_plugin.rs +++ b/src/cmd_plugin.rs @@ -50,11 +50,18 @@ fn resolve_slug( Some(n) => n, None => ask.text("Plugin name?", None, "the NAME argument")?, }; - naming::slug(&raw).ok_or_else(|| { + let slug = naming::slug(&raw).ok_or_else(|| { invalid(format!( "'{raw}' does not make a plugin name: start with a letter, and use letters, digits, spaces or hyphens" )) - }) + })?; + let fun = naming::camel(&slug); + if naming::is_reserved(&fun) { + return Err(invalid(format!( + "'{raw}' would make the factory `{fun}`, which is a reserved word in TypeScript; pick another name" + ))); + } + Ok(slug) } /// Relative, and never climbing out: `..` or an absolute path would put the @@ -85,6 +92,17 @@ fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> } let slug = resolve_slug(opts.name, ask)?; + let fun = naming::camel(&slug); + let src = std::fs::read_to_string(&entry_path)?; + // A second binding of a name the entry already has is a SyntaxError, and it + // would break the app rather than only the new plugin. + if naming::used_in(&src, &fun) { + return Err(invalid(format!( + "{} already uses `{fun}`, so the plugin's factory would collide with it; pick another name", + entry_path.strip_prefix(root).unwrap_or(&entry_path).display() + ))); + } + let dir = root.join(&folder).join(&slug); if dir.exists() { return Err(Error::new( @@ -102,11 +120,9 @@ fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> Path::new(&folder).join(&slug).join("index.ts").display() ); - let fun = naming::camel(&slug); let call = format!("{fun}()"); // Both entry candidates live in src/, so the plugin folder is one level up. let from = format!("../{folder}/{slug}/index"); - let src = std::fs::read_to_string(&entry_path)?; let imported = wire::add_import(&src, &fun, &from); match wire::add_to_createapp(&imported, "plugins", &call) { Some(wired) => { diff --git a/src/naming.rs b/src/naming.rs index 82dddcc..1a7212e 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -51,6 +51,75 @@ pub fn camel(slug: &str) -> String { first + &words.map(capitalised).collect::() } +/// Words that cannot name a function in a TypeScript module: JS keywords, the +/// strict-mode reserved words (modules are always strict) and the literals. +/// `camel` of a slug is lowercase-first, so only lowercase spellings matter. +const RESERVED: &[&str] = &[ + "arguments", + "await", + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "finally", + "for", + "function", + "if", + "implements", + "import", + "in", + "instanceof", + "interface", + "let", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "static", + "super", + "switch", + "this", + "throw", + "true", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield", +]; + +/// True when `ident` cannot be used as the factory's name. +pub fn is_reserved(ident: &str) -> bool { + RESERVED.contains(&ident) +} + +/// True when `ident` appears as a whole identifier anywhere in `src`. +/// +/// ponytail: a token scan, not a parse, so a match inside a comment or a string +/// also counts. That refuses a name that would have been fine, never the other +/// way round; a scope-aware check is the upgrade if it ever gets in the way. +pub fn used_in(src: &str, ident: &str) -> bool { + src.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) + .any(|token| token == ident) +} + #[cfg(test)] mod tests { use super::*; @@ -75,6 +144,18 @@ mod tests { assert_eq!(slug("rate.limit"), None); } + #[test] + fn reserved_words_and_uses_are_found() { + assert!(is_reserved("delete")); + assert!(is_reserved("class")); + assert!(!is_reserved("pluginAlgo")); + let src = "import { createApp } from 'x';\nexport const app = createApp({});\n"; + assert!(used_in(src, "createApp")); + assert!(used_in(src, "app")); + assert!(!used_in(src, "appModule")); + assert!(!used_in(src, "create")); + } + #[test] fn identifiers_follow_the_slug() { assert_eq!(camel("plugin-algo"), "pluginAlgo"); diff --git a/tests/plugin.rs b/tests/plugin.rs index e26c726..645399d 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -353,3 +353,59 @@ fn package_rejects_a_bad_scope_or_npm_name() { .failure() .stderr(contains("npm name")); } + +#[test] +fn a_name_whose_factory_would_be_a_reserved_word_writes_nothing() { + for name in ["delete", "class", "default", "new", "import"] { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", name]) + .assert() + .failure() + .stderr(contains("reserved word")); + assert!(!d.path().join("plugins").exists(), "{name}"); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + APP + ); + } +} + +#[test] +fn a_package_whose_factory_would_be_a_reserved_word_writes_nothing() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "delete", + "--package", + "p", + "--scope", + "acme", + ]) + .assert() + .failure() + .stderr(contains("reserved word")); + assert!(!d.path().join("p").exists()); +} + +/// `create app` → `createApp`, and `app` → `app`: both already exist in the entry, and a second +/// binding of the same name is a SyntaxError that would break the app, not just the plugin. +#[test] +fn in_app_refuses_a_factory_name_the_entry_already_uses() { + for name in ["create app", "app"] { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", name]) + .assert() + .failure() + .stderr(contains("already")); + assert!(!d.path().join("plugins").exists(), "{name}"); + assert_eq!( + std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(), + APP, + "{name}" + ); + } +} -- 2.54.1 From 4358091d07fe8890af1b11b265a54f7dc407287f Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:11:55 -0500 Subject: [PATCH 12/14] fix(plugin): close the review's gaps in names, prompts and the generated test The collision check scanned the whole file as text, so every scaffolded app refused `core`, `tea` or `module` because they appear inside import strings. It now reads identifiers from the parse tree. Typing `npm` at the registry question silently produced a JSR-only package. An answer that is not offered is now asked again. The generated test only awaited boot(); it now checks the plugin's token is in app.graph(), and fails if it is not. engines.node moves to >=22.18, the first Node that runs `node --test` on .ts unflagged. Signed-off-by: Diego Resendez --- src/ask.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++ src/cmd_plugin.rs | 20 ++++++-------- src/naming.rs | 15 ----------- src/plugin_files.rs | 5 ++-- src/wire.rs | 31 ++++++++++++++++++++++ tests/plugin.rs | 58 +++++++++++++++++++++++++++++++++++++++++ 6 files changed, 163 insertions(+), 29 deletions(-) diff --git a/src/ask.rs b/src/ask.rs index e28942b..c28082e 100644 --- a/src/ask.rs +++ b/src/ask.rs @@ -63,6 +63,32 @@ impl Ask { }) } + /// One of `choices`, each `(key, value)`: the answer may be the key or the + /// value, and Enter takes `default`. Anything else is asked again. Quietly + /// taking the default would turn a typed `npm` into a JSR-only package. + pub fn choice( + &mut self, + question: &str, + choices: &[(&str, &'static str)], + default: &'static str, + flag: &str, + ) -> io::Result<&'static str> { + if !self.interactive { + return Ok(default); + } + let keys: Vec<&str> = choices.iter().map(|(k, _)| *k).collect(); + loop { + let answer = self.line(question)?.to_lowercase(); + if answer.is_empty() { + return Ok(default); + } + if let Some((_, v)) = choices.iter().find(|(k, v)| answer == *k || answer == *v) { + return Ok(v); + } + writeln!(self.output, "answer {} (or pass {flag})", keys.join(" or "))?; + } + } + /// `flag` names what to pass instead, for the error off a TTY. pub fn text( &mut self, @@ -145,6 +171,43 @@ mod tests { assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof); } + #[test] + fn choice_asks_again_on_an_answer_that_is_not_offered() { + let mut ask = scripted("npm\n3\n2\n"); + let picked = ask + .choice( + "Publish to:", + &[("1", "jsr"), ("2", "both")], + "jsr", + "--registry", + ) + .unwrap(); + assert_eq!(picked, "both"); + let shown = String::from_utf8(ask.output.clone()).unwrap(); + assert!(shown.contains("answer 1 or 2"), "{shown}"); + } + + #[test] + fn choice_takes_the_default_on_enter_and_off_a_tty() { + let choices = [("1", "jsr"), ("2", "both")]; + assert_eq!( + scripted("\n") + .choice("P?", &choices, "jsr", "--registry") + .unwrap(), + "jsr" + ); + assert_eq!( + scripted("both\n") + .choice("P?", &choices, "jsr", "--registry") + .unwrap(), + "both" + ); + assert_eq!( + piped().choice("P?", &choices, "jsr", "--registry").unwrap(), + "jsr" + ); + } + #[test] fn off_a_tty_nothing_is_asked() { let mut ask = piped(); diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs index bbd86e6..f631ee0 100644 --- a/src/cmd_plugin.rs +++ b/src/cmd_plugin.rs @@ -96,7 +96,7 @@ fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> let src = std::fs::read_to_string(&entry_path)?; // A second binding of a name the entry already has is a SyntaxError, and it // would break the app rather than only the new plugin. - if naming::used_in(&src, &fun) { + if wire::binds(&src, &fun) { return Err(invalid(format!( "{} already uses `{fun}`, so the plugin's factory would collide with it; pick another name", entry_path.strip_prefix(root).unwrap_or(&entry_path).display() @@ -193,17 +193,13 @@ fn package_mode( 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(), - } + ask.choice( + "Publish to: (1) JSR only [default] (2) JSR + npm", + &[("1", "jsr"), ("2", "both")], + "jsr", + "--registry", + )? + .to_string() } }; diff --git a/src/naming.rs b/src/naming.rs index 1a7212e..e6e2610 100644 --- a/src/naming.rs +++ b/src/naming.rs @@ -110,16 +110,6 @@ pub fn is_reserved(ident: &str) -> bool { RESERVED.contains(&ident) } -/// True when `ident` appears as a whole identifier anywhere in `src`. -/// -/// ponytail: a token scan, not a parse, so a match inside a comment or a string -/// also counts. That refuses a name that would have been fine, never the other -/// way round; a scope-aware check is the upgrade if it ever gets in the way. -pub fn used_in(src: &str, ident: &str) -> bool { - src.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$')) - .any(|token| token == ident) -} - #[cfg(test)] mod tests { use super::*; @@ -149,11 +139,6 @@ mod tests { assert!(is_reserved("delete")); assert!(is_reserved("class")); assert!(!is_reserved("pluginAlgo")); - let src = "import { createApp } from 'x';\nexport const app = createApp({});\n"; - assert!(used_in(src, "createApp")); - assert!(used_in(src, "app")); - assert!(!used_in(src, "appModule")); - assert!(!used_in(src, "create")); } #[test] diff --git a/src/plugin_files.rs b/src/plugin_files.rs index 8867162..75658c8 100644 --- a/src/plugin_files.rs +++ b/src/plugin_files.rs @@ -100,7 +100,7 @@ fn deno_json(p: &Package) -> String { } const ENGINES: &str = r#" "engines": { - "node": ">=22", + "node": ">=22.18", "deno": ">=2", "bun": ">=1.3" },"#; @@ -179,9 +179,10 @@ import {{ createApp }} from '@green-tea/core'; import {{ {fun} }} from '../src/index.ts'; -test('mounts into an app, and the app boots', async () => {{ +test('mounts, boots, and puts its token in the graph', async () => {{ const app = createApp({{ modules: [], plugins: [{fun}()] }}); await app.boot(); + assert.ok(app.graph().nodes.some((node) => node.provides.includes('{slug}'))); }}); test('two instances mount side by side under different tokens', async () => {{ diff --git a/src/wire.rs b/src/wire.rs index e44e012..cb749ea 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -215,6 +215,27 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option insert_into_object_array(src, object, key, symbol) } +/// True when `ident` is an identifier anywhere in `src`: an import, a +/// declaration or a use. Read from the parse tree, so a word inside a string +/// (`'@green-tea/core'`) or a comment does not count; those are not bindings +/// and cannot collide. +pub fn binds(src: &str, ident: &str) -> bool { + fn visit(node: Node, src: &str, ident: &str) -> bool { + if matches!( + node.kind(), + "identifier" | "type_identifier" | "shorthand_property_identifier_pattern" + ) && node.utf8_text(src.as_bytes()).ok() == Some(ident) + { + return true; + } + let mut c = node.walk(); + let found = node.children(&mut c).any(|child| visit(child, src, ident)); + found + } + let tree = parser().parse(src, None).unwrap(); + visit(tree.root_node(), src, ident) +} + /// Inserts `item` into the `key: [...]` array of the first `createApp(...)` /// call's argument object, creating the key if absent. `item` is any array /// element: a symbol for `modules`, a call like `algo()` for `plugins`. @@ -452,6 +473,16 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option> { #[cfg(test)] mod tests { + #[test] + fn binds_sees_identifiers_not_strings_or_comments() { + let src = "import { createApp } from '@green-tea/core';\n// green tea\nexport const app = createApp({});\n"; + assert!(binds(src, "createApp")); + assert!(binds(src, "app")); + assert!(!binds(src, "core")); + assert!(!binds(src, "green")); + assert!(!binds(src, "appModule")); + } + use super::*; const MOD: &str = r#"import { Module } from '@green-tea/core'; diff --git a/tests/plugin.rs b/tests/plugin.rs index 645399d..fefcdb5 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -409,3 +409,61 @@ fn in_app_refuses_a_factory_name_the_entry_already_uses() { ); } } + +/// The scaffolded app.ts imports from '@green-tea/core' and './app.module'. Words inside those +/// strings are not bindings, so `core`, `tea` and `module` are free names for a plugin. +#[test] +fn words_inside_strings_and_comments_are_not_collisions() { + let app = "import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\n// the green tea app\nexport const app = createApp({ modules: [AppModule] });\n"; + for name in ["core", "tea", "module", "green"] { + let d = project(app); + matcha(d.path()) + .args(["create", "plugin", name]) + .assert() + .success(); + assert!( + d.path().join(format!("plugins/{name}/index.ts")).exists(), + "{name}" + ); + } +} + +#[test] +fn package_engines_need_the_node_that_strips_types() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "acme", + ]) + .assert() + .success(); + let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap(); + // `node --test test/*.test.ts` needs unflagged type stripping, which is 22.18+. + assert!(pj.contains("\"node\": \">=22.18\""), "{pj}"); +} + +#[test] +fn the_generated_test_asserts_the_token_is_in_the_graph() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "p", + "--scope", + "acme", + ]) + .assert() + .success(); + let t = std::fs::read_to_string(d.path().join("p/test/algo.test.ts")).unwrap(); + assert!(t.contains("app.graph()"), "{t}"); + assert!(t.contains("provides.includes('algo')"), "{t}"); +} -- 2.54.1 From ecdc46cac3a8ab7d43d51471d777a6aa0a705be5 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:26:29 -0500 Subject: [PATCH 13/14] fix(plugin): the review's smaller findings - `--package` takes a directory only as `--package=DIR`, so `create plugin --package algo` names the plugin instead of writing into ./algo. - A NAME passed on the command line is checked before any question. - The package directory is named in its errors, a file there is reported as a file, and a failed write lists what was already written. - An in-app plugin folder is removed again if the entry cannot be written, so the rerun does not stop on "already exists". - `--folder .` and `./plugins/` give clean import paths. - Flags for the other mode are named as ignored; plugin flags on another create kind are an error. - Array elements are read from the parse tree, so `algo({ a, b })` is one element when checking for a duplicate. - Scopes follow JSR's rule: 2 to 20 characters, no leading hyphen. - Packages ship a LICENSE (MIT, which the README says to change), the license field in both manifests, and @types/node for the test file. Signed-off-by: Diego Resendez --- CHANGELOG.md | 2 +- README.md | 13 +-- src/cli.rs | 4 +- src/cmd_plugin.rs | 201 ++++++++++++++++++++++++++++++++-------- src/main.rs | 18 +++- src/plugin_files.rs | 50 +++++++++- src/wire.rs | 37 +++++++- tests/plugin.rs | 221 +++++++++++++++++++++++++++++++++++++------- 8 files changed, 460 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83463c3..d5c5e58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says w ### Added - **`matcha create plugin`.** By default it scaffolds an in-app plugin in a folder of its own, - `plugins//`, and registers it in `createApp({ plugins })`. With `--package [DIR]` it writes + `plugins//`, and registers it in `createApp({ plugins })`. With `--package` (or `--package=DIR`) it writes a package instead. JSR is the default, and `--registry both` adds an ESM-only npm build. The package passes `deno test`, `node --test`, `bun test` and `deno publish --dry-run` as generated. At a terminal it asks for what the flags leave out. Without one it takes the defaults, and fails diff --git a/README.md b/README.md index 16678d0..aaef998 100644 --- a/README.md +++ b/README.md @@ -119,18 +119,19 @@ An in-app plugin by default, or a package of its own. ```sh matcha create plugin "Plugin Algo" # plugins/plugin-algo/, registered in createApp matcha create plugin algo --folder lib/plugins -matcha create plugin algo --package ./algo --scope acme # a JSR package -matcha create plugin algo --package ./algo --scope acme --registry both # JSR + npm, ESM only +matcha create plugin algo --package=./algo --scope acme # a JSR package +matcha create plugin algo --package=./algo --scope acme --registry both # JSR + npm, ESM only ``` In-app, each plugin gets a folder of its own under `plugins/` (or `--folder`, relative to the project root) and is registered in `createApp({ plugins })`. It lives in a folder so it can become a package later without being pulled out of the app. -`--package [DIR]` writes a package into `DIR`, or into the current directory, and either one has to -be empty. JSR is the default, because it records which runtimes a package supports. -`--registry both` adds npm with a `tsc` build to ESM only, and suggests the -`@scope/green-tea-` name without requiring it. The package passes `deno test`, `node --test`, +`--package` writes a package into the current directory, or `--package=DIR` into `DIR`, and either +one has to be empty. The `=` is required, so a word after a bare `--package` is the plugin's +name. JSR is the default, because it records which runtimes a package supports. `--registry both` +adds npm with a `tsc` build to ESM only, and suggests the `@scope/green-tea-` name without +requiring it. The package passes `deno test`, `node --test`, `bun test` and `deno publish --dry-run` as generated. At a terminal it asks for whatever the flags leave out. Without a terminal (CI, a pipe) it takes the diff --git a/src/cli.rs b/src/cli.rs index e03153f..b5289e1 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -30,8 +30,8 @@ pub enum Command { name: Option, #[arg(long)] check: bool, - /// plugin: a package of its own, in DIR (default: the current directory, which must be empty) - #[arg(long, num_args = 0..=1, value_name = "DIR")] + /// plugin: a package of its own, in --package=DIR (default: the current directory, which must be empty) + #[arg(long, num_args = 0..=1, require_equals = true, value_name = "DIR")] package: Option>, /// plugin, in-app: folder relative to the project root (default: plugins) #[arg(long)] diff --git a/src/cmd_plugin.rs b/src/cmd_plugin.rs index f631ee0..b71f107 100644 --- a/src/cmd_plugin.rs +++ b/src/cmd_plugin.rs @@ -27,13 +27,31 @@ pub fn run_with( ask: &mut Ask, root: &Path, ) -> io::Result<()> { + // A NAME given on the command line is checked before any question. + if let Some(name) = &opts.name { + check_name(name)?; + } let package = match opts.package { Some(_) => true, None => ask.yes_no("Separate it as a package?", false)?, }; if package { + for (flag, given) in [("--folder", opts.folder.is_some()), ("--check", opts.check)] { + if given { + println!("note: {flag} only applies to an in-app plugin; ignored"); + } + } package_mode(opts, ask, root) } else { + for (flag, given) in [ + ("--scope", opts.scope.is_some()), + ("--registry", opts.registry.is_some()), + ("--npm-name", opts.npm_name.is_some()), + ] { + if given { + println!("note: {flag} only applies to --package; ignored"); + } + } in_app(opts, ask, root) } } @@ -42,15 +60,10 @@ fn invalid(msg: String) -> Error { Error::new(ErrorKind::InvalidInput, msg) } -fn resolve_slug( - name: Option, - ask: &mut Ask, -) -> io::Result { - let raw = match name { - Some(n) => n, - None => ask.text("Plugin name?", None, "the NAME argument")?, - }; - let slug = naming::slug(&raw).ok_or_else(|| { +/// The slug for `raw`, or why it cannot be one: not a name, or a factory that +/// would be a reserved word. +fn check_name(raw: &str) -> io::Result { + let slug = naming::slug(raw).ok_or_else(|| { invalid(format!( "'{raw}' does not make a plugin name: start with a letter, and use letters, digits, spaces or hyphens" )) @@ -64,6 +77,17 @@ fn resolve_slug( Ok(slug) } +fn resolve_slug( + name: Option, + ask: &mut Ask, +) -> io::Result { + let raw = match name { + Some(n) => n, + None => ask.text("Plugin name?", None, "the NAME argument")?, + }; + check_name(&raw) +} + /// Relative, and never climbing out: `..` or an absolute path would put the /// plugin outside the project it is being wired into. fn inside_project(folder: &str) -> bool { @@ -84,70 +108,121 @@ fn in_app(opts: Opts, ask: &mut Ask, root: &Path) -> Some(f) => f, None => ask.text("Folder?", Some("plugins"), "--folder")?, }; - let folder = folder.trim_end_matches('/').to_string(); if !inside_project(&folder) { return Err(invalid(format!( "the plugin folder has to be inside the project, got '{folder}'" ))); } + // `.`, `./plugins` and `plugins/` all mean what they say without leaving a + // `./` or a trailing slash in the import path. + let folder: Vec = Path::new(&folder) + .components() + .filter_map(|c| match c { + Component::Normal(p) => Some(p.to_string_lossy().into_owned()), + _ => None, + }) + .collect(); + let folder = folder.join("/"); let slug = resolve_slug(opts.name, ask)?; let fun = naming::camel(&slug); let src = std::fs::read_to_string(&entry_path)?; + let entry_shown = entry_path + .strip_prefix(root) + .unwrap_or(&entry_path) + .display() + .to_string(); // A second binding of a name the entry already has is a SyntaxError, and it // would break the app rather than only the new plugin. if wire::binds(&src, &fun) { return Err(invalid(format!( - "{} already uses `{fun}`, so the plugin's factory would collide with it; pick another name", - entry_path.strip_prefix(root).unwrap_or(&entry_path).display() + "{entry_shown} already uses `{fun}`, so the plugin's factory would collide with it; pick another name" ))); } - let dir = root.join(&folder).join(&slug); + let shown = Path::new(&folder).join(&slug); + let dir = root.join(&shown); if dir.exists() { return Err(Error::new( ErrorKind::AlreadyExists, - format!( - "{} already exists", - Path::new(&folder).join(&slug).display() - ), + format!("{} already exists", shown.display()), )); } - std::fs::create_dir_all(&dir)?; - std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?; - println!( - "✓ {}", - Path::new(&folder).join(&slug).join("index.ts").display() - ); let call = format!("{fun}()"); // Both entry candidates live in src/, so the plugin folder is one level up. - let from = format!("../{folder}/{slug}/index"); - let imported = wire::add_import(&src, &fun, &from); - match wire::add_to_createapp(&imported, "plugins", &call) { + let from = if folder.is_empty() { + format!("../{slug}/index") + } else { + format!("../{folder}/{slug}/index") + }; + let wired = wire::add_to_createapp(&wire::add_import(&src, &fun, &from), "plugins", &call); + + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join("index.ts"), plugin_files::factory(&slug))?; + println!("✓ {}", shown.join("index.ts").display()); + + match wired { Some(wired) => { - std::fs::write(&entry_path, wired)?; + // The plugin folder and its registration land together or not at + // all: a folder left behind would make the rerun say "already exists". + if let Err(e) = std::fs::write(&entry_path, wired) { + let _ = std::fs::remove_dir_all(&dir); + return Err(Error::new( + e.kind(), + format!( + "could not write {entry_shown} ({e}); removed {} again", + shown.display() + ), + )); + } println!("✓ registered {call} in createApp"); } None => println!( - "→ could not auto-register; add {call} to createApp plugins[] in {}, and import {{ {fun} }} from '{from}'", - entry_path.strip_prefix(root).unwrap_or(&entry_path).display() + "→ could not auto-register; add {call} to createApp plugins[] in {entry_shown}, and import {{ {fun} }} from '{from}'" ), } 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 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. +/// JSR's scope rule: 2 to 20 characters, lowercase letters, digits and +/// hyphens, and not starting with a hyphen. fn valid_scope(s: &str) -> bool { - !s.is_empty() + (2..=20).contains(&s.len()) + && !s.starts_with('-') && s.chars() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') } +/// Writes every file, reporting each; on a failure, the error names the files +/// already written, so a half-filled directory is not a mystery on the rerun. +fn write_all(dir: &Path, root: &Path, files: &[(String, String)]) -> io::Result<()> { + let mut written: Vec<&str> = Vec::new(); + for (rel, content) in files { + let path = dir.join(rel); + let result = std::fs::create_dir_all(path.parent().unwrap()) + .and_then(|()| std::fs::write(&path, content)); + if let Err(e) = result { + let so_far = if written.is_empty() { + "none".to_string() + } else { + written.join(", ") + }; + return Err(Error::new( + e.kind(), + format!("could not write {rel} ({e}); already written: {so_far}"), + )); + } + println!("✓ {}", path.strip_prefix(root).unwrap_or(&path).display()); + written.push(rel); + } + Ok(()) +} + /// 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| { @@ -173,8 +248,17 @@ fn package_mode( Some(Some(d)) => root.join(d), _ => root.to_path_buf(), }; + let dir_shown = dir.strip_prefix(root).unwrap_or(&dir).display().to_string(); + let dir_shown = if dir_shown.is_empty() { + ".".to_string() + } else { + dir_shown + }; + if dir.is_file() { + return Err(invalid(format!("{dir_shown} is a file; {EMPTY_DIR}"))); + } if dir.exists() && std::fs::read_dir(&dir)?.next().is_some() { - return Err(invalid(EMPTY_DIR.into())); + return Err(invalid(format!("{dir_shown}: {EMPTY_DIR}"))); } let slug = resolve_slug(opts.name, ask)?; @@ -185,7 +269,7 @@ fn package_mode( 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" + "'{scope}' is not a JSR scope: 2 to 20 lowercase letters, digits or hyphens, not starting with a hyphen" ))); } @@ -223,14 +307,51 @@ fn package_mode( }; 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()); - } + write_all(&dir, root, &plugin_files::package(&package))?; println!( "→ next: fill in the Runtimes table in README.md, then `deno test` and `deno publish`" ); Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn opts(name: Option<&str>) -> Opts { + Opts { + name: name.map(str::to_string), + package: None, + folder: None, + scope: None, + registry: None, + npm_name: None, + check: false, + } + } + + /// A NAME passed on the command line is checked before any question: nobody should answer + /// "package?" and "folder?" to learn the name was never going to work. With no answers + /// scripted, asking anything would end in an end-of-input error instead. + #[test] + fn a_bad_name_fails_before_any_question() { + let mut ask = Ask::new(true, Cursor::new(Vec::new()), Vec::new()); + let err = run_with(opts(Some("🍵")), &mut ask, Path::new("/nonexistent")).unwrap_err(); + assert!( + err.to_string().contains("does not make a plugin name"), + "{err}" + ); + } + + #[test] + fn write_all_reports_what_it_wrote_before_failing() { + let d = tempfile::tempdir().unwrap(); + let files = vec![ + ("a".to_string(), "x".to_string()), + ("a/b".to_string(), "y".to_string()), + ]; + let err = write_all(d.path(), d.path(), &files).unwrap_err(); + assert!(err.to_string().contains("already written: a"), "{err}"); + } +} diff --git a/src/main.rs b/src/main.rs index 2bb1686..4753ad0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,7 +47,23 @@ fn main() { registry, npm_name, } => { - let result = if kind == "plugin" { + let stray: Vec<&str> = [ + ("--package", package.is_some()), + ("--folder", folder.is_some()), + ("--scope", scope.is_some()), + ("--registry", registry.is_some()), + ("--npm-name", npm_name.is_some()), + ] + .into_iter() + .filter(|(_, on)| *on) + .map(|(flag, _)| flag) + .collect(); + let result = if kind != "plugin" && !stray.is_empty() { + Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{} only apply to create plugin", stray.join(", ")), + )) + } else if kind == "plugin" { cmd_plugin::run(cmd_plugin::Opts { name, package, diff --git a/src/plugin_files.rs b/src/plugin_files.rs index 75658c8..833f8c7 100644 --- a/src/plugin_files.rs +++ b/src/plugin_files.rs @@ -65,6 +65,7 @@ pub fn package(p: &Package) -> Vec<(String, String)> { "CHANGELOG.md".to_string(), "# Changelog\n\n## [Unreleased]\n\n- First version.\n".to_string(), ), + ("LICENSE".to_string(), license(p)), ( ".gitignore".to_string(), "node_modules\ndist\n.DS_Store\n".to_string(), @@ -91,7 +92,7 @@ fn deno_json(p: &Package) -> String { "test": "deno test --allow-env --allow-read" }}, "publish": {{ - "include": ["src", "README.md", "CHANGELOG.md", "deno.json"] + "include": ["src", "README.md", "CHANGELOG.md", "LICENSE", "deno.json"] }} }} "#, @@ -112,13 +113,15 @@ fn package_json(p: &Package) -> String { "name": "{name}", "version": "0.1.0", "private": true, + "license": "MIT", "type": "module", {ENGINES} "scripts": {{ "test": "node --test test/*.test.ts" }}, "devDependencies": {{ - "@green-tea/core": "{CORE_VERSION}" + "@green-tea/core": "{CORE_VERSION}", + "@types/node": "^22" }} }} "#, @@ -145,6 +148,7 @@ fn package_json(p: &Package) -> String { }}, "devDependencies": {{ "@green-tea/core": "{CORE_VERSION}", + "@types/node": "^22", "typescript": "^5" }} }} @@ -197,6 +201,43 @@ test('two instances under one name are refused', () => {{ ) } +/// MIT as a starting point, which the README tells the author to change. The +/// holder is the scope, the closest thing to an author matcha knows. +fn license(p: &Package) -> String { + // Whole years since the epoch, averaged over leap years: a copyright line + // needs the year, not the date, and this needs no dependency. + let year = 1970 + + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() / 31_556_952) + .unwrap_or(0); + let scope = &p.scope; + format!( + "MIT License + +Copyright (c) {year} {scope} + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the \"Software\"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +" + ) +} + fn readme(p: &Package) -> String { let jsr = p.jsr_name(); let fun = camel(&p.slug); @@ -239,6 +280,11 @@ import {{ {fun} }} from '{jsr}'; const app = createApp({{ modules: [AppModule], plugins: [{fun}()] }}); ``` +## License + +MIT, as generated. Change `LICENSE` and the `license` fields in `deno.json` and `package.json` +if you publish under another. + ## 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/src/wire.rs b/src/wire.rs index cb749ea..a077335 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -261,7 +261,7 @@ pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option { fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option { if let Some((open, close)) = find_key_array_span(object, src, key) { let inner = &src[open + 1..close]; - if inner.split(',').map(str::trim).any(|s| s == symbol) { + if array_elements(object, src, key).iter().any(|e| e == symbol) { return Some(src.to_string()); // idempotent } let joined = if inner.trim().is_empty() { @@ -305,6 +305,32 @@ fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> } } +/// The text of each element of `object`'s `key: [...]` array, read from the +/// parse tree: `algo({ a: 1, b: 2 })` is one element, which a split on `,` is not. +fn array_elements(object: Node, src: &str, key: &str) -> Vec { + let mut c = object.walk(); + for pair in object.named_children(&mut c) { + let is_key = pair.kind() == "pair" + && pair + .child_by_field_name("key") + .and_then(|k| k.utf8_text(src.as_bytes()).ok()) + == Some(key); + let Some(array) = pair + .child_by_field_name("value") + .filter(|v| is_key && v.kind() == "array") + else { + continue; + }; + let mut ac = array.walk(); + return array + .named_children(&mut ac) + .filter_map(|e| e.utf8_text(src.as_bytes()).ok()) + .map(|t| t.split_whitespace().collect::>().join(" ")) + .collect(); + } + Vec::new() +} + /// True when `object` has any direct `pair` child whose key text equals `key`, /// regardless of the value's kind. Used to avoid creating a duplicate key when /// an existing pair's value isn't an array literal. @@ -473,6 +499,15 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option> { #[cfg(test)] mod tests { + #[test] + fn an_element_with_commas_inside_is_still_one_element() { + let src = "const app = createApp({ plugins: [algo({ a: 1, b: 2 })] });\n"; + assert_eq!( + add_to_createapp(src, "plugins", "algo({ a: 1, b: 2 })").as_deref(), + Some(src) + ); + } + #[test] fn binds_sees_identifiers_not_strings_or_comments() { let src = "import { createApp } from '@green-tea/core';\n// green tea\nexport const app = createApp({});\n"; diff --git a/tests/plugin.rs b/tests/plugin.rs index fefcdb5..f4b9b07 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -169,8 +169,7 @@ fn package_jsr_writes_the_tree_into_dir() { "create", "plugin", "Plugin Algo", - "--package", - "algo-pkg", + "--package=algo-pkg", "--scope", "@acme", ]) @@ -182,6 +181,7 @@ fn package_jsr_writes_the_tree_into_dir() { [ ".gitignore", "CHANGELOG.md", + "LICENSE", "README.md", "deno.json", "package.json", @@ -217,8 +217,7 @@ fn package_both_adds_the_npm_build() { "create", "plugin", "algo", - "--package", - "p", + "--package=p", "--scope", "acme", "--registry", @@ -247,8 +246,7 @@ fn both_package_json_is_esm_only() { "create", "plugin", "algo", - "--package", - "p", + "--package=p", "--scope", "acme", "--registry", @@ -270,8 +268,7 @@ fn package_accepts_any_npm_name_and_notes_the_convention() { "create", "plugin", "algo", - "--package", - "p", + "--package=p", "--scope", "acme", "--registry", @@ -312,7 +309,7 @@ fn package_in_an_empty_current_directory() { fn package_off_a_tty_needs_a_scope() { let d = tempdir().unwrap(); matcha(d.path()) - .args(["create", "plugin", "algo", "--package", "p"]) + .args(["create", "plugin", "algo", "--package=p"]) .assert() .failure() .stderr(contains("--scope")); @@ -327,8 +324,7 @@ fn package_rejects_a_bad_scope_or_npm_name() { "create", "plugin", "algo", - "--package", - "p", + "--package=p", "--scope", "Ac Me", ]) @@ -340,8 +336,7 @@ fn package_rejects_a_bad_scope_or_npm_name() { "create", "plugin", "algo", - "--package", - "q", + "--package=q", "--scope", "acme", "--registry", @@ -379,8 +374,7 @@ fn a_package_whose_factory_would_be_a_reserved_word_writes_nothing() { "create", "plugin", "delete", - "--package", - "p", + "--package=p", "--scope", "acme", ]) @@ -432,15 +426,7 @@ fn words_inside_strings_and_comments_are_not_collisions() { fn package_engines_need_the_node_that_strips_types() { let d = tempdir().unwrap(); matcha(d.path()) - .args([ - "create", - "plugin", - "algo", - "--package", - "p", - "--scope", - "acme", - ]) + .args(["create", "plugin", "algo", "--package=p", "--scope", "acme"]) .assert() .success(); let pj = std::fs::read_to_string(d.path().join("p/package.json")).unwrap(); @@ -452,18 +438,187 @@ fn package_engines_need_the_node_that_strips_types() { fn the_generated_test_asserts_the_token_is_in_the_graph() { let d = tempdir().unwrap(); matcha(d.path()) - .args([ - "create", - "plugin", - "algo", - "--package", - "p", - "--scope", - "acme", - ]) + .args(["create", "plugin", "algo", "--package=p", "--scope", "acme"]) .assert() .success(); let t = std::fs::read_to_string(d.path().join("p/test/algo.test.ts")).unwrap(); assert!(t.contains("app.graph()"), "{t}"); assert!(t.contains("provides.includes('algo')"), "{t}"); } + +#[test] +fn package_into_a_path_that_is_a_file_names_it() { + let d = tempdir().unwrap(); + std::fs::write(d.path().join("taken"), "x").unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package=taken", + "--scope", + "acme", + ]) + .assert() + .failure() + .stderr(contains("taken is a file")); +} + +#[test] +fn the_empty_directory_error_names_the_directory() { + let d = tempdir().unwrap(); + std::fs::create_dir_all(d.path().join("busy")).unwrap(); + std::fs::write(d.path().join("busy/keep.txt"), "x").unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package=busy", + "--scope", + "acme", + ]) + .assert() + .failure() + .stderr(contains("busy: a plugin package needs an empty directory")); +} + +#[cfg(unix)] +#[test] +fn in_app_leaves_nothing_behind_when_the_entry_cannot_be_written() { + use std::os::unix::fs::PermissionsExt; + let d = project(APP); + let entry = d.path().join("src/app.ts"); + std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o444)).unwrap(); + matcha(d.path()) + .args(["create", "plugin", "algo"]) + .assert() + .failure(); + std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o644)).unwrap(); + assert!( + !d.path().join("plugins/algo").exists(), + "the plugin folder is rolled back" + ); + assert_eq!(std::fs::read_to_string(&entry).unwrap(), APP); +} + +#[test] +fn folder_dot_and_leading_dot_slash_give_clean_imports() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", "."]) + .assert() + .success(); + assert!(d.path().join("algo/index.ts").exists()); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("from '../algo/index'"), "{app}"); + + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "algo", "--folder", "./plugins/"]) + .assert() + .success(); + let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap(); + assert!(app.contains("from '../plugins/algo/index'"), "{app}"); +} + +#[test] +fn plugin_flags_on_another_kind_are_an_error() { + let d = project(APP); + matcha(d.path()) + .args(["create", "controller", "Users", "--scope", "acme"]) + .assert() + .failure() + .stderr(contains("only apply to create plugin")); + assert!(!d.path().join("src/controllers").exists()); +} + +#[test] +fn flags_for_the_other_mode_are_named_as_ignored() { + let d = project(APP); + matcha(d.path()) + .args(["create", "plugin", "algo", "--scope", "acme"]) + .assert() + .success() + .stdout(contains("--scope only applies to --package; ignored")); + + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "--scope", + "acme", + "--folder", + "x", + "--check", + ]) + .assert() + .success() + .stdout(contains( + "--folder only applies to an in-app plugin; ignored", + )) + .stdout(contains( + "--check only applies to an in-app plugin; ignored", + )); +} + +/// `--package algo` used to take `algo` as the directory. It now needs `--package=DIR`, so a +/// bare word after `--package` is the plugin's name. +#[test] +fn a_word_after_package_is_the_name_not_the_directory() { + let d = tempdir().unwrap(); + matcha(d.path()) + .args(["create", "plugin", "--package", "algo", "--scope", "acme"]) + .assert() + .success(); + let deno = std::fs::read_to_string(d.path().join("deno.json")).unwrap(); + assert!(deno.contains("\"name\": \"@acme/algo\""), "{deno}"); +} + +#[test] +fn scopes_jsr_would_refuse_are_refused() { + for scope in ["-", "-acme", "a", "abcdefghijklmnopqrstu"] { + let d = tempdir().unwrap(); + matcha(d.path()) + // `=` so a leading hyphen is a value, not another flag. + .args([ + "create", + "plugin", + "algo", + "--package", + &format!("--scope={scope}"), + ]) + .assert() + .failure() + .stderr(contains("is not a JSR scope")); + assert!(!d.path().join("deno.json").exists(), "{scope}"); + } +} + +#[test] +fn packages_ship_a_license_and_node_types() { + for registry in ["jsr", "both"] { + let d = tempdir().unwrap(); + matcha(d.path()) + .args([ + "create", + "plugin", + "algo", + "--package", + "--scope", + "acme", + "--registry", + registry, + ]) + .assert() + .success(); + let license = std::fs::read_to_string(d.path().join("LICENSE")).unwrap(); + assert!(license.starts_with("MIT License"), "{registry}"); + let pj = std::fs::read_to_string(d.path().join("package.json")).unwrap(); + assert!(pj.contains("\"license\": \"MIT\""), "{registry}: {pj}"); + assert!(pj.contains("\"@types/node\""), "{registry}: {pj}"); + } +} -- 2.54.1 From 9e719b159d5df8fae75f1c6d05284094118a02cd Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 24 Sep 2026 13:28:05 -0500 Subject: [PATCH 14/14] test(plugin): skip the rollback test where the user can write a read-only file CI runs as root, which ignores a 0444 mode, so the entry write never fails there and there is nothing to roll back. The test now says it skipped instead of failing on a write that worked. Signed-off-by: Diego Resendez --- tests/plugin.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/plugin.rs b/tests/plugin.rs index f4b9b07..62d6b0f 100644 --- a/tests/plugin.rs +++ b/tests/plugin.rs @@ -490,6 +490,12 @@ fn in_app_leaves_nothing_behind_when_the_entry_cannot_be_written() { let d = project(APP); let entry = d.path().join("src/app.ts"); std::fs::set_permissions(&entry, std::fs::Permissions::from_mode(0o444)).unwrap(); + // Root ignores the mode (CI containers run as root), so there is no failed + // write to roll back from. Say so rather than pass on a write that worked. + if std::fs::OpenOptions::new().write(true).open(&entry).is_ok() { + eprintln!("skipped: this user can write a 0444 file, so the failure cannot be staged"); + return; + } matcha(d.path()) .args(["create", "plugin", "algo"]) .assert() -- 2.54.1