The CLI catches up with the framework: graph/explain/openapi/doctor, an edge target, and a scaffold that is not two releases behind #11
No files matched your search
@@ -36,7 +36,7 @@ matcha new my-api # scaffold from the official starter
|
||||
matcha new my-api --template-url gh:owner/repo # scaffold from any git template
|
||||
matcha run # detect node/deno/bun and run in watch
|
||||
matcha create controller Users # generate + auto-wire into @Module
|
||||
matcha add sse # add a capability (sse|stream|buffer) to your controller
|
||||
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
|
||||
```
|
||||
@@ -80,6 +80,21 @@ 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.
|
||||
|
||||
### `add` capabilities
|
||||
|
||||
| | generates |
|
||||
|---|---|
|
||||
| `sse` | `@Sse` stream tagged with `sse(data, { id })`, reading `@header('last-event-id')` to resume |
|
||||
| `ws` | `@Ws` duplex handler: consume `@inbound()`, return a `channel()` — needs `ws` on Node |
|
||||
| `stream` | `@Stream` chunked response |
|
||||
| `upload` | `@Post` with `@body(): MultipartBody` — needs `busboy` |
|
||||
| `buffer` | `@Get` with a custom `@Transformer` shaping the whole response |
|
||||
|
||||
`matcha add <cap>` edits the only controller under `src/controllers`; with more
|
||||
than one it refuses and lists them, and `--controller <path>` picks. Repeats are
|
||||
no-ops. Both peer dependencies are lazy-loaded by core, so neither is needed to
|
||||
compile — only to serve the route.
|
||||
|
||||
### `create` / `add` auto-wiring
|
||||
|
||||
`create` and `add` edit your TypeScript with tree-sitter: they insert imports
|
||||
|
||||
@@ -79,4 +79,17 @@ echo "▸ matcha graph"
|
||||
"$MATCHA" explain /zen | grep -q '\[sse\]' || { echo "explain did not report the sse route"; exit 1; }
|
||||
echo "✓ graph and explain resolve"
|
||||
|
||||
# Every `matcha add` capability, spliced into one controller and type-checked
|
||||
# together. The stubs name core's real surface — `sse()` with an id, `@Ws` with
|
||||
# `@inbound()`, `MultipartBody`, `@Transformer` — so this is the thing that
|
||||
# notices when that surface moves. No peer dependency is installed on purpose:
|
||||
# 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
|
||||
"$MATCHA" add "$cap" >/dev/null || { echo "matcha add $cap failed"; exit 1; }
|
||||
done
|
||||
"${CHECK[@]}" || { echo "the generated handlers do not type-check"; exit 1; }
|
||||
echo "✓ every add capability type-checks"
|
||||
|
||||
echo "✓ $RUNTIME starter is good"
|
||||
+4
-1
@@ -49,7 +49,10 @@ pub enum Command {
|
||||
},
|
||||
/// Add a capability to a controller
|
||||
Add {
|
||||
#[arg(value_parser = ["sse", "stream", "buffer"])]
|
||||
#[arg(value_parser = ["sse", "stream", "buffer", "ws", "upload"])]
|
||||
capability: String,
|
||||
/// Which controller to edit (default: the only one in src/controllers)
|
||||
#[arg(long)]
|
||||
controller: Option<String>,
|
||||
},
|
||||
}
|
||||
+258
-54
@@ -1,66 +1,198 @@
|
||||
//! `matcha add <sse|stream|buffer>` — appends a capability handler method to
|
||||
//! the single controller found under `src/controllers`, wiring in the
|
||||
//! decorator import via `wire::add_import` and splicing the method body via
|
||||
//! `wire::insert_method`.
|
||||
//! `matcha add <capability>` — append a ready handler to a controller, with the
|
||||
//! decorator imports it needs merged into the existing `@green-tea/core` import.
|
||||
//!
|
||||
//! Each capability is one row in [`CAPABILITIES`]: what to import, the method to
|
||||
//! splice, the literal that makes the insert idempotent, and the optional peer
|
||||
//! dependency the handler needs at runtime. Adding a capability is adding a row.
|
||||
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::wire;
|
||||
|
||||
/// Returns `(decorator symbol, method source, dedup marker)` for a known
|
||||
/// capability, or `None` for an unrecognized one.
|
||||
///
|
||||
/// The dedup marker is the route-path string literal baked into that
|
||||
/// capability's `handler()` template (e.g. `'/events'`, `'/stream'`,
|
||||
/// `'/data'`). It is unique per capability, unlike the decorator name — both
|
||||
/// `buffer` and any pre-existing handler can legitimately use `@Get` — so
|
||||
/// it's what `run` checks for before inserting, to keep `matcha add <cap>`
|
||||
/// idempotent per capability rather than per decorator.
|
||||
fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> {
|
||||
match cap {
|
||||
"sse" => Some((
|
||||
"Sse",
|
||||
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
|
||||
"'/events'",
|
||||
)),
|
||||
"stream" => Some((
|
||||
"Stream",
|
||||
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
|
||||
"'/stream'",
|
||||
)),
|
||||
"buffer" => Some((
|
||||
"Get",
|
||||
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
|
||||
"'/data'",
|
||||
)),
|
||||
_ => None,
|
||||
/// A handler `matcha add` can splice into a controller.
|
||||
struct Capability {
|
||||
/// Name as typed on the command line.
|
||||
name: &'static str,
|
||||
/// Symbols merged into the controller's `@green-tea/core` value import.
|
||||
imports: &'static [&'static str],
|
||||
/// Symbols that must arrive as `import type`, because they appear in a
|
||||
/// decorated signature. See [`wire::add_type_import`].
|
||||
type_imports: &'static [&'static str],
|
||||
/// The method source, spliced before the class's closing brace.
|
||||
method: &'static str,
|
||||
/// The route-path literal baked into `method`, used to keep the insert
|
||||
/// idempotent. It is the marker rather than the decorator name because a
|
||||
/// decorator is not unique — `buffer` uses `@Get`, and so does any handler
|
||||
/// the user already wrote.
|
||||
marker: &'static str,
|
||||
/// An optional peer dependency the handler needs at runtime, and the
|
||||
/// runtimes that need it. green-tea lazy-loads both, so a missing one is a
|
||||
/// clear error at the first request rather than a crash at boot — but it is
|
||||
/// still an error, and the person who just generated the handler is the one
|
||||
/// who can avoid it.
|
||||
peer: Option<(&'static str, &'static str)>,
|
||||
}
|
||||
|
||||
const CAPABILITIES: &[Capability] = &[
|
||||
Capability {
|
||||
name: "sse",
|
||||
// `sse()` and `@header` are what make the stream resumable. Without them
|
||||
// an `EventSource` reconnect silently restarts the iterable from its
|
||||
// beginning and loses whatever happened in the gap.
|
||||
imports: &["Sse", "sse", "header"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Sse('/events')
|
||||
events(@header('last-event-id') lastEventId?: string) {
|
||||
// The browser echoes the last id it saw back on reconnect. green-tea stores
|
||||
// nothing — no buffer, no replay — so what the gap means is this handler's
|
||||
// to decide: a paged log re-reads from an offset, a live sensor has no past
|
||||
// worth delivering.
|
||||
let next = lastEventId ? Number(lastEventId) + 1 : 0;
|
||||
return (async function* () {
|
||||
for (;;) {
|
||||
yield sse({ n: next }, { id: String(next) });
|
||||
next++;
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
})();
|
||||
}
|
||||
"#,
|
||||
marker: "'/events'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "stream",
|
||||
imports: &["Stream"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Stream('/stream')
|
||||
stream() {
|
||||
return (async function* () {
|
||||
yield 'chunk';
|
||||
})();
|
||||
}
|
||||
"#,
|
||||
marker: "'/stream'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "buffer",
|
||||
// "buffer" is the *transport* — the whole response at once, as opposed
|
||||
// to the incremental sse/stream/ws ones — and `@Transformer` is what
|
||||
// shapes it. The stub used to return `Buffer.from('hello')`, which is
|
||||
// not what the name means and never worked: `TransformerFn` returns
|
||||
// `body: string`, the default `JsonTransformer` is `JSON.stringify`,
|
||||
// and a Node Buffer stringifies to `{"type":"Buffer","data":[...]}`.
|
||||
imports: &["Get", "Transformer"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Get('/data')
|
||||
@Transformer((rows) => ({
|
||||
status: 200,
|
||||
headers: { 'content-type': 'text/csv' },
|
||||
body: (rows as string[]).join('\n'),
|
||||
}))
|
||||
data() {
|
||||
return ['id,name', '1,matcha'];
|
||||
}
|
||||
"#,
|
||||
marker: "'/data'",
|
||||
peer: None,
|
||||
},
|
||||
Capability {
|
||||
name: "ws",
|
||||
imports: &["Ws", "inbound", "channel"],
|
||||
type_imports: &[],
|
||||
method: r#"
|
||||
@Ws('/echo')
|
||||
echo(@inbound() incoming: AsyncIterable<string>) {
|
||||
// Two iterables: `@inbound()` is what the client sends, and the one returned
|
||||
// is what it receives. The pump is deliberately not awaited — the handler
|
||||
// returns the outbound channel now and fills it as messages arrive.
|
||||
const outbound = channel<string>();
|
||||
(async () => {
|
||||
for await (const message of incoming) outbound.push(`echo: ${message}`);
|
||||
outbound.close();
|
||||
})();
|
||||
return outbound;
|
||||
}
|
||||
"#,
|
||||
marker: "'/echo'",
|
||||
peer: Some(("ws", "Node")),
|
||||
},
|
||||
Capability {
|
||||
name: "upload",
|
||||
imports: &["Post", "body"],
|
||||
type_imports: &["MultipartBody"],
|
||||
method: r#"
|
||||
@Post('/upload')
|
||||
upload(@body() form: MultipartBody) {
|
||||
return Object.entries(form.files).map(([field, uploaded]) => {
|
||||
// A repeated part name arrives as an array, so a field holds either shape.
|
||||
const file = Array.isArray(uploaded) ? uploaded[0] : uploaded;
|
||||
return { field, filename: file.filename, size: file.size };
|
||||
});
|
||||
}
|
||||
"#,
|
||||
marker: "'/upload'",
|
||||
peer: Some(("busboy", "every runtime")),
|
||||
},
|
||||
];
|
||||
|
||||
/// The capability names, for clap's `value_parser` and for error messages.
|
||||
pub fn names() -> Vec<&'static str> {
|
||||
CAPABILITIES.iter().map(|c| c.name).collect()
|
||||
}
|
||||
|
||||
fn find(name: &str) -> Option<&'static Capability> {
|
||||
CAPABILITIES.iter().find(|c| c.name == name)
|
||||
}
|
||||
|
||||
/// Resolves which controller to edit. With `--controller` the path is taken as
|
||||
/// given; without it there must be exactly one `*.controller.ts` under
|
||||
/// `src/controllers`, since guessing between several would edit the wrong file
|
||||
/// as often as the right one.
|
||||
fn resolve_controller(explicit: Option<&str>) -> std::io::Result<PathBuf> {
|
||||
if let Some(path) = explicit {
|
||||
let p = PathBuf::from(path);
|
||||
return if p.exists() {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(Error::new(
|
||||
ErrorKind::NotFound,
|
||||
format!("no such controller: {path}"),
|
||||
))
|
||||
};
|
||||
}
|
||||
|
||||
/// Finds the single `*.controller.ts` file in `src/controllers`. Errors if
|
||||
/// there are zero or more than one — this v1 has no way to disambiguate.
|
||||
fn only_controller() -> std::io::Result<PathBuf> {
|
||||
let dir = std::path::Path::new("src/controllers");
|
||||
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
|
||||
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
|
||||
.collect();
|
||||
hits.sort();
|
||||
match hits.len() {
|
||||
1 => Ok(hits.pop().unwrap()),
|
||||
0 => Err(Error::new(
|
||||
ErrorKind::NotFound,
|
||||
"no *.controller.ts in src/controllers",
|
||||
)),
|
||||
_ => Err(Error::other(
|
||||
"multiple controllers; specify which (not yet supported)",
|
||||
)),
|
||||
_ => {
|
||||
let list: Vec<String> = hits.iter().map(|p| format!(" {}", p.display())).collect();
|
||||
Err(Error::other(format!(
|
||||
"{} controllers found — pass --controller <path>:\n{}",
|
||||
hits.len(),
|
||||
list.join("\n")
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the class name following `export class `. This is a plain text
|
||||
/// scan rather than a tree-sitter query — `insert_method` does the real
|
||||
/// grammar-aware work once the name is known.
|
||||
/// Extracts the class name following `export class `. A plain text scan rather
|
||||
/// than a tree-sitter query — `insert_method` does the grammar-aware work once
|
||||
/// the name is known.
|
||||
fn class_name(src: &str) -> Option<String> {
|
||||
let idx = src.find("export class ")? + "export class ".len();
|
||||
let rest = &src[idx..];
|
||||
@@ -68,31 +200,103 @@ fn class_name(src: &str) -> Option<String> {
|
||||
Some(rest[..end].to_string())
|
||||
}
|
||||
|
||||
pub fn run(cap: &str) -> std::io::Result<()> {
|
||||
let (decorator, method, marker) = handler(cap)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
|
||||
let path = only_controller()?;
|
||||
pub fn run(cap: &str, controller: Option<&str>) -> std::io::Result<()> {
|
||||
let capability = find(cap).ok_or_else(|| {
|
||||
Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!("unknown capability {cap} (try: {})", names().join(", ")),
|
||||
)
|
||||
})?;
|
||||
|
||||
let path = resolve_controller(controller)?;
|
||||
let src = std::fs::read_to_string(&path)?;
|
||||
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
|
||||
if src.contains(marker) {
|
||||
if src.contains(capability.marker) {
|
||||
println!("→ {cap} already present in {class}");
|
||||
return Ok(());
|
||||
}
|
||||
// wire::add_import merges `decorator` into an existing
|
||||
// `import { ... } from '@green-tea/core';` brace when one is already
|
||||
// present, rather than appending a second import line for the same
|
||||
// module (which would be a duplicate ESM binding — a hard SyntaxError,
|
||||
// not a harmless dupe).
|
||||
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
|
||||
match wire::insert_method(&with_import, &class, &method) {
|
||||
|
||||
// add_import merges each symbol into an existing
|
||||
// `import { ... } from '@green-tea/core';` brace rather than appending a
|
||||
// second import line for the same module — which would be a duplicate ESM
|
||||
// binding, a hard SyntaxError rather than a harmless dupe.
|
||||
let mut edited = src;
|
||||
for symbol in capability.imports {
|
||||
edited = wire::add_import(&edited, symbol, "@green-tea/core");
|
||||
}
|
||||
for symbol in capability.type_imports {
|
||||
edited = wire::add_type_import(&edited, symbol, "@green-tea/core");
|
||||
}
|
||||
|
||||
match wire::insert_method(&edited, &class, capability.method) {
|
||||
Some(out) => {
|
||||
std::fs::write(&path, out)?;
|
||||
println!("✓ added @{decorator} to {class}");
|
||||
println!("✓ added {cap} handler to {class} ({})", path.display());
|
||||
if let Some((package, runtimes)) = capability.peer {
|
||||
println!(
|
||||
"→ needs the optional peer dependency '{package}' on {runtimes}: npm i {package}"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => println!(
|
||||
"→ could not edit {}; add @{decorator} handler manually",
|
||||
"→ could not edit {}; add the {cap} handler manually",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_capability_marker_appears_in_its_own_method() {
|
||||
for cap in CAPABILITIES {
|
||||
assert!(
|
||||
cap.method.contains(cap.marker),
|
||||
"{}: marker {} is not in the method it guards",
|
||||
cap.name,
|
||||
cap.marker
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker is what makes a second `matcha add <cap>` a no-op, so two
|
||||
/// capabilities sharing one would make each look already-present after the
|
||||
/// other had been added.
|
||||
#[test]
|
||||
fn markers_are_unique_across_capabilities() {
|
||||
for (i, a) in CAPABILITIES.iter().enumerate() {
|
||||
for b in &CAPABILITIES[i + 1..] {
|
||||
assert_ne!(
|
||||
a.marker, b.marker,
|
||||
"{} and {} share a marker",
|
||||
a.name, b.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A generated handler that references a symbol it did not import does not
|
||||
/// compile, and `matcha add` would have written it anyway.
|
||||
#[test]
|
||||
fn every_capability_imports_the_symbols_it_uses() {
|
||||
for cap in CAPABILITIES {
|
||||
for symbol in cap.imports.iter().chain(cap.type_imports) {
|
||||
assert!(
|
||||
cap.method.contains(*symbol),
|
||||
"{} imports {symbol} without using it",
|
||||
cap.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_capability_lists_the_known_ones() {
|
||||
let err = run("telepathy", None).unwrap_err();
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert!(err.to_string().contains("sse"));
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -60,8 +60,11 @@ fn main() {
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Command::Add { capability } => {
|
||||
if let Err(e) = cmd_add::run(&capability) {
|
||||
Command::Add {
|
||||
capability,
|
||||
controller,
|
||||
} => {
|
||||
if let Err(e) = cmd_add::run(&capability, controller.as_deref()) {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
+98
-7
@@ -64,10 +64,27 @@ fn has_error(node: Node) -> bool {
|
||||
/// accepted; if merging somehow produces broken text, this falls back to
|
||||
/// appending a fresh import line rather than returning broken source.
|
||||
pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
insert_import(src, symbol, from, false)
|
||||
}
|
||||
|
||||
/// Same as [`add_import`], but for `import type { ... } from '<from>';`.
|
||||
///
|
||||
/// A type used in a decorated method signature has to arrive this way. Under
|
||||
/// `isolatedModules` with `emitDecoratorMetadata` — Deno's defaults — a type
|
||||
/// reached through a value import is TS1272, because the emitted
|
||||
/// `design:paramtypes` would reference a binding the compiler erased. Node and
|
||||
/// bun's `tsc` accept it, so the same generated handler compiles on two
|
||||
/// runtimes and fails on the third.
|
||||
pub fn add_type_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
insert_import(src, symbol, from, true)
|
||||
}
|
||||
|
||||
fn insert_import(src: &str, symbol: &str, from: &str, type_only: bool) -> String {
|
||||
let tree = parser().parse(src, None).unwrap();
|
||||
let root = tree.root_node();
|
||||
let keyword = if type_only { "import type" } else { "import" };
|
||||
|
||||
if let Some(named_imports) = find_named_imports(&root, src, from) {
|
||||
if let Some(named_imports) = find_named_imports(&root, src, from, type_only) {
|
||||
let mut c = named_imports.walk();
|
||||
let already_present = named_imports.named_children(&mut c).any(|spec| {
|
||||
spec.kind() == "import_specifier"
|
||||
@@ -98,7 +115,7 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
// through to the append-a-new-line path below rather than return it.
|
||||
}
|
||||
|
||||
let line = format!("import {{ {symbol} }} from '{from}';");
|
||||
let line = format!("{keyword} {{ {symbol} }} from '{from}';");
|
||||
if src.contains(&line) {
|
||||
return src.to_string();
|
||||
}
|
||||
@@ -120,18 +137,41 @@ pub fn add_import(src: &str, symbol: &str, from: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether an `import_statement` is the `import type { ... }` form.
|
||||
///
|
||||
/// Read off the statement's own text rather than its grammar node: the `type`
|
||||
/// modifier's shape differs between tree-sitter-typescript versions, and the
|
||||
/// node here is always a well-formed import statement, so the prefix is exact.
|
||||
fn is_type_only(stmt: &Node, src: &str) -> bool {
|
||||
stmt.utf8_text(src.as_bytes())
|
||||
.map(|text| text.trim_start().starts_with("import type"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Finds the `named_imports` (`{ A, B, C }`) brace of the top-level `import
|
||||
/// { ... } from '<from>';` statement whose module specifier string literal
|
||||
/// equals `from` exactly. Returns `None` when no import statement has that
|
||||
/// source, or when the matching statement has no named-imports clause at all
|
||||
/// (e.g. a bare default import) — callers treat that as "can't merge, fall
|
||||
/// back to appending a new line".
|
||||
fn find_named_imports<'a>(root: &Node<'a>, src: &str, from: &str) -> Option<Node<'a>> {
|
||||
/// equals `from` exactly and whose type-only-ness matches `type_only`. Returns
|
||||
/// `None` when no import statement has that source, or when the matching
|
||||
/// statement has no named-imports clause at all (e.g. a bare default import) —
|
||||
/// callers treat that as "can't merge, fall back to appending a new line".
|
||||
///
|
||||
/// The `type_only` split matters in both directions: merging a value symbol
|
||||
/// into an `import type` line erases it at runtime, and merging a type into a
|
||||
/// value line is the TS1272 that [`add_type_import`] exists to avoid.
|
||||
fn find_named_imports<'a>(
|
||||
root: &Node<'a>,
|
||||
src: &str,
|
||||
from: &str,
|
||||
type_only: bool,
|
||||
) -> Option<Node<'a>> {
|
||||
let mut c = root.walk();
|
||||
for stmt in root.children(&mut c) {
|
||||
if stmt.kind() != "import_statement" {
|
||||
continue;
|
||||
}
|
||||
if is_type_only(&stmt, src) != type_only {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = stmt.child_by_field_name("source") else {
|
||||
continue;
|
||||
};
|
||||
@@ -568,4 +608,55 @@ export class AppModule {}
|
||||
let src = "const app = createApp({ modules: MODULES });\n";
|
||||
assert!(add_to_createapp_modules(src, "UsersModule").is_none());
|
||||
}
|
||||
|
||||
/// A type in a decorated signature must not ride the value import: under
|
||||
/// `isolatedModules` + `emitDecoratorMetadata` that is TS1272, which node's
|
||||
/// and bun's tsc accept and Deno rejects.
|
||||
#[test]
|
||||
fn type_import_gets_its_own_statement() {
|
||||
let src = "import { Route } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "MultipartBody", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import type { MultipartBody } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
out.contains("import { Route } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The dangerous direction: a value symbol merged into an `import type`
|
||||
/// line is erased at compile time, so the decorator it names is simply
|
||||
/// undefined at runtime.
|
||||
#[test]
|
||||
fn value_import_never_merges_into_a_type_import() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_import(src, "Post", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import { Post } from '@green-tea/core';"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
!out.contains("import type { MultipartBody, Post }"),
|
||||
"Post was merged into the type-only import:\n{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_import_merges_into_an_existing_type_import() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "UploadedFile", "@green-tea/core");
|
||||
assert!(
|
||||
out.contains("import type { MultipartBody, UploadedFile }"),
|
||||
"{out}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_import_is_idempotent() {
|
||||
let src = "import type { MultipartBody } from '@green-tea/core';\n";
|
||||
let out = add_type_import(src, "MultipartBody", "@green-tea/core");
|
||||
assert_eq!(out, src);
|
||||
}
|
||||
}
|
||||
+117
-1
@@ -21,7 +21,17 @@ fn add_sse_appends_handler() {
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Sse("));
|
||||
assert!(out.contains("import { Route, Get, Sse }") || out.contains("Sse }"));
|
||||
// The generated stream is resumable, which takes three symbols, not one:
|
||||
// `@Sse` to declare the route, `sse()` to tag each event with an id, and
|
||||
// `@header` to read the id the browser echoes back on reconnect.
|
||||
for symbol in ["Sse", "sse", "header"] {
|
||||
assert!(
|
||||
out.contains(&format!("{symbol},")) || out.contains(&format!("{symbol} }}")),
|
||||
"{symbol} not imported:\n{out}"
|
||||
);
|
||||
}
|
||||
assert!(out.contains("last-event-id"));
|
||||
assert!(out.contains("id: String(next)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -83,3 +93,109 @@ fn add_errors_when_multiple_controllers_and_writes_nothing() {
|
||||
original
|
||||
);
|
||||
}
|
||||
|
||||
fn seed(dir: &std::path::Path, name: &str) {
|
||||
std::fs::create_dir_all(dir.join("src/controllers")).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(format!("src/controllers/{name}.controller.ts")),
|
||||
format!(
|
||||
"import {{ Route, Get }} from '@green-tea/core';\n\n@Route('/')\nexport class {}Controller {{\n @Get('/')\n home() {{}}\n}}\n",
|
||||
name.to_uppercase()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_ws_wires_the_duplex_handler_and_names_its_peer_dependency() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "ws"])
|
||||
.assert()
|
||||
.success()
|
||||
// `ws` is lazy-required, so its absence is a runtime error rather than a
|
||||
// boot failure — the moment to mention it is when the handler is written.
|
||||
.stdout(predicates::str::contains("npm i ws"));
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Ws('/echo')"));
|
||||
assert!(out.contains("@inbound()"));
|
||||
assert!(out.contains("channel<string>()"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_upload_wires_multipart_and_names_busboy() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "upload"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicates::str::contains("npm i busboy"));
|
||||
|
||||
let out = std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(out.contains("@Post('/upload')"));
|
||||
assert!(out.contains("MultipartBody"));
|
||||
}
|
||||
|
||||
/// With more than one controller the CLI used to refuse and stop. It still
|
||||
/// refuses to guess, but `--controller` is now the way through.
|
||||
#[test]
|
||||
fn add_targets_the_named_controller_when_several_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
seed(d.path(), "users");
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args(["add", "sse"])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains("--controller"));
|
||||
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args([
|
||||
"add",
|
||||
"sse",
|
||||
"--controller",
|
||||
"src/controllers/users.controller.ts",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let users =
|
||||
std::fs::read_to_string(d.path().join("src/controllers/users.controller.ts")).unwrap();
|
||||
assert!(users.contains("@Sse("));
|
||||
let home =
|
||||
std::fs::read_to_string(d.path().join("src/controllers/home.controller.ts")).unwrap();
|
||||
assert!(
|
||||
!home.contains("@Sse("),
|
||||
"the other controller was edited too"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_rejects_a_controller_path_that_does_not_exist() {
|
||||
let d = tempdir().unwrap();
|
||||
seed(d.path(), "home");
|
||||
Command::cargo_bin("matcha")
|
||||
.unwrap()
|
||||
.current_dir(d.path())
|
||||
.args([
|
||||
"add",
|
||||
"sse",
|
||||
"--controller",
|
||||
"src/controllers/nope.controller.ts",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.stderr(predicates::str::contains("no such controller"));
|
||||
}
|
||||
Reference in new issue
Block a user