Author SHA1 Message Date
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
15 changed files with 279 additions and 33 deletions

No files matched your search

+3 -3
View File
@@ -65,13 +65,13 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
- name: Compare the scaffold pin against the beta dist-tag - name: Compare the scaffold pin against the latest dist-tag
run: | run: |
pinned=$(grep -oP 'CORE_VERSION: &str = "\K[^"]+' src/template.rs) 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" echo "pinned=$pinned latest=$latest"
if [ "$pinned" != "$latest" ]; then 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." echo "Bump CORE_VERSION in src/template.rs and let the starter job prove it still boots."
exit 1 exit 1
fi fi
+24
View File
@@ -13,6 +13,12 @@ is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says w
### Added ### 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 - **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 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 chain, a handler declares its needs in its signature, and the graph is checked at boot. It also points
@@ -34,6 +40,24 @@ is pinned to is `CORE_VERSION` in `src/template.rs`, and each entry below says w
question and gets one JSON document back, then renders it as text unless `--json` is passed. 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 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. 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 ## [26.9.0-beta.1] - 2026-09-24
+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 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 **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 the logic breaks. A generator gets a test that the generated code carries what it must; a
+2 -6
View File
@@ -70,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 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, 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 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 ### Introspection
@@ -194,11 +194,7 @@ which boots real workerd locally.
Two differences the edge cannot hide. `@Html('file')`, `static` and multipart Two differences the edge cannot hide. `@Html('file')`, `static` and multipart
uploads need a filesystem workerd does not have, and shutdown teardown never 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** runs — an isolate is discarded, not closed.
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.
## Development ## 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 # core lazy-requires `ws` and `busboy`, so neither is needed to compile, and a
# check that needed them would be hiding that fact. # check that needed them would be hiding that fact.
echo "▸ matcha add (every capability)" 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; } "$MATCHA" add "$cap" >/dev/null || { echo "matcha add $cap failed"; exit 1; }
done 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; } "${CHECK[@]}" || { echo "the generated handlers do not type-check"; exit 1; }
echo "✓ every add capability type-checks" echo "✓ every add capability type-checks"
+33
View File
@@ -139,6 +139,39 @@ const CAPABILITIES: &[Capability] = &[
marker: "'/upload'", marker: "'/upload'",
peer: Some(("busboy", "every runtime")), 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. /// The capability names, for clap's `value_parser` and for error messages.
+94 -8
View File
@@ -5,7 +5,7 @@
use std::io::{Error, ErrorKind}; use std::io::{Error, ErrorKind};
use std::path::Path; 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 /// A piece that lives inside a module: a file under `src/<subdir>/` plus an
/// entry in one of `@Module`'s arrays. /// entry in one of `@Module`'s arrays.
@@ -56,14 +56,74 @@ pub fn kinds() -> Vec<&'static str> {
["module"] ["module"]
.into_iter() .into_iter()
.chain(PIECES.iter().map(|p| p.kind)) .chain(PIECES.iter().map(|p| p.kind))
.chain(["plugin"]) .chain(["transformer", "plugin"])
.collect() .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<()> { 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" { if kind == "module" {
return create_module(name, check); return create_module(name, check);
} }
if kind == "transformer" {
return create_transformer(name, check);
}
match PIECES.iter().find(|p| p.kind == kind) { match PIECES.iter().find(|p| p.kind == kind) {
Some(piece) => create_piece(name, check, piece), Some(piece) => create_piece(name, check, piece),
None => Err(Error::new( None => Err(Error::new(
@@ -87,8 +147,7 @@ fn create_piece(name: &str, check: bool, piece: &Piece) -> std::io::Result<()> {
let file = Path::new("src") let file = Path::new("src")
.join(subdir) .join(subdir)
.join(format!("{lower}.{ext}.ts")); .join(format!("{lower}.{ext}.ts"));
std::fs::create_dir_all(file.parent().unwrap())?; write_new(&file, (piece.stub)(name))?;
std::fs::write(&file, (piece.stub)(name))?;
println!("✓ {}", file.display()); println!("✓ {}", file.display());
let symbol = format!("{name}{suffix}"); let symbol = format!("{name}{suffix}");
@@ -117,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<()> { fn create_module(name: &str, check: bool) -> std::io::Result<()> {
let lower = name.to_lowercase(); let lower = name.to_lowercase();
let file = Path::new("src").join(format!("{lower}.module.ts")); let file = Path::new("src").join(format!("{lower}.module.ts"));
std::fs::create_dir_all(file.parent().unwrap())?; write_new(&file, module_stub(name))?;
std::fs::write(&file, module_stub(name))?;
println!("✓ {}", file.display()); println!("✓ {}", file.display());
let symbol = format!("{name}Module"); let symbol = format!("{name}Module");
@@ -145,6 +203,34 @@ fn create_module(name: &str, check: bool) -> std::io::Result<()> {
maybe_check(check) maybe_check(check)
} }
/// 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<()> { pub(crate) fn maybe_check(check: bool) -> std::io::Result<()> {
if check { if check {
match crate::check::run(Path::new(".")) { match crate::check::run(Path::new(".")) {
@@ -164,14 +250,14 @@ fn controller_stub(name: &str) -> String {
} }
fn step_stub(name: &str) -> String { fn step_stub(name: &str) -> String {
let lower = name.to_lowercase(); let lower = token(name);
format!( 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" "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 { fn provider_stub(name: &str) -> String {
let lower = name.to_lowercase(); let lower = token(name);
format!( 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" "import {{ Provider }} from '@green-tea/core';\n\n@Provider({{ provides: '{lower}' }})\nexport class {name}Provider {{\n provide() {{\n return {{ {lower}: null }};\n }}\n}}\n"
) )
+2 -2
View File
@@ -13,8 +13,8 @@ use crate::runtime::Runtime;
/// pin to the oldest matching prerelease that nothing can move off. When core /// 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 /// 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 /// mattering; until then the `core-freshness` CI job fails when this falls
/// behind the `beta` dist-tag, which is what keeps it current. /// behind the `latest` dist-tag, which is what keeps it current.
pub const CORE_VERSION: &str = "26.9.0-beta.2"; pub const CORE_VERSION: &str = "26.11.0-rc.1";
pub static SHARED: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/shared"); 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_DENO: Dir = include_dir!("$CARGO_MANIFEST_DIR/template/runtimes/deno");
-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}}", "name": "{{project_name}}",
"type": "module", "type": "module",
"private": true, "private": true,
"engines": { "node": ">=22" },
"scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy" }, "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" } "devDependencies": { "tsx": "^4", "typescript": "^5", "wrangler": "^4" }
} }
+1
View File
@@ -2,6 +2,7 @@
"name": "{{project_name}}", "name": "{{project_name}}",
"type": "module", "type": "module",
"private": true, "private": true,
"engines": { "node": ">=22" },
"scripts": { "dev": "tsx watch src/main.ts" }, "scripts": { "dev": "tsx watch src/main.ts" },
"dependencies": { "@green-tea/core": "{{core_version}}" }, "dependencies": { "@green-tea/core": "{{core_version}}" },
"devDependencies": { "tsx": "^4", "typescript": "^5" } "devDependencies": { "tsx": "^4", "typescript": "^5" }
+3 -1
View File
@@ -1,4 +1,6 @@
import { app } from './app'; 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'); console.log('🍵 green-tea running on http://localhost:3000');
+34
View File
@@ -199,3 +199,37 @@ fn add_rejects_a_controller_path_that_does_not_exist() {
.failure() .failure()
.stderr(predicates::str::contains("no such controller")); .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}"
);
}
+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(); let main = std::fs::read_to_string(d.path().join("src/main.ts")).unwrap();
assert!(!main.contains("UsersModule"), "main.ts was edited: {main}"); 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}"
);
}
+1 -1
View File
@@ -191,7 +191,7 @@ fn package_jsr_writes_the_tree_into_dir() {
); );
let deno = std::fs::read_to_string(pkg.join("deno.json")).unwrap(); let deno = std::fs::read_to_string(pkg.join("deno.json")).unwrap();
assert!(deno.contains("\"name\": \"@acme/plugin-algo\""), "{deno}"); assert!(deno.contains("\"name\": \"@acme/plugin-algo\""), "{deno}");
assert!(deno.contains("npm:@green-tea/core@26.9.0-beta.2"), "{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 // Without it `deno test` needs a `deno install` first, and then fails to
// type-check `node:assert` for want of @types/node. // type-check `node:assert` for want of @types/node.
assert!(deno.contains("\"nodeModulesDir\": \"auto\""), "{deno}"); assert!(deno.contains("\"nodeModulesDir\": \"auto\""), "{deno}");