Author SHA1 Message Date
chrnx 647aef5a1b Merge pull request 'chore(release): 26.11.0-rc.1' (#22) from release/26.11.0-rc.1 into develop
Release / prepare (push) Successful in 2s
CI / starter (deno) (pull_request) Failing after 28s
CI / starter (bun) (pull_request) Successful in 45s
CI / starter (edge) (pull_request) Successful in 38s
CI / core-freshness (pull_request) Has been skipped
Release / publish-crate (push) Has been skipped
CI / starter (node) (push) Successful in 42s
CI / starter (node) (pull_request) Successful in 43s
CI / installer (ubuntu-latest) (pull_request) Successful in 12s
Release / build (macos-14, aarch64-apple-darwin) (push) Successful in 33s
CI / check (push) Successful in 35s
CI / installer (macos-14) (push) Successful in 4s
Release / build (macos-14, x86_64-apple-darwin) (push) Successful in 13s
CI / starter (bun) (push) Successful in 35s
Release / build (ubuntu-latest, aarch64-unknown-linux-musl) (push) Successful in 1m29s
CI / starter (deno) (push) Failing after 37s
Release / build (ubuntu-latest, x86_64-unknown-linux-musl) (push) Successful in 1m29s
CI / installer (macos-14) (pull_request) Successful in 5s
CI / starter (edge) (push) Successful in 40s
CI / core-freshness (push) Has been skipped
Release / promote-tag (push) Successful in 5s
Release / verify-linux-arm64 (push) Has been cancelled
CI / installer (ubuntu-latest) (push) Successful in 10s
CI / check (pull_request) Successful in 26s
Promote → GitHub / push-github (push) Successful in 5s
2026-11-17 23:40:15 +00:00
chrnx 42b5cc2616 chore(release): 26.11.0-rc.1
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 11s
CI / starter (node) (pull_request) Successful in 42s
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 36s
CI / starter (bun) (pull_request) Successful in 42s
CI / starter (deno) (pull_request) Failing after 37s
CI / starter (edge) (pull_request) Successful in 44s
matcha now releases with core: this version scaffolds @green-tea/core 26.11.0-rc.1. Bump Cargo.toml and the lockfile, close the CHANGELOG section, and record the edge and core-freshness changes from #21.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-11-17 17:37:51 -06:00
chrnx 04d7a25402 Merge pull request 'feat(add,create): matcha add cookie and matcha create transformer' (#21) from feat/cookie-transformer into develop
CI / starter (deno) (push) Failing after 36s
CI / starter (edge) (push) Successful in 49s
CI / core-freshness (push) Has been skipped
CI / installer (ubuntu-latest) (push) Successful in 10s
CI / starter (node) (push) Successful in 43s
CI / installer (macos-14) (push) Successful in 3s
CI / check (push) Successful in 36s
CI / starter (bun) (push) Successful in 39s
2026-11-17 23:35:29 +00:00
chrnx 8e45c1170f feat(templates): scaffold against core 26.11.0-rc.1; edge installs core from npm
CI / check (pull_request) Successful in 36s
CI / starter (bun) (pull_request) Successful in 45s
CI / starter (deno) (pull_request) Failing after 32s
CI / starter (edge) (pull_request) Successful in 52s
CI / core-freshness (pull_request) Has been skipped
CI / starter (node) (pull_request) Successful in 35s
CI / installer (ubuntu-latest) (pull_request) Successful in 12s
CI / installer (macos-14) (pull_request) Successful in 4s
core#93 is fixed in RC.1: the npm ESM build's createRequire banner no longer throws on workerd, so the edge starter drops its .npmrc and the npm:@jsr alias and installs @green-tea/core from npm like every other runtime. doctor still reads the alias, so edge projects scaffolded before this keep working.

The weekly core-freshness job compares against core's latest dist-tag: release candidates and the stable release publish there, and beta stays on 26.9.0-beta.2.

Starter smoke passes locally on node, deno, bun and edge. Deno needs --minimum-dependency-age=0 until RC.1 is a day old.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-11-17 17:31:03 -06:00
chrnx 8bd558991d feat(add,create): matcha add cookie and matcha create transformer
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Failing after 31s
CI / starter (deno) (pull_request) Failing after 32s
CI / starter (edge) (pull_request) Failing after 37s
CI / installer (ubuntu-latest) (pull_request) Successful in 9s
CI / core-freshness (pull_request) Has been skipped
CI / starter (node) (pull_request) Failing after 32s
add cookie reads a cookie with @cookie and sets one through a
@Transformer and setCookie, since core sends Set-Cookie only as a
header. create transformer writes a typed TransformerFn and prints how to
attach it; there is nothing to wire into a module. starter-smoke now
covers both.

add cookie uses @cookie and setCookie, which are new in core RC.1, so
this lands together with the CORE_VERSION bump.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 23:02:35 -05:00
chrnx d9f2b07802 Merge pull request 'fix(create,starters): safe names and no overwrite in create; node starter awaits listen and declares engines' (#20) from fix/create-names into develop
CI / check (push) Successful in 28s
CI / starter (bun) (push) Successful in 31s
CI / starter (deno) (push) Successful in 41s
CI / installer (ubuntu-latest) (push) Successful in 10s
CI / starter (edge) (push) Successful in 39s
CI / core-freshness (push) Has been skipped
CI / starter (node) (push) Successful in 34s
CI / installer (macos-14) (push) Successful in 3s
2026-10-31 04:00:19 +00:00
chrnx a8f1658e4d fix(create,starters): safe names and no overwrite in create; node starter awaits listen and declares engines
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Successful in 31s
CI / starter (deno) (pull_request) Successful in 33s
CI / starter (edge) (pull_request) Successful in 38s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 12s
CI / starter (node) (pull_request) Successful in 32s
matcha create derives the class name and its token from what was typed:
current-user becomes CurrentUserStep providing currentUser, where it used
to write a file that did not parse. It refuses names that cannot be a
class, and step or provider names whose token core already provides. It
also refuses to replace an existing file instead of silently discarding
edits.

The node starter awaits app.listen so boot and bind failures stop the
process with their own error, and the node and edge starters declare
engines node >=22 to match core.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 21:00:58 -05:00
chrnx 865d87487b Merge pull request 'feat(agents): scaffold AGENTS.md and CLAUDE.md, and add matcha agents' (#19) from feat/agents-md into develop
CI / starter (deno) (push) Successful in 31s
CI / starter (edge) (push) Successful in 39s
CI / core-freshness (push) Has been skipped
CI / installer (ubuntu-latest) (push) Successful in 11s
CI / starter (node) (push) Successful in 33s
CI / installer (macos-14) (push) Successful in 3s
CI / check (push) Successful in 28s
CI / starter (bun) (push) Successful in 32s
2026-10-31 01:45:38 +00:00
chrnx 9641bd51a7 feat(agents): scaffold AGENTS.md and CLAUDE.md, and add matcha agents
CI / installer (macos-14) (pull_request) Successful in 2s
CI / check (pull_request) Successful in 26s
CI / starter (bun) (pull_request) Successful in 31s
CI / starter (deno) (pull_request) Successful in 32s
CI / starter (node) (pull_request) Successful in 33s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 10s
CI / starter (edge) (pull_request) Successful in 5m38s
LLM coding agents have no training data on green-tea, so they write
Express. Every starter now ships an AGENTS.md, with a CLAUDE.md that
imports it. It states the rules that differ: a graph, not a chain;
needs declared in the signature; the graph validated at boot; reuse
existing tokens. It also points the agent at matcha
routes|tokens|explain --json and at the llms.txt inside the installed
core.

matcha agents writes the same files into an older project, with the
core version that project actually depends on. It leaves existing
files alone unless --force is given.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 20:35:23 -05:00
chrnx ea510c5112 Merge pull request 'feat(introspect): routes, tokens and --json, over one query layer an MCP server can reuse' (#18) from feat/introspect-json into develop
CI / installer (macos-14) (push) Successful in 3s
CI / check (push) Successful in 27s
CI / starter (bun) (push) Successful in 31s
CI / starter (deno) (push) Successful in 32s
CI / starter (edge) (push) Successful in 38s
CI / core-freshness (push) Has been skipped
CI / installer (ubuntu-latest) (push) Successful in 12s
CI / starter (node) (push) Successful in 33s
2026-10-31 01:35:19 +00:00
chrnx 9acb0b34c9 fix(tokens): name the request as the source of its built-in tokens
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Successful in 30s
CI / starter (deno) (pull_request) Successful in 31s
CI / starter (edge) (pull_request) Successful in 36s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 13s
CI / starter (node) (pull_request) Successful in 33s
matcha tokens listed req as '— (nothing provides it)'. An agent reading
that would write a provider for req. A needed token with no producing
node must come from the request (req, params, body, …): app.ready() has
already validated the graph, so a truly missing token would have failed
it. Mark those source: "request" in the JSON and 'the request (built
in)' in the text.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 10:54:29 -05:00
chrnx a4827f2e13 feat(introspect): routes, tokens and --json, over one query layer an MCP server can reuse
CI / installer (macos-14) (pull_request) Successful in 4s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Successful in 30s
CI / starter (deno) (pull_request) Successful in 32s
CI / starter (edge) (pull_request) Successful in 36s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 14s
CI / starter (node) (pull_request) Successful in 32s
Agents that inspect a green-tea app should read its graph instead of
guessing it.

- Add `matcha routes`: every route with its transport and chain.
- Add `matcha tokens`: every token, who provides it and who needs it,
  handlers included.
- explain, routes and tokens take --json. It prints one JSON document
  on stdout; a refused query prints a structured error on stderr and
  exits 1.

All introspection now goes through src/introspect.rs. Each Query
variant runs one script that prints a single JSON envelope, and the
CLI renders the data as text unless --json is given. Text output is
unchanged. A future `matcha mcp` serves the same queries as tools
without a second implementation, which is why the formatting moved
from the generated script into Rust.

Adds serde_json (dtolnay, 1.0.154).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-30 10:51:21 -05:00
chrnx 47d1d6e037 Merge pull request 'ci: move workflow actions off the deprecated Node 20 runtime' (#17) from chore/ci-node24-actions into develop
CI / installer (macos-14) (push) Successful in 3s
CI / check (push) Successful in 25s
CI / starter (bun) (push) Successful in 30s
CI / starter (deno) (push) Successful in 33s
CI / starter (edge) (push) Successful in 35s
CI / core-freshness (push) Has been skipped
CI / installer (ubuntu-latest) (push) Successful in 16s
CI / starter (node) (push) Successful in 32s
2026-10-18 04:42:30 +00:00
chrnx 99c8578120 ci: move workflow actions off the deprecated Node 20 runtime
CI / installer (macos-14) (pull_request) Successful in 10s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Successful in 31s
CI / starter (deno) (pull_request) Successful in 32s
CI / starter (edge) (pull_request) Successful in 37s
CI / core-freshness (pull_request) Has been skipped
CI / starter (node) (pull_request) Successful in 31s
CI / installer (ubuntu-latest) (pull_request) Successful in 10s
actions/checkout and actions/setup-node v4 -> v5, softprops/action-gh-release
v2 -> v3; all three run on Node 24. setup-deno@v2, setup-bun@v2 and
crates-io-auth-action@v1 already resolve to Node 24 releases. Jobs keep
node-version 22.

Refs Green-Tea/core#103

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-17 22:55:51 -05:00
chrnx 202c4b2711 Merge pull request 'matcha create plugin, and scaffold core 26.9.0-beta.2' (#14) from feature/plugin-scaffold into develop
CI / installer (macos-14) (push) Successful in 3s
CI / starter (bun) (push) Successful in 31s
CI / starter (deno) (push) Successful in 34s
CI / check (push) Successful in 29s
Release / build (ubuntu-latest, aarch64-unknown-linux-musl) (push) Successful in 1m5s
Release / promote-tag (push) Successful in 6s
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 28s
CI / starter (edge) (push) Successful in 37s
CI / installer (ubuntu-latest) (push) Successful in 11s
CI / starter (node) (push) Successful in 35s
Release / build (macos-14, aarch64-apple-darwin) (push) Successful in 15s
CI / starter (bun) (pull_request) Successful in 31s
CI / starter (deno) (pull_request) Successful in 33s
CI / core-freshness (push) Has been skipped
Promote → GitHub / push-github (push) Successful in 6s
Release / build (ubuntu-latest, x86_64-unknown-linux-musl) (push) Successful in 1m5s
CI / starter (edge) (pull_request) Successful in 36s
Release / build (macos-14, x86_64-apple-darwin) (push) Successful in 13s
CI / core-freshness (pull_request) Has been skipped
CI / installer (ubuntu-latest) (pull_request) Successful in 10s
Release / publish-crate (push) Has been skipped
Release / prepare (push) Successful in 3s
CI / starter (node) (pull_request) Successful in 34s
Release / verify-linux-arm64 (push) Has been cancelled
2026-09-24 19:30:15 +00:00
chrnx 9e719b159d test(plugin): skip the rollback test where the user can write a read-only file
CI / installer (macos-14) (pull_request) Successful in 3s
CI / check (pull_request) Successful in 27s
CI / starter (bun) (pull_request) Successful in 31s
CI / starter (node) (pull_request) Successful in 32s
CI / installer (ubuntu-latest) (pull_request) Successful in 11s
CI / starter (deno) (pull_request) Successful in 31s
CI / starter (edge) (pull_request) Successful in 38s
CI / core-freshness (pull_request) Has been skipped
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 <diego.resendez@zero-oneit.com>
2026-09-24 13:28:05 -05:00
chrnx ecdc46cac3 fix(plugin): the review's smaller findings
CI / installer (ubuntu-latest) (pull_request) Successful in 11s
CI / installer (macos-14) (pull_request) Successful in 4s
CI / check (pull_request) Failing after 29s
CI / starter (bun) (pull_request) Successful in 32s
CI / starter (deno) (pull_request) Successful in 33s
CI / starter (edge) (pull_request) Successful in 37s
CI / core-freshness (pull_request) Has been skipped
CI / starter (node) (pull_request) Successful in 34s
- `--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 <diego.resendez@zero-oneit.com>
2026-09-24 13:26:29 -05:00
chrnx 4358091d07 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 <diego.resendez@zero-oneit.com>
2026-09-24 13:11:55 -05:00
chrnx e4a350fcbf 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 <diego.resendez@zero-oneit.com>
2026-09-24 13:05:46 -05:00
chrnx 70b51e5de4 docs: document create plugin, and version 26.9.0-beta.1
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-24 13:02:40 -05:00
chrnx 52241cc9a6 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 <diego.resendez@zero-oneit.com>
2026-09-24 13:00:43 -05:00
chrnx efe7ad6027 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 <diego.resendez@zero-oneit.com>
2026-09-24 12:58:16 -05:00
chrnx 42c1148903 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 <diego.resendez@zero-oneit.com>
2026-09-24 12:57:32 -05:00
chrnx 3c3b7aaf8e 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 <diego.resendez@zero-oneit.com>
2026-09-24 12:54:51 -05:00
chrnx f2a3c16023 feat(plugin): ask questions at a terminal and take defaults everywhere else
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-24 12:53:44 -05:00
chrnx c5b4a56ccd feat(plugin): derive a plugin's slug and identifiers from what was typed
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-24 12:53:17 -05:00
34 changed files with 3151 additions and 283 deletions

No files matched your search

+7 -7
View File
@@ -15,7 +15,7 @@ jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
@@ -38,7 +38,7 @@ jobs:
matrix:
runtime: [node, deno, bun, edge]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
@@ -64,14 +64,14 @@ jobs:
if: github.event_name == 'schedule'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Compare the scaffold pin against the beta dist-tag
- uses: actions/checkout@v5
- name: Compare the scaffold pin against the latest dist-tag
run: |
pinned=$(grep -oP 'CORE_VERSION: &str = "\K[^"]+' src/template.rs)
latest=$(npm view @green-tea/core dist-tags.beta)
latest=$(npm view @green-tea/core dist-tags.latest)
echo "pinned=$pinned latest=$latest"
if [ "$pinned" != "$latest" ]; then
echo "::error::matcha scaffolds @green-tea/core@$pinned but the beta tag is $latest."
echo "::error::matcha scaffolds @green-tea/core@$pinned but the latest tag is $latest."
echo "Bump CORE_VERSION in src/template.rs and let the starter job prove it still boots."
exit 1
fi
@@ -87,7 +87,7 @@ jobs:
matrix:
os: [ubuntu-latest, macos-14]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Lint the installer
if: matrix.os == 'ubuntu-latest'
run: |
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Push main to GitHub
+5 -5
View File
@@ -50,7 +50,7 @@ jobs:
os: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Install Rust
run: |
@@ -131,7 +131,7 @@ jobs:
fi
- name: Upload to release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
# A tag with a hyphen is a prerelease (26.9.0-beta.1). Unflagged, it
# would answer /releases/latest — which is what install.sh resolves
@@ -163,7 +163,7 @@ jobs:
if: ${{ github.server_url == 'https://github.com' }}
runs-on: ubuntu-24.04-arm
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Install the published arm64 binary and run it
run: |
set -eu
@@ -185,7 +185,7 @@ jobs:
if: ${{ github.server_url != 'https://github.com' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Push the tag to GitHub
@@ -209,7 +209,7 @@ jobs:
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Install Rust
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
+87 -2
View File
@@ -5,10 +5,92 @@ All notable changes to `matcha-cli` are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
matcha uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, matching
green-tea's convention. **The CLI ships on its own version line**: `matcha` 26.8 does not
mean `@green-tea/core` 26.8, and the two release independently. The core version a scaffold
green-tea's convention. **From 26.11.0-rc.1 matcha releases with core**: `matcha` X scaffolds
`@green-tea/core` X. Before that the CLI ran on its own version line. 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.11.0-rc.1] - 2026-11-17
### Added
- **`matcha add cookie`** adds `GET /prefs`, which reads a cookie with `@cookie('theme')`, and
`POST /prefs`, which sets it through a `@Transformer` and `setCookie()`. Core has no response-cookie
API, so the transformer is where a `Set-Cookie` header is sent. Needs `@green-tea/core` RC.1.
- **`matcha create transformer <Name>`** writes `src/transformers/<name>.transformer.ts`, a typed
`TransformerFn`, and prints the `@Transformer(...)` line that attaches it. A transformer belongs to
a route, not a module, so there is nothing to wire.
- **Every starter ships an `AGENTS.md` and a `CLAUDE.md` that imports it.** green-tea is new, so a
coding agent falls back on Express habits. The file states the rules that differ: it is a graph, not a
chain, a handler declares its needs in its signature, and the graph is checked at boot. It also points
the agent at `matcha routes|tokens|explain --json`, so it reads the app instead of guessing, and at the
`llms.txt` shipped inside the installed `@green-tea/core`.
- **`matcha agents`** writes the same two files into a project that predates them. The files name the
core version the project actually depends on. An existing file is left alone unless `--force` is passed.
- **`matcha routes` and `matcha tokens`.** `routes` lists every route with its transport and chain.
`tokens` lists every token, with who provides it and who needs it, handlers included. It is
the check to run before writing `@needs('x')`.
- **`--json` on `explain`, `routes` and `tokens`** (`graph --format json` already had it). It
prints one JSON document on stdout, so an agent inspecting an app reads the graph instead of
guessing it. A refused query (an unknown pattern) prints a structured error on stderr and
exits 1.
### Changed
- **Scaffolds pin `@green-tea/core` 26.11.0-rc.1**, the API-freeze release candidate, and matcha's own
version now matches it.
- **The edge starter installs core from npm.** core#93 is fixed in RC.1, so the `.npmrc` and the
`npm:@jsr/green-tea__core` alias are gone. `matcha doctor` still reads the alias, so edge projects
scaffolded before this keep working.
- The weekly `core-freshness` CI job compares `CORE_VERSION` against core's `latest` dist-tag, where
release candidates and the stable release publish. `beta` stays on 26.9.0-beta.2.
- Introspection runs through one query layer (`src/introspect.rs`): every command asks one
question and gets one JSON document back, then renders it as text unless `--json` is passed.
Text output is unchanged. The layer is also the seam a future `matcha mcp` would serve over
MCP. It adds `serde_json` as a dependency.
- **The node starter awaits `app.listen(3000)`.** A port already in use, or a provider that fails at
boot, now stops the process with its own error rather than an unhandled rejection.
- **The node and edge starters declare `engines: { node: ">=22" }`**, matching `@green-tea/core`,
which no longer supports Node 18 or 20.
- **`matcha create step|provider` derives the token from the class name in camelCase.**
`create step current-user` writes `CurrentUserStep` providing `currentUser`. It used to write
`current-userStep` and `return { current-user: null }`, which does not parse. A single word is
unchanged (`Users` still provides `users`).
### Fixed
- **`matcha create` no longer overwrites a file that already exists.** Running it twice with the same
name silently replaced the first file, edits included. Now it refuses and names the file.
- **`matcha create` rejects names that cannot become a class** (`2fast`, `us.ers`) instead of
writing a file that does not compile. For a step or provider, it also rejects names whose token
core already provides (`logger`, `rooms`, `events`, `bus`, and the request tokens `req`,
`params`, `query`, `body`, `headers`, `cookies`, `inbound`, `abort`). `createApp` would refuse the
first group, and the second would shadow what every route reads.
## [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/<name>/`, 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
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
@@ -182,6 +264,9 @@ 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.11.0-rc.1...HEAD
[26.11.0-rc.1]: https://github.com/Expressive-Tea/matcha/compare/v26.9.0-beta.1...v26.11.0-rc.1
[26.9.0-beta.1]: https://github.com/Expressive-Tea/matcha/compare/v26.9.0-beta.0...v26.9.0-beta.1
[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
+1 -1
View File
@@ -126,7 +126,7 @@ scripts/starter-smoke.sh <the runtime you touched>
```
CI runs the smoke for all four runtimes on a matrix, plus a weekly `core-freshness` job
that fails when `CORE_VERSION` in `src/template.rs` falls behind core's `beta` dist-tag.
that fails when `CORE_VERSION` in `src/template.rs` falls behind core's `latest` dist-tag.
**Non-trivial logic leaves a check behind.** Not a suite — the smallest thing that fails if
the logic breaks. A generator gets a test that the generated code carries what it must; a
Generated
+36 -1
View File
@@ -240,6 +240,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "libc"
version = "0.2.186"
@@ -254,12 +260,13 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "matcha-cli"
version = "26.9.0-beta.0"
version = "26.11.0-rc.1"
dependencies = [
"assert_cmd",
"clap",
"include_dir",
"predicates",
"serde_json",
"tempfile",
"tree-sitter",
"tree-sitter-typescript",
@@ -394,6 +401,15 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.228"
@@ -414,6 +430,19 @@ dependencies = [
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -511,3 +540,9 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "matcha-cli"
version = "26.9.0-beta.0"
version = "26.11.0-rc.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"
@@ -15,6 +15,7 @@ path = "src/main.rs"
[dependencies]
clap = { version = "4", features = ["derive"] }
include_dir = "0.7"
serde_json = "1"
tree-sitter = "0.22"
tree-sitter-typescript = "0.21"
+51 -6
View File
@@ -38,11 +38,15 @@ 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
matcha routes # every route and the chain it runs
matcha tokens # every token: who provides it, who needs it
matcha openapi # structural OpenAPI 3.1 for the route table
matcha doctor # check the project for confusing misconfigurations
matcha agents # write AGENTS.md/CLAUDE.md for coding agents (new projects get them)
```
### The starter
@@ -51,6 +55,12 @@ matcha doctor # check the project for confusing mis
with the green-tea logo and streams a rotating zen message over `@Sse('/zen')`.
Open the browser and it's already alive — `matcha run` boots it.
It also writes an `AGENTS.md` (and a `CLAUDE.md` that imports it) for coding
agents. green-tea is new enough that an agent's training data says Express, so
the file states the rules that differ, points at `matcha routes|tokens|explain
--json` for reading the app, and at the `llms.txt` inside the installed core.
`matcha agents` adds the same files to an older project.
The graph is composed in `src/app.ts`, which exports the app; `src/main.ts`
imports it and binds a port. The split is what lets `matcha graph` and
`matcha explain` read your application without starting a server.
@@ -60,7 +70,7 @@ prerelease-only, and npm's semver excludes a prerelease from any range whose
comparators carry a different `major.minor.patch` — so `^26.7.0-beta.0` never
resolves past `26.7.0-beta.0` however many betas ship after it. CI scaffolds,
installs, boots and introspects a real starter on every runtime, and a weekly
job fails when the pin falls behind the `beta` dist-tag.
job fails when the pin falls behind the `latest` dist-tag.
### Introspection
@@ -74,6 +84,9 @@ matcha graph --format dot # Graphviz
matcha graph --format json # the raw GraphView
matcha graph --out docs/graph.mmd # to a file instead of stdout
matcha explain /users/:id # providers → steps → handler, with needs/provides
matcha routes # every route: method, pattern, transport, chain
matcha tokens # every token, who provides it, who needs it
matcha explain /users/:id --json # any of explain/routes/tokens as JSON, for a program or an agent
matcha openapi --title "My API" --api-version 1.0.0 --out openapi.json
```
@@ -89,6 +102,17 @@ be installed, since this runs your code under your runtime.
`explain` takes the route **pattern** as declared, not a concrete URL:
`/users/:id`, not `/users/42`. A miss lists the patterns that are registered.
`tokens` answers the question to ask before writing `@needs('x')`: does anything
provide `x`, and who else depends on it? A token nothing provides is listed with
`— (nothing provides it)`, which is the boot error you are about to get.
**For agents.** `--json` prints the same data the text is rendered from: exactly
one JSON document on stdout, so a program parses stdout and nothing else. When a
query is refused (an unknown route pattern), stderr carries
`{"error": {"code", "message", …}}` and the exit code is 1. Every query is one
self-contained document, so the same set can later be served over MCP without a
second implementation.
### `add` capabilities
| | generates |
@@ -111,6 +135,31 @@ 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` 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>` 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`
@@ -145,11 +194,7 @@ which boots real workerd locally.
Two differences the edge cannot hide. `@Html('file')`, `static` and multipart
uploads need a filesystem workerd does not have, and shutdown teardown never
runs — an isolate is discarded, not closed. And core is installed from **JSR**
here rather than npm: the npm ESM build carries a `createRequire(import.meta.url)`
banner that throws at load on workerd. The scaffolded `.npmrc` says so and links
[the issue](https://github.com/Expressive-Tea/green-tea/issues/93); both it and
the alias can go once that is fixed.
runs — an isolate is discarded, not closed.
## Development
+2 -1
View File
@@ -96,9 +96,10 @@ echo "✓ graph, explain and openapi resolve"
# core lazy-requires `ws` and `busboy`, so neither is needed to compile, and a
# check that needed them would be hiding that fact.
echo "▸ matcha add (every capability)"
for cap in sse ws upload stream buffer; do
for cap in sse ws upload stream buffer cookie; do
"$MATCHA" add "$cap" >/dev/null || { echo "matcha add $cap failed"; exit 1; }
done
"$MATCHA" create transformer Csv >/dev/null || { echo "matcha create transformer failed"; exit 1; }
"${CHECK[@]}" || { echo "the generated handlers do not type-check"; exit 1; }
echo "✓ every add capability type-checks"
+226
View File
@@ -0,0 +1,226 @@
//! 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<R, W> {
interactive: bool,
input: R,
output: W,
}
impl Ask<io::StdinLock<'static>, 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<R: BufRead, W: Write> Ask<R, W> {
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<String> {
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<bool> {
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,
})
}
/// 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,
question: &str,
default: Option<&str>,
flag: &str,
) -> io::Result<String> {
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<Cursor<Vec<u8>>, Vec<u8>> {
Ask::new(true, Cursor::new(answers.as_bytes().to_vec()), Vec::new())
}
fn piped() -> Ask<Cursor<Vec<u8>>, Vec<u8>> {
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 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();
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"
);
}
}
+46 -1
View File
@@ -26,12 +26,34 @@ 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<String>,
#[arg(long)]
check: bool,
/// 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<Option<String>>,
/// plugin, in-app: folder relative to the project root (default: plugins)
#[arg(long)]
folder: Option<String>,
/// plugin, package: the JSR scope
#[arg(long)]
scope: Option<String>,
/// plugin, package: where it publishes (default: jsr)
#[arg(long, value_parser = ["jsr", "both"])]
registry: Option<String>,
/// plugin, package, both: the npm name (default: @<scope>/green-tea-<slug>)
#[arg(long)]
npm_name: Option<String>,
},
/// Check the project for the misconfigurations that fail confusingly
Doctor,
/// Write AGENTS.md and CLAUDE.md: green-tea's rules for coding agents
Agents {
/// Overwrite the files if they exist
#[arg(long)]
force: bool,
},
/// Print the dependency graph (Mermaid, DOT, or JSON)
Graph {
#[arg(long, default_value = "mermaid", value_parser = ["mermaid", "dot", "json"])]
@@ -64,6 +86,29 @@ pub enum Command {
entry: Option<String>,
#[arg(long)]
out: Option<String>,
/// Print the answer as JSON, for a program or an agent
#[arg(long)]
json: bool,
},
/// List every route, its transport, and the chain it runs
Routes {
#[arg(long)]
entry: Option<String>,
#[arg(long)]
out: Option<String>,
/// Print the answer as JSON, for a program or an agent
#[arg(long)]
json: bool,
},
/// List every token: who provides it and who needs it
Tokens {
#[arg(long)]
entry: Option<String>,
#[arg(long)]
out: Option<String>,
/// Print the answer as JSON, for a program or an agent
#[arg(long)]
json: bool,
},
/// Add a capability to a controller
Add {
+33
View File
@@ -139,6 +139,39 @@ const CAPABILITIES: &[Capability] = &[
marker: "'/upload'",
peer: Some(("busboy", "every runtime")),
},
Capability {
name: "cookie",
// Reading is a decorator. Writing is a `Set-Cookie` header, which core only builds
// (`setCookie`) and a transformer sends: core has no response-cookie API of its own.
imports: &["Get", "Post", "Transformer", "body", "cookie", "setCookie"],
type_imports: &[],
method: r#"
@Get('/prefs')
prefs(@cookie('theme') theme?: string) {
return { theme: theme ?? 'light' };
}
@Post('/prefs')
@Transformer((value) => {
const { theme } = value as { theme: string };
return {
status: 200,
headers: {
'content-type': 'application/json',
// Secure and HttpOnly are on by default. Safari, a LAN IP or a plain-HTTP host other
// than localhost drops a Secure cookie: pass `secure: false` there in development.
'set-cookie': setCookie('theme', encodeURIComponent(theme), { maxAge: 60 * 60 * 24 * 365 }),
},
body: JSON.stringify({ theme }),
};
})
savePrefs(@body('theme') theme: string) {
return { theme };
}
"#,
marker: "'/prefs'",
peer: None,
},
];
/// The capability names, for clap's `value_parser` and for error messages.
+122
View File
@@ -0,0 +1,122 @@
//! `matcha agents` — write `AGENTS.md` and `CLAUDE.md` into a project that was
//! scaffolded before matcha wrote them, so a coding agent opening it finds
//! green-tea's rules instead of applying Express habits.
use std::path::Path;
use crate::template::{self, AGENT_FILES, CORE_VERSION};
pub fn run(dir: &Path, force: bool) -> std::io::Result<()> {
let name = project_name(dir);
let version = core_version(dir).unwrap_or_else(|| CORE_VERSION.to_string());
for file in AGENT_FILES {
let path = dir.join(file);
if path.exists() && !force {
println!("· {file} exists, left as is (--force to overwrite)");
continue;
}
let contents = template::agent_file(file, &name, &version)
.expect("agent files are embedded in the binary");
std::fs::write(&path, contents)?;
println!("✓ {file}");
}
Ok(())
}
/// `package.json`'s `name`, else the directory's.
fn project_name(dir: &Path) -> String {
std::fs::read_to_string(dir.join("package.json"))
.ok()
.and_then(|pkg| field(&pkg, "\"name\""))
.or_else(|| {
std::fs::canonicalize(dir)
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
})
.unwrap_or_else(|| "this project".to_string())
}
/// The core version the project actually depends on, so the file names the
/// version whose rules apply: `package.json` (npm, Bun, edge) or `deno.json`'s
/// `jsr:@green-tea/core@…` import.
fn core_version(dir: &Path) -> Option<String> {
if let Ok(pkg) = std::fs::read_to_string(dir.join("package.json")) {
if let Some(v) = field(&pkg, "\"@green-tea/core\"") {
return Some(v.trim_start_matches(['^', '~', '=']).to_string());
}
}
let deno = std::fs::read_to_string(dir.join("deno.json")).ok()?;
let at = deno.find("@green-tea/core@")? + "@green-tea/core@".len();
Some(
deno[at..]
.chars()
.take_while(|c| !matches!(c, '"' | '/'))
.collect(),
)
}
/// The string value after `key:` in a JSON text. Enough for the two flat
/// fields read here, without a JSON parse of a file that may not be valid.
fn field(json: &str, key: &str) -> Option<String> {
let rest = &json[json.find(key)? + key.len()..];
let rest = rest
.trim_start()
.strip_prefix(':')?
.trim_start()
.strip_prefix('"')?;
Some(rest[..rest.find('"')?].to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn writes_both_files_with_the_projects_own_core_version() {
let d = tempdir().unwrap();
std::fs::write(
d.path().join("package.json"),
r#"{ "name": "shop", "dependencies": { "@green-tea/core": "26.9.0-beta.1" } }"#,
)
.unwrap();
run(d.path(), false).unwrap();
let agents = std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap();
assert!(agents.contains("# AGENTS.md — shop"));
assert!(agents.contains("26.9.0-beta.1"));
assert_eq!(
std::fs::read_to_string(d.path().join("CLAUDE.md"))
.unwrap()
.trim(),
"@AGENTS.md"
);
}
#[test]
fn leaves_an_existing_file_alone_unless_forced() {
let d = tempdir().unwrap();
std::fs::write(d.path().join("AGENTS.md"), "mine").unwrap();
run(d.path(), false).unwrap();
assert_eq!(
std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap(),
"mine"
);
run(d.path(), true).unwrap();
assert_ne!(
std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap(),
"mine"
);
}
#[test]
fn reads_the_version_from_a_deno_import() {
let d = tempdir().unwrap();
std::fs::write(
d.path().join("deno.json"),
r#"{ "imports": { "@green-tea/core": "jsr:@green-tea/core@26.9.0-beta.2" } }"#,
)
.unwrap();
assert_eq!(core_version(d.path()).as_deref(), Some("26.9.0-beta.2"));
}
}
+97 -9
View File
@@ -5,7 +5,7 @@
use std::io::{Error, ErrorKind};
use std::path::Path;
use crate::{entry, wire};
use crate::{entry, naming, wire};
/// A piece that lives inside a module: a file under `src/<subdir>/` plus an
/// entry in one of `@Module`'s arrays.
@@ -53,15 +53,77 @@ 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(["transformer", "plugin"])
.collect()
}
/// Tokens core already owns. A step or provider that provides one fails `createApp` (the framework
/// tokens) or shadows what every route reads from the request (the request tokens).
const TAKEN_TOKENS: &[&str] = &[
"logger", "rooms", "events", "bus", "req", "params", "query", "body", "headers", "cookies",
"inbound", "abort",
];
/// `Users` stays `Users`; `current-user`, `current_user` and `current user` become `CurrentUser`.
/// `None` for anything that cannot become a TypeScript class name.
fn class_name(name: &str) -> Option<String> {
let name = name.trim();
if name.starts_with(|c: char| c.is_ascii_alphabetic())
&& name.chars().all(|c| c.is_ascii_alphanumeric())
{
let (first, rest) = name.split_at(1);
return Some(first.to_ascii_uppercase() + rest);
}
naming::slug(name).map(|s| naming::pascal(&s))
}
/// The token a step or provider named `CurrentUser` provides: `currentUser`.
fn token(class: &str) -> String {
let (first, rest) = class.split_at(1);
first.to_ascii_lowercase() + rest
}
/// Refuses to replace a file the person may already have edited.
fn write_new(file: &Path, contents: String) -> std::io::Result<()> {
if file.exists() {
return Err(Error::new(
ErrorKind::AlreadyExists,
format!(
"{} already exists; matcha create does not overwrite it",
file.display()
),
));
}
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(file, contents)
}
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
let Some(class) = class_name(name) else {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("'{name}' cannot name a class: use letters and digits, starting with a letter (Users, CurrentUser, current-user)"),
));
};
let name = class.as_str();
if (kind == "step" || kind == "provider") && TAKEN_TOKENS.contains(&token(name).as_str()) {
return Err(Error::new(
ErrorKind::InvalidInput,
format!(
"a {kind} named {name} would provide '{}', which core already provides; pick another name",
token(name)
),
));
}
if kind == "module" {
return create_module(name, check);
}
if kind == "transformer" {
return create_transformer(name, check);
}
match PIECES.iter().find(|p| p.kind == kind) {
Some(piece) => create_piece(name, check, piece),
None => Err(Error::new(
@@ -85,8 +147,7 @@ fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
let file = Path::new("src")
.join(subdir)
.join(format!("{lower}.{ext}.ts"));
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, (piece.stub)(name))?;
write_new(&file, (piece.stub)(name))?;
println!("✓ {}", file.display());
let symbol = format!("{name}{suffix}");
@@ -115,8 +176,7 @@ fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
fn create_module(name: &str, check: bool) -> std::io::Result<()> {
let lower = name.to_lowercase();
let file = Path::new("src").join(format!("{lower}.module.ts"));
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(&file, module_stub(name))?;
write_new(&file, module_stub(name))?;
println!("✓ {}", file.display());
let symbol = format!("{name}Module");
@@ -143,7 +203,35 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> {
maybe_check(check)
}
fn maybe_check(check: bool) -> std::io::Result<()> {
/// Writes `src/transformers/<name>.transformer.ts`. Nothing to wire: a transformer is attached
/// per route with `@Transformer`, so the hint says where it goes instead.
fn create_transformer(name: &str, check: bool) -> std::io::Result<()> {
let lower = name.to_lowercase();
let file = Path::new("src/transformers").join(format!("{lower}.transformer.ts"));
let symbol = format!("{}Transformer", token(name));
write_new(&file, transformer_stub(&symbol))?;
println!("✓ {}", file.display());
println!(
"→ attach it to a route: @Transformer({symbol}), imported from './transformers/{lower}.transformer'"
);
maybe_check(check)
}
fn transformer_stub(symbol: &str) -> String {
format!(
"import type {{ TransformerFn }} from '@green-tea/core';\n\n\
/**\n * Turns what a handler returns into the response. Attach it to a route with\n\
* `@Transformer({symbol})`; routes without one use the default JSON transformer.\n\
* Set the status and headers here (`set-cookie` takes an array, one header per cookie).\n */\n\
export const {symbol}: TransformerFn = (value) => ({{\n\
status: 200,\n\
headers: {{ 'content-type': 'application/json' }},\n\
body: JSON.stringify(value),\n\
}});\n"
)
}
pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> {
if check {
match crate::check::run(Path::new(".")) {
Ok(true) => println!("✓ type-check passed"),
@@ -162,14 +250,14 @@ fn controller_stub(name: &str) -> String {
}
fn step_stub(name: &str) -> String {
let lower = name.to_lowercase();
let lower = token(name);
format!(
"import {{ Step }} from '@green-tea/core';\n\n@Step({{ provides: '{lower}', needs: [] }})\nexport class {name}Step {{\n run(ctx: Record<string, unknown>) {{\n return {{ {lower}: null }};\n }}\n}}\n"
)
}
fn provider_stub(name: &str) -> String {
let lower = name.to_lowercase();
let lower = token(name);
format!(
"import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n"
)
+233 -215
View File
@@ -1,41 +1,36 @@
//! `matcha graph` and `matcha explain <pattern>` — introspection of the
//! dependency graph the framework builds from `needs`/`provides`.
//! `matcha graph`, `routes`, `tokens`, `explain` and `openapi`: the CLI over
//! [`crate::introspect`].
//!
//! Both work the same way: write a short script next to the project, import its
//! entry file, `await app.ready()`, print, delete the script. `ready()` is the
//! reason this is cheap and safe to run — it resolves the graph and is
//! documented as deliberately *not* running provider factories, so drawing a
//! diagram does not open your database connections. It is also required rather
//! than optional: on a mesh app the graph is not knowable until its teapots
//! have been asked, and `graph()`/`explain()` throw until then.
//!
//! The formatting lives in the generated script rather than here on purpose.
//! Rust would have to parse the JSON back to lay out a chain, and nothing about
//! that layout needs Rust — `console.log` already has the values.
//! Each command asks one [`Query`] and renders the JSON that comes back, as
//! text for a person or, with `--json`, unchanged for a program. An agent
//! inspecting an app uses the second form; the future `matcha mcp` serves the
//! same documents without going through this file at all.
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::path::Path;
use crate::entry;
use crate::runtime::{self, Runtime};
use serde_json::Value;
/// Written into the project root so the runtime resolves `@green-tea/core` from
/// the project's own `node_modules`/import map, then removed. Dotted so it is
/// invisible to a `src/**` glob if a run dies before cleanup.
const SCRIPT_NAME: &str = ".matcha-introspect.ts";
use crate::introspect::{self, Diagram, Query, Refusal, Target};
/// How a command prints its answer.
#[derive(Clone, Copy, PartialEq)]
pub enum Render {
Text,
Json,
}
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
pub fn graph(
dir: &Path,
format: &str,
entry_override: Option<&str>,
entry: Option<&str>,
out: Option<&str>,
) -> std::io::Result<()> {
let print = match format {
"mermaid" => "console.log(app.toMermaid());",
"dot" => "console.log(app.toDOT());",
"json" => "console.log(JSON.stringify(app.graph(), null, 2));",
let (query, render) = match format {
"mermaid" => (Query::Diagram(Diagram::Mermaid), Render::Text),
"dot" => (Query::Diagram(Diagram::Dot), Render::Text),
"json" => (Query::Graph, Render::Json),
other => {
return Err(Error::new(
ErrorKind::InvalidInput,
@@ -43,42 +38,54 @@ pub fn graph(
))
}
};
emit(dir, entry_override, out, print)
answer(dir, entry, out, &query, render, |data| {
data.as_str().unwrap_or_default().to_string()
})
}
/// `matcha routes` — every route, its transport, and the chain it runs.
pub fn routes(
dir: &Path,
entry: Option<&str>,
out: Option<&str>,
render: Render,
) -> std::io::Result<()> {
answer(dir, entry, out, &Query::Routes, render, routes_text)
}
/// `matcha tokens` — every token, who provides it and who needs it. The
/// question to ask before writing `@needs('x')`: does anything provide `x`?
pub fn tokens(
dir: &Path,
entry: Option<&str>,
out: Option<&str>,
render: Render,
) -> std::io::Result<()> {
answer(dir, entry, out, &Query::Tokens, render, tokens_text)
}
/// `matcha explain <pattern>` — one route's chain, in execution order, with
/// each node's needs and provides.
///
/// The argument is the route *pattern* as declared (`/users/:id`), not a
/// concrete URL: `explainRoute` matches the pattern string exactly. A miss
/// therefore lists what is actually registered, which is the only useful thing
/// to say to someone who just guessed wrong.
/// concrete URL: `explain` matches the pattern string exactly. A miss lists
/// what is actually registered, which is the only useful thing to say to
/// someone who just guessed wrong.
pub fn explain(
dir: &Path,
route: &str,
entry_override: Option<&str>,
entry: Option<&str>,
out: Option<&str>,
render: Render,
) -> std::io::Result<()> {
let route = js_string(route);
let body = format!(
r#"let explained;
try {{
explained = app.explain({route});
}} catch {{
const patterns = app.graph().routes.map((r) => ` ${{r.method.padEnd(6)}} ${{r.pattern}}`);
console.error(`no route matching pattern {route}\n\nregistered patterns:\n${{patterns.join('\n')}}`);
process.exit(1);
}}
const lines = [`${{explained.method}} ${{explained.pattern}} [${{explained.transport}}]`];
const width = Math.max(...explained.chain.map((n) => n.kind.length));
for (const node of explained.chain) {{
const needs = node.needs.length ? ` needs: ${{node.needs.join(', ')}}` : '';
const provides = node.provides.length ? ` provides: ${{node.provides.join(', ')}}` : '';
lines.push(` ${{node.kind.padEnd(width)}} ${{node.name}}${{needs}}${{provides}} (${{node.origin}})`);
}}
console.log(lines.join('\n'));"#
);
emit(dir, entry_override, out, &body)
answer(
dir,
entry,
out,
&Query::Explain(route.to_string()),
render,
explain_text,
)
}
/// `matcha openapi` — the structural OpenAPI 3.1 document for the route table.
@@ -91,198 +98,176 @@ pub fn openapi(
dir: &Path,
title: Option<&str>,
version: Option<&str>,
entry_override: Option<&str>,
entry: Option<&str>,
out: Option<&str>,
) -> std::io::Result<()> {
// `app.openapi()` takes an optional info object; passing nothing lets core
// apply its own defaults rather than having the CLI invent a title.
let info = match (title, version) {
(None, None) => String::new(),
(t, v) => {
let mut fields = Vec::new();
if let Some(t) = t {
fields.push(format!("title: {}", js_string(t)));
}
if let Some(v) = v {
fields.push(format!("version: {}", js_string(v)));
}
format!("{{ {} }}", fields.join(", "))
}
let query = Query::OpenApi {
title: title.map(str::to_string),
version: version.map(str::to_string),
};
emit(
dir,
entry_override,
out,
&format!("console.log(JSON.stringify(app.openapi({info}), null, 2));"),
)
answer(dir, entry, out, &query, Render::Json, |_| String::new())
}
/// Resolves the entry, generates the script around `body`, runs it under the
/// detected runtime, and routes its stdout to a file or to ours.
fn emit(
/// Asks, renders, and writes to `out` or stdout. A refusal goes to stderr — as
/// JSON under `--json`, so a program reads the same shape either way — and
/// exits 1. A failed run has already printed its own diagnosis (the child's
/// stderr is inherited), so it exits with no second message on top.
fn answer(
dir: &Path,
entry_override: Option<&str>,
entry: Option<&str>,
out: Option<&str>,
body: &str,
query: &Query,
render: Render,
text: impl Fn(&Value) -> String,
) -> std::io::Result<()> {
let entry_path = match entry_override {
Some(explicit) => {
let p = dir.join(explicit);
if !p.exists() {
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
}
PathBuf::from(explicit)
let target = Target { dir, entry };
let data = match introspect::query(&target, query) {
Ok(Ok(data)) => data,
Ok(Err(refusal)) => {
report_refusal(&refusal, render);
std::process::exit(1);
}
None => entry::find(dir).map(|p| p.strip_prefix(dir).unwrap_or(&p).to_path_buf()).ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
format!(
"no {} found — pass --entry <file>. It must export the app: `export const app = createApp(...)`",
entry::candidates()
),
)
})?,
Err(e) if e.kind() == ErrorKind::Other => std::process::exit(1),
Err(e) => return Err(e),
};
let rt = runtime::detect(dir).ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
"no runtime detected (need deno.json, bun.lock, or package.json)",
)
})?;
let script_path = dir.join(SCRIPT_NAME);
std::fs::write(&script_path, script(&entry_path, body))?;
let result = run(rt, dir, SCRIPT_NAME);
std::fs::remove_file(&script_path).ok();
let output = result?;
// The child has already written its own diagnosis to the inherited stderr —
// a type error, a boot failure, or the script's own "no route matching
// pattern" with the registered ones listed. Wrapping that in a second
// `error: npx exited with 1` adds a line and no information, so the exit
// code is relayed and nothing is said on top of it.
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
let mut printed = match render {
Render::Json => serde_json::to_string_pretty(&data).map_err(Error::other)?,
Render::Text => text(&data),
};
if !printed.ends_with('\n') {
printed.push('\n');
}
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
match out {
Some(file) => {
std::fs::write(dir.join(file), &stdout)?;
std::fs::write(dir.join(file), &printed)?;
println!("✓ {file}");
}
None => print!("{stdout}"),
None => print!("{printed}"),
}
Ok(())
}
/// The generated script: import the app, resolve the graph, run `body`.
fn script(entry_path: &Path, body: &str) -> String {
format!(
"// generated by matcha; safe to delete\nimport {{ app }} from {};\n\nif (!app) {{\n console.error('{} does not export `app` — matcha needs `export const app = createApp(...)`');\n process.exit(1);\n}}\nawait app.ready();\n{body}\n",
js_string(&specifier(entry_path)),
entry_path.display(),
)
}
/// Runs `script` under `rt` in `dir`. The child's stderr is inherited rather
/// than captured: a type error or a boot failure is the reason someone runs
/// this, and it should reach them as it happens.
fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::Output> {
let (prog, args) = runner(rt, script);
let child = Command::new(prog)
.args(&args)
.current_dir(dir)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|e| Error::new(e.kind(), format!("could not run {prog}: {e}")))?;
child.wait_with_output()
}
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
let s = script.to_string();
match rt {
// Edge resolves its graph under node: `src/app.ts` imports core, never
// `edgeHandler`, so nothing here needs workerd — and workerd could not
// print to a terminal anyway.
Runtime::Node | Runtime::Edge => ("npx", vec!["tsx".into(), s]),
// `ready()` opens no provider connections, but a mesh app does reach its
// teapots there, so net is part of resolving the graph rather than extra.
Runtime::Deno => (
"deno",
vec![
"run".into(),
"--allow-read".into(),
"--allow-env".into(),
"--allow-net".into(),
s,
],
),
Runtime::Bun => ("bun", vec!["run".into(), s]),
fn report_refusal(refusal: &Refusal, render: Render) {
if render == Render::Json {
eprintln!("{}", serde_json::json!({ "error": refusal.0 }));
return;
}
}
/// A project-root-relative path as an ES module specifier: forward slashes,
/// always `./`-prefixed, extension kept so Deno resolves it without leaning on
/// `sloppy-imports`.
fn specifier(path: &Path) -> String {
let raw = path.to_string_lossy().replace('\\', "/");
format!("./{}", raw.strip_prefix("./").unwrap_or(&raw))
}
/// Single-quoted JS string literal. Route patterns reach this from argv, so the
/// quote and the backslash have to be escaped rather than assumed absent.
fn js_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('\'');
for ch in value.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'\'' => out.push_str("\\'"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
_ => out.push(ch),
eprintln!("{}", refusal.message());
if let Some(registered) = refusal.0["registered"].as_array() {
eprintln!("\nregistered patterns:");
for r in registered {
eprintln!(" {:<6} {}", str_of(&r["method"]), str_of(&r["pattern"]));
}
}
out.push('\'');
out
}
fn str_of(v: &Value) -> &str {
v.as_str().unwrap_or("")
}
fn list_of(v: &Value) -> Vec<&str> {
v.as_array()
.map(|a| a.iter().map(str_of).collect())
.unwrap_or_default()
}
fn routes_text(data: &Value) -> String {
let routes = data.as_array().cloned().unwrap_or_default();
let width = routes
.iter()
.map(|r| str_of(&r["method"]).len())
.max()
.unwrap_or(0);
routes
.iter()
.map(|r| {
let chain = list_of(&r["chain"]).join(" → ");
format!(
"{:<width$} {} [{}] {}",
str_of(&r["method"]),
str_of(&r["pattern"]),
str_of(&r["transport"]),
chain
)
})
.collect::<Vec<_>>()
.join("\n")
}
fn tokens_text(data: &Value) -> String {
let names = |v: &Value| {
v.as_array()
.map(|a| {
a.iter()
.map(|n| match n["route"].as_str() {
Some(route) => format!("{} ({route})", str_of(&n["name"])),
None => str_of(&n["name"]).to_string(),
})
.collect::<Vec<_>>()
.join(", ")
})
.unwrap_or_default()
};
data.as_array()
.cloned()
.unwrap_or_default()
.iter()
.map(|t| {
let provided = names(&t["providedBy"]);
let needed = names(&t["neededBy"]);
format!(
"{}\n provided by: {}\n needed by: {}",
str_of(&t["token"]),
if provided.is_empty() {
if t["source"] == "request" {
"the request (built in)"
} else {
"— (nothing provides it)"
}
} else {
&provided
},
if needed.is_empty() { "—" } else { &needed },
)
})
.collect::<Vec<_>>()
.join("\n")
}
fn explain_text(data: &Value) -> String {
let chain = data["chain"].as_array().cloned().unwrap_or_default();
let width = chain
.iter()
.map(|n| str_of(&n["kind"]).len())
.max()
.unwrap_or(0);
let mut lines = vec![format!(
"{} {} [{}]",
str_of(&data["method"]),
str_of(&data["pattern"]),
str_of(&data["transport"])
)];
for n in &chain {
let needs = list_of(&n["needs"]);
let provides = list_of(&n["provides"]);
let mut line = format!(" {:<width$} {}", str_of(&n["kind"]), str_of(&n["name"]));
if !needs.is_empty() {
line.push_str(&format!(" needs: {}", needs.join(", ")));
}
if !provides.is_empty() {
line.push_str(&format!(" provides: {}", provides.join(", ")));
}
line.push_str(&format!(" ({})", str_of(&n["origin"])));
lines.push(line);
}
lines.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn specifier_is_dot_slash_prefixed_with_extension() {
assert_eq!(specifier(Path::new("src/app.ts")), "./src/app.ts");
assert_eq!(specifier(Path::new("./src/app.ts")), "./src/app.ts");
}
#[test]
fn js_string_escapes_quote_and_backslash() {
assert_eq!(js_string("a'b"), r"'a\'b'");
assert_eq!(js_string(r"a\b"), r"'a\\b'");
}
#[test]
fn script_imports_the_entry_and_awaits_ready() {
let out = script(Path::new("src/app.ts"), "console.log(1);");
assert!(out.contains("import { app } from './src/app.ts';"));
assert!(out.contains("await app.ready();"));
assert!(out.contains("console.log(1);"));
}
#[test]
fn node_runs_through_tsx() {
assert_eq!(
runner(Runtime::Node, ".matcha-introspect.ts"),
(
"npx",
vec!["tsx".to_string(), ".matcha-introspect.ts".to_string()]
)
);
}
use serde_json::json;
#[test]
fn unknown_format_is_rejected() {
@@ -290,4 +275,37 @@ mod tests {
let err = graph(d.path(), "svg", None, None).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidInput);
}
#[test]
fn explain_text_keeps_the_layout_it_had() {
let data = json!({
"method": "GET", "pattern": "/users/:id", "transport": "http",
"chain": [
{ "kind": "provider", "name": "db", "needs": [], "provides": ["db"], "origin": "src/db.ts" },
{ "kind": "handler", "name": "Users.get", "needs": ["db"], "provides": [], "origin": "src/users.ts" }
]
});
assert_eq!(
explain_text(&data),
"GET /users/:id [http]\n provider db provides: db (src/db.ts)\n handler Users.get needs: db (src/users.ts)"
);
}
#[test]
fn tokens_text_names_the_request_for_its_built_in_tokens() {
let data = json!([{ "token": "req", "source": "request", "providedBy": [], "neededBy": [{ "kind": "step", "name": "user" }] }]);
assert_eq!(
tokens_text(&data),
"req\n provided by: the request (built in)\n needed by: user"
);
}
#[test]
fn tokens_text_says_when_nothing_provides_a_token() {
let data = json!([{ "token": "user", "providedBy": [], "neededBy": [{ "kind": "handler", "name": "Me.get", "route": "/me" }] }]);
assert_eq!(
tokens_text(&data),
"user\n provided by: — (nothing provides it)\n needed by: Me.get (/me)"
);
}
}
+357
View File
@@ -0,0 +1,357 @@
//! `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<String>,
/// `None`: not asked for. `Some(None)`: `--package` with no directory.
pub package: Option<Option<String>>,
pub folder: Option<String>,
pub scope: Option<String>,
pub registry: Option<String>,
pub npm_name: Option<String>,
pub check: bool,
}
pub fn run(opts: Opts) -> io::Result<()> {
run_with(opts, &mut Ask::stdio(), Path::new("."))
}
pub fn run_with<R: BufRead, W: Write>(
opts: Opts,
ask: &mut Ask<R, W>,
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)
}
}
fn invalid(msg: String) -> Error {
Error::new(ErrorKind::InvalidInput, msg)
}
/// 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<String> {
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)
}
fn resolve_slug<R: BufRead, W: Write>(
name: Option<String>,
ask: &mut Ask<R, W>,
) -> io::Result<String> {
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 {
!folder.is_empty()
&& Path::new(folder)
.components()
.all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
}
fn in_app<R: BufRead, W: Write>(opts: Opts, ask: &mut Ask<R, W>, 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")?,
};
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<String> = 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!(
"{entry_shown} already uses `{fun}`, so the plugin's factory would collide with it; pick another name"
)));
}
let shown = Path::new(&folder).join(&slug);
let dir = root.join(&shown);
if dir.exists() {
return Err(Error::new(
ErrorKind::AlreadyExists,
format!("{} already exists", shown.display()),
));
}
let call = format!("{fun}()");
// Both entry candidates live in src/, so the plugin folder is one level up.
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) => {
// 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 {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=<dir> or run it in an empty folder";
const NPM_CONVENTION: &str =
"green-tea-<x> is the naming convention; the plugin listing uses it to find green-tea plugins.";
/// 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 {
(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| {
!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<R: BufRead, W: Write>(
opts: Opts,
ask: &mut Ask<R, W>,
root: &Path,
) -> io::Result<()> {
// 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(),
};
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(format!("{dir_shown}: {EMPTY_DIR}")));
}
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: 2 to 20 lowercase letters, digits or hyphens, not starting with a hyphen"
)));
}
let registry = match opts.registry {
Some(r) => r,
None => {
ask.say(&format!("\n{}\n", plugin_files::JSR_BANNER))?;
ask.choice(
"Publish to: (1) JSR only [default] (2) JSR + npm",
&[("1", "jsr"), ("2", "both")],
"jsr",
"--registry",
)?
.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 };
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}");
}
}
+352
View File
@@ -0,0 +1,352 @@
//! Introspection queries against a project's app: one query in, one JSON
//! document out.
//!
//! This is the data layer under `matcha graph`, `routes`, `tokens`, `explain`
//! and `openapi`. The CLI renders what comes back, as text or with `--json` as
//! it is; a future `matcha mcp` serves the same documents as tools. Keeping the
//! JSON as the contract is what lets that server be a thin layer over
//! [`query`] rather than a second implementation, and it is why the human
//! formatting lives in Rust (`cmd_graph`) instead of in the generated script.
//!
//! How a query runs: write a short script next to the project, import its entry
//! file, `await app.ready()`, print one JSON envelope, delete the script.
//! `ready()` resolves the graph and is documented as *not* running provider
//! factories, so asking about the graph does not open database connections. It
//! is also required: on a mesh app the graph is not knowable until its teapots
//! have been asked, and `graph()`/`explain()` throw until then.
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use serde_json::Value;
use crate::entry;
use crate::runtime::{self, Runtime};
/// Written into the project root so the runtime resolves `@green-tea/core` from
/// the project's own `node_modules`/import map, then removed. Dotted so it is
/// invisible to a `src/**` glob if a run dies before cleanup.
const SCRIPT_NAME: &str = ".matcha-introspect.ts";
/// What to ask the app. Each variant is one future MCP tool.
#[derive(Debug, Clone, PartialEq)]
pub enum Query {
/// The whole graph as data: nodes and routes (`app.graph()`).
Graph,
/// The graph as a diagram string; `mermaid` or `dot`.
Diagram(Diagram),
/// Every route with its transport and the chain it runs.
Routes,
/// Every token: who provides it and who needs it.
Tokens,
/// One route's chain in execution order, by declared pattern.
Explain(String),
/// The structural OpenAPI 3.1 document.
OpenApi {
title: Option<String>,
version: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Diagram {
Mermaid,
Dot,
}
/// A query the app answered with a refusal rather than data — a route pattern
/// that is not registered, say. Carried as JSON so a caller (a person, an agent,
/// an MCP client) gets the same machine-readable reason.
#[derive(Debug, Clone, PartialEq)]
pub struct Refusal(pub Value);
impl Refusal {
pub fn message(&self) -> &str {
self.0["message"].as_str().unwrap_or("query refused")
}
}
/// Where the app lives: the project directory and, optionally, an entry file
/// other than the default `src/app.ts` / `src/main.ts`.
pub struct Target<'a> {
pub dir: &'a Path,
pub entry: Option<&'a str>,
}
/// Runs `query` against the app in `target`. `Ok(Ok(data))` is the answer,
/// `Ok(Err(refusal))` is the app saying no in a structured way, and `Err` is
/// everything that stopped the question being asked — no entry, no runtime, a
/// type error or a failed boot. The child's stderr is inherited, so those reach
/// the terminal as they happen.
pub fn query(target: &Target, query: &Query) -> std::io::Result<Result<Value, Refusal>> {
let entry_path = resolve_entry(target)?;
let rt = runtime::detect(target.dir).ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
"no runtime detected (need deno.json, bun.lock, or package.json)",
)
})?;
let script_path = target.dir.join(SCRIPT_NAME);
std::fs::write(&script_path, script(&entry_path, &body(query)))?;
let result = run(rt, target.dir, SCRIPT_NAME);
std::fs::remove_file(&script_path).ok();
let output = result?;
if !output.status.success() {
return Err(Error::other(format!(
"the app could not be inspected (exit {})",
output.status.code().unwrap_or(1)
)));
}
parse_envelope(&String::from_utf8_lossy(&output.stdout))
}
/// The envelope is the script's last stdout line, so anything the app logs
/// while booting cannot be mistaken for the answer.
fn parse_envelope(stdout: &str) -> std::io::Result<Result<Value, Refusal>> {
let line = stdout
.lines()
.rev()
.find(|l| !l.trim().is_empty())
.unwrap_or("");
let envelope: Value = serde_json::from_str(line).map_err(|e| {
Error::new(
ErrorKind::InvalidData,
format!("the introspection script printed no answer ({e})"),
)
})?;
match envelope["ok"].as_bool() {
Some(true) => Ok(Ok(envelope["data"].clone())),
Some(false) => Ok(Err(Refusal(envelope["error"].clone()))),
None => Err(Error::new(
ErrorKind::InvalidData,
"malformed introspection answer",
)),
}
}
/// The JavaScript expression (or statements ending in `data = …`) that computes
/// the answer. Everything is plain data built from public `App` methods.
fn body(query: &Query) -> String {
match query {
Query::Graph => "data = app.graph();".into(),
Query::Diagram(Diagram::Mermaid) => "data = app.toMermaid();".into(),
Query::Diagram(Diagram::Dot) => "data = app.toDOT();".into(),
Query::Routes => "data = app.graph().routes;".into(),
Query::Tokens => TOKENS.into(),
Query::Explain(pattern) => format!(
r#"try {{
data = app.explain({pattern});
}} catch {{
refuse({{
code: 'route_not_found',
message: `no route matching pattern ${{{pattern}}}`,
registered: app.graph().routes.map((r) => ({{ method: r.method, pattern: r.pattern }})),
}});
}}"#,
pattern = js_string(pattern)
),
Query::OpenApi { title, version } => {
let mut fields = Vec::new();
if let Some(t) = title {
fields.push(format!("title: {}", js_string(t)));
}
if let Some(v) = version {
fields.push(format!("version: {}", js_string(v)));
}
// No info object at all lets core apply its own defaults rather than
// having the CLI invent a title.
let info = if fields.is_empty() {
String::new()
} else {
format!("{{ {} }}", fields.join(", "))
};
format!("data = app.openapi({info});")
}
}
}
/// Tokens, from the graph's nodes plus each route's handler (only `explain`
/// knows what a handler needs). Sorted, so the answer is stable across runs.
///
/// A token that something needs and no node provides is one the request itself
/// carries (`req`, `params`, `body`, …). That is an inference, and a sound one:
/// `app.ready()` has validated the graph, so a needed token with no producer
/// would already have failed it. Marking those `"source": "request"` keeps an
/// agent from reading "nothing provides it" and writing a provider for `req`.
const TOKENS: &str = r#"const tokens = new Map();
const entry = (t) => tokens.get(t) ?? tokens.set(t, { token: t, providedBy: [], neededBy: [] }).get(t);
const graph = app.graph();
for (const n of graph.nodes) {
for (const t of n.provides) entry(t).providedBy.push({ kind: n.kind, name: n.name, origin: n.origin });
for (const t of n.needs) entry(t).neededBy.push({ kind: n.kind, name: n.name, origin: n.origin });
}
for (const pattern of new Set(graph.routes.map((r) => r.pattern))) {
for (const n of app.explain(pattern).chain) {
if (n.kind !== 'handler') continue;
for (const t of n.needs) entry(t).neededBy.push({ kind: 'handler', name: n.name, origin: n.origin, route: pattern });
}
}
for (const t of tokens.values()) t.source = t.providedBy.length ? 'graph' : 'request';
data = [...tokens.values()].sort((a, b) => a.token.localeCompare(b.token));"#;
fn resolve_entry(target: &Target) -> std::io::Result<PathBuf> {
match target.entry {
Some(explicit) => {
if !target.dir.join(explicit).exists() {
return Err(Error::new(ErrorKind::NotFound, format!("no such entry: {explicit}")));
}
Ok(PathBuf::from(explicit))
}
None => entry::find(target.dir)
.map(|p| p.strip_prefix(target.dir).unwrap_or(&p).to_path_buf())
.ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
format!(
"no {} found — pass --entry <file>. It must export the app: `export const app = createApp(...)`",
entry::candidates()
),
)
}),
}
}
/// The generated script: import the app, resolve the graph, run `body`, print
/// one envelope. `refuse` ends the script with a structured error instead of
/// data.
fn script(entry_path: &Path, body: &str) -> String {
format!(
"// generated by matcha; safe to delete\n\
import {{ app }} from {};\n\n\
if (!app) {{\n console.error('{} does not export `app` — matcha needs `export const app = createApp(...)`');\n process.exit(1);\n}}\n\
const refuse = (error) => {{\n console.log(JSON.stringify({{ ok: false, error }}));\n process.exit(0);\n}};\n\
await app.ready();\n\
let data;\n\
{body}\n\
console.log(JSON.stringify({{ ok: true, data }}));\n",
js_string(&specifier(entry_path)),
entry_path.display(),
)
}
/// Runs `script` under `rt` in `dir`, stdout captured, stderr inherited.
fn run(rt: Runtime, dir: &Path, script: &str) -> std::io::Result<std::process::Output> {
let (prog, args) = runner(rt, script);
let child = Command::new(prog)
.args(&args)
.current_dir(dir)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.map_err(|e| Error::new(e.kind(), format!("could not run {prog}: {e}")))?;
child.wait_with_output()
}
fn runner(rt: Runtime, script: &str) -> (&'static str, Vec<String>) {
let s = script.to_string();
match rt {
// Edge resolves its graph under node: `src/app.ts` imports core, never
// `edgeHandler`, so nothing here needs workerd — and workerd could not
// print to a terminal anyway.
Runtime::Node | Runtime::Edge => ("npx", vec!["tsx".into(), s]),
// `ready()` opens no provider connections, but a mesh app does reach its
// teapots there, so net is part of resolving the graph rather than extra.
Runtime::Deno => (
"deno",
vec![
"run".into(),
"--allow-read".into(),
"--allow-env".into(),
"--allow-net".into(),
s,
],
),
Runtime::Bun => ("bun", vec!["run".into(), s]),
}
}
/// A project-root-relative path as an ES module specifier: forward slashes,
/// always `./`-prefixed, extension kept so Deno resolves it without leaning on
/// `sloppy-imports`.
fn specifier(path: &Path) -> String {
let raw = path.to_string_lossy().replace('\\', "/");
format!("./{}", raw.strip_prefix("./").unwrap_or(&raw))
}
/// Single-quoted JS string literal. Route patterns reach this from argv, so the
/// quote and the backslash have to be escaped rather than assumed absent.
pub(crate) fn js_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('\'');
for ch in value.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'\'' => out.push_str("\\'"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
_ => out.push(ch),
}
}
out.push('\'');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn specifier_is_dot_slash_prefixed_with_extension() {
assert_eq!(specifier(Path::new("src/app.ts")), "./src/app.ts");
assert_eq!(specifier(Path::new("./src/app.ts")), "./src/app.ts");
}
#[test]
fn js_string_escapes_quote_and_backslash() {
assert_eq!(js_string("a'b"), r"'a\'b'");
assert_eq!(js_string(r"a\b"), r"'a\\b'");
}
#[test]
fn script_imports_the_entry_awaits_ready_and_prints_one_envelope() {
let out = script(Path::new("src/app.ts"), "data = 1;");
assert!(out.contains("import { app } from './src/app.ts';"));
assert!(out.contains("await app.ready();"));
assert!(out.contains("data = 1;"));
assert!(out.contains("JSON.stringify({ ok: true, data })"));
}
#[test]
fn node_runs_through_tsx() {
assert_eq!(
runner(Runtime::Node, ".matcha-introspect.ts"),
(
"npx",
vec!["tsx".to_string(), ".matcha-introspect.ts".to_string()]
)
);
}
#[test]
fn the_envelope_is_the_last_line_so_boot_logs_cannot_pose_as_the_answer() {
let out = "{\"level\":\"info\",\"msg\":\"booted\"}\n{\"ok\":true,\"data\":[1]}\n";
assert_eq!(parse_envelope(out).unwrap(), Ok(serde_json::json!([1])));
}
#[test]
fn a_refusal_comes_back_structured() {
let out =
"{\"ok\":false,\"error\":{\"code\":\"route_not_found\",\"message\":\"no route\"}}";
let refusal = parse_envelope(out).unwrap().unwrap_err();
assert_eq!(refusal.0["code"], "route_not_found");
assert_eq!(refusal.message(), "no route");
}
#[test]
fn explain_escapes_the_pattern() {
assert!(body(&Query::Explain("/a'b".into())).contains(r"app.explain('/a\'b')"));
}
}
+95 -3
View File
@@ -1,12 +1,18 @@
mod ask;
mod check;
mod cli;
mod cmd_add;
mod cmd_agents;
mod cmd_create;
mod cmd_doctor;
mod cmd_graph;
mod cmd_new;
mod cmd_plugin;
mod cmd_run;
mod entry;
mod introspect;
mod naming;
mod plugin_files;
mod runtime;
mod template;
mod wire;
@@ -33,8 +39,58 @@ 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 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,
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);
}
}
Command::Agents { force } => {
if let Err(e) = cmd_agents::run(std::path::Path::new("."), force) {
eprintln!("error: {e}");
std::process::exit(1);
}
@@ -73,12 +129,40 @@ fn main() {
std::process::exit(1);
}
}
Command::Explain { route, entry, out } => {
Command::Explain {
route,
entry,
out,
json,
} => {
if let Err(e) = cmd_graph::explain(
std::path::Path::new("."),
&route,
entry.as_deref(),
out.as_deref(),
render(json),
) {
eprintln!("error: {e}");
std::process::exit(1);
}
}
Command::Routes { entry, out, json } => {
if let Err(e) = cmd_graph::routes(
std::path::Path::new("."),
entry.as_deref(),
out.as_deref(),
render(json),
) {
eprintln!("error: {e}");
std::process::exit(1);
}
}
Command::Tokens { entry, out, json } => {
if let Err(e) = cmd_graph::tokens(
std::path::Path::new("."),
entry.as_deref(),
out.as_deref(),
render(json),
) {
eprintln!("error: {e}");
std::process::exit(1);
@@ -95,3 +179,11 @@ fn main() {
}
}
}
fn render(json: bool) -> cmd_graph::Render {
if json {
cmd_graph::Render::Json
} else {
cmd_graph::Render::Text
}
}
+151
View File
@@ -0,0 +1,151 @@
//! 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<String> {
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<Item = &str> {
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::<String>()
}
/// 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)
}
#[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 reserved_words_and_uses_are_found() {
assert!(is_reserved("delete"));
assert!(is_reserved("class"));
assert!(!is_reserved("pluginAlgo"));
}
#[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");
}
}
+293
View File
@@ -0,0 +1,293 @@
//! 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};
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
/// 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 }}),
}});
}},
}};
}}
"
)
}
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<String>,
}
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(),
),
("LICENSE".to_string(), license(p)),
(
".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",
"nodeModulesDir": "auto",
"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", "LICENSE", "deno.json"]
}}
}}
"#,
name = p.jsr_name()
)
}
const ENGINES: &str = r#" "engines": {
"node": ">=22.18",
"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,
"license": "MIT",
"type": "module",
{ENGINES}
"scripts": {{
"test": "node --test test/*.test.ts"
}},
"devDependencies": {{
"@green-tea/core": "{CORE_VERSION}",
"@types/node": "^22"
}}
}}
"#,
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}",
"@types/node": "^22",
"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, 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 () => {{
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/);
}});
"
)
}
/// 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);
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}()] }});
```
## 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
"
)
}
+54 -9
View File
@@ -13,8 +13,8 @@ use crate::runtime::Runtime;
/// pin to the oldest matching prerelease that nothing can move off. When core
/// 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";
/// behind the `latest` dist-tag, which is what keeps it current.
pub const CORE_VERSION: &str = "26.11.0-rc.1";
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
@@ -50,11 +50,7 @@ fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
std::fs::create_dir_all(parent)?;
}
let contents = std::str::from_utf8(f.contents())
.map(|s| {
s.replace("{{project_name}}", name)
.replace("{{core_version}}", CORE_VERSION)
.into_bytes()
})
.map(|s| render(s, name, CORE_VERSION).into_bytes())
.unwrap_or_else(|_| f.contents().to_vec());
std::fs::write(out, contents)?;
}
@@ -63,6 +59,28 @@ fn write_dir(dir: &Dir, dest: &Path, name: &str) -> std::io::Result<()> {
Ok(())
}
fn render(template: &str, project_name: &str, core_version: &str) -> String {
template
.replace("{{project_name}}", project_name)
.replace("{{core_version}}", core_version)
}
/// The files that tell a coding agent how this project and green-tea work:
/// `AGENTS.md` (read by Codex, OpenCode and others) and a `CLAUDE.md` that
/// imports it. `matcha new` writes them with the starter; `matcha agents`
/// writes them into a project that predates them.
pub const AGENT_FILES: [&str; 2] = ["AGENTS.md", "CLAUDE.md"];
/// Renders one of [`AGENT_FILES`] for a project already on `core_version`.
pub fn agent_file(file: &str, project_name: &str, core_version: &str) -> Option<String> {
let f = SHARED.get_file(file)?;
Some(render(
std::str::from_utf8(f.contents()).ok()?,
project_name,
core_version,
))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -122,6 +140,28 @@ mod tests {
}
}
/// Every starter tells a coding agent where green-tea's rules are, with the
/// version it was scaffolded on, and points it at the introspection
/// commands rather than at guessing.
#[test]
fn every_runtime_scaffolds_the_agent_files() {
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun, Runtime::Edge] {
let d = tempdir().unwrap();
write_starter(d.path(), "my-api", rt).unwrap();
let agents = std::fs::read_to_string(d.path().join("AGENTS.md")).unwrap();
assert!(agents.contains("# AGENTS.md — my-api"), "{rt:?}");
assert!(agents.contains(CORE_VERSION), "{rt:?}");
assert!(!agents.contains("{{"), "{rt:?} left a placeholder");
assert!(agents.contains("matcha tokens --json"), "{rt:?}");
assert!(
agents.contains("node_modules/@green-tea/core/llms.txt"),
"{rt:?}"
);
let claude = std::fs::read_to_string(d.path().join("CLAUDE.md")).unwrap();
assert_eq!(claude.trim(), "@AGENTS.md", "{rt:?}");
}
}
#[test]
fn deno_writes_shared_and_deno_overlay() {
let d = tempdir().unwrap();
@@ -137,7 +177,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 +220,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());
}
}
+80 -7
View File
@@ -215,15 +215,43 @@ pub fn add_to_module_array(src: &str, key: &str, symbol: &str) -> Option<String>
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<String> {
/// 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`.
/// 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<String> {
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<String> {
add_to_createapp(src, "modules", symbol)
}
/// Inserts `symbol` into the `key: [...]` array directly inside `object`
@@ -233,7 +261,7 @@ pub fn add_to_createapp_modules(src: &str, symbol: &str) -> Option<String> {
fn insert_into_object_array(src: &str, object: Node, key: &str, symbol: &str) -> Option<String> {
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() {
@@ -277,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<String> {
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::<Vec<_>>().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.
@@ -445,6 +499,25 @@ fn find_module_object<'a>(root: &Node<'a>, src: &str) -> Option<Node<'a>> {
#[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";
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';
+5 -1
View File
@@ -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');
+5 -1
View File
@@ -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');
-9
View File
@@ -1,9 +0,0 @@
# core is installed from JSR here, and from npm on every other runtime.
#
# Not a preference: the npm ESM build carries tsup's
# `createRequire(import.meta.url)` banner at module scope, and `import.meta.url`
# is undefined on workerd — so `@green-tea/core/edge` throws at load, before any
# of its own code runs. JSR publishes transpiled source with no bundler and no
# banner, and boots clean. See Green-Tea/core#93; once that is fixed this file
# and the `npm:@jsr/...` alias in package.json can both go.
@jsr:registry=https://npm.jsr.io
+2 -1
View File
@@ -2,7 +2,8 @@
"name": "{{project_name}}",
"type": "module",
"private": true,
"engines": { "node": ">=22" },
"scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy" },
"dependencies": { "@green-tea/core": "npm:@jsr/green-tea__core@{{core_version}}" },
"dependencies": { "@green-tea/core": "{{core_version}}" },
"devDependencies": { "tsx": "^4", "typescript": "^5", "wrangler": "^4" }
}
+1
View File
@@ -2,6 +2,7 @@
"name": "{{project_name}}",
"type": "module",
"private": true,
"engines": { "node": ">=22" },
"scripts": { "dev": "tsx watch src/main.ts" },
"dependencies": { "@green-tea/core": "{{core_version}}" },
"devDependencies": { "tsx": "^4", "typescript": "^5" }
+3 -1
View File
@@ -1,4 +1,6 @@
import { app } from './app';
app.listen(3000);
// Awaited, so a boot or bind failure stops the process with its own error instead of surfacing
// later as an unhandled rejection.
await app.listen(3000);
console.log('🍵 green-tea running on http://localhost:3000');
+58
View File
@@ -0,0 +1,58 @@
# AGENTS.md — {{project_name}}
A [green-tea](https://green-tea.expressive-tea.io/docs/) app (`@green-tea/core` {{core_version}}), scaffolded by
matcha. Read this before editing.
## green-tea is not Express
green-tea is new, so code that looks right from Express, Fastify or NestJS habits is usually wrong here.
- The request pipeline is a **dependency graph**, not a middleware chain. There is no `app.use`, no
`next()`, and nothing mutates `req` or `res`.
- A `@Provider` builds a value once at boot. A `@Step` computes a value per request. Each declares
`provides` and `needs`, and green-tea derives the order from those declarations.
- A handler declares what it needs **in its signature**: `@needs('user')`, `@param('id')`, `@body()`,
`@query()`, `@cookie('name')`. Return a value to answer: an object becomes JSON 200, `undefined` becomes 204.
Throw `Unauthorized`, `NotFound` or another `HttpError` to fail the request.
- `createApp` validates the graph at boot. A token nothing provides, a token with two producers, or a node
that needs what it provides all fail before the app serves anything.
- **Reuse what the graph already has.** Before writing a new step, check whether a token you need, such as
`user`, already exists. Before writing `@needs('x')`, check that something provides `x`.
## Look before you edit
Ask the app what it contains instead of guessing. These commands read `src/app.ts` without starting a
server or opening connections:
```bash
matcha routes --json # every route, its transport, and the chain it runs
matcha tokens --json # every token: who provides it, who needs it
matcha explain /some/:pattern --json # one route's chain, in execution order
matcha graph --format json # the whole graph
```
`explain` takes the route **pattern** as declared (`/users/:id`), not a URL.
## Where things are
- `src/app.ts` builds and exports `app` (`createApp({ modules: [...] })`). Introspection and tests import it.
- `src/main.ts` serves `app`. It is the only file that differs per runtime.
- `src/app.module.ts` lists the providers, steps and controllers with `@Module`.
- `matcha create controller|step|provider|module <Name>` generates a piece and wires it into the module.
- `matcha add sse|ws|upload|stream|buffer` adds a capability to a controller.
## Check your work
- Type-check: `npx tsc --noEmit` (Node, edge), `deno check src/main.ts` (Deno), `bunx tsc --noEmit` (Bun).
- Test without a port: `await app.fetch(new Request('http://x/api/thing'))` returns a `Response`.
- `matcha doctor` finds the misconfigurations that fail confusingly.
## The full guide
The rules, decorators, built-in tokens and common mistakes for the installed version are in the package
itself:
- npm / Bun: `node_modules/@green-tea/core/llms.txt`
- Deno (JSR): `https://jsr.io/@green-tea/core/{{core_version}}/llms.txt`
The complete docs as one file: https://green-tea.expressive-tea.io/docs/llms-full.txt
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+34
View File
@@ -199,3 +199,37 @@ fn add_rejects_a_controller_path_that_does_not_exist() {
.failure()
.stderr(predicates::str::contains("no such controller"));
}
#[test]
fn add_cookie_reads_with_the_decorator_and_writes_through_a_transformer() {
let d = tempdir().unwrap();
std::fs::create_dir_all(d.path().join("src/controllers")).unwrap();
std::fs::write(
d.path().join("src/controllers/home.controller.ts"),
"import { Route, Get } from '@green-tea/core';\n\n\
@Route('/')\nexport class HomeController {\n @Get('/')\n home() {}\n}\n",
)
.unwrap();
for _ in 0..2 {
Command::cargo_bin("matcha")
.unwrap()
.current_dir(d.path())
.args(["add", "cookie"])
.assert()
.success();
}
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
assert!(out.contains("@cookie('theme')"), "{out}");
assert!(out.contains("'set-cookie': setCookie("), "{out}");
for symbol in ["Post", "Transformer", "body", "cookie", "setCookie"] {
assert!(
out.contains(&format!("{symbol},")) || out.contains(&format!("{symbol} }}")),
"{symbol} not imported:\n{out}"
);
}
assert_eq!(
out.matches("@Post('/prefs')").count(),
1,
"not idempotent:\n{out}"
);
}
+4 -1
View File
@@ -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")
+77
View File
@@ -119,3 +119,80 @@ fn create_module_prefers_app_ts_over_main_ts() {
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
assert!(!main.contains("UsersModule"), "main.ts was edited: {main}");
}
fn create(dir: &std::path::Path, kind: &str, name: &str) -> assert_cmd::assert::Assert {
Command::cargo_bin("matcha")
.unwrap()
.current_dir(dir)
.args(["create", kind, name])
.assert()
}
#[test]
fn create_step_keeps_camel_case_in_the_token_and_reads_kebab_input() {
let d = tempdir().unwrap();
seed_module(d.path());
create(d.path(), "step", "current-user").success();
let step = std::fs::read_to_string(d.path().join("src/steps/currentuser.step.ts")).unwrap();
assert!(step.contains("class CurrentUserStep"), "{step}");
assert!(step.contains("provides: 'currentUser'"), "{step}");
assert!(step.contains("return { currentUser: null }"), "{step}");
}
#[test]
fn create_refuses_a_token_core_already_provides() {
let d = tempdir().unwrap();
seed_module(d.path());
create(d.path(), "provider", "Logger")
.failure()
.stderr(predicates::str::contains("core already provides"));
create(d.path(), "step", "req").failure();
assert!(!d.path().join("src/providers/logger.provider.ts").exists());
}
#[test]
fn create_refuses_a_name_that_cannot_be_a_class() {
let d = tempdir().unwrap();
seed_module(d.path());
create(d.path(), "controller", "2fast").failure();
create(d.path(), "controller", "us.ers").failure();
}
#[test]
fn create_does_not_overwrite_an_existing_file() {
let d = tempdir().unwrap();
seed_module(d.path());
create(d.path(), "controller", "Users").success();
let file = d.path().join("src/controllers/users.controller.ts");
std::fs::write(&file, "// edited\n").unwrap();
create(d.path(), "controller", "Users")
.failure()
.stderr(predicates::str::contains("already exists"));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "// edited\n");
}
#[test]
fn create_transformer_writes_a_typed_function_and_says_where_it_goes() {
let d = tempdir().unwrap();
seed_module(d.path());
create(d.path(), "transformer", "csv-export")
.success()
.stdout(predicates::str::contains(
"@Transformer(csvExportTransformer)",
));
let file = std::fs::read_to_string(d.path().join("src/transformers/csvexport.transformer.ts"))
.unwrap();
assert!(
file.contains("import type { TransformerFn } from '@green-tea/core'"),
"{file}"
);
assert!(
file.contains("export const csvExportTransformer: TransformerFn"),
"{file}"
);
let module = std::fs::read_to_string(d.path().join("src/app.module.ts")).unwrap();
assert!(
!module.contains("Transformer"),
"a transformer is not a module member:\n{module}"
);
}
+630
View File
@@ -0,0 +1,630 @@
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"));
}
fn files_under(dir: &std::path::Path) -> Vec<String> {
fn walk(base: &std::path::Path, dir: &std::path::Path, out: &mut Vec<String>) {
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",
"LICENSE",
"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.11.0-rc.1"), "{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}");
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-<x> 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"));
}
#[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}"
);
}
}
/// 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}");
}
#[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();
// 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()
.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}");
}
}