feat(graph): draw the graph, and stop scaffolding a two-month-old core
The CLI's last feature work was 12 July; core has shipped 26.8 and 26.9 since. Two consequences, fixed together because they share an entry-file convention. Every runtime overlay pinned `^26.7.0-beta.0`. Core is prerelease-only, and npm's semver excludes a prerelease from any range whose comparators carry a different major.minor.patch — so that caret is not a loose pin, it is a pin to the oldest matching prerelease that nothing can move off. Every project `matcha new` has produced since July installed 26.7.0-beta.0 and could not upgrade: no logger, no request budget, no resumable `@Sse` id, and none of the crashes 26.9 fixed. The pin is now exact, lives in one `CORE_VERSION` const, and Deno resolves through JSR — which is core's native path for Deno and the one 26.9 repaired. Nothing caught that because CI never ran JavaScript. `cargo test` proves the CLI writes the files it means to write; it cannot prove those files describe a project the current core will run. `scripts/starter-smoke.sh` scaffolds, installs, type-checks, boots, curls `/` and the `/zen` stream, and introspects a real starter per runtime; a weekly job fails when the pin falls behind the `beta` dist-tag. The smoke immediately found a second defect: the bun overlay carried no Bun types, so `tsc --noEmit` — and therefore `matcha create --check` — failed on every bun project the CLI has ever scaffolded. `matcha graph` and `matcha explain <pattern>` close the widest gap in the surface: the framework's claim is that an API is a graph rather than a middleware chain, `toMermaid`/`toDOT`/`graph`/`explain` have been exported all along, and the CLI could not draw any of it. Both reach the app through `app.ready()`, which resolves the graph and is documented as deliberately not running provider factories — asking for a diagram must not open your database connections. Formatting lives in the generated script rather than in Rust, which keeps serde out for output `console.log` already has the values for. That needed an app the CLI can import without binding a port, so the starter now composes the graph in `src/app.ts` and leaves `src/main.ts` holding only the serve call. `create module` follows, preferring `src/app.ts` and falling back to `src/main.ts` so projects scaffolded before the split keep working. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012x1UPw987zNSxjH2DxHy2C
This commit is contained in:
21 files changed
+747
-27
No files matched your search
@@ -6,6 +6,10 @@ on:
|
||||
branches: [develop, main]
|
||||
push:
|
||||
branches: [develop, main]
|
||||
# Weekly, so a core release that breaks the starter or leaves the pin behind
|
||||
# shows up here rather than in somebody's `matcha new`.
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
|
||||
jobs:
|
||||
check:
|
||||
@@ -21,3 +25,53 @@ jobs:
|
||||
- run: cargo fmt --check
|
||||
- run: cargo clippy --all-targets -- -D warnings
|
||||
- run: cargo test --locked
|
||||
|
||||
# `cargo test` proves the CLI writes the files it means to write. It cannot
|
||||
# prove those files describe a project the current @green-tea/core will run —
|
||||
# which is how the templates sat two core releases behind for two months with
|
||||
# a green build the whole time. This job scaffolds, installs, type-checks,
|
||||
# boots and introspects a real starter, per runtime.
|
||||
starter:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
runtime: [node, deno, bun]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: |
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
|
||||
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||
- run: cargo build
|
||||
- name: Install Deno
|
||||
if: matrix.runtime == 'deno'
|
||||
run: |
|
||||
curl -fsSL https://deno.land/install.sh | sh -s -- --yes
|
||||
echo "$HOME/.deno/bin" >> "$GITHUB_PATH"
|
||||
- name: Install Bun
|
||||
if: matrix.runtime == 'bun'
|
||||
run: |
|
||||
curl -fsSL https://bun.sh/install | bash
|
||||
echo "$HOME/.bun/bin" >> "$GITHUB_PATH"
|
||||
- run: scripts/starter-smoke.sh ${{ matrix.runtime }}
|
||||
|
||||
# The pin in src/template.rs is exact because core is prerelease-only and no
|
||||
# caret range can move off its first matching prerelease. Exact pins go stale
|
||||
# silently, so this is the thing that notices. Scheduled only: a core release
|
||||
# should nag on Monday, not redden an unrelated pull request.
|
||||
core-freshness:
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Compare the scaffold pin against the beta dist-tag
|
||||
run: |
|
||||
pinned=$(grep -oP 'CORE_VERSION: &str = "\K[^"]+' src/template.rs)
|
||||
latest=$(npm view @green-tea/core dist-tags.beta)
|
||||
echo "pinned=$pinned latest=$latest"
|
||||
if [ "$pinned" != "$latest" ]; then
|
||||
echo "::error::matcha scaffolds @green-tea/core@$pinned but the beta tag is $latest."
|
||||
echo "Bump CORE_VERSION in src/template.rs and let the starter job prove it still boots."
|
||||
exit 1
|
||||
fi
|
||||
@@ -37,6 +37,8 @@ matcha new my-api --template-url gh:owner/repo # scaffold from any git templat
|
||||
matcha run # detect node/deno/bun and run in watch
|
||||
matcha create controller Users # generate + auto-wire into @Module
|
||||
matcha add sse # add a capability (sse|stream|buffer) to your controller
|
||||
matcha graph # draw the dependency graph
|
||||
matcha explain /users/:id # one route's chain, in execution order
|
||||
```
|
||||
|
||||
### The starter
|
||||
@@ -45,6 +47,39 @@ matcha add sse # add a capability (sse|stream|buffer
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
The `@green-tea/core` version is pinned exactly, not with a caret. Core is
|
||||
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.
|
||||
|
||||
### Introspection
|
||||
|
||||
green-tea derives execution order from what each node declares it `needs` and
|
||||
`provides`, so the graph is a real artifact rather than a diagram someone drew.
|
||||
`matcha graph` prints it and `matcha explain` prints one route's slice of it.
|
||||
|
||||
```bash
|
||||
matcha graph # Mermaid (default)
|
||||
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
|
||||
```
|
||||
|
||||
Both import `src/app.ts` (override with `--entry`) and call `app.ready()`, which
|
||||
resolves the graph and deliberately does **not** run provider factories — asking
|
||||
for a diagram will not open your database connections. Your dependencies have to
|
||||
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.
|
||||
|
||||
### `create` / `add` auto-wiring
|
||||
|
||||
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
||||
@@ -63,6 +98,18 @@ idempotent and revert themselves if they would break the file's syntax. Pass
|
||||
|
||||
Edge is a deploy target, not a `matcha run` target.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
cargo test # unit + CLI integration
|
||||
scripts/starter-smoke.sh node # scaffold, install, type-check, boot, introspect
|
||||
scripts/starter-smoke.sh deno # (also bun) — needs that runtime installed
|
||||
```
|
||||
|
||||
`starter-smoke.sh` is the check that `cargo test` cannot be: `cargo test` proves
|
||||
the CLI writes the files it means to write, not that those files describe a
|
||||
project the current core will run.
|
||||
|
||||
## License
|
||||
|
||||
MIT — same as the green-tea framework. Contributions require a DCO sign-off (`git commit -s`).
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Scaffolds a starter with the matcha binary, installs it, type-checks it, boots
|
||||
# it, and asks it for its graph.
|
||||
#
|
||||
# This is the check the repository did not have. `cargo test` proves the CLI
|
||||
# writes the files it means to write; it cannot prove those files describe a
|
||||
# project the current `@green-tea/core` will run — which is exactly how the
|
||||
# templates sat two core releases behind for two months without a red build.
|
||||
#
|
||||
# Usage: scripts/starter-smoke.sh <node|deno|bun>
|
||||
set -euo pipefail
|
||||
|
||||
RUNTIME="${1:?usage: starter-smoke.sh <node|deno|bun>}"
|
||||
MATCHA="${MATCHA:-$PWD/target/debug/matcha}"
|
||||
[ -x "$MATCHA" ] || { echo "no matcha binary at $MATCHA (cargo build first)" >&2; exit 2; }
|
||||
|
||||
case "$RUNTIME" in
|
||||
node) TEMPLATE_PORT=3000; INSTALL=(npm install); CHECK=(npx --yes tsc --noEmit) ;;
|
||||
deno) TEMPLATE_PORT=8000; INSTALL=(deno install); CHECK=(deno check src/main.ts) ;;
|
||||
bun) TEMPLATE_PORT=8000; INSTALL=(bun install); CHECK=(bunx --bun tsc --noEmit) ;;
|
||||
*) echo "unknown runtime: $RUNTIME" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
# The starter hardcodes its port, so the script rewrites it to a free one rather
|
||||
# than colliding with whatever the person running this already has on 3000. A
|
||||
# check that only survives on a clean CI runner is a check nobody runs locally.
|
||||
PORT="${PORT:-$((20000 + RANDOM % 20000))}"
|
||||
|
||||
WORK="$(mktemp -d)"
|
||||
SERVER=""
|
||||
cleanup() {
|
||||
[ -n "$SERVER" ] && { pkill -P "$SERVER" 2>/dev/null || true; kill "$SERVER" 2>/dev/null || true; }
|
||||
rm -rf "$WORK"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
cd "$WORK"
|
||||
echo "▸ matcha new demo --runtime $RUNTIME"
|
||||
"$MATCHA" new demo --runtime "$RUNTIME"
|
||||
cd demo
|
||||
sed -i.bak "s/$TEMPLATE_PORT/$PORT/g" src/main.ts && rm -f src/main.ts.bak
|
||||
|
||||
echo "▸ ${INSTALL[*]}"
|
||||
"${INSTALL[@]}"
|
||||
|
||||
echo "▸ ${CHECK[*]}"
|
||||
"${CHECK[@]}"
|
||||
|
||||
echo "▸ matcha run (boot on :$PORT)"
|
||||
"$MATCHA" run >"$WORK/server.log" 2>&1 &
|
||||
SERVER=$!
|
||||
for _ in $(seq 1 60); do
|
||||
curl -fsS -o /dev/null "http://localhost:$PORT/" 2>/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# The starter's two halves: the @Html page, and the @Sse stream that is the
|
||||
# reason the starter is alive rather than a JSON hello.
|
||||
code=$(curl -fsS -o /dev/null -w '%{http_code}' "http://localhost:$PORT/" 2>/dev/null || echo 000)
|
||||
[ "$code" = 200 ] || { echo "GET / returned $code"; echo '--- server log ---'; cat "$WORK/server.log"; exit 1; }
|
||||
# Read one frame and stop. `head -1` closing the pipe kills curl with SIGPIPE,
|
||||
# which under `pipefail` fails the pipeline for a stream that arrived exactly as
|
||||
# intended — hence the capture-then-compare instead of a piped `grep -q`.
|
||||
zen="$(curl -fsS -N --max-time 5 "http://localhost:$PORT/zen" 2>/dev/null | head -1 || true)"
|
||||
case "$zen" in
|
||||
'data: {"zen":'*) ;;
|
||||
*) echo "GET /zen did not stream an SSE frame (got: ${zen:-<nothing>})"; cat "$WORK/server.log"; exit 1 ;;
|
||||
esac
|
||||
echo "✓ serves / and streams /zen"
|
||||
|
||||
pkill -P "$SERVER" 2>/dev/null || true; kill "$SERVER" 2>/dev/null || true; SERVER=""
|
||||
|
||||
# Introspection runs against the same project, so it also proves the entry file
|
||||
# the templates scaffold still exports the `app` that graph/explain import.
|
||||
echo "▸ matcha graph"
|
||||
"$MATCHA" graph | grep -q '^flowchart LR' || { echo "graph produced no mermaid"; exit 1; }
|
||||
"$MATCHA" graph --format dot | grep -q '^digraph green_tea' || { echo "graph produced no DOT"; exit 1; }
|
||||
"$MATCHA" explain /zen | grep -q '\[sse\]' || { echo "explain did not report the sse route"; exit 1; }
|
||||
echo "✓ graph and explain resolve"
|
||||
|
||||
echo "✓ $RUNTIME starter is good"
|
||||
+20
@@ -27,6 +27,26 @@ pub enum Command {
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
},
|
||||
/// Print the dependency graph (Mermaid, DOT, or JSON)
|
||||
Graph {
|
||||
#[arg(long, default_value = "mermaid", value_parser = ["mermaid", "dot", "json"])]
|
||||
format: String,
|
||||
/// Entry file exporting `app` (default: src/app.ts, then src/main.ts)
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
/// Write to this file instead of stdout
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Explain one route's chain, in execution order
|
||||
Explain {
|
||||
/// The route pattern as declared, e.g. /users/:id
|
||||
route: String,
|
||||
#[arg(long)]
|
||||
entry: Option<String>,
|
||||
#[arg(long)]
|
||||
out: Option<String>,
|
||||
},
|
||||
/// Add a capability to a controller
|
||||
Add {
|
||||
#[arg(value_parser = ["sse", "stream", "buffer"])]
|
||||
|
||||
+12
-9
@@ -5,7 +5,7 @@
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::Path;
|
||||
|
||||
use crate::wire;
|
||||
use crate::{entry, wire};
|
||||
|
||||
pub fn run(kind: &str, name: &str, check: bool) -> std::io::Result<()> {
|
||||
match kind {
|
||||
@@ -86,7 +86,7 @@ fn create_piece(
|
||||
}
|
||||
|
||||
/// Writes `src/<name>.module.ts` and registers it in the `createApp({ modules })`
|
||||
/// call in `src/main.ts`. Emit-only + hint on failure.
|
||||
/// call in the project's entry file. Emit-only + hint on failure.
|
||||
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"));
|
||||
@@ -96,20 +96,23 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> {
|
||||
|
||||
let symbol = format!("{name}Module");
|
||||
let from = format!("./{lower}.module");
|
||||
let main_path = Path::new("src/main.ts");
|
||||
if !main_path.exists() {
|
||||
println!("→ register {symbol} in createApp({{ modules }}) manually (no src/main.ts found)");
|
||||
let Some(entry_path) = entry::find(Path::new(".")) else {
|
||||
println!(
|
||||
"→ register {symbol} in createApp({{ modules }}) manually (no {} found)",
|
||||
entry::candidates()
|
||||
);
|
||||
return maybe_check(check);
|
||||
}
|
||||
let src = std::fs::read_to_string(main_path)?;
|
||||
};
|
||||
let src = std::fs::read_to_string(&entry_path)?;
|
||||
let imported = wire::add_import(&src, &symbol, &from);
|
||||
match wire::add_to_createapp_modules(&imported, &symbol) {
|
||||
Some(wired) => {
|
||||
std::fs::write(main_path, wired)?;
|
||||
std::fs::write(&entry_path, wired)?;
|
||||
println!("✓ registered {symbol} in createApp");
|
||||
}
|
||||
None => println!(
|
||||
"→ could not auto-register; add {symbol} to createApp modules[] in src/main.ts"
|
||||
"→ could not auto-register; add {symbol} to createApp modules[] in {}",
|
||||
entry_path.display()
|
||||
),
|
||||
}
|
||||
maybe_check(check)
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! `matcha graph` and `matcha explain <pattern>` — introspection of the
|
||||
//! dependency graph the framework builds from `needs`/`provides`.
|
||||
//!
|
||||
//! 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.
|
||||
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
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";
|
||||
|
||||
/// `matcha graph` — the whole graph, as Mermaid, Graphviz DOT, or JSON.
|
||||
pub fn graph(
|
||||
dir: &Path,
|
||||
format: &str,
|
||||
entry_override: 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));",
|
||||
other => {
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown format '{other}' (mermaid, dot, json)"),
|
||||
))
|
||||
}
|
||||
};
|
||||
emit(dir, entry_override, out, print)
|
||||
}
|
||||
|
||||
/// `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.
|
||||
pub fn explain(
|
||||
dir: &Path,
|
||||
route: &str,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
) -> 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)
|
||||
}
|
||||
|
||||
/// 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(
|
||||
dir: &Path,
|
||||
entry_override: Option<&str>,
|
||||
out: Option<&str>,
|
||||
body: &str,
|
||||
) -> 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)
|
||||
}
|
||||
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()
|
||||
),
|
||||
)
|
||||
})?,
|
||||
};
|
||||
|
||||
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 stdout = String::from_utf8_lossy(&output.stdout).into_owned();
|
||||
match out {
|
||||
Some(file) => {
|
||||
std::fs::write(dir.join(file), &stdout)?;
|
||||
println!("✓ {file}");
|
||||
}
|
||||
None => print!("{stdout}"),
|
||||
}
|
||||
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 {
|
||||
Runtime::Node => ("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.
|
||||
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_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()]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_format_is_rejected() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let err = graph(d.path(), "svg", None, None).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Where the application graph is composed: the file holding the `createApp`
|
||||
//! call and exporting the `app` it returns.
|
||||
//!
|
||||
//! `src/app.ts` is what `matcha new` scaffolds, and it exists as its own file
|
||||
//! precisely so the graph can be imported without binding a port. Projects
|
||||
//! scaffolded before that split — and hand-written ones that never took it —
|
||||
//! keep the whole thing in `src/main.ts`, so that stays a candidate.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Candidate entry files, most specific first.
|
||||
const CANDIDATES: [&str; 2] = ["src/app.ts", "src/main.ts"];
|
||||
|
||||
/// The first candidate that exists under `dir`, or `None` when neither does.
|
||||
pub fn find(dir: &Path) -> Option<PathBuf> {
|
||||
CANDIDATES.iter().map(|c| dir.join(c)).find(|p| p.exists())
|
||||
}
|
||||
|
||||
/// The candidate list as prose, for the error a caller prints when `find`
|
||||
/// returns `None`.
|
||||
pub fn candidates() -> String {
|
||||
CANDIDATES.join(" or ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn touch(dir: &Path, rel: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_app_over_main() {
|
||||
let d = tempdir().unwrap();
|
||||
touch(d.path(), "src/main.ts");
|
||||
touch(d.path(), "src/app.ts");
|
||||
assert_eq!(find(d.path()), Some(d.path().join("src/app.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_main() {
|
||||
let d = tempdir().unwrap();
|
||||
touch(d.path(), "src/main.ts");
|
||||
assert_eq!(find(d.path()), Some(d.path().join("src/main.ts")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn none_when_neither_exists() {
|
||||
let d = tempdir().unwrap();
|
||||
assert_eq!(find(d.path()), None);
|
||||
}
|
||||
}
|
||||
+24
@@ -2,8 +2,10 @@ mod check;
|
||||
mod cli;
|
||||
mod cmd_add;
|
||||
mod cmd_create;
|
||||
mod cmd_graph;
|
||||
mod cmd_new;
|
||||
mod cmd_run;
|
||||
mod entry;
|
||||
mod runtime;
|
||||
mod template;
|
||||
mod wire;
|
||||
@@ -36,6 +38,28 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Graph { format, entry, out } => {
|
||||
if let Err(e) = cmd_graph::graph(
|
||||
std::path::Path::new("."),
|
||||
&format,
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Explain { route, entry, out } => {
|
||||
if let Err(e) = cmd_graph::explain(
|
||||
std::path::Path::new("."),
|
||||
&route,
|
||||
entry.as_deref(),
|
||||
out.as_deref(),
|
||||
) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Add { capability } => {
|
||||
if let Err(e) = cmd_add::run(&capability) {
|
||||
eprintln!("error: {e}");
|
||||
|
||||
+79
-1
@@ -3,6 +3,19 @@ use std::path::Path;
|
||||
|
||||
use crate::runtime::Runtime;
|
||||
|
||||
/// The `@green-tea/core` version `matcha new` writes into a scaffolded project,
|
||||
/// substituted for `{{core_version}}` in the runtime overlays.
|
||||
///
|
||||
/// **Pinned exactly, on purpose.** Core is 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. A caret here is not a looser pin, it is a
|
||||
/// 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";
|
||||
|
||||
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared");
|
||||
pub static RUNTIME_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
|
||||
pub static RUNTIME_NODE: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/node");
|
||||
@@ -35,7 +48,11 @@ 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).into_bytes())
|
||||
.map(|s| {
|
||||
s.replace("{{project_name}}", name)
|
||||
.replace("{{core_version}}", CORE_VERSION)
|
||||
.into_bytes()
|
||||
})
|
||||
.unwrap_or_else(|_| f.contents().to_vec());
|
||||
std::fs::write(out, contents)?;
|
||||
}
|
||||
@@ -49,6 +66,60 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// The graph has to be importable without binding a port, which is why the
|
||||
/// scaffold composes it in `src/app.ts` and leaves `src/main.ts` holding
|
||||
/// only the runtime's serve call. `matcha graph` and `matcha explain`
|
||||
/// import the former; breaking the split breaks both.
|
||||
#[test]
|
||||
fn every_runtime_exports_the_app_from_its_own_module() {
|
||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun] {
|
||||
let d = tempdir().unwrap();
|
||||
write_starter(d.path(), "my-api", rt).unwrap();
|
||||
|
||||
let app = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||
assert!(
|
||||
app.contains("export const app = createApp("),
|
||||
"{rt:?} app.ts"
|
||||
);
|
||||
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(
|
||||
main.contains("import { app } from './app';"),
|
||||
"{rt:?} main.ts"
|
||||
);
|
||||
assert!(
|
||||
!main.contains("createApp("),
|
||||
"{rt:?} main.ts still composes the graph"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Core is prerelease-only, and a caret over a prerelease never resolves
|
||||
/// past its own `major.minor.patch` — `^26.7.0-beta.0` pinned every
|
||||
/// scaffold to 26.7.0-beta.0 while three later betas shipped. Nothing here
|
||||
/// may carry a range.
|
||||
#[test]
|
||||
fn no_runtime_scaffolds_a_caret_range_for_core() {
|
||||
for rt in [Runtime::Node, Runtime::Deno, Runtime::Bun] {
|
||||
let d = tempdir().unwrap();
|
||||
write_starter(d.path(), "my-api", rt).unwrap();
|
||||
|
||||
let manifest = ["package.json", "deno.json"]
|
||||
.iter()
|
||||
.map(|f| d.path().join(f))
|
||||
.find(|p| p.exists())
|
||||
.map(|p| std::fs::read_to_string(p).unwrap())
|
||||
.unwrap();
|
||||
let pin = manifest
|
||||
.lines()
|
||||
.find(|l| l.contains("@green-tea/core\":"))
|
||||
.unwrap_or_else(|| panic!("{rt:?} declares no core dependency"));
|
||||
assert!(pin.contains(CORE_VERSION), "{rt:?}: {pin}");
|
||||
assert!(!pin.contains('^'), "{rt:?} pins core with a caret: {pin}");
|
||||
assert!(!pin.contains('~'), "{rt:?} pins core with a tilde: {pin}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deno_writes_shared_and_deno_overlay() {
|
||||
let d = tempdir().unwrap();
|
||||
@@ -66,6 +137,10 @@ mod tests {
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
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();
|
||||
assert!(deno_json.contains(&format!("jsr:@green-tea/core@{CORE_VERSION}")));
|
||||
assert!(!deno_json.contains("{{core_version}}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -83,6 +158,9 @@ mod tests {
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(main.contains("app.listen"));
|
||||
assert!(!d.path().join("deno.json").exists());
|
||||
|
||||
assert!(pkg.contains(&format!("\"@green-tea/core\": \"{CORE_VERSION}\"")));
|
||||
assert!(!pkg.contains("{{core_version}}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,5 +3,6 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": { "dev": "bun --watch run src/main.ts" },
|
||||
"dependencies": { "@green-tea/core": "^26.7.0-beta.0" }
|
||||
"dependencies": { "@green-tea/core": "{{core_version}}" },
|
||||
"devDependencies": { "@types/bun": "^1" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
Bun.serve({ port: 8000, fetch: app.fetch });
|
||||
console.log('🍵 green-tea running on http://localhost:8000');
|
||||
@@ -3,7 +3,9 @@
|
||||
"target": "esnext",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"types": ["bun"],
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": { "experimentalDecorators": true },
|
||||
"compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true },
|
||||
"unstable": ["sloppy-imports"],
|
||||
"imports": { "@green-tea/core": "npm:@green-tea/core@^26.7.0-beta.0" },
|
||||
"imports": { "@green-tea/core": "jsr:@green-tea/core@{{core_version}}" },
|
||||
"tasks": { "dev": "deno run --watch --allow-net --allow-read --allow-env src/main.ts" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
Deno.serve({ port: 8000 }, app.fetch);
|
||||
console.log('🍵 green-tea running on http://localhost:8000');
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": { "dev": "tsx watch src/main.ts" },
|
||||
"dependencies": { "@green-tea/core": "^26.7.0-beta.0" },
|
||||
"dependencies": { "@green-tea/core": "{{core_version}}" },
|
||||
"devDependencies": { "tsx": "^4", "typescript": "^5" }
|
||||
}
|
||||
@@ -1,7 +1,4 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
const app = createApp({ modules: [AppModule] });
|
||||
import { app } from './app';
|
||||
|
||||
app.listen(3000);
|
||||
console.log('🍵 green-tea running on http://localhost:3000');
|
||||
@@ -4,6 +4,7 @@
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
/**
|
||||
* The application graph, exported rather than kept local so it can be reached
|
||||
* without serving: `matcha graph` and `matcha explain` import this file and
|
||||
* call `app.ready()`, which resolves the graph and does not boot providers.
|
||||
* `src/main.ts` is the half that binds a port.
|
||||
*/
|
||||
export const app = createApp({ modules: [AppModule] });
|
||||
+3
-1
@@ -11,7 +11,9 @@ fn help_lists_all_subcommands() {
|
||||
.stdout(contains("new"))
|
||||
.stdout(contains("run"))
|
||||
.stdout(contains("create"))
|
||||
.stdout(contains("add"));
|
||||
.stdout(contains("add"))
|
||||
.stdout(contains("graph"))
|
||||
.stdout(contains("explain"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -84,3 +84,38 @@ fn create_module_writes_and_registers_in_createapp() {
|
||||
assert!(main.contains("AppModule, UsersModule"));
|
||||
assert!(main.contains("import { UsersModule }"));
|
||||
}
|
||||
|
||||
/// A project scaffolded today composes its graph in `src/app.ts`, so that is
|
||||
/// where a new module has to be registered. `src/main.ts` only serves, and
|
||||
/// wiring a module into it would put the module in a file that never calls
|
||||
/// `createApp` — silently, since `add_to_createapp_modules` would simply find
|
||||
/// nothing to edit and the CLI would print its "add it manually" hint.
|
||||
#[test]
|
||||
fn create_module_prefers_app_ts_over_main_ts() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::create_dir_all(d.path().join("src")).unwrap();
|
||||
std::fs::write(
|
||||
d.path().join("src/app.ts"),
|
||||
"import { createApp } from '@green-tea/core';\nimport { AppModule } from './app.module';\n\nexport const app = createApp({ modules: [AppModule] });\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
d.path().join("src/main.ts"),
|
||||
"import { app } from './app';\n\napp.listen(3000);\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["create", "module", "Users"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let app_ts = std::fs::read_to_string(d.path().join("src/app.ts")).unwrap();
|
||||
assert!(app_ts.contains("AppModule, UsersModule"));
|
||||
assert!(app_ts.contains("import { UsersModule }"));
|
||||
|
||||
let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
|
||||
assert!(!main.contains("UsersModule"), "main.ts was edited: {main}");
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use assert_cmd::Command;
|
||||
use predicates::str::contains;
|
||||
use tempfile::tempdir;
|
||||
|
||||
/// Both introspection commands need a file that exports the app. Without one
|
||||
/// there is nothing to import, and the failure has to name the fix — a stack
|
||||
/// trace from a runtime that could not resolve a module does not.
|
||||
#[test]
|
||||
fn graph_without_an_entry_says_what_is_missing() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("graph")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("--entry"))
|
||||
.stderr(contains("export const app = createApp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explain_rejects_an_entry_that_does_not_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::write(d.path().join("package.json"), "{}").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["explain", "/users", "--entry", "src/nope.ts"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("no such entry"));
|
||||
}
|
||||
|
||||
/// Runtime detection comes after the entry is found, so a project with an entry
|
||||
/// and no manifest is a distinct failure with its own message.
|
||||
#[test]
|
||||
fn graph_without_a_runtime_says_so() {
|
||||
let d = tempdir().unwrap();
|
||||
std::fs::create_dir_all(d.path().join("src")).unwrap();
|
||||
std::fs::write(d.path().join("src/app.ts"), "export const app = {};\n").unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.arg("graph")
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(contains("no runtime detected"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_rejects_an_unknown_format() {
|
||||
let d = tempdir().unwrap();
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["graph", "--format", "svg"])
|
||||
.assert()
|
||||
.failure();
|
||||
}
|
||||
Reference in new issue
Block a user