diff --git a/.claude/hooks/block-prose-punctuation.sh b/.claude/hooks/block-prose-punctuation.sh index 0adfa78e7..acbe90332 100755 --- a/.claude/hooks/block-prose-punctuation.sh +++ b/.claude/hooks/block-prose-punctuation.sh @@ -306,7 +306,7 @@ fi # positives (a wrongly blocked write), the same tradeoff as the rules above: # e.g. a sentence-ending "built on webjs." is not flagged (trailing period), # and the `bin/webjs.js` "webjs commands:" usage banner may rarely trip it. -webjs_cli='create|dev|start|test|check|ci|routes|db|ui|doctor|types|typecheck|mcp|vendor|help|version|add|init|generate|migrate|push|studio|seed|pin|unpin|list|audit|outdated|update|view|diff|info|build|source|status|stop|regenerate' +webjs_cli='create|dev|start|test|check|ci|routes|db|ui|doctor|types|typecheck|mcp|vendor|help|version|add|init|generate|migrate|push|studio|seed|pin|unpin|list|audit|outdated|update|view|diff|info|build|source|status|stop|verify|regenerate' # Scan copy: drop fenced code blocks, inline code spans, and emphasis markers # so a `webjs` inside code is never considered and **webjs** still matches. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e00c686bd..95724d019 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,6 +143,10 @@ jobs: # machines, which are independent and must be kept in step by hand. - name: WebJs form-action guard parity on Bun run: bun test/bun/form-action-guard.mjs + # notFound() / forbidden() / unauthorized() in an action called over RPC + # (#1697): 404 / 403 / 401 through the Bun.serve listener, never a 500. + - name: Action control flow over RPC on Bun + run: bun test/bun/action-control-flow-rpc.mjs # live() in an attribute hole (#1443): the SSR unwrap must produce # byte-identical attribute emission on Bun, across both server machines. # The bug class this guards was a server/client disagreement (a falsy diff --git a/AGENTS.md b/AGENTS.md index 11483ba28..a85732521 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -115,7 +115,7 @@ Every code change MUST include, automatically: 1. **Tests, every applicable layer (not just unit).** Ship the tests that prove the change across EVERY layer it touches: **unit** (`packages/*/test/**`, `test/**`, including the counterfactual that fails when reverted), **browser** (`*/test/**/browser/*` via `npm run test:browser`, for hydration / DOM / slots / client router / custom-element upgrade), **e2e** (`test/e2e/*.test.mjs` via `WEBJS_E2E=1`, including network probes / navigation / streaming), and **smoke** (`test/examples/*/smoke/*`). A unit test is NECESSARY BUT NOT SUFFICIENT for any client-router / component / browser-facing change (the headline behaviour is a browser/e2e assertion). **Bun parity is part of the task, not an afterthought:** WebJs runs on Node 24+ AND Bun (#508), so a change to a runtime-sensitive surface (the serializer, the node:http vs `Bun.serve` listener + request path, SSR / action / CSRF dispatch, streams, `node:crypto`, the TS stripper, auth / session / cors) MUST be proven on Bun (`node scripts/run-bun-tests.js` + the touched `test/bun/*.mjs` under `bun`) AND ship an added/updated `test/bun/.mjs` cross-runtime assertion. `npm test` does NOT run browser, e2e, or Bun; run the layers you touched yourself and report the result (GitHub Actions runs every layer on the PR). Never report work done with failing or missing tests. See https://webjs.dev/docs/testing. Enforced by `.claude/hooks/require-tests-with-src.sh` (the scaffold variant WARNS unless `WEBJS_TEST_GATE=block`) and `.claude/hooks/require-bun-parity-with-runtime-src.sh` (BLOCKS a commit that stages runtime-sensitive source with no `test/bun/**` test; escape hatch `WEBJS_BUN_VERIFIED=1`). 2. **Documentation, part of the definition of done (not optional).** A task is NOT done until EVERY doc surface its change touches is in sync: the docs site (`website/app/(site)/docs/`, the canonical documentation), per-package `AGENTS.md` for contributor-facing changes, the marketing `website/`, the scaffold templates (`packages/cli/templates/`), `README.md` for a headline capability, and the brief (`packages/mcp/src/brief.js`, pasted verbatim into this file and `packages/cli/templates/AGENTS.md`) only when a Lit or Next.js habit can no longer produce correct code. Updating `AGENTS.md` alone reproduces the #488 gap (docs site left stale). Invoke the `webjs-doc-sync` skill to sync every applicable surface. Enforced by `.claude/hooks/require-docs-with-src.sh`, which BLOCKS a commit that stages public `packages/*/src` source with no doc surface alongside it (a genuinely internal refactor / CI / release / perf change with no behaviour change bypasses with `WEBJS_NO_DOC_GATE=1`). Every commit gate's escape hatch works either in the environment or written in front of the commit it applies to (`WEBJS_NO_DOC_GATE=1 git commit ...`), since a hook cannot see an environment an agent sets for one command. -3. **Scaffold sync (when a feature changes what apps should do).** The scaffold `webjs create` emits is minimal: a root layout, a starting home page, a theme toggle, db wiring and a starter test, one example module (`modules/users/`) the agent reads and then deletes, plus `AGENTS.md`: the brief, a few scaffold rules, and a "This app" section the agent fills in as it builds (`CLAUDE.md` imports it). The feature gallery (`gallery/`, deployed at gallery.webjs.dev) is a standalone app and ships in no scaffold. So when a WebJs feature is added or changed, ask: does the generator (`packages/cli/lib/create.js`), a gallery demo (`gallery/`), or the brief need to move? Verify by generating an app and running `generate + boot + webjs check` (the generators emit strings, so an escaping bug only shows in a freshly generated app). See `framework-dev.md`. +3. **Scaffold sync (when a feature changes what apps should do).** The scaffold `webjs create` emits is minimal: a root layout (dark mode follows the OS), a starting home page, db wiring and a starter test, the UI kit's config and theme with no kit code pre-installed, an empty `modules/` for the features (its layout is in `AGENTS.md`), plus `AGENTS.md`: the brief, a few scaffold rules, and a "This app" section the agent fills in as it builds (`CLAUDE.md` imports it). The feature gallery (`gallery/`, deployed at gallery.webjs.dev) is a standalone app and ships in no scaffold. So when a WebJs feature is added or changed, ask: does the generator (`packages/cli/lib/create.js`), a gallery demo (`gallery/`), or the brief need to move? Verify by generating an app and running `generate + boot + webjs check` (the generators emit strings, so an escaping bug only shows in a freshly generated app). See `framework-dev.md`. 4. **Convention validation.** Run `webjs check` and fix violations. Run it from INSIDE an app, never from the repo root: the root is a workspace, not an app, so the command refuses there with exit 1 rather than reporting the cross-app collisions no single runtime ever sees (#1301). In this repo that means `( cd gallery && npx webjs check )`, `( cd examples/blog && npx webjs check )` and `( cd website && npx webjs check )`. Run `webjs doctor` too when you touched an in-repo app (`gallery`, `examples/blog`, `website`): the required `conventions` CI job runs it over all three, and it fails on a hard toolchain check or on whatever that app's `webjs.doctor.gate` marks `error` (today `UNMARKED_ASSET_LINKS` in `website` and `examples/blog`), so a clean `webjs check` alone is not enough to predict that job (#1257). The repo root has no local CI battery (#1630): GitHub Actions runs the whole list on the PR. Inside `gallery` / `examples/blog` / `website`, `npm run ci` runs that app's own `webjs.ci` list (#1471); in a linked worktree invoke the branch's CLI by path (`node ../packages/cli/bin/webjs.js ci` inside an app) because the hoisted bin resolves into the primary checkout. ### Git workflow (mandatory) @@ -171,9 +171,11 @@ routing and Lit components, with the differences below. Before hand-writing auth, sessions, caching, rate limits, uploads, realtime or SEO, run `npx webjs source`, which lists what WebJs provides for each need. `npx webjs source ` then prints one export's signature and example. -After each edit run `npx webjs check` and `npx webjs status`. The framework -source is in `node_modules/@webjsdev/*` (no build, so it is the code that -runs) and the human docs are at https://webjs.dev/docs. +After each edit run `npx webjs check`. To verify the app, run `npx webjs verify`: +check, typecheck, the tests, and every route booted in-process, in one call, +with no dev server to start, curl or stop. The framework source is in +`node_modules/@webjsdev/*` (no build, so it is the code that runs) and the +human docs are at https://webjs.dev/docs. --- @@ -204,7 +206,7 @@ These hold for the framework and every app built on it. Hit one as a runtime err ## CLI and scaffolding -`webjs create [--template api] [--db sqlite|postgres] [--runtime node|bun] [--skip-ci]` scaffolds an app (full-stack by default, `api` for a backend with no UI); always scaffold rather than hand-roll, and keep app data in the wired-up database, never JSON files. The other commands: `webjs dev`, `start`, `test`, `check [--rules] [--json]`, `ci`, `routes`, `mcp`, `status`, `stop`, `source `, `doctor`, `audit`, `types`, `regenerate`, `typecheck`, `db`, `ui`, `vendor`, `version`, `help [command]`. `webjs help ` prints each one's options; the docs site has the full reference. Run this repo's own apps (`website/`, `gallery/`, `examples/blog/`) from inside them with their `npm run dev` / `npm start`. +`webjs create [--template api] [--db sqlite|postgres] [--runtime node|bun] [--skip-ci]` scaffolds an app (full-stack by default, `api` for a backend with no UI); always scaffold rather than hand-roll, and keep app data in the wired-up database, never JSON files. The other commands: `webjs dev`, `start`, `test`, `check [--rules] [--json]`, `ci`, `routes`, `mcp`, `status`, `stop`, `verify`, `source `, `doctor`, `audit`, `types`, `regenerate`, `typecheck`, `db`, `ui`, `vendor`, `version`, `help [command]`. `webjs help ` prints each one's options; the docs site has the full reference. Run this repo's own apps (`website/`, `gallery/`, `examples/blog/`) from inside them with their `npm run dev` / `npm start`. `webjs check` carries correctness rules only (code that is wrong to ship), run unconditionally; anything a sensible app could do differently is a convention in prose, not a check. Run it from INSIDE an app, never from the repo root. diff --git a/README.md b/README.md index 002760fc6..a67403be9 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ older, unrelated Java framework also used the name WebJS. > - Any product UI (todo, blog, notes, dashboard, marketplace, social, e-commerce, a SaaS with accounts…) → **default** (`webjs create `) > - Backend-only HTTP/JSON API, no UI → **`--template api`** > -> **The scaffold is minimal, grown in place.** It ships a root layout, a starting home page, a theme toggle, database wiring, a starter test, and one example feature module (`modules/users/`) to copy and then delete. The framework context is a short brief in `AGENTS.md`, which also carries a section the agent keeps current about the app: WebJs follows Next.js App Router routing and Lit's component APIs, so the brief lists only what differs, and `webjs check` refuses the rest with the fix. Build the app the user asked for on top of the scaffold; `npx webjs source` lists what WebJs already provides. Runnable demos of every feature live at [gallery.webjs.dev](https://gallery.webjs.dev) (source in `gallery/`). +> **The scaffold is minimal, grown in place.** It ships a root layout, a starting home page, database wiring, a starter test, the UI kit's config and theme (components are added on demand), and an empty `modules/` whose layout `AGENTS.md` describes. The framework context is a short brief in `AGENTS.md`, which also carries a section the agent keeps current about the app: WebJs follows Next.js App Router routing and Lit's component APIs, so the brief lists only what differs, and `webjs check` refuses the rest with the fix. Build the app the user asked for on top of the scaffold; `npx webjs source` lists what WebJs already provides. Runnable demos of every feature live at [gallery.webjs.dev](https://gallery.webjs.dev) (source in `gallery/`). > > Full rules: [`AGENTS.md` → How AI agents must scaffold](./AGENTS.md#how-ai-agents-must-scaffold). > Full framework docs (every API, every recipe): **https://webjs.dev/docs**. diff --git a/examples/blog/components/ui/button.ts b/examples/blog/components/ui/button.ts index 4dc8ac583..596678583 100644 --- a/examples/blog/components/ui/button.ts +++ b/examples/blog/components/ui/button.ts @@ -65,8 +65,8 @@ export interface ButtonClassOptions { } /** Compose Tailwind classes for a button. Stable shape: object-arg, both optional. */ -export function buttonClass(opts: ButtonClassOptions = {}): string { +export function buttonClass(opts: ButtonClassOptions & { className?: string } = {}): string { const variant = opts.variant ?? 'default'; const size = opts.size ?? 'default'; - return cn(BASE, VARIANTS[variant], SIZES[size]); + return cn(BASE, VARIANTS[variant], SIZES[size], opts.className); } diff --git a/gallery/modules/gallery/ui/button.ts b/gallery/modules/gallery/ui/button.ts index e7ac82fb8..9057178b9 100644 --- a/gallery/modules/gallery/ui/button.ts +++ b/gallery/modules/gallery/ui/button.ts @@ -81,8 +81,8 @@ export interface ButtonClassOptions { * (`buttonClass()` is the primary call-to-action). `cn` de-duplicates, so you * can append your own layout classes: `class="${buttonClass()} w-full"`. */ -export function buttonClass(opts: ButtonClassOptions = {}): string { +export function buttonClass(opts: ButtonClassOptions & { className?: string } = {}): string { const variant = opts.variant ?? 'default'; const size = opts.size ?? 'default'; - return cn(BASE, VARIANTS[variant], SIZES[size]); + return cn(BASE, VARIANTS[variant], SIZES[size], opts.className); } diff --git a/packages/cli/AGENTS.md b/packages/cli/AGENTS.md index a2fd994c0..0bb16cb9d 100644 --- a/packages/cli/AGENTS.md +++ b/packages/cli/AGENTS.md @@ -292,12 +292,13 @@ README.md npm-facing package readme. |---|---| | `webjs dev` | Runs `startServer({ dev: true })` in a child under WebJs's own reload supervisor (#514, #1521, `lib/dev-supervisor.js` plans, `lib/dev-reload.js` runs): on Node the child re-evaluates edited modules in place through `@webjsdev/server`'s `module.registerHooks` resolve hook (#1689) and announces that over IPC, after which the supervisor restarts it only for a restart file (an env file such as `.env` or `.env.local`, `package.json`, a lockfile, `instrumentation.*`, `env.*`), falling back to a restart on every watched change when the child never announces (a Node with no `registerHooks`, an older `@webjsdev/server`); on Bun the child runs under `bun --hot`, whose re-run of this CLI is handed to the first run's server (`lib/dev-hot-rerun.js`, #1575) so one server lives for the whole session, and only the same restart files restart it. On both, a watcher error (EACCES / ENOENT on one path) is a warning, never a crash, and a crashed child is restarted on the next change or after a backoff. `--no-hot` opts out and runs the server in-process on either runtime. In the parent (pre-spawn) it runs the configured dev orchestration (#550, `lib/run-tasks.js`): the `webjs.dev.before` steps (one-shot) to completion, then the `webjs.dev.parallel` watchers (e.g. the Tailwind CLI) alongside the server, torn down on exit. So a bare `webjs dev` runs the same before-steps and watchers as `npm run dev`. The scaffold ships `webjs db migrate` as both a `dev.before` and a `start.before` step (#725), so a `db:generate`'d migration is applied on the next boot in dev and prod alike with no manual `db:migrate`; `.env` is loaded before the dev before-steps (same as start), so a Postgres dev migrate sees `DATABASE_URL`. Local binaries (`drizzle-kit`, `tailwindcss`) resolve because the spawn PATH is prepended with the ancestor `node_modules/.bin` dirs, npm-style. **Before dispatching either dev or start**, a directory-relative resolve probe (`checkFrameworkResolves` from `lib/doctor.js`) checks that `@webjsdev/core` resolves from `process.cwd()`; if not (the fresh-git-worktree-without-node_modules trap, #954), it prints the cause + remedy and exits 1 instead of letting a raw `ERR_MODULE_NOT_FOUND` bubble from deep in SSR. A no-op single resolve on the happy path. | | `webjs start` | `startServer({ dev: false })`, plain HTTP/1.1 (front a reverse proxy for TLS + HTTP/2). Shares the dev framework-resolve preflight above (#954). Both `dev` and `start` first refuse with exit 1 when the cwd has no `app/` (#1526, `refuseOutsideApp` in the bin, `findServeTarget` / `notAnAppServeMessage` in `lib/check-target.js`, the same predicate as `webjs check`'s #1301 guard): at a workspace root the message names the member apps, inside an app's subdirectory the app root. A route folder named `app` (`/app` when the app has `app/app/page.ts`) is refused too, naming ``, because `findServeTarget` checks `nearestAppRoot` (both `app/` and `package.json`), the rule `webjs stop` and `webjs status` resolve by, so a server is never recorded where they cannot find it. It runs before the resolve probe and every before-step, and the dev child skips it (its parent checked the same cwd). Without it a launch from a workspace root booted, said it was ready, and answered 404 for every route. Tests: `test/cli/check-target.test.mjs`, `test/e2e/dev-workspace-member.test.mjs` (hoisted bin under Node and Bun). | -| `webjs test [--server\|--browser]` | Runtime-native test runner (#570): server tests run under `node --test` on Node and `bun test` on Bun (`bun --test` is invalid), dispatched on `process.versions.bun`; browser tests run the app's resolved `@web/test-runner` (`wtr`) bin via `process.execPath` (no `npx`). Server tests of a SQLite app get a fresh database (`lib/test-db.js`: `wantsTestDatabase` + `prepareTestDatabase`, which runs this CLI's own `db migrate` against a temp file, or `db push --force` while the app has no migrations yet (#1686), and passes `DATABASE_URL` to the run), the Rails test-database habit; a shell `DATABASE_URL`, a non-SQLite dialect, or `WEBJS_TEST_DB=0` leaves it off. Tests: `test/cli/test-db.test.mjs` (strips `NODE_TEST_CONTEXT` so the inner `node --test` sets its own exit code). | +| `webjs test [--server\|--browser]` | Runtime-native test runner (#570): server tests run under `node --test` on Node and `bun test` on Bun (`bun --test` is invalid), dispatched on `process.versions.bun`; browser tests run the app's resolved `@web/test-runner` (`wtr`) bin via `process.execPath` (no `npx`). Server tests of a SQLite app get a fresh database (`lib/test-db.js`: `wantsTestDatabase` + `prepareTestDatabase`, which runs this CLI's own `db migrate` against a temp file, or `db push --force` while the app has no migrations yet (#1686), and passes `DATABASE_URL` to the run), the Rails test-database habit; on Node, where each test file is a process of its own, `lib/test-db-preload.js` (passed with `--import`) gives each file its own copy of the migrated template, since one shared file failed with `database is locked` (#1697); a shell `DATABASE_URL`, a non-SQLite dialect, or `WEBJS_TEST_DB=0` leaves it off. Tests: `test/cli/test-db.test.mjs` (strips `NODE_TEST_CONTEXT` so the inner `node --test` sets its own exit code). | | `webjs ci [-f\|--fail-fast] [--only ]... [--json] [--signoff]` | Local CI (#1471), the Rails `bin/ci` posture: runs the step list `package.json` declares under `webjs.ci.steps` (`readCiConfig` in `lib/ci-config.js`, `runCi` in `lib/ci-runner.js`). Each step is timed with a `✅` / `❌` result line, the run ends with a failure list and one total line, and the exit is 1 on any failure (130 on interrupt). A group with `parallel: N` runs N steps at once with each step's output captured and replayed whole; a group nested in it takes one slot and runs sequentially. Every child gets `CI=true`, `node_modules/.bin` on PATH, and the step's `env`; `.env` is loaded first like dev / start. The predicate is the CONFIG, not an `app/` directory, so a workspace root (this monorepo) is a legitimate target; no block is exit 1 naming the workspace members that declare one (`--json`: `{ error: { code: 'NO_CI_CONFIG' } }`), a malformed block is `INVALID_CI_CONFIG` with every problem's JSON path, an unknown `--only` title is `UNKNOWN_ONLY`. `--json` puts one document on stdout (`{ ok, seconds, interrupted, steps[] }`, failed steps carrying their captured output) and the human report on stderr. Under `GITHUB_ACTIONS` each step is a `::group::` and a failure an `::error::` annotation, and a `$GITHUB_STEP_SUMMARY` table is appended, so one cloud job running the whole list still names the layer that broke. `--signoff` runs `gh signoff` after a green run (a red run prints the do-not-merge heading). Tests: `test/cli/ci.test.mjs`, `test/bun/ci-runner.mjs` (both runtimes), `test/ci-config/`, `test/ci-runner/` | | `webjs check [--rules] [--json]` | `checkConventions()` from `@webjsdev/server/check`. `--rules` lists the checks. `--json` emits the structured violations + a summary count as JSON (via `projectCheck` from `@webjsdev/mcp/check-report`, the same projector the MCP `check` tool uses, #415), so an agent in a loop consumes structured data instead of regex-scraping stdout; the non-zero exit on violations is preserved. Report-only: each violation carries a prose `fix` hint, but there is no `--fix` autofix flag (the rules either rewrite code or rename files, so an automatic codemod is not safe). Refuses with exit 1 in a directory that has no `app/`, naming the workspace member apps to run it in when the directory declares `workspaces` (#1301): every rule assumes ONE application, so a workspace root reports collisions no single runtime ever sees (67 false findings at this repo's root). The predicate is the `app/` directory alone, which both scaffold templates create, and `--rules` is exempt and works anywhere. Under `--json` the refusal is the SECOND shape this flag can emit, `{ error: { code: 'NOT_AN_APP', message, cwd, apps } }`, and it deliberately carries neither `violations` nor `summary`, so a consumer that ignores the exit code and reads `report.violations.length` throws instead of being told a workspace is clean. Branch on `error` before reading `violations`. Guard in `lib/check-target.js` | | `webjs routes [--json\|--table] [--no-headers]` | Prints the route table to stdout (#975): every page (path, owner file, dynamic params) and every `route.{js,ts}` handler (path, owner file, HTTP methods). Reuses `buildRouteTable` from `@webjsdev/server` (the ONE walker, shared with `webjs types` + the dev server) and the shared `projectRoutes` projector from `@webjsdev/mcp/routes-report`, so `--json` is byte-identical to the MCP `list_routes` tool (the same split as `check --json` / `check-report.js`). Default is a grouped tree; `--table` is aligned KIND/PATH/METHODS/FILE columns and `--no-headers` drops the header row for piping. Read-only. Tests: `test/cli/routes.test.mjs` | | `webjs status [path...] [--port N] [--boot] [--json] [--timeout <s>]` | `runStatus` in `lib/status.js` (#1664), pure of `process` (port, fetch, clock and output injected). Waits a short grace for the watcher, then polls the dev server's `GET /__webjs/dev/status?wait=<s>` (retrying a refused connection, since the dev server restarts for a restart-file edit or a crash) until it reports `settled`, requests each given path (the app root when none is given, under `webjs.basePath`, read with `readAppBasePath`) plus every page with a recorded render error, so a page an edit broke or fixed is re-rendered, re-reads the status, and prints every error since the last rebuild with file, line and code frame, then any `warnings` (browser-looking code in a page, layout or boundary, which runs only on the server, #1686), which never change the exit. Exit 0 when settled, ready and clean with every path below 400; 1 on any problem or no settle before `--timeout` (default 30s). With no server on the port (a 1.5s probe) or with `--boot`, the bin calls `runStatusBoot` instead, which creates the dev request handler in-process and hands `runStatus` a `fetch` that calls it, so the whole flow is reused; with no paths named it probes `bootProbePaths(projectRoutes(...))`, every page and GET route handler that needs no parameter (an optional catch-all at its parent path), lists the skipped dynamic routes, and fails a derived path only at 500 (`namedFailStatus`), since a redirect or a signed-out 401 is an answer. Agents in the #1687 evals spent 10 to 25 tool calls per build starting a dev server, curling and killing it; this is one call. `runStatus` itself still returns 2 (`NO_SERVER_EXIT_CODE`) when called directly with no server. A 404 from the endpoint means a production server and is reported as such. Port resolution matches `webjs dev` (`loadAppEnv` then `resolvePort`), then the live dev record's port (`recordedDevPort`, port 0 ignored). It resolves the app root with `findAppRoot` (`lib/check-target.js`, shared with `webjs stop`: the nearest directory at or above the cwd holding both `app/` and `package.json`), `chdir`s there, and exits 1 outside any app (`--json`: `{ error: { code: 'NOT_AN_APP' } }`). Tests: `test/cli/status.test.mjs` (drives it against the real dev handler in-process), `test/cli/status-record.test.mjs` (a spawned `webjs dev`, run from a subdirectory) | | `webjs stop` | `stopServers` in `lib/stop.js`. Each server records `{ port, pid, startTime }` in `.webjs/dev-server.json` / `.webjs/start-server.json` through `recordServer` in `lib/server-record.js` (re-exported by `lib/port.js`); `webjs status` reads only the dev one. WHO writes and WHEN is deliberate: a supervised `webjs dev` is recorded by the SUPERVISOR (the process to signal, since a stopped child alone would be restarted), BEFORE its `dev.before` steps and for its whole lifetime, so a stop during a slow before-step or a crash-restart backoff finds it; the child records nothing. That early record carries the argv/env port, which the bind can contradict (`--port 0`, a `.env` `PORT` edit that restarts the child on another port), so each child sends `{ webjs: DEV_LISTENING_MESSAGE, port }` over the IPC channel once bound (`boundPort` reads the `startServer` handle) and the supervisor's `onListening` rewrites the record's port with `updateRecordedPort`, after every respawn too, keeping its own pid and start time. `webjs start` and `webjs dev --no-hot` record themselves only once bound, with the bound port, so a server that fails on a taken port never writes. `recordServer` never overwrites a record whose process is still a live server, and the exit handler removes the record only while it names this process, so a second server that fails with EADDRINUSE leaves the first one's record intact. A refused server that keeps running (one on another port) takes the record over once the holder is gone: every server records through `claimServerRecord`, which retries `recordServer` on an unref'd 2s interval (`RECLAIM_INTERVAL_MS`) with the port it serves on then (the supervisor tracks its child's last reported bind), so stop and status never lose a running server. Until the supervisor installs its handlers, the dev parent stops the in-flight before-step (`runBeforeSteps`' `onSpawn`) and exits through its exit handlers on SIGTERM / SIGINT / SIGHUP; those early handlers come off only after the inline or supervisor handlers are installed, with nothing awaited in between (a source-order test in `test/cli/stop.test.mjs` pins it), since a signal landing while neither is installed takes the default action and skips the exit handlers. The `dev.parallel` tasks live as long as the dev parent (an `exit` handler kills them on every path), under `--no-hot` too. Liveness is ONE helper both stop and status use (`isLiveServer`): the pid is alive (a zombie is not) and is the process that wrote the record, decided by its start time (`/proc/<pid>/stat` field 22 on Linux, `ps -o lstart=` elsewhere, run with `TZ=UTC` and the C locale because `lstart` is local time and the recording supervisor may have loaded a `.env` `TZ` that `webjs stop` never does), else by its command line running the CLI entry with `dev` / `start`, else (Windows) by liveness alone. Stop SIGTERMs the recorded pid, waits up to 10s, then SIGKILLs. It resolves the app root with `findAppRoot` (`lib/check-target.js`: the nearest directory at or above the cwd holding both `app/` and `package.json`, else the nearest holding `app/`, so a route folder named `app` (`app/app/page.ts`) is never taken for the root; `webjs status` uses the same) and exits 1 outside any app (`notInsideAppMessage`). Exit 0 when nothing is left running, 1 when a server would not exit. Eval agents spent 54 turns across 24 builds on pkill / kill / pgrep. Tests: `test/cli/stop.test.mjs`, `test/port/dev-port-record.test.mjs`, `test/cli/status-record.test.mjs` | +| `webjs verify` | `runVerify` in `lib/verify.js` (#1697), the Rails `bin/ci` shape for the local loop, run on the `webjs ci` engine (`runCi`, every step captured, its own report silenced): `webjs check` and `webjs typecheck` in parallel, then `webjs test`, then the app's `webjs.dev.before` steps as one `prepare` step and `webjs status --boot`. It deliberately does not run `webjs.ci.steps`, the full gate with doctor, a network audit, browser and e2e tests. It loads no env file itself, so each step reads the files for its own mode. Every step runs after a failure too; a pass prints one line, a failure the tail of its output with stack frames dropped (the code frame locates it). Exit 0 or 1. Eval agents spent about 19 late turns per build starting a dev server, curling and stopping it, past the 100K-token price tier. Tests: `test/cli/verify.test.mjs` | | `webjs mcp` | Delegates to `runMcpServer()` from the standalone `@webjsdev/mcp` package (#415; full surface in `packages/mcp/AGENTS.md`). A read-only MCP stdio server: INTROSPECTION (`list_routes` / `list_actions` / `list_components` / `check`), `init` (the WebJs brief), `source`, and `ui`. No docs corpus, resources, or prompts. The scaffold's `.claude.json` registers the server directly as `{ "command": "npx", "args": ["@webjsdev/mcp"] }` (mountable in any MCP host, e.g. Cursor `.cursor/mcp.json`); `webjs mcp` stays as a back-compat alias. STDOUT is the JSON-RPC channel (diagnostics go to stderr) | | `webjs doctor` | `runDoctorChecks()` from `lib/doctor.js` (delegating to `lib/doctor/runner.js`). TWO route checks share ONE `analyzeRouteModules()` call so the module graph is built once per run: `ROUTE_BROWSER_CODE` (#1686, which WARNS on a route module's `hints`, code in a page, layout or boundary that looks meant for the browser but runs only on the server) and `ORPHAN_COMPONENTS` (which warns ONLY on an orphan, a component class with no registration call or a computed tag, which the scanner cannot see and which therefore never upgrades; gateable like any other code via `webjs.doctor.gate`). A project-health checklist over existing signals (Node major, tsconfig `erasableSyntaxOnly`, `.env` drift vs `.env.example`, vendor-pin freshness, the `.gitignore` keeping `.webjs/vendor/` committable (`vendor-gitignore`, moved here from `webjs check` in #461 as a warn since it is a project-config concern, not source correctness), `@webjsdev/*` version coherence (`WEBJS_VERSIONS`, which resolves each declared dep's INSTALLED version through Node's own resolver anchored at the app dir rather than reading `<appDir>/node_modules/<dep>/package.json`, so a workspace-hoisted install resolves and the check agrees with `FRAMEWORK_RESOLVE` instead of contradicting it, #1300; the resolve tries `<dep>/package.json` FIRST because a bin-only package like `@webjsdev/cli` has no main entry, and falls back through the main entry plus a bounded walk to the package root on `ERR_PACKAGE_PATH_NOT_EXPORTED` because `@webjsdev/server` locks its manifest out of its `exports` map, so neither half alone resolves all four packages. Local to `lib/doctor.js` rather than `getPackageVersion` from `@webjsdev/server`, since doctor must run when the framework does not resolve at all (#954) and that helper returns null for a bin-only package. Before the fix the check warned on every healthy workspace install, which made it ungatable), a framework-resolve probe (#954: `checkFrameworkResolves` + the exported `frameworkResolves` helper WARN when `@webjsdev/core` cannot be resolved FROM the app dir via a directory-relative `createRequire` probe, naming the fresh-git-worktree-without-node_modules cause and the fix; silent PASS when it resolves, so a healthy app is untouched), importmap coherence, git pre-commit hook, and a route-module advisory (#1686: `checkRouteBrowserCode` reads the shared `analyzeRouteModules` report and WARNS, naming the file and the hint, for each page, layout or boundary holding code that looks meant for the browser; advisory-only, skipped when there is no `app/`), a framework-link integrity check (#1442: `checkFrameworkLinks` + the exported `inspectFrameworkLink` helper WARN when the `@webjsdev/core` entry in node_modules is a symlink that DANGLES or resolves OUTSIDE the tree that PHYSICALLY owns that `node_modules`, which is what an install run inside a linked worktree leaves behind. `FRAMEWORK_RESOLVE` cannot see it, because a link into a live foreign checkout resolves perfectly and silently runs another branch's framework source. The owner rule is what keeps it correct in a linked worktree, where `node_modules` is itself a symlink at the primary's, so the owning tree is the PRIMARY and a target inside it is right rather than foreign; the link target is resolved against the directory the link physically sits in, since resolving `../../packages/core` lexically through a symlinked `node_modules` lands under the worktree and would report every healthy linked worktree as corrupted), and an unmarked-stylesheet-link advisory (#1095: `checkUnmarkedAssetLinks` scans every `app/**` route module that renders markup (`page` / `layout`, plus the always-shipped `error` / `not-found` / `forbidden` / `unauthorized` / `loading` boundaries and `global-error`, which writes its own `<head>`), skipping `_private` folders the router never routes, for a `<link rel="stylesheet">` whose href is a STATIC, quoted, root-absolute literal (a `public/` file is served at the URL root), i.e. one not wrapped in `asset()`, and WARNs with `file:line`, since that url is un-versioned and a deploy cannot bust a CDN's copy. Scoped to `rel="stylesheet"`: a cross-origin sheet must keep its exact url, `rel="icon"` is a legitimate deliberate non-mark (the website leaves its favicons bare so the SEO repo-health tests parse the hrefs literally), `rel="preload"` MUST stay unversioned or its hint could never match the request the CSS `url()` makes, and an `href=${expr}` hole is undecidable from source and is exactly the marked shape. It reads the author's SOURCE and rewrites nothing, deliberately: the automatic form was built and rejected in #1196, and this is the same authoring-time posture Rails and Remix take)), and a static build-output freshness advisory (`STATIC_ASSET_FRESHNESS`, #967: `checkStaticAssetFreshness` WARNS when a `webjs.dev.regenerate` output is `stale` or `unrecorded` against the build record in `.webjs/regenerate.json` (#1672). It reads the record through `regenerateStatus` from `@webjsdev/server` (dynamic import, like the route and coherence checks), so the doctor and the dev server share one definition of fresh rather than two walkers that can drift; an unresolvable server or one older than the CLI degrades to a `bestEffort` warning, capped so it can never be gated to error. A missing output passes, as a fresh clone before its first build. The fix is `webjs regenerate`, which works in CI with no dev server). PURE checks render with a `[pass]` / `[off]` / `[warn]` / `[fail]` marker; the exit is non-zero when a HARD check fails (Node below the floor, or `erasableSyntaxOnly` missing in an existing tsconfig) OR when a check the app gated `error` reports something (#1257, see below); an ungated warn (drift / staleness) never fails the exit. Each `DoctorResult` carries a stable SCREAMING_SNAKE `code` (#975, the `DOCTOR_CODES` map; e.g. `NODE_VERSION`, `TSCONFIG_ERASABLE`, `IMPORTMAP_COHERENCE`) so an agent branches on the failure KIND, not the message text. `--json` emits `{ results, summary }` where `results` is the raw `DoctorResult[]` (each carrying a `code` + its effective `severity`) and `summary` is `{ pass, warn, fail, off, strict, ok }` (the same array-under-a-key convention as `check --json`). A REJECTED `webjs.doctor` config is the one path that adds a third key, `configErrors`, an array of `{ kind }` entries (`malformed` / `unknown-key` / `unknown-code` / `bad-severity`) with `results` empty because no check ran; `--strict` additionally fails the exit on every REMAINING warning (on top of hard failures and gated errors), so doctor can gate a fully-clean fix loop. The only network touch (pin freshness, plus the importmap-coherence live resolve) is best-effort: a fetch failure is a warn, never a hard fail. The importmap-coherence check (#450) runs `@webjsdev/server`'s `checkImportmapCoherence` IDENTICALLY over the live importmap AND the vendored `.webjs/vendor/importmap.json`, warning when a pinned package needs a newer version of another pinned package than is pinned (the #446 skew class); it reads dependency metadata from the already-installed node_modules manifests (no network of its own) and degrades to "could not verify" when a manifest is unavailable. Tests: `test/cli/doctor.test.mjs` | | `webjs types` | `generateRouteTypes()` from `@webjsdev/server`, writes `.webjs/routes.d.ts` (typed `Route` union + per-route params, #258). Also auto-emitted at `webjs dev` startup | @@ -343,7 +344,7 @@ verbatim. transforms, never a new template. 2. **Scaffold is reference, not the final product.** The scaffold output ships a starting `app/page.ts`, an example - `User` Drizzle model, an example `theme-toggle` component. AI agents + `User` Drizzle model and an empty `modules/`. AI agents asked to build a real app MUST replace those with the actual app. The post-scaffold success message in `lib/create.js` prints this rule verbatim. diff --git a/packages/cli/README.md b/packages/cli/README.md index 4345742a1..9494be133 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -49,6 +49,7 @@ webjs check # validate source-code conventions (CI gate) webjs doctor # verify the project/toolchain setup (per-check severity via webjs.doctor.gate, so CI can gate a subset) webjs test # run server + browser tests webjs status [path...] # after an edit, wait for the dev server to settle and print every error since the last rebuild +webjs verify # check, typecheck, test, then boot the app in-process and request every route # (file, line, code frame); exit 1 on a problem, 2 if no dev server; --json for agents webjs stop # stop this app's running dev or start server (no pkill needed) webjs ci # local CI: run the webjs.ci step list in package.json (check, doctor, diff --git a/packages/cli/bin/webjs.js b/packages/cli/bin/webjs.js index b50b871f4..3b054ef38 100755 --- a/packages/cli/bin/webjs.js +++ b/packages/cli/bin/webjs.js @@ -84,6 +84,8 @@ const USAGE = `webjs commands: --only runs one step or group by title; --signoff runs "gh signoff" after a green run webjs routes [--json|--table] [--no-headers] Print the route table (path / owner file / methods). Default tree; --json matches the MCP list_routes shape; --no-headers drops the --table header webjs stop Stop this app's running dev or start server (the one its .webjs/ record names) + webjs verify Check, typecheck, test, then boot the app in-process and request every route; + one line per step, a failing step's output, exit 1 on any failure webjs status [path...] [--port N] [--json] Wait for a running dev server to settle after an edit, request each path, and report every error since the last rebuild; exit 1 on any problem, 2 if no server webjs mcp Start the read-only MCP server (routes / actions / components / check) @@ -340,6 +342,16 @@ const HELP = { ], examples: ['webjs stop', 'npx webjs dev --port 8910 & npx webjs status /; npx webjs stop'], }, + verify: { + usage: 'webjs verify', + summary: "Whether the app works, in one call: `webjs check`, `webjs typecheck` and `webjs test`, then the app's `webjs.dev.before` steps (its migrations and stylesheet) and an in-process boot that requests every page and GET route needing no parameter (`webjs status --boot`). No dev server is started, so none has to be stopped. Every step runs even after a failure; a passing step prints one line, a failing one the tail of its output. Run it when a feature is done instead of starting a server and curling routes.", + notesTitle: 'Exit status', + notes: [ + '0 when every step passed.', + '1 when any step failed, or when run outside any app.', + ], + examples: ['webjs verify', 'npx webjs verify'], + }, status: { usage: 'webjs status [path...] [--port N] [--boot] [--json] [--timeout <seconds>]', summary: 'Wait for a running `webjs dev` server to settle after an edit (the change rebuilt and the app analysed again), request each given path (the app root when none is given) plus every page with a recorded render error, then print every error: render, TypeScript strip, rebuild, route handler, server action, middleware. A render error stays listed until its page renders again. With no dev server on the port it boots the app in-process instead and probes every route that needs no parameter, so no server has to be started or stopped. Use it after each edit instead of sleeping and fetching a page.', @@ -938,8 +950,15 @@ async function main() { testDb = prepareTestDatabase(cwd, { cliBin: fileURLToPath(import.meta.url) }); console.log(`webjs test: using a fresh ${testDb.pushed ? 'test database with the schema pushed (no migrations yet)' : 'migrated test database'} (set WEBJS_TEST_DB=0 to use DATABASE_URL instead)\n`); } - const child = spawn(process.execPath, testArgs, { - stdio: 'inherit', cwd, env: { ...process.env, ...(testDb ? { DATABASE_URL: testDb.url } : {}) }, + // On Node each test file is a process of its own, and they gave one + // shared SQLite file `database is locked` errors; each one copies the + // migrated template instead (lib/test-db-preload.js, #1697). + const dbEnv = testDb ? { DATABASE_URL: testDb.url, WEBJS_TEST_DB_TEMPLATE: testDb.url.replace(/^file:/, '') } : {}; + const preload = testDb && !process.versions.bun + ? ['--import', new URL('../lib/test-db-preload.js', import.meta.url).href] + : []; + const child = spawn(process.execPath, [...preload, ...testArgs], { + stdio: 'inherit', cwd, env: { ...process.env, ...dbEnv }, }); const code = await new Promise(r => child.on('exit', r)); testDb?.cleanup(); @@ -1943,6 +1962,28 @@ Full docs: https://webjs.dev/docs`); const { stopServers } = await import('../lib/stop.js'); process.exit(await stopServers({ cwd: process.cwd() })); } + case 'verify': { + // One call for whether the app works (#1697): check, typecheck, test, + // then the dev before-steps and an in-process boot of every route. + const { findAppRoot, notInsideAppMessage } = await import('../lib/check-target.js'); + const { root: appDir, workspaceApps } = await findAppRoot(process.cwd()); + if (!appDir) { + console.error(notInsideAppMessage('verify', workspaceApps)); + process.exit(1); + } + // No env file is loaded here: each step is this CLI run as its own + // command, which loads the files for its own mode (`test` for the tests, + // `development` for the boot), as it would run alone. + process.chdir(appDir); + const { readAppTasks } = await import('../lib/app-tasks.js'); + const { shellQuote } = await import('../lib/run-tasks.js'); + const { runVerify } = await import('../lib/verify.js'); + process.exit(await runVerify({ + appDir, + cli: `${shellQuote(process.execPath)} ${shellQuote(fileURLToPath(import.meta.url))}`, + beforeSteps: readAppTasks(appDir).dev.before, + })); + } case 'status': { // Dev status (#1664): wait for the running dev server to settle, request // the given paths, report every error since the last rebuild. diff --git a/packages/cli/lib/ci-runner.js b/packages/cli/lib/ci-runner.js index 5e5ff12e7..87eca643f 100644 --- a/packages/cli/lib/ci-runner.js +++ b/packages/cli/lib/ci-runner.js @@ -186,6 +186,7 @@ export function stepSummaryMarkdown(result) { * env?: NodeJS.ProcessEnv, * actions?: boolean, * closeGraceMs?: number, + * markCi?: boolean, * }} [opts] * @returns {{ done: Promise<CiResult>, interrupt: () => void }} */ @@ -202,6 +203,9 @@ export function runCi(steps, cwd, opts = {}) { baseEnv: envWithLocalBin(cwd, opts.env || process.env), actions: !!opts.actions, closeGraceMs: opts.closeGraceMs ?? CLOSE_GRACE_MS, + // `webjs verify` runs the same engine for a local check and turns this + // off, so its steps see the shell's own CI, as `npm test` would. + markCi: opts.markCi !== false, cwd, /** @type {StepResult[]} */ results: [], @@ -369,7 +373,7 @@ function report(r, ctx) { async function runOne(step, group, ctx, capture) { const env = { ...ctx.baseEnv, - CI: 'true', + ...(ctx.markCi ? { CI: 'true' } : {}), // Colour for a captured child follows the runner's own colour decision // (a TTY with no NO_COLOR), so a user's NO_COLOR is honoured inside the // tools too rather than overridden by FORCE_COLOR. diff --git a/packages/cli/lib/create.js b/packages/cli/lib/create.js index cd29e550f..2d6b32efb 100644 --- a/packages/cli/lib/create.js +++ b/packages/cli/lib/create.js @@ -3,8 +3,8 @@ * * Creates a directory with: * - app/ with a root layout + page - * - modules/ skeleton - * - components/ with a theme toggle + * - an empty modules/ for the features (AGENTS.md lays out a module) + * - the UI kit's components.json and theme, with no kit code installed * - test/unit/ and test/e2e/ with example tests * - AGENTS.md, CLAUDE.md * - package.json with WebJs deps + test scripts @@ -95,27 +95,11 @@ function resolveUiRegistryRoot() { const UI_REGISTRY_ROOT = resolveUiRegistryRoot(); /** - * Add kit components to a freshly initialised app through the kit's own CLI - * (`webjsui add`), so the files are byte for byte what an agent's - * `npx webjs ui add <name>` writes: baked for the app's style, imports - * rewritten to its cn() helper. Local-first, so it makes no network call. - * @param {string} appDir - * @param {string[]} names - */ -function addUiComponents(appDir, names) { - const bin = resolve(UI_REGISTRY_ROOT, '..', '..', 'bin', 'webjsui.js'); - const r = spawnSync(process.execPath, [bin, 'add', ...names, '--cwd', appDir, '--yes', '--no-deps'], { encoding: 'utf8' }); - if (r.status !== 0) { - throw new Error(`[webjs create] could not add ${names.join(', ')} from the UI kit: ${(r.stderr || r.stdout || '').trim()}`); - } -} - -/** - * Write `lib/utils/cn.ts` (the `cn()` helper) and `components.json` so the - * scaffolded app is pre-initialised for `webjs ui add`. Reads the registry's - * `lib/utils.ts` verbatim and writes it under `lib/utils/cn.ts` in the - * scaffolded app so cn() sits in the same folder as the other browser-safe - * helpers (ui.ts, format.ts). + * Write `components.json` and the kit theme so the scaffolded app is + * pre-initialised for `webjs ui add`. No kit code is pre-installed: the first + * `add` writes `lib/utils/cn.ts` (and `dom.ts` when a component needs it) as + * registry dependencies, so an agent never reads library code it did not ask + * for (#1697). * * @param {string} appDir */ @@ -123,21 +107,6 @@ async function writeUiBootstrap(appDir) { // Caller (scaffoldApp) has already invoked assertUiRegistryAvailable(), // so the source files below are guaranteed to exist. - // 1) lib/utils/cn.ts: the cn() helper (pure; safe to import into a page). - const utilsContent = await readFile( - join(UI_REGISTRY_ROOT, 'lib', 'utils.ts'), 'utf8', - ); - await mkdir(join(appDir, 'lib', 'utils'), { recursive: true }); - await writeFile(join(appDir, 'lib', 'utils', 'cn.ts'), utilsContent); - - // 1b) lib/utils/dom.ts: the client-only DOM helper (onBeforeCache). Split out - // of cn.ts so importing cn() does not pin a page to the browser (#819). Any - // `webjs ui add` component that uses onBeforeCache imports it from here. - const domContent = await readFile( - join(UI_REGISTRY_ROOT, 'lib', 'dom.ts'), 'utf8', - ); - await writeFile(join(appDir, 'lib', 'utils', 'dom.ts'), domContent); - // 2) components.json: byte for byte what `webjsui init` writes (see the // DEFAULT_ALIASES / DEFAULT_TAILWIND_CSS constants in // packages/ui/src/commands/init.js, which #1129 made the single source of @@ -277,11 +246,10 @@ function setThemeVars(css, selector, vars) { /** * Fail loudly when the @webjsdev/ui registry is not on disk. The scaffold - * reads component sources, the cn() helper, and the @webjsdev/ui theme from - * UI_REGISTRY_ROOT and weaves them into a generated app/page.ts that - * imports `components/ui/button.ts`. If the registry is missing, the - * generated app boots to ERR_MODULE_NOT_FOUND on first request, which is - * a confusing failure for end-users to debug. + * reads the @webjsdev/ui theme from UI_REGISTRY_ROOT, and the app's first + * `webjs ui add` copies components and the cn() helper from it. If the + * registry is missing, the scaffold writes an unstyled app and every add + * fails, which is a confusing failure for end-users to debug. * * The check guards against an @webjsdev/ui published tarball that forgets * to ship `packages/registry/` in its `files` array (the bug fixed in @@ -785,8 +753,6 @@ export async function scaffoldApp(name, cwd, opts = {}) { 'test/hello/browser/hello.test.js', 'test/hello/e2e/hello.test.ts', 'web-test-runner.config.js', - // Optional boot-time APM hook (setOnError). Delete if unused. - 'instrumentation.ts', '.env.example', // Shipped without a dot (npm strips a published .gitignore) and renamed on copy. 'gitignore', @@ -1246,10 +1212,23 @@ export type ActionResult<T> = | { success: false; error: string; status: number }; `); + // The shared AGENTS.md lays out a module but names no example, since the + // full-stack app ships none. Say what this template's users module is, so + // it is replaced rather than kept in the finished app (#1697). + const agentsPath = join(appDir, 'AGENTS.md'); + const agents = await readFile(agentsPath, 'utf8'); + const anchor = /the feature's tests\r?\n/.exec(agents); + if (!anchor) { + throw new Error('[webjs create] templates/AGENTS.md lost the module layout line the api template annotates ("the feature\'s tests"); update the anchor in create.js.'); + } + const at = anchor.index + anchor[0].length; + await writeFile(agentsPath, agents.slice(0, at) + + '`modules/users/` with `app/api/users/` is an example of that layout: replace it with the app\'s own features.\n' + + agents.slice(at)); } if (!isApi) { - // The UI template: layout + page + theme toggle + Tailwind + // The UI template: layout + page + Tailwind // The Tailwind stylesheet is compiled from public/input.css (written below) // to a STATIC public/tailwind.css by css:build, and lib/utils/ui.ts helpers @@ -1291,17 +1270,9 @@ export type ActionResult<T> = assertUiRegistryAvailable(); // Pre-initialise @webjsdev/ui so the scaffold boots ready for - // `webjs ui add <name>`: writes components.json + lib/utils/cn.ts + - // styles/globals.css (the @webjsdev/ui theme). + // `webjs ui add <name>`: writes components.json + styles/globals.css (the + // @webjsdev/ui theme). No kit component is pre-installed (#1697). await writeUiBootstrap(appDir); - // The kit components the shell uses (the theme toggle's Button, the home - // page form's Input and Label), installed by the kit's own `add` - // (local-first, no network), exactly as `npx webjs ui add <name>` would. - addUiComponents(appDir, ['button', 'input', 'label']); - - // Pages style with Tailwind on the kit's tokens. The app is pre-initialised - // for `webjs ui add <name>` via writeUiBootstrap above and ships one kit - // component, the Button its theme toggle uses; the rest are added on demand. // The @webjsdev/ui theme (`--color-primary`, `--color-card`, the @theme maps, // @custom-variant, @keyframes) plus the app @theme mappings are compiled from @@ -1326,8 +1297,7 @@ export type ActionResult<T> = @source "../lib/**/*.{ts,js}"; /* Base styles, on the kit's tokens. The light tokens are on :root and the - dark ones on .dark, which the head script keeps in step with the saved - choice or the OS. color-scheme switches on the same class, so native + dark ones on .dark, which the head script keeps in step with the OS. color-scheme switches on the same class, so native controls and scrollbars always match the tokens: with JavaScript off the page is light throughout rather than light tokens over dark controls. */ @layer base { @@ -1390,81 +1360,34 @@ html:has(> body > header[class~="2xl:fixed"]) { @variant 2xl { scroll-padding-to await writeFile(join(appDir, 'app', 'layout.ts'), `import { html, cspNonce, asset } from '@webjsdev/core'; import type { LayoutProps } from '@webjsdev/core'; -import '#components/theme-toggle.ts'; - -/** - * Root layout: the ONLY file that writes the document shell. It wires a neutral - * design-token palette, the light/dark theme, and the Tailwind stylesheet, then - * renders \${children} in a bare container. Grow it in place: add a header, nav, - * footer, or reading column here as your app needs them. Design tokens live as - * plain CSS custom properties (they resolve with JavaScript disabled) and are - * mapped into Tailwind via @theme in public/input.css, so bg-background, - * text-foreground, bg-card, bg-primary, and border-border all work. - */ - -// The favicon and manifest are app/icon.svg and app/manifest.webmanifest: the -// framework links them into <head> itself, so nothing is declared here. Replace -// the placeholder icon with this app's own. -// LayoutProps types every layout argument (children, params, searchParams, -// url) from the framework, so children is a TemplateResult rather than an -// untyped value. Derive types like this everywhere instead of widening to -// unknown. +// The root layout, the only file that writes the document shell. Grow it in +// place (header, nav, footer). The favicon and manifest are app/icon.svg and +// app/manifest.webmanifest, which the framework links itself. Design tokens +// are in styles/globals.css, mapped into Tailwind by public/input.css. export default function RootLayout({ children }: LayoutProps) { - // Read the in-flight request's CSP nonce so the theme-detection inline script - // passes strict CSP. Returns '' when no CSP nonce is set. - const nonce = cspNonce(); + const nonce = cspNonce(); // '' unless CSP is on return html\` <script nonce="\${nonce}"> - // Light/dark theme, applied BEFORE first paint so a saved dark choice - // never flashes light. This is the one thing that cannot be a component: - // a component (the theme toggle included) upgrades only once its module - // has loaded, after the first paint. <theme-toggle> takes over from there - // (Lit's lifecycle), following the OS while the choice is "system". The - // dark tokens and color-scheme both switch on the .dark class; data-theme - // records a saved choice. With JavaScript off nothing sets .dark and the - // page is light throughout. Delete this block for a single-theme app. + // Dark mode follows the OS, set before first paint. The kit's dark + // tokens switch on the .dark class. (function(){ - try { - var t = null; - try { t = localStorage.getItem('webjs_theme'); } catch (_) {} - var el = document.documentElement; - if (t === 'light' || t === 'dark') el.dataset.theme = t; - el.classList.toggle('dark', t === 'dark' || (t !== 'light' && matchMedia('(prefers-color-scheme: dark)').matches)); - } catch (_) {} + var m = matchMedia('(prefers-color-scheme: dark)'); + var set = function(){ document.documentElement.classList.toggle('dark', m.matches); }; + set(); + m.addEventListener('change', set); })(); </script> <meta name="color-scheme" content="light"> - <!-- Geist for text and headings and Geist Mono for code, the webjs.dev/ui - type. Swap these for your own fonts (and update --font-sans in - styles/globals.css, or apply a preset with webjs ui init --preset, - which prints the faces to load). --> + <!-- Geist and Geist Mono; swap them with --font-sans in styles/globals.css. --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="anonymous"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@100..900&family=Geist+Mono:wght@400;500;700&display=swap"> - <!-- Tailwind: a STATIC stylesheet compiled from public/input.css to - public/tailwind.css by css:build (run automatically by the dev and start - tasks; in dev it is also recompiled on request when a source changes, so - it never goes stale). A real stylesheet, so the app is fully styled with - JavaScript DISABLED (no in-browser compile). - - asset() adds a content hash in production (/tailwind.css?v=...) - and the framework then serves it immutable for a year, so a deploy that - changes the CSS changes the url and no browser or CDN can serve the old - bytes. Mark the thing that FETCHES: do not wrap a <link rel="preload"> - whose asset is really fetched by an @font-face url() in the CSS, or the - preload can never match the request and the file downloads twice. --> - + <!-- Compiled from public/input.css by css:build, so the page is styled + with JavaScript off. asset() versions the url in production. --> <link rel="stylesheet" href=\${asset('/tailwind.css')}> - <!-- No style block here: the base styles, color-scheme and the pinned-header - offset are in public/input.css, on the kit's tokens, and every token - (the --header-h navbar height included) is in styles/globals.css. --> - <!-- Top navbar, on every page: brand on the left, links + theme toggle on - the right. It floats (no separator) and is in normal flow, so it just - scrolls with the page. To pin it, add fixed inset-x-0 top-0 z-20 to its - class (position: fixed, never sticky, which flickers on iOS during a nav). - Its height is the --header-h token, so keep it one row: nothing measures - it, which is what keeps the offset right after a client-router swap. --> + <!-- One row, --header-h tall. To pin it, add fixed inset-x-0 top-0 z-20 + (fixed, never sticky, which flickers on iOS). --> <header class="max-w-5xl mx-auto px-4 sm:px-6 h-(--header-h) flex items-center justify-between gap-4"> <a href="/" class="inline-flex items-center gap-2 no-underline text-foreground font-display font-bold tracking-tight"> <span class="size-5.5 rounded-md bg-linear-to-br from-foreground to-muted-foreground" aria-hidden="true"></span> @@ -1473,205 +1396,37 @@ export default function RootLayout({ children }: LayoutProps) { <nav class="flex items-center gap-4 text-sm" aria-label="Primary"> <a href="https://webjs.dev/docs" target="_blank" rel="noopener" class="hidden sm:inline text-muted-foreground hover:text-foreground no-underline transition-colors">Docs</a> <a href="https://github.com/webjsdev/webjs" target="_blank" rel="noopener" class="hidden sm:inline text-muted-foreground hover:text-foreground no-underline transition-colors">GitHub</a> - <theme-toggle></theme-toggle> </nav> </header> - <!-- Fill the viewport minus the navbar, so a short page has no spurious - scrollbar (min-h-dvh alone would overflow by the navbar height). --> - <main class="min-h-[calc(100dvh-var(--header-h))] max-w-5xl mx-auto px-4 sm:px-6 py-8"> + <!-- The viewport minus the header. Each page renders its own main element. --> + <div class="min-h-[calc(100dvh-var(--header-h))] max-w-5xl mx-auto px-4 sm:px-6 py-8"> \${children} - </main> + </div> \`; } `); - // The example module: modules/<feature>/ holds a feature's server actions, - // queries, components, utils and types, and the routes in app/ stay thin. - // One tiny feature over the schema's users table: an action the home page - // binds as a form, a server-only query it reads, a component that renders - // the result, the types, and a test. - await mkdir(join(appDir, 'modules', 'users', 'actions'), { recursive: true }); - await mkdir(join(appDir, 'modules', 'users', 'queries'), { recursive: true }); - await mkdir(join(appDir, 'modules', 'users', 'components'), { recursive: true }); - await writeFile(join(appDir, 'modules', 'users', 'components', 'user-list.ts'), `import { WebComponent, html } from '@webjsdev/core'; -import type { User } from '../types.ts'; - -/** - * The users feature's component, written as in Lit. The page passes the users - * in as a property (.users=\${users}); a component never queries the database - * itself, since it also runs in the browser. - */ -export class UserList extends WebComponent { - static properties = { users: { type: Array } }; - declare users: User[]; - - constructor() { - super(); - this.users = []; - } + // modules/ is where each feature goes (actions, queries, components, utils, + // types); the scaffold ships it empty, and AGENTS.md describes the layout. + await mkdir(join(appDir, 'modules'), { recursive: true }); + await writeFile(join(appDir, 'modules', '.gitkeep'), ''); - render() { - if (this.users.length === 0) { - return html\`<p class="text-sm text-muted-foreground m-0">No users yet. Add the first one above.</p>\`; - } - return html\` - <ul class="grid gap-1 m-0 p-0 list-none text-sm text-muted-foreground"> - \${this.users.map((user) => html\`<li>\${user.email}</li>\`)} - </ul> - \`; - } -} -UserList.register('user-list'); -`); - await writeFile(join(appDir, 'modules', 'users', 'types.ts'), `// The users feature's types, derived from the schema rather than written by hand. -export type { User } from '#db/schema.server.ts'; -`); - await writeFile(join(appDir, 'modules', 'users', 'queries', 'list-users.server.ts'), `import { desc } from 'drizzle-orm'; -import { db } from '#db/connection.server.ts'; -import { users } from '#db/schema.server.ts'; -import type { User } from '../types.ts'; - -// A query: server-only code (a .server.ts file with no 'use server'), called -// from a page, which runs on the server. Without 'use server' it is never -// callable from the browser. One function per file. -export async function listUsers(limit = 5): Promise<User[]> { - return db.select().from(users).orderBy(desc(users.createdAt)).limit(limit); -} -`); - await writeFile(join(appDir, 'modules', 'users', 'actions', 'add-user.server.ts'), `'use server'; - -import { revalidatePath } from '@webjsdev/server'; -import type { ActionResult } from '@webjsdev/server'; -import { db } from '#db/connection.server.ts'; -import { users } from '#db/schema.server.ts'; -import type { User } from '../types.ts'; - -// A server action, bound by the home page as <form action=\${addUser}>, so it -// works with JavaScript off. A failure re-renders the page with this result on -// actionData; a success redirects back and revalidatePath('/') refreshes it. -// One function per file. -export async function addUser(formData: FormData): Promise<ActionResult<User>> { - const email = String(formData.get('email') ?? '').trim().toLowerCase(); - if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) { - return { success: false, fieldErrors: { email: 'Enter a valid email address.' }, status: 422 }; - } - // A duplicate email inserts nothing and returns no row, so only a duplicate - // is a field error; any other database error throws and renders the error - // page, where onError and the dev overlay see it. - const [user] = await db.insert(users).values({ email }).onConflictDoNothing().returning(); - if (!user) { - return { success: false, fieldErrors: { email: 'That email is already added.' }, status: 422 }; - } - revalidatePath('/'); - return { success: true, data: user }; -} -`); - await writeFile(join(appDir, 'modules', 'users', 'actions', 'clear-users.server.ts'), `'use server'; - -import { revalidatePath } from '@webjsdev/server'; -import type { ActionResult } from '@webjsdev/server'; -import { db } from '#db/connection.server.ts'; -import { users } from '#db/schema.server.ts'; - -// A server action with no input, bound by the home page's Clear list button -// as <form action=\${clearUsers}>. One function per file. -export async function clearUsers(): Promise<ActionResult> { - await db.delete(users); - revalidatePath('/'); - return { success: true }; -} -`); - await mkdir(join(appDir, 'test', 'users'), { recursive: true }); - await writeFile(join(appDir, 'test', 'users', 'users.test.ts'), `// The example module's test: its actions against the test database, which -// \`webjs test\` prepares from db/schema.server.ts. Tests in one file run in -// order, so the clear test runs last. -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import { addUser } from '#modules/users/actions/add-user.server.ts'; -import { clearUsers } from '#modules/users/actions/clear-users.server.ts'; -import { listUsers } from '#modules/users/queries/list-users.server.ts'; - -const form = (email: string) => { - const fd = new FormData(); - fd.set('email', email); - return fd; -}; - -test('addUser refuses an invalid email', async () => { - const result = await addUser(form('not-an-email')); - assert.equal(result.success, false); - assert.ok(result.fieldErrors?.email); -}); - -test('addUser adds a user, which listUsers then returns', async () => { - const email = \`ada-\${Date.now()}@example.com\`; - const result = await addUser(form(email)); - assert.equal(result.success, true); - assert.ok((await listUsers()).some((u) => u.email === email)); -}); - -test('addUser refuses an email that is already added', async () => { - const email = \`grace-\${Date.now()}@example.com\`; - assert.equal((await addUser(form(email))).success, true); - const again = await addUser(form(email)); - assert.equal(again.success, false); - assert.match(again.fieldErrors?.email ?? '', /already added/); -}); - -test('clearUsers empties the list', async () => { - await addUser(form(\`grace-\${Date.now()}@example.com\`)); - const result = await clearUsers(); - assert.equal(result.success, true); - assert.deepEqual(await listUsers(), []); -}); -`); - - // Home page: the logo, then the example module at work (a form bound to its - // action, its component rendering what its query returns). Reshape it into the app's real landing page. - await writeFile(join(appDir, 'app', 'page.ts'), `import { html, nothing } from '@webjsdev/core'; -import type { PageProps } from '@webjsdev/core'; -import { buttonClass } from '#components/ui/button.ts'; -import { inputClass } from '#components/ui/input.ts'; -import { labelClass } from '#components/ui/label.ts'; -import { addUser } from '#modules/users/actions/add-user.server.ts'; -import { clearUsers } from '#modules/users/actions/clear-users.server.ts'; -import { listUsers } from '#modules/users/queries/list-users.server.ts'; -import '#modules/users/components/user-list.ts'; + // Home page: the logo. Reshape it into the app's real landing page. + await writeFile(join(appDir, 'app', 'page.ts'), `import { html } from '@webjsdev/core'; export const metadata = { title: '${displayName}', }; -// A thin route: the data and the mutation live in modules/users/. -export default async function Home({ actionData }: PageProps) { - const latest = await listUsers(); - const error = actionData?.fieldErrors?.email; +export default function Home() { return html\` - <section class="py-16 flex flex-col items-center text-center gap-4"> - <!-- The WebJs logo, one file per theme (public/brand/), as the heading. --> + <main class="py-16 flex flex-col items-center text-center gap-4"> <h1 class="m-0"> <img src="/brand/webjs-lockup-on-light.svg" alt="WebJs" width="228" height="60" class="block h-15 w-auto dark:hidden"> <img src="/brand/webjs-lockup-on-dark.svg" alt="WebJs" width="228" height="60" class="hidden h-15 w-auto dark:block"> </h1> <p class="text-muted-foreground max-w-lg m-0">Your WebJs app starts here. Edit app/page.ts.</p> - </section> - <!-- The example module (modules/users/): replace it with your own features. --> - <section class="mx-auto max-w-sm grid gap-4"> - <form action=\${addUser} class="grid gap-3"> - <div class="grid gap-2"> - <label class=\${labelClass()} for="email">Email</label> - <input class=\${inputClass()} id="email" name="email" type="email" required - aria-invalid=\${error ? 'true' : nothing} aria-describedby=\${error ? 'email-error' : nothing}> - \${error ? html\`<p id="email-error" role="alert" class="text-sm text-destructive m-0">\${error}</p>\` : nothing} - </div> - <button class=\${buttonClass()} type="submit">Add user</button> - </form> - <user-list .users=\${latest}></user-list> - \${latest.length > 0 ? html\` - <form action=\${clearUsers}> - <button class=\${buttonClass({ variant: 'outline' })} type="submit">Clear list</button> - </form>\` : nothing} - </section> + </main> \`; } `); @@ -1679,95 +1434,6 @@ export default async function Home({ actionData }: PageProps) { // AGENTS.md is copied via the `templateFiles` loop above, from // `packages/cli/templates/AGENTS.md` with `{{APP_NAME}}` substitution. - // --- Theme toggle component --- - - await writeFile(join(appDir, 'components', 'theme-toggle.ts'), `import { WebComponent, html } from '@webjsdev/core'; -import { buttonClass } from '#components/ui/button.ts'; - -type Theme = 'system' | 'light' | 'dark'; - -/** - * <theme-toggle> is a light-DOM component styled with Tailwind utilities. - * - * Light DOM is the default: no static shadow = true, no static styles. It - * is the UI kit's ghost icon Button (components/ui/button.ts), and it reacts - * through Lit's APIs (reactive state, an @click binding, the connected / - * disconnected lifecycle), never a <style> block or a document query. The - * one DOM write is the .dark class on <html>, which is the theme switch - * itself and no component renders. - */ -export class ThemeToggle extends WebComponent { - // Lit's internal reactive state (its @state()): no attribute, re-renders on change. - static properties = { theme: { state: true } }; - declare theme: Theme; - #os: MediaQueryList | null = null; - readonly #onOsChange = () => this.#apply(); - - constructor() { - super(); - this.theme = 'system'; - } - - connectedCallback() { - super.connectedCallback(); - let saved: string | null = null; - try { saved = localStorage.getItem('webjs_theme'); } catch {} - this.theme = saved === 'light' || saved === 'dark' ? saved : 'system'; - // The head script in app/layout.ts applied the theme before paint; from - // here the toggle keeps it current, following the OS while on "system". - this.#os = window.matchMedia('(prefers-color-scheme: dark)'); - this.#os.addEventListener('change', this.#onOsChange); - } - - disconnectedCallback() { - super.disconnectedCallback(); - this.#os?.removeEventListener('change', this.#onOsChange); - } - - cycle() { - const next: Theme = this.theme === 'system' ? 'light' - : this.theme === 'light' ? 'dark' : 'system'; - this.theme = next; - try { - if (next === 'system') localStorage.removeItem('webjs_theme'); - else localStorage.setItem('webjs_theme', next); - } catch {} - this.#apply(); - } - - /** The tokens in styles/globals.css and color-scheme both switch on .dark; data-theme records a saved choice. */ - #apply() { - const t = this.theme; - const el = document.documentElement; - if (t === 'system') delete el.dataset.theme; - else el.dataset.theme = t; - el.classList.toggle('dark', t === 'dark' || (t === 'system' && !!this.#os?.matches)); - } - - render() { - const t = this.theme; - const label = t === 'system' ? 'AUTO' : t === 'light' ? 'LIGHT' : 'DARK'; - const icon = t === 'light' ? ICONS.sun : t === 'dark' ? ICONS.moon : ICONS.system; - return html\` - <button - type="button" - class=\${buttonClass({ variant: 'ghost', size: 'icon' })} - @click=\${() => this.cycle()} - aria-label="Cycle theme (currently \${label})" - title="Theme: \${label.toLowerCase()}" - >\${icon}</button> - \`; - } -} - -const ICONS = { - sun: html\`<svg class="w-4 h-4 stroke-current fill-none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 3v2M12 19v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M3 12h2M19 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>\`, - moon: html\`<svg class="w-4 h-4 stroke-current fill-none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z"/></svg>\`, - system: html\`<svg class="w-4 h-4 stroke-current fill-none" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M3 5h18v11H3zM8 20h8M12 16v4"/></svg>\`, -}; - -ThemeToggle.register('theme-toggle'); -`); } // end if (!isApi) // AGENTS.md is already in place via the shared `templateFiles` loop @@ -1794,7 +1460,6 @@ ThemeToggle.register('theme-toggle'); } else { console.log(` ${name}/ app/{layout,page}.ts ← the starting page, grow it in place - components/theme-toggle.ts public/input.css ← Tailwind entry (compiles to public/tailwind.css) db/{schema,connection}.server.ts ← Drizzle ${guide} @@ -1804,11 +1469,9 @@ ThemeToggle.register('theme-toggle'); • Read AGENTS.md. Its brief is the whole difference from Next.js routing and Lit components; run 'npx webjs check' after each edit. Fill in its "This app" section as you build, and keep it current. - • This scaffold is a minimal starting point. Its one example feature, - modules/users/, shows the module shape: read it, then delete it, its test - and whatever uses it before building. - Add routes under app/, components under components/, and features under - modules/<feature>/, and keep server-only code behind .server.ts. + • This scaffold is a minimal starting point. Add routes under app/ and each + feature under modules/<feature>/ (actions, queries, components, utils, + types), and keep server-only code behind .server.ts. • Use the wired-up database (Drizzle): define real models in db/schema.server.ts, then run 'npm run db:generate' and 'npm run db:migrate'. Never store app data in JSON files, in-memory arrays, or localStorage. diff --git a/packages/cli/lib/test-db-preload.js b/packages/cli/lib/test-db-preload.js new file mode 100644 index 000000000..47896e547 --- /dev/null +++ b/packages/cli/lib/test-db-preload.js @@ -0,0 +1,22 @@ +/** + * Preloaded (`node --import`) into every process `webjs test` starts on Node. + * `node --test` runs each test file in a child process of its own, and they + * all shared one migrated SQLite file, so two files writing at once failed + * with `database is locked`: a transaction that upgrades from read to write + * gets SQLITE_BUSY at once, whatever the busy timeout (#1697). Each child + * copies the migrated template and points `DATABASE_URL` at its copy, the + * database-per-worker shape of Rails' parallel tests. The copy lives beside + * the template, in the directory `webjs test` removes when the run ends. + * Bun's runner keeps every file in one process, so it never reaches here. + * + * @module + */ +import { copyFileSync } from 'node:fs'; + +const template = process.env.WEBJS_TEST_DB_TEMPLATE; +// NODE_TEST_CONTEXT is set in the per-file children only, not in the runner. +if (template && process.env.NODE_TEST_CONTEXT) { + const own = template.replace(/\.db$/, `-${process.pid}.db`); + copyFileSync(template, own); + process.env.DATABASE_URL = 'file:' + own; +} diff --git a/packages/cli/lib/verify.js b/packages/cli/lib/verify.js new file mode 100644 index 000000000..4876bf25d --- /dev/null +++ b/packages/cli/lib/verify.js @@ -0,0 +1,119 @@ +/** + * `webjs verify`: the whole "does the app work" check in one call (#1697), the + * shape of Rails' `bin/ci` for the local loop. It runs `webjs check` and + * `webjs typecheck` in parallel, then `webjs test`, then the app's + * `webjs.dev.before` steps (the migrations and stylesheet `webjs dev` would + * apply) and an in-process boot that requests every page and GET route needing + * no parameter (`webjs status --boot`). + * + * Eval agents spent about 19 turns per build after the app first booted, most + * of them starting a dev server, curling routes and stopping it, and those late + * turns are the expensive ones: the context is past the 100K-token price tier + * by then. One call replaces that loop. + * + * It runs on the `webjs ci` engine (`runCi` in ci-runner.js) with every step + * captured and its own report silenced, so there is one runner for captured + * steps, parallel groups and the stream-close handling. It does NOT run the + * app's `webjs.ci.steps`: that list is the full gate (doctor, a network + * dependency audit, browser and e2e tests), and verify is the fast check an + * agent runs when a feature is done. Every step runs even after a failure, so + * one call reports everything; a pass is one line, a failure the tail of its + * output. + * + * Pure of `process`: the engine's spawn, the output and the before-steps are + * injectable, so the flow is unit-tested without spawning a real step. + * + * @module + */ +import { runCi } from './ci-runner.js'; + +/** How many trailing lines of a failing step's output to print. */ +export const FAIL_TAIL_LINES = 40; + +/** + * A V8 / JavaScriptCore stack frame: indented `at`, ending in a source + * location (`file:12:5`, in parentheses or not) or `<anonymous>`. A message + * line that merely starts with "at" (" at least one row expected") is kept. + */ +const STACK_FRAME = /^\s+at\s.*(?::\d+:\d+\)?|<anonymous>\)?|\(native\))\s*$/; + +/** + * The last `n` non-empty lines of a step's output, without stack frames: a + * failing render is reported with its file, line and code frame, so the raw + * frames the server also logs are only noise to an agent. + * @param {string} output + * @param {number} [n] + * @returns {string} + */ +export function tail(output, n = FAIL_TAIL_LINES) { + const lines = output.replace(/\x1b\[[0-9;]*m/g, '').split('\n') + .filter((l) => l.trim() && !STACK_FRAME.test(l)); + return (lines.length > n ? ['...', ...lines.slice(-n)] : lines).join('\n'); +} + +/** + * The steps verify runs, as `webjs ci` nodes. + * @param {string} cli the command that runs this CLI (`node <bin>`) + * @param {string[]} beforeSteps the app's `webjs.dev.before` commands + * @returns {import('./ci-config.js').CiNode[]} + */ +export function verifySteps(cli, beforeSteps) { + const step = (title, run) => ({ kind: /** @type {'step'} */ ('step'), title, run, env: {} }); + /** @type {import('./ci-config.js').CiNode[]} */ + const nodes = [ + { kind: 'group', title: 'checks', parallel: 2, steps: [step('check', `${cli} check`), step('typecheck', `${cli} typecheck`)] }, + step('test', `${cli} test`), + ]; + // What `webjs dev` runs first, so the boot serves the schema and styles the + // app would. Its own step, so its output shows only when it fails. + if (beforeSteps.length) nodes.push(step('prepare', beforeSteps.join(' && '))); + nodes.push(step('boot', `${cli} status --boot`)); + return nodes; +} + +/** + * @param {{ + * appDir: string, + * cli: string, + * env?: NodeJS.ProcessEnv, + * beforeSteps?: string[], + * spawn?: Function, + * out?: (s: string) => void, + * }} opts + * @returns {Promise<number>} the exit code: 0 when every step passed, else 1 + */ +export async function runVerify(opts) { + const { appDir, cli, beforeSteps = [], out = (s) => process.stdout.write(s + '\n') } = opts; + // A nested `node --test` would report to the parent run instead of setting + // its own exit code, so no step inherits the context. + const env = { ...(opts.env || process.env) }; + delete env.NODE_TEST_CONTEXT; + const { done } = runCi(verifySteps(cli, beforeSteps), appDir, { + env, + captureAll: true, + // A local check, not CI: a test or config that branches on CI behaves + // as it does under `npm test`. + markCi: false, + write: () => {}, + ...(opts.spawn ? { spawn: opts.spawn } : {}), + }); + const result = await done; + const order = ['check', 'typecheck', 'test', 'prepare', 'boot']; + const steps = [...result.steps].sort((a, b) => order.indexOf(a.title) - order.indexOf(b.title)); + let failed = 0; + for (const r of steps) { + const secs = r.seconds.toFixed(1); + if (r.ok) { + out(`ok ${r.title} (${secs}s)`); + } else { + failed++; + out(`FAIL ${r.title} (${secs}s, exit ${r.code ?? r.signal})`); + const t = tail(r.output || ''); + if (t) out(t.split('\n').map((l) => ` ${l}`).join('\n')); + } + } + out(failed + ? `webjs verify: ${failed} of ${steps.length} steps failed` + : `webjs verify: all ${steps.length} steps passed (check, typecheck, test, every route booted)`); + return failed || !result.ok ? 1 : 0; +} diff --git a/packages/cli/templates/AGENTS.md b/packages/cli/templates/AGENTS.md index dcdc67eff..a4e1361b1 100644 --- a/packages/cli/templates/AGENTS.md +++ b/packages/cli/templates/AGENTS.md @@ -31,15 +31,22 @@ routing and Lit components, with the differences below. Before hand-writing auth, sessions, caching, rate limits, uploads, realtime or SEO, run `npx webjs source`, which lists what WebJs provides for each need. `npx webjs source <Export>` then prints one export's signature and example. -After each edit run `npx webjs check` and `npx webjs status`. The framework -source is in `node_modules/@webjsdev/*` (no build, so it is the code that -runs) and the human docs are at https://webjs.dev/docs. +After each edit run `npx webjs check`. To verify the app, run `npx webjs verify`: +check, typecheck, the tests, and every route booted in-process, in one call, +with no dev server to start, curl or stop. The framework source is in +`node_modules/@webjsdev/*` (no build, so it is the code that runs) and the +human docs are at https://webjs.dev/docs. -Keep app data in the wired-up Drizzle database (`db/`), never in a JSON file -or an in-memory array. Put each feature in `modules/<feature>/` (`actions/` with -one `'use server'` action per `*.server.ts`, `queries/`, `components/`, `types.ts`) -and keep routes thin. `modules/users/` is an example of that shape: read it, then -delete it, its test and whatever uses it before you build the app. +Keep app data in the wired-up Drizzle database (`db/`), never in a JSON file or +an in-memory array. One folder per feature under `modules/`, and thin routes in `app/`: + modules/<feature>/actions/*.server.ts 'use server', one action per file + modules/<feature>/queries/*.server.ts server-only reads that pages call + modules/<feature>/components/*.ts Lit components (the code that ships) + modules/<feature>/utils/*.ts pure helpers the feature shares + modules/<feature>/types.ts types derived from the schema + test/<feature>/*.test.ts the feature's tests +`npx webjs source modules` prints a worked module, and `npx webjs source testing` and +`npx webjs source progressive-enhancement` a test and a form bound to an action. In components, use Lit's APIs over raw DOM calls: `@click=${...}` and `ref()`, not `document.getElementById`, `document.querySelector` or `addEventListener`. @@ -51,9 +58,7 @@ Style with Tailwind utilities on the kit's design tokens (`bg-background`, `text `border-border`, `rounded-lg`; the theme lives in `styles/globals.css`), never hard-coded colours or hand-written CSS. Change the whole look with a theme: `npx webjs ui init --preset <code>` from webjs.dev/ui/create. -`npx webjs help` lists every CLI command, and `npx webjs stop` stops a server you started. The `webjs` -MCP server in `.claude.json` answers the same questions as tools (`list_routes`, `list_actions`, -`list_components`, `check`, `source`, `ui`). +`npx webjs help` lists every CLI command, and `npx webjs stop` stops a server you started. Hooks, so you need not open them: each edit returns that file's `webjs check` and type errors (fix them at once); `extends HTMLElement`, an em-dash, a spaced hyphen or semicolon as a pause in comments or markdown, and a commit on `main` are refused; a server-only import diff --git a/packages/cli/templates/instrumentation.ts b/packages/cli/templates/instrumentation.ts deleted file mode 100644 index 9e3017213..000000000 --- a/packages/cli/templates/instrumentation.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Optional boot-time hook (app root, sibling of app/). register() runs once at -// server start, the place to wire APM / logging / tracing. setOnError(fn) (from -// @webjsdev/server) registers a sink for every request error the framework -// catches (an SSR render crash, a thrown server action, a 500), so you can -// forward it to Sentry / a logger with the request context. Call setOnError -// INSIDE register() so it runs within the instrumentation context (a top-level -// call has no context yet and is a no-op). Delete this file if you do not need -// the hook. -import { setOnError } from '@webjsdev/server'; - -export function register() { - setOnError((error, ctx) => { - // Replace with your APM. `ctx` carries request context (e.g. a correlation id). - console.error('[instrumentation] request error:', error, ctx ?? ''); - }); -} diff --git a/packages/mcp/src/brief.js b/packages/mcp/src/brief.js index 2df4f3b23..046c894f4 100644 --- a/packages/mcp/src/brief.js +++ b/packages/mcp/src/brief.js @@ -46,7 +46,9 @@ export const BRIEF = [ 'Before hand-writing auth, sessions, caching, rate limits, uploads, realtime or', 'SEO, run `npx webjs source`, which lists what WebJs provides for each need.', '`npx webjs source <Export>` then prints one export\'s signature and example.', - 'After each edit run `npx webjs check` and `npx webjs status`. The framework', - 'source is in `node_modules/@webjsdev/*` (no build, so it is the code that', - 'runs) and the human docs are at https://webjs.dev/docs.', + 'After each edit run `npx webjs check`. To verify the app, run `npx webjs verify`:', + 'check, typecheck, the tests, and every route booted in-process, in one call,', + 'with no dev server to start, curl or stop. The framework source is in', + '`node_modules/@webjsdev/*` (no build, so it is the code that runs) and the', + 'human docs are at https://webjs.dev/docs.', ].join('\n'); diff --git a/packages/mcp/src/catalog.js b/packages/mcp/src/catalog.js index e21878275..e071b0b2a 100644 --- a/packages/mcp/src/catalog.js +++ b/packages/mcp/src/catalog.js @@ -32,15 +32,15 @@ export const FEATURE_CATALOG = [ { need: 'Auth', names: ['createAuth', 'Credentials', 'GitHub', 'Google', 'AuthError'], note: "Auth.js's API: auth(), signIn(), signOut(), handlers" }, { need: 'Sessions and cookies', names: ['session', 'getSession', 'cookies', 'headers'] }, { need: 'Redirects and errors', names: ['redirect', 'permanentRedirect', 'notFound', 'forbidden', 'unauthorized'] }, - { need: 'Caching', names: ['cache', 'revalidatePath', 'revalidateTag', 'revalidateAll'] }, + { need: 'Caching', names: ['cache', 'revalidatePath', 'revalidateTag', 'revalidateAll'], note: 'a page renders per request unless it exports revalidate' }, { need: 'Rate limits and CORS', names: ['rateLimit', 'cors', 'clientIp'] }, { need: 'File uploads', names: ['getFileStore', 'setFileStore', 'diskStore', 'generateKey', 'signedUrl', 'verifySignedUrl'] }, { need: 'Realtime', names: ['broadcast'], note: 'a route.ts exporting WS handles WebSocket connections' }, { need: 'Streaming responses', names: ['stream', 'streamResponse', 'acceptsStream'] }, - { need: 'Route handlers', names: ['json', 'readBody', 'route'] }, + { need: 'Route handlers', names: ['json', 'readBody', 'route'], note: 'route.ts exports GET(req, { params }), params awaited' }, { need: 'SEO', names: ['sitemap', 'sitemapIndex', 'robots'] }, { need: 'Env validation', names: ['validateEnv'], note: 'an env.ts schema checks process.env at boot' }, - { need: 'Server tests', names: ['testRequest', 'submitForm', 'invokeActionForTest', 'loginAndGetCookies', 'createRequestHandler'] }, + { need: 'Server tests', names: ['testRequest', 'submitForm', 'invokeActionForTest', 'loginAndGetCookies', 'createRequestHandler'], note: 'npx webjs test gives a SQLite app a fresh migrated database, never db/dev.db' }, ], }, { @@ -78,5 +78,11 @@ export function featureCatalog(catalog = FEATURE_CATALOG) { out.push(` ${g.need}: ${g.names.join(', ')}${g.note ? ` (${g.note})` : ''}`); } } + out.push( + '', + 'Database: Drizzle tables in db/schema.server.ts; npx webjs db generate then', + 'npx webjs db migrate; npx webjs db seed then runs db/seed.server.ts once as a', + 'plain script (its top-level code inserts the rows; make it safe to re-run).', + ); return out.join('\n'); } diff --git a/packages/mcp/src/guides.js b/packages/mcp/src/guides.js index cc9464cf9..047673bdd 100644 --- a/packages/mcp/src/guides.js +++ b/packages/mcp/src/guides.js @@ -61,14 +61,15 @@ One folder per feature under modules/<feature>/, and thin routes: modules/posts/actions/create-post.server.ts 'use server', one action per file modules/posts/queries/list-posts.server.ts server-only reads, called by pages modules/posts/components/post-list.ts Lit components (these ship) + modules/posts/utils/slug.ts pure helpers the feature shares modules/posts/types.ts types derived from the schema app/posts/page.ts awaits a query, renders components db/schema.server.ts every table, one defineRelations Each table goes in db/schema.server.ts with its row type beside it (export type Post = typeof posts.$inferSelect), and its relations in the one -defineRelations call. modules/users/ in a fresh app is a working example of -the whole shape: read it, then replace it with the app's own features. +defineRelations call. A test per feature goes in test/posts/ (see the testing +guide). Next: npx webjs source progressive-enhancement (or optimistic-ui, type-safety, data-flow) Docs: https://webjs.dev/docs/conventions`, diff --git a/packages/mcp/test/catalog.test.mjs b/packages/mcp/test/catalog.test.mjs index bd73357e8..bc8e5f8c9 100644 --- a/packages/mcp/test/catalog.test.mjs +++ b/packages/mcp/test/catalog.test.mjs @@ -92,6 +92,16 @@ test('the catalogue text names every entry and stays short', () => { assert.ok(text.length < 2500, `the catalogue stays under 2500 characters (${text.length})`); }); +// #1697: the facts agents in the eval builds grepped node_modules for, after +// reading this very listing. Each cost one to sixteen turns across builds. +test('the catalogue answers the lookups agents grepped the framework source for', () => { + const text = featureCatalog(); + assert.match(text, /fresh migrated database, never db\/dev\.db/, 'which database `webjs test` uses'); + assert.match(text, /webjs db seed then runs db\/seed\.server\.ts once as a\nplain script/, 'which file the seed command runs, and how (#1697 round 9: agents still asked how)'); + assert.match(text, /renders per request unless it exports revalidate/, 'whether pages are cached by default'); + assert.match(text, /GET\(req, \{ params \}\)/, 'what a route handler receives'); +}); + test('the MCP source tool returns the catalogue for no arguments, and a listing for `package`', async () => { const deps = { roots: [], readFile, readdir: listDir }; assert.equal(await runSourceTool(deps, {}), featureCatalog()); diff --git a/packages/server/AGENTS.md b/packages/server/AGENTS.md index 22fde30d1..a70b54212 100644 --- a/packages/server/AGENTS.md +++ b/packages/server/AGENTS.md @@ -57,7 +57,7 @@ with metadata, Suspense, streaming) for HTML, or `api.js` / | `actions.js` | `.server.js` / `.server.ts` scanner. Generates RPC stubs for browser-bound imports and serves the RPC endpoints. `buildActionIndex` is a pure file -> hash mapping (loads no module). The generated stub reads the SSR seed before its `fetch` (#472): `__call(fn, args)` computes `stringify(args)` (both the seed lookup key and the RPC body) and returns `takeSeed(hash, fn, key)` on a hit, else POSTs; so a seeded first call does no network and a later refetch / arg-change misses and goes to RPC. **Input validation (#245):** `runValidate(validate, input)` is the shared seam the RPC path and the `route()` REST adapter route through, so a validator declared via the `validate` config export (#488) interprets a `{ success, fieldErrors }` envelope, a throw, and a transform-return identically across transports. `invokeAction` (RPC) runs it on the first arg before the body, returning a `{ success: false, fieldErrors, status: 422 }` envelope as a normal 200 RPC payload on a structured failure (the client reads `result.fieldErrors`) and a sanitized error response on a throw (#749: `actionErrorResponse` returns a GENERIC message + a correlation `digest` in prod via `action-error.js`, never the raw message, the full error logged server-side; `redirect()` / `notFound()` sentinels pass through). A public REST endpoint is a `route.ts` that imports and calls the action (optionally via the `route()` adapter in `action-route.js`). **Streaming results (#489):** when a completed action returns a streamable value (`isStreamable` from `action-stream.js`), `invokeAction` returns `streamActionResponse` instead of buffering; the generated stub carries a `__readStream` decode path its `__handle` dispatches to on the `application/vnd.webjs+stream` content type | | `action-route.js` | The optional `route(action, opts?)` adapter (#488): wraps a plain `'use server'` action as a `route.ts`-style handler `(req, ctx?) => Promise<Response>`, merging `{ ...query, ...params, ...jsonBody }` into the single input object, running the optional `opts.validate` through the shared `runValidate` seam (422 on a structured failure or a schema library's throw, with its issues as `fieldErrors` plus the raw `issues`; 400 on any other thrown validator), and dispatching through `runWithActionSignal` + the `opts.middleware` chain. A returned `Response` passes through verbatim; otherwise the result is `Response.json`'d. The always-works baseline is a hand-written `route.ts` that imports and calls the action; this adapter is the one-liner convenience | | `action-stream.js` | Streaming RPC results (#489), server side. `isStreamable(value)` detects a return value that should stream (a web `ReadableStream`, an async iterable, an async generator, a Node `Readable`; NOT a plain object / array / string / Promise / ActionResult). `streamActionResponse(source, { signal, onError, headers })` builds the `application/vnd.webjs+stream` `Response`: a back-pressured `ReadableStream` of frames (one rich-serialized CHUNK per source value via core's `encodeFrame`, a terminal END, or an ERROR frame carrying a SANITIZED message if the source throws mid-flight (#749: a generic message + a `digest` in prod via `action-error.js`, the real message in dev, a `redirect()` / `notFound()` sentinel passed through), since the 200 status is already sent). Back-pressure is real (chunks are pulled + serialized one at a time as the consumer reads); an aborted request signal (#492, client disconnect / superseded render) returns the source iterator, stopping a server generator. Wired in `actions.js`'s `invokeAction` after the action runs: a COMPLETED action whose result `isStreamable` streams (never cached / ETagged / seeded; a mutation still emits `X-Webjs-Invalidate`), a middleware short-circuit falls through to normal verb handling. The generated client stub's `__handle` branches on the stream content type and returns an async iterable the caller `for await`s | -| `action-error.js` | Server-action error sanitization (#749). `errorDigest(err)` is a short correlation hash (Web Crypto via `crypto-utils.js`) of the error message + stack, returned to the client AND logged server-side so a generic client error maps to the full log line; `isControlFlowThrow(err)` detects the `redirect()` / `notFound()` `__webjs` sentinels (passed through, not sanitized); `GENERIC_ERROR_MESSAGE` is the client-facing prod string. A leaf module so both the buffered path (`actions.js` `actionErrorResponse`) and the streaming path (`action-stream.js` error frame) import it without a cycle. The prod contract: a thrown action NEVER returns its raw message to the client (Postgres constraint names, internal IPs, fs paths are not author-controlled); a user-facing message rides the `ActionResult` `{ success: false, error }` envelope instead. The generated client stub and `invokeActionForTest` attach `digest` to the thrown error | +| `action-error.js` | Server-action error sanitization (#749). `errorDigest(err)` is a short correlation hash (Web Crypto via `crypto-utils.js`) of the error message + stack, returned to the client AND logged server-side so a generic client error maps to the full log line; `isControlFlowThrow(err)` detects the `redirect()` / `notFound()` `__webjs` sentinels (passed through, not sanitized); `controlFlowStatus(err)` maps `notFound()` / `forbidden()` / `unauthorized()` to 404 / 403 / 401, which `actions.js` answers over RPC with the kind in `x-webjs-control` and never hands to `onError` (#1697), and the generated stub and `invokeActionForTest` rethrow the matching sentinel; `GENERIC_ERROR_MESSAGE` is the client-facing prod string. A leaf module so both the buffered path (`actions.js` `actionErrorResponse`) and the streaming path (`action-stream.js` error frame) import it without a cycle. The prod contract: a thrown action NEVER returns its raw message to the client (Postgres constraint names, internal IPs, fs paths are not author-controlled); a user-facing message rides the `ActionResult` `{ success: false, error }` envelope instead. The generated client stub and `invokeActionForTest` attach `digest` to the thrown error | | `api.js` | `route.ts` `GET` / `POST` / `PUT` / `DELETE` handler dispatch | | `middleware-load.js` | Root and segment middleware, the Next.js way: the function is the default export, a named `middleware` or a named `proxy` (a root `proxy.{ts,js,mts,mjs}` file too, both files being a boot error), `export const config = { matcher }` compiled with `URLPattern` (string, array, `has` / `missing`), returning `undefined` continues, `next()` is memoized, `request.cookies` is the `cookies()` store, and `request.nextUrl` throws in dev. A load failure fails CLOSED. The wrapper and its compiled matcher are memoized per imported module object, since segment middleware is loaded on every request; a dev edit yields a new module (the re-import is keyed on content), so it gets a fresh wrapper. Tests: `test/dev/middleware-conventions.test.js` | | `auth.js` | `createAuth()` with Credentials / Google / GitHub providers; JWT signing. `readSession()` (reached by `auth()`) calls `markDynamicAccess()`, so an `auth()`-gated page is auto-excluded from the HTML cache even if it wrongly set `revalidate` (#241, the auth-path leak fix). The session-`user` type is opt-in (#451): the overlay exposes an augmentable `AuthUser` interface and a generic `createAuth<TUser>()`, so `auth().user` can be typed with no cast and typo-checked, defaulting to `Record<string, unknown>` when neither is used (types-only, no runtime effect) | diff --git a/packages/server/src/action-error.js b/packages/server/src/action-error.js index cf4d82ffb..dd56580d8 100644 --- a/packages/server/src/action-error.js +++ b/packages/server/src/action-error.js @@ -41,6 +41,30 @@ export function isControlFlowThrow(err) { return isRedirect(err) || isNotFound(err) || isForbidden(err) || isUnauthorized(err); } +/** + * The response header that names a `notFound()` / `forbidden()` / + * `unauthorized()` thrown by an action called over RPC. The generated stub + * reads it and rejects with the same sentinel, so `isForbidden(err)` holds on + * the client the way it does on the server. + */ +export const CONTROL_HEADER = 'x-webjs-control'; + +/** + * The status an RPC answers for a boundary sentinel thrown in an action: the + * same 404 / 403 / 401 the no-JS form path renders. Not an error, so it is + * never logged or sanitized. `null` for anything else (a redirect has its own + * branch). + * + * @param {unknown} err + * @returns {{ kind: 'not-found' | 'forbidden' | 'unauthorized', status: number } | null} + */ +export function controlFlowStatus(err) { + if (isNotFound(err)) return { kind: 'not-found', status: 404 }; + if (isForbidden(err)) return { kind: 'forbidden', status: 403 }; + if (isUnauthorized(err)) return { kind: 'unauthorized', status: 401 }; + return null; +} + /** * A short, stable correlation digest for a thrown error (a hash of its message * and stack). The SAME value is logged server-side and returned to the client, diff --git a/packages/server/src/actions.js b/packages/server/src/actions.js index a6eb74057..a1777aa68 100644 --- a/packages/server/src/actions.js +++ b/packages/server/src/actions.js @@ -15,7 +15,7 @@ import { revalidateTags } from './cache-tags.js'; import { runWithActionSignal } from './action-signal.js'; import { runActionChain } from './action-middleware.js'; import { isStreamable, streamActionResponse } from './action-stream.js'; -import { isControlFlowThrow, errorDigest, GENERIC_ERROR_MESSAGE } from './action-error.js'; +import { isControlFlowThrow, controlFlowStatus, CONTROL_HEADER, errorDigest, GENERIC_ERROR_MESSAGE } from './action-error.js'; import { ifNoneMatchSatisfied } from './conditional-get.js'; import { getBodyLimits, refreshHeaderValue } from './context.js'; import { basePath } from './importmap.js'; @@ -372,7 +372,7 @@ function buildStubBody({ hash, method, fnNames, actionUrl }) { // `method` is a default POST), so the first client call resolves from the // seed with no hydration round-trip. The browser-cache staleness check is // GET-only (only a GET is browser-cached). - const imports = ['stringify as __s', 'parse as __p', 'takeSeed as __seedTake', 'SEED_MISS as __MISS', 'markStale as __markStale', 'parseTagHeader as __tagHdr', 'activeActionSignal as __sig', 'applyActionRefresh as __refresh', 'followActionRedirect as __redirect', 'installActionBind as __bindable', + const imports = ['stringify as __s', 'parse as __p', 'takeSeed as __seedTake', 'SEED_MISS as __MISS', 'markStale as __markStale', 'parseTagHeader as __tagHdr', 'activeActionSignal as __sig', 'applyActionRefresh as __refresh', 'followActionRedirect as __redirect', 'installActionBind as __bindable', 'notFound as __nf', 'forbidden as __fb', 'unauthorized as __ua', // Streaming RPC (#489): an action returning a stream / async iterable sends // back a framed body; the stub decodes it into an async iterable the caller // `for await`s. The imports are small constants + one decoder factory. @@ -399,6 +399,10 @@ function buildStubBody({ hash, method, fnNames, actionUrl }) { // revalidatePath() in the action: refresh the page on screen in place when // it was revalidated, BEFORE the caller's await resolves (Next behaviour). lines.push(` const rf = res.headers.get('x-webjs-refresh'); if (rf) await __refresh(rf);`); + // notFound() / forbidden() / unauthorized() in the action: reject with the + // same sentinel, so `isForbidden(err)` holds in the caller's catch. After + // the refresh, since a mutation may have run before the throw. + lines.push(` const cf = res.headers.get(${J(CONTROL_HEADER)}); if (cf === 'not-found') __nf(); if (cf === 'forbidden') __fb(); if (cf === 'unauthorized') __ua();`); lines.push(` if (key != null) { const t = __tagHdr(res.headers.get('x-webjs-tags')); if (t.length) __regTags(key, t, since); }`); lines.push(` const ct = res.headers.get('content-type') || '';`); // A streamed result (#489): the action returned a stream / async iterable. @@ -583,6 +587,8 @@ export async function invokeAction(idx, hash, fnName, req, onError, allowedOrigi // A THROWN validator behaves like a thrown action: a sanitized error // response (non-200, so the client stub throws), with prod stack // sanitization. The onError sink sees the original error too. + const cf = controlFlowStatus(v.thrown); + if (cf) return controlFlowResponse(v.thrown, cf); if (typeof onError === 'function') onError(v.thrown); return actionErrorResponse(v.thrown, idx.dev); } @@ -647,23 +653,54 @@ export async function invokeAction(idx, hash, fnName, req, onError, allowedOrigi // go (`x-webjs-redirect: <url>;<push|replace>`, push by default as in a // Next server action), and the client router navigates there. A mutation // that ran still evicts its `invalidates` tags and reports revalidatePath. + // A revalidatePath() the action called before the throw is reported to the + // browser either way, since that path was already evicted on the server. + const refreshHeaders = () => { + const refresh = refreshHeaderValue(); + return refresh ? { 'x-webjs-refresh': refresh } : {}; + }; if (isRedirect(e)) { const r = /** @type {any} */ (e); /** @type {Record<string, string>} */ const headers = { 'x-webjs-redirect': `${headerSafeLocation(r.url)};${r.redirectType === 'replace' ? 'replace' : 'push'}` }; + // redirect() is how an action that succeeded navigates away, so it + // still evicts the action's declared `invalidates` tags. if (ranAction && method !== 'GET') { const inv = resolveTags(actionConfigFn(mod, 'invalidates'), args); if (inv.length) { await revalidateTags(inv); headers['x-webjs-invalidate'] = inv.join(','); } } - const refresh = refreshHeaderValue(); - if (refresh) headers['x-webjs-refresh'] = refresh; - return rpcResponse(null, { headers: { ...headers, 'cache-control': 'no-store' } }); + return rpcResponse(null, { headers: { ...headers, ...refreshHeaders(), 'cache-control': 'no-store' } }); } + // notFound() / forbidden() / unauthorized() (Next.js parity with the + // no-JS form path): the same 404 / 403 / 401, not a logged 500. The + // declared `invalidates` tags are NOT evicted, as on the form path: the + // throw is usually a guard at the top of the action, so evicting would let + // any anonymous caller flush the tagged caches over and over. + const cf = controlFlowStatus(e); + if (cf) return controlFlowResponse(e, cf, refreshHeaders()); if (typeof onError === 'function') onError(e); return actionErrorResponse(e, idx.dev); } } +/** + * The RPC answer for a boundary sentinel thrown in an action: its status, the + * kind in `x-webjs-control` for the stub to rethrow, never cached. + * + * @param {unknown} err + * @param {{ kind: string, status: number }} cf + * @param {Record<string, string>} [effects] the refresh header of a + * revalidatePath() the action called before the throw + * @returns {Promise<Response>} + */ +function controlFlowResponse(err, cf, effects = {}) { + const msg = err instanceof Error ? err.message : String(err); + return rpcResponse({ error: msg }, { + status: cf.status, + headers: { ...effects, [CONTROL_HEADER]: cf.kind, 'cache-control': 'no-store' }, + }); +} + /** * Build a GET action's response (#488): the serialized body plus a weak ETag * (content hash), the `Cache-Control` from the `cache` config (else `no-store`), diff --git a/packages/server/src/form-dispatch.js b/packages/server/src/form-dispatch.js index cd337d7a4..8e8783c6c 100644 --- a/packages/server/src/form-dispatch.js +++ b/packages/server/src/form-dispatch.js @@ -416,12 +416,23 @@ function withSubmittedValues(result, formData) { return { ...result, values: { ...textValuesOf(formData), ...ownValues } }; } +/** + * The body a page POST with no action identity gets, naming the fix (#1697): + * agents verifying a form with curl posted the visible fields alone and read + * the framework source to learn why the page answered 405. + */ +export const MISSING_ACTION_HINT = + 'Method Not Allowed. A POST to a page runs the server action named by the form\'s ' + + `hidden ${FORM_ACTION_FIELD} field, so send that field with the others (copy its value ` + + 'from the rendered form), or in a test call submitForm() from @webjsdev/server, which does.'; + /** * A page path exists but only renders: the method is the problem, not the url. + * @param {string} [body] * @returns {Response} */ -function methodNotAllowed() { - return new Response('Method Not Allowed', { +function methodNotAllowed(body = 'Method Not Allowed') { + return new Response(body, { status: 405, headers: { allow: 'GET, HEAD' }, }); @@ -499,7 +510,9 @@ export async function runFormAction(route, params, url, req, ssrOpts, deps) { // only as a bare 405. The dev-time client guard covers it instead. if (typeof id !== 'string' || !id) { reportFormActionMissing(url, req, formData, onError, logger, !!ssrOpts.dev, route); - return methodNotAllowed(); + // The hint names framework internals, so only dev serves it; production + // answers any scanner or bot with the bare status. + return methodNotAllowed(ssrOpts.dev ? MISSING_ACTION_HINT : undefined); } // The field is framework wire, not app data. Removing it keeps an action // that iterates the FormData (building a record, echoing values back into a diff --git a/packages/server/src/testing.js b/packages/server/src/testing.js index 1665a3b97..1c7fd710f 100644 --- a/packages/server/src/testing.js +++ b/packages/server/src/testing.js @@ -33,7 +33,8 @@ */ import { hashFile, RPC_CONTENT_TYPE } from './actions.js'; -import { FORM_ACTION_FIELD, redirect } from '@webjsdev/core'; +import { FORM_ACTION_FIELD, redirect, notFound, forbidden, unauthorized } from '@webjsdev/core'; +import { CONTROL_HEADER } from './action-error.js'; import { getSerializer } from './serializer.js'; import { join, sep } from 'node:path'; @@ -314,9 +315,29 @@ export async function submitForm(handle, path, fields = {}, opts = {}) { // fields it is filling in (a layout's logout form beside a page's task form). // When the field names do not single one out, refuse rather than post the // first, which used to submit a logout silently and pass a later assertion. + const keys = typeof fields.keys === 'function' ? [...new Set(fields.keys())] : Object.keys(fields); + const wanted = keys.map((k) => k.replace(/\[\]$/, '')); + // The only bound form has no fields at all while the test submits some: the + // form the test means is not on the page (no row to cancel, a section the + // user cannot see), and the one left is a layout's logout button. Posting it + // signed the user out and passed the assertion that followed (#1697). + // Narrow on purpose: an unbound form falls through to the clearer "carries + // no __webjs_action" error, a form with fields of its own is posted (a test + // may send a field the form lacks, a mass-assignment check), and a form + // whose controls live outside it (`form="<id>"`) is left alone. + const only = candidates.length === 1 ? candidates[0] : null; + const onlyTag = only ? only.slice(0, only.indexOf('>') + 1) : ''; + const onlyId = /\bid="([^"]+)"/.exec(onlyTag)?.[1]; + if (only && isBound(only) && opts.index === undefined && !opts.match && wanted.length + && formFieldNames(only).length === 0 && !(onlyId && html.includes(`form="${onlyId}"`))) { + throw new Error( + `submitForm: no form on ${path} (${status}) has the submitted fields (${wanted.join(', ')}). ` + + `The only bound form is ${onlyTag}, which has no fields, so the form the test means is not ` + + 'rendered for this request. Check the page state the test set up, or pass { match } to post ' + + 'that form anyway.', + ); + } if (candidates.length > 1 && opts.index === undefined) { - const keys = typeof fields.keys === 'function' ? [...new Set(fields.keys())] : Object.keys(fields); - const wanted = keys.map((k) => k.replace(/\[\]$/, '')); const covering = candidates.filter((f) => { const names = new Set(formFieldNames(f)); return wanted.every((k) => names.has(k)); @@ -487,6 +508,14 @@ export async function invokeActionForTest(app, serverFilePath, fnName, args = [] const type = rd.slice(cut + 1) === 'replace' ? 'replace' : 'push'; redirect(cut === -1 ? rd : rd.slice(0, cut), type); } + // notFound() / forbidden() / unauthorized(): rethrow the sentinel, as the + // client stub does, so a test asserts with isForbidden(err). With + // throwOnError: false the test asked for the response instead, so the + // parsed body (and its status) comes back like any other non-2xx. + const cf = throwOnError ? res.headers.get(CONTROL_HEADER) : null; + if (cf === 'not-found') notFound(); + if (cf === 'forbidden') forbidden(); + if (cf === 'unauthorized') unauthorized(); const ct = res.headers.get('content-type') || ''; let parsed; if (ct.includes(RPC_CONTENT_TYPE)) parsed = serializer.deserialize(text); diff --git a/packages/server/test/actions/action-control-flow-rpc.test.js b/packages/server/test/actions/action-control-flow-rpc.test.js new file mode 100644 index 000000000..6f7723d0a --- /dev/null +++ b/packages/server/test/actions/action-control-flow-rpc.test.js @@ -0,0 +1,128 @@ +/** + * notFound() / forbidden() / unauthorized() inside a server action called over + * RPC answer the same 404 / 403 / 401 the no-JS form path renders (#1697), are + * never handed to the error sink as a failure, and the generated stub plus + * invokeActionForTest reject with the matching sentinel. They used to answer a + * logged 500, which an agent then spent turns chasing. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve, dirname } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import { buildActionIndex, resolveServerModule, invokeAction, serveActionStub, RPC_CONTENT_TYPE } from '../../src/actions.js'; +import { withRequest } from '../../src/context.js'; +import { createRequestHandler } from '../../src/dev.js'; +import { invokeActionForTest } from '../../src/testing.js'; +import { isNotFound, isForbidden, isUnauthorized } from '../../../core/src/nav.js'; +import { stringify as wjStringify, parse as wjParse } from '../../../core/src/serialize.js'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CORE = pathToFileURL(resolve(__dirname, '../../../core/index.js')).toString(); +const SERVER = pathToFileURL(resolve(__dirname, '../../index.js')).toString(); + +async function scaffold() { + const dir = await mkdtemp(join(tmpdir(), 'webjs-rpc-control-')); + await mkdir(join(dir, 'actions'), { recursive: true }); + await writeFile(join(dir, 'package.json'), '{"name":"c","type":"module"}'); + await writeFile(join(dir, 'actions/guard.server.js'), `'use server'; + import { notFound, forbidden, unauthorized } from ${JSON.stringify(CORE)}; + export async function missing() { notFound(); } + export async function denied() { forbidden(); } + export async function anon() { unauthorized(); } + `); + await writeFile(join(dir, 'actions/mutate.server.js'), `'use server'; + import { forbidden } from ${JSON.stringify(CORE)}; + import { revalidatePath } from ${JSON.stringify(SERVER)}; + export const invalidates = () => ['posts']; + export async function guarded() { forbidden(); } + export async function archive() { revalidatePath('/posts'); forbidden(); } + `); + await writeFile(join(dir, 'actions/checked.server.js'), `'use server'; + import { forbidden } from ${JSON.stringify(CORE)}; + export const validate = () => forbidden(); + export async function checked() { return 1; } + `); + return dir; +} + +async function call(dir, file, fn, dev, onError) { + const idx = await buildActionIndex(dir, dev); + const abs = resolveServerModule(idx, file); + const hash = idx.fileToHash.get(abs); + const req = new Request(`http://x/__webjs/action/${hash}/${fn}`, { + method: 'POST', + headers: { 'content-type': RPC_CONTENT_TYPE, 'sec-fetch-site': 'same-origin' }, + body: await wjStringify([]), + }); + return withRequest(req, () => invokeAction(idx, hash, fn, req, onError)); +} + +for (const [fn, status, kind] of [['missing', 404, 'not-found'], ['denied', 403, 'forbidden'], ['anon', 401, 'unauthorized']]) { + for (const dev of [true, false]) { + test(`${fn}() over RPC answers ${status} in ${dev ? 'dev' : 'prod'}, not a logged 500`, async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/guard.server.js', fn, dev, () => assert.fail('a boundary sentinel is not an error')); + assert.equal(res.status, status); + assert.equal(res.headers.get('x-webjs-control'), kind); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const body = wjParse(await res.text()); + assert.match(body.error, /^webjs: /, 'the sentinel message, never the generic prod one'); + assert.equal(body.digest, undefined); + }); + } +} + +// Reviews of #1698. A guard that throws forbidden() at the top of an action +// counts as the action having run, so evicting the declared tags on a throw +// let any anonymous caller flush the tagged caches; the no-JS form path never +// evicted them. A revalidatePath() the action really called is still reported. +test('a guard that throws forbidden() evicts no tags, as on the form path', async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/mutate.server.js', 'guarded', false, () => assert.fail('not an error')); + assert.equal(res.status, 403); + assert.equal(res.headers.get('x-webjs-invalidate'), null, 'no declared tags evicted'); + assert.equal(res.headers.get('x-webjs-refresh'), null); +}); + +test('a revalidatePath() called before the throw is still reported to the browser', async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/mutate.server.js', 'archive', false, () => assert.fail('not an error')); + assert.equal(res.status, 403); + assert.equal(res.headers.get('x-webjs-refresh'), '%2Fposts'); + assert.equal(res.headers.get('x-webjs-invalidate'), null); +}); + +test('a validator that throws forbidden() answers 403 too', async () => { + const dir = await scaffold(); + const res = await call(dir, '/actions/checked.server.js', 'checked', false, () => assert.fail('not an error')); + assert.equal(res.status, 403); + assert.equal(res.headers.get('x-webjs-control'), 'forbidden'); +}); + +test('the generated stub rethrows the sentinel the header names', async () => { + const dir = await scaffold(); + const idx = await buildActionIndex(dir, false); + const stub = await serveActionStub(idx, resolveServerModule(idx, '/actions/guard.server.js')); + assert.match(stub, /notFound as __nf, forbidden as __fb, unauthorized as __ua/); + assert.match(stub, /res\.headers\.get\("x-webjs-control"\); if \(cf === 'not-found'\) __nf\(\); if \(cf === 'forbidden'\) __fb\(\); if \(cf === 'unauthorized'\) __ua\(\);/); + // The refresh a mutation earned is applied before the stub rejects. + assert.ok(stub.indexOf('x-webjs-refresh') < stub.indexOf('x-webjs-control'), 'refresh before the sentinel rethrow'); +}); + +test('invokeActionForTest rejects with the sentinel, so isForbidden(err) holds', async () => { + const dir = await scaffold(); + const app = await createRequestHandler({ appDir: dir, dev: true }); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'denied'), (e) => isForbidden(e)); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'missing'), (e) => isNotFound(e)); + await assert.rejects(invokeActionForTest(app, 'actions/guard.server.js', 'anon'), (e) => isUnauthorized(e)); +}); + +test('invokeActionForTest with throwOnError: false returns the 403 body instead of throwing', async () => { + const dir = await scaffold(); + const app = await createRequestHandler({ appDir: dir, dev: true }); + const result = await invokeActionForTest(app, 'actions/guard.server.js', 'denied', [], { throwOnError: false }); + assert.match(result.error, /forbidden/); +}); diff --git a/packages/server/test/actions/action-error-sanitization.test.js b/packages/server/test/actions/action-error-sanitization.test.js index 55fc4adcd..f6cf14308 100644 --- a/packages/server/test/actions/action-error-sanitization.test.js +++ b/packages/server/test/actions/action-error-sanitization.test.js @@ -101,7 +101,8 @@ test('prod: a redirect()/notFound() control-flow throw passes through (not gener const orig = console.error; console.error = () => {}; try { const { res, body } = await callBoom(dir, false, 'cf'); - assert.equal(res.status, 500); + // A 404 since #1697, the status the no-JS form path renders. + assert.equal(res.status, 404); assert.equal(body.error, 'webjs: notFound()', 'control-flow message preserved'); assert.equal(body.digest, undefined, 'no digest for a control-flow sentinel'); } finally { diff --git a/packages/server/test/routing/form-dispatch.test.js b/packages/server/test/routing/form-dispatch.test.js index 1194bda91..376b26e14 100644 --- a/packages/server/test/routing/form-dispatch.test.js +++ b/packages/server/test/routing/form-dispatch.test.js @@ -269,6 +269,23 @@ test('a page that binds no action answers 405 on POST, not 404', async () => { const post = await app.handle(new Request('http://x/info', form({ x: '1' }))); assert.equal(post.status, 405); assert.equal(post.headers.get('allow'), 'GET, HEAD'); + // #1697: the body names the missing field and the test helper, since agents + // verifying a form with curl read the framework source to learn why. + const body = await post.text(); + assert.match(body, /__webjs_action/); + assert.match(body, /submitForm\(\)/); + + // Production serves the bare status: the hint names framework internals. + const prod = await createRequestHandler({ + appDir: makeApp({ + 'app/info/page.ts': `import { html } from ${CORE};\nexport default () => html\`<p>read-only</p>\`;\n`, + }), + dev: false, + }); + await prod.warmup(); + const prodPost = await prod.handle(new Request('http://x/info', form({ x: '1' }))); + assert.equal(prodPost.status, 405); + assert.equal(await prodPost.text(), 'Method Not Allowed'); }); test('a non-form POST to a page is 405, decided BEFORE the body is parsed', async () => { diff --git a/packages/server/test/testing/submit-form.test.js b/packages/server/test/testing/submit-form.test.js index d4fbb053d..8398f1e97 100644 --- a/packages/server/test/testing/submit-form.test.js +++ b/packages/server/test/testing/submit-form.test.js @@ -37,6 +37,7 @@ async function makeApp() { await mkdir(join(dir, 'app/plain'), { recursive: true }); await mkdir(join(dir, 'app/tricky'), { recursive: true }); await mkdir(join(dir, 'app/poll'), { recursive: true }); + await mkdir(join(dir, 'app/lonely'), { recursive: true }); await mkdir(join(dir, 'modules/acct/actions'), { recursive: true }); await writeFile(join(dir, 'modules/acct/actions/signup.server.ts'), @@ -71,6 +72,13 @@ export default () => html\` <form action=\${signup}><input name="email"></form> <form action=\${subscribe}><input name="list"></form> \`; +`); + // Only a layout-style bound form with no fields (a logout button), as on a + // page whose own form is not rendered for this user. + await writeFile(join(dir, 'app/lonely/page.ts'), + `import { html } from ${CORE}; +import { subscribe } from '../../modules/acct/actions/newsletter.server.ts'; +export default () => html\`<form action=\${subscribe}><button>Log out</button></form>\`; `); // A page whose markup breaks a naive form scan two ways. await writeFile(join(dir, 'app/tricky/page.ts'), @@ -175,6 +183,33 @@ test('fields that single out no form are refused, naming every candidate', async ); }); +test('a lone bound form holding none of the submitted fields is refused, not posted (#1697)', async () => { + // A round 9 eval build tested a cross-user cancel on a page that rendered no + // cancel form for that user; the helper posted the layout's logout instead, + // and the 303 it got read as the cancel being refused. + const a = await handler(); + await assert.rejects( + () => submitForm(a.handle, '/lonely', { bookingId: '1' }), + (err) => /no form on \/lonely .*has the submitted fields \(bookingId\)/.test(err.message) + && /which has no fields/.test(err.message) + && /not rendered for\s+this request/.test(err.message), + ); + const noFields = await submitForm(a.handle, '/lonely', {}); + assert.equal(noFields.status, 303, 'a field-less submit still posts the field-less form'); + const forced = await submitForm(a.handle, '/lonely', { bookingId: '1' }, { match: 'Log out' }); + assert.equal(forced.status, 303, 'and { match } posts it on purpose'); +}); + +test('a lone bound form with fields of its own is posted even when the test sends other fields', async () => { + // A review of #1698: refusing whenever no submitted field matched also + // refused a test that posts a field the form lacks on purpose (a + // mass-assignment check) and fields the scan cannot see. Only a field-less + // form (a logout button) is refused now. + const a = await handler(); + const res = await submitForm(a.handle, '/signup', { role: 'admin' }); + assert.equal(res.status, 422, 'posted to the signup action, which refused the missing email'); +}); + test('an unbound form is reported as unbound, not silently submitted', async () => { const a = await handler(); await assert.rejects( diff --git a/packages/ui/AGENTS.md b/packages/ui/AGENTS.md index 6d9dc546c..1708f6dc9 100644 --- a/packages/ui/AGENTS.md +++ b/packages/ui/AGENTS.md @@ -284,7 +284,10 @@ function per component (`buttonVariants`, `badgeVariants`, `toggleVariants`, `tabsListVariants`, and later `buttonGroupVariants`, `markerVariants`, `navigationMenuTriggerStyle`). The kit exports each under the same name, beside its own helper, so shadcn code ports verbatim. Each returns exactly what the -helper returns, and like `cva` it merges a `className` option into the result. +helper returns, and like `cva` both merge a `className` option into the result +(#1697: the kit's own name takes it too, since an agent writes +`buttonClass({ variant, className })` from the same habit). With no +`className` the helper's output is unchanged. ## Blocks and charts (#1666, D18) diff --git a/packages/ui/packages/registry/components/attachment.ts b/packages/ui/packages/registry/components/attachment.ts index 621e9e9c3..b49391784 100644 --- a/packages/ui/packages/registry/components/attachment.ts +++ b/packages/ui/packages/registry/components/attachment.ts @@ -50,8 +50,8 @@ const ATTACHMENT_ORIENTATIONS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } = {}): string { - return cn(ATTACHMENT_BASE, ATTACHMENT_SIZES[opts.size ?? 'default'], ATTACHMENT_ORIENTATIONS[opts.orientation ?? 'horizontal']); +export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } & { className?: string } = {}): string { + return cn(ATTACHMENT_BASE, ATTACHMENT_SIZES[opts.size ?? 'default'], ATTACHMENT_ORIENTATIONS[opts.orientation ?? 'horizontal'], opts.className); } /** @@ -59,7 +59,7 @@ export function attachmentClass(opts: { size?: keyof typeof ATTACHMENT_SIZES; or * it merges a `className` into the result. */ export function attachmentVariants(opts: { size?: keyof typeof ATTACHMENT_SIZES; orientation?: keyof typeof ATTACHMENT_ORIENTATIONS } & { className?: string } = {}): string { - return cn(attachmentClass(opts), opts.className); + return attachmentClass(opts); } const ATTACHMENT_MEDIA_BASE = @@ -71,8 +71,8 @@ const ATTACHMENT_MEDIA_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } = {}): string { - return cn(ATTACHMENT_MEDIA_BASE, ATTACHMENT_MEDIA_VARIANTS[opts.variant ?? 'icon']); +export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } & { className?: string } = {}): string { + return cn(ATTACHMENT_MEDIA_BASE, ATTACHMENT_MEDIA_VARIANTS[opts.variant ?? 'icon'], opts.className); } /** @@ -80,7 +80,7 @@ export function attachmentMediaClass(opts: { variant?: keyof typeof ATTACHMENT_M * it merges a `className` into the result. */ export function attachmentMediaVariants(opts: { variant?: keyof typeof ATTACHMENT_MEDIA_VARIANTS } & { className?: string } = {}): string { - return cn(attachmentMediaClass(opts), opts.className); + return attachmentMediaClass(opts); } /** Set `data-slot="attachment-content"` on the element. */ diff --git a/packages/ui/packages/registry/components/badge.ts b/packages/ui/packages/registry/components/badge.ts index ee961acdb..4ac3c7b5e 100644 --- a/packages/ui/packages/registry/components/badge.ts +++ b/packages/ui/packages/registry/components/badge.ts @@ -39,8 +39,8 @@ const VARIANTS = { export type BadgeVariant = keyof typeof VARIANTS; -export function badgeClass(opts: { variant?: BadgeVariant } = {}): string { - return cn(BASE, VARIANTS[opts.variant ?? 'default']); +export function badgeClass(opts: { variant?: BadgeVariant } & { className?: string } = {}): string { + return cn(BASE, VARIANTS[opts.variant ?? 'default'], opts.className); } /** @@ -49,5 +49,5 @@ export function badgeClass(opts: { variant?: BadgeVariant } = {}): string { * merges a `className` into the result. */ export function badgeVariants(opts: { variant?: BadgeVariant } & { className?: string } = {}): string { - return cn(badgeClass(opts), opts.className); + return badgeClass(opts); } diff --git a/packages/ui/packages/registry/components/bubble.ts b/packages/ui/packages/registry/components/bubble.ts index 6a7aea581..2e9f1714d 100644 --- a/packages/ui/packages/registry/components/bubble.ts +++ b/packages/ui/packages/registry/components/bubble.ts @@ -51,8 +51,8 @@ const BUBBLE_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } = {}): string { - return cn(BUBBLE_BASE, BUBBLE_VARIANTS[opts.variant ?? 'default']); +export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } & { className?: string } = {}): string { + return cn(BUBBLE_BASE, BUBBLE_VARIANTS[opts.variant ?? 'default'], opts.className); } /** @@ -60,7 +60,7 @@ export function bubbleClass(opts: { variant?: keyof typeof BUBBLE_VARIANTS } = { * it merges a `className` into the result. */ export function bubbleVariants(opts: { variant?: keyof typeof BUBBLE_VARIANTS } & { className?: string } = {}): string { - return cn(bubbleClass(opts), opts.className); + return bubbleClass(opts); } /** Set `data-slot="bubble-content"` on the element. */ @@ -82,8 +82,8 @@ const BUBBLE_REACTIONS_ALIGNS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } = {}): string { - return cn(BUBBLE_REACTIONS_BASE, BUBBLE_REACTIONS_SIDES[opts.side ?? 'bottom'], BUBBLE_REACTIONS_ALIGNS[opts.align ?? 'end']); +export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } & { className?: string } = {}): string { + return cn(BUBBLE_REACTIONS_BASE, BUBBLE_REACTIONS_SIDES[opts.side ?? 'bottom'], BUBBLE_REACTIONS_ALIGNS[opts.align ?? 'end'], opts.className); } /** @@ -91,5 +91,5 @@ export function bubbleReactionsClass(opts: { side?: keyof typeof BUBBLE_REACTION * it merges a `className` into the result. */ export function bubbleReactionsVariants(opts: { side?: keyof typeof BUBBLE_REACTIONS_SIDES; align?: keyof typeof BUBBLE_REACTIONS_ALIGNS } & { className?: string } = {}): string { - return cn(bubbleReactionsClass(opts), opts.className); + return bubbleReactionsClass(opts); } diff --git a/packages/ui/packages/registry/components/button-group.ts b/packages/ui/packages/registry/components/button-group.ts index 04342e01c..2526bdc15 100644 --- a/packages/ui/packages/registry/components/button-group.ts +++ b/packages/ui/packages/registry/components/button-group.ts @@ -46,8 +46,8 @@ const ORIENTATIONS = { export type ButtonGroupOrientation = keyof typeof ORIENTATIONS; /** The group container. Pair with `role="group"` and `data-orientation`. */ -export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } = {}): string { - return cn(BASE, ORIENTATIONS[opts.orientation ?? 'horizontal']); +export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } & { className?: string } = {}): string { + return cn(BASE, ORIENTATIONS[opts.orientation ?? 'horizontal'], opts.className); } /** @@ -56,7 +56,7 @@ export function buttonGroupClass(opts: { orientation?: ButtonGroupOrientation } * Like cva, it merges a `className` into the result. */ export function buttonGroupVariants(opts: { orientation?: ButtonGroupOrientation } & { className?: string } = {}): string { - return cn(buttonGroupClass(opts), opts.className); + return buttonGroupClass(opts); } /** A non-interactive label or value sitting inside the group. */ diff --git a/packages/ui/packages/registry/components/button.ts b/packages/ui/packages/registry/components/button.ts index 055a88ee3..7edc4b093 100644 --- a/packages/ui/packages/registry/components/button.ts +++ b/packages/ui/packages/registry/components/button.ts @@ -74,10 +74,10 @@ export interface ButtonClassOptions { } /** Compose Tailwind classes for a button. Stable shape: object-arg, both optional. */ -export function buttonClass(opts: ButtonClassOptions = {}): string { +export function buttonClass(opts: ButtonClassOptions & { className?: string } = {}): string { const variant = opts.variant ?? 'default'; const size = opts.size ?? 'default'; - return cn(BASE, VARIANTS[variant], SIZES[size]); + return cn(BASE, VARIANTS[variant], SIZES[size], opts.className); } /** @@ -86,5 +86,5 @@ export function buttonClass(opts: ButtonClassOptions = {}): string { * merges a `className` into the result. */ export function buttonVariants(opts: ButtonClassOptions & { className?: string } = {}): string { - return cn(buttonClass(opts), opts.className); + return buttonClass(opts); } diff --git a/packages/ui/packages/registry/components/code-block.ts b/packages/ui/packages/registry/components/code-block.ts index 6d449dee2..c8d322ee0 100644 --- a/packages/ui/packages/registry/components/code-block.ts +++ b/packages/ui/packages/registry/components/code-block.ts @@ -56,13 +56,13 @@ const CODE_BLOCK_VARIANTS = { export type CodeBlockVariant = keyof typeof CODE_BLOCK_VARIANTS; /** The frame's classes. */ -export function codeBlockClass(opts: { variant?: CodeBlockVariant } = {}): string { - return cn('cn-code-block group/code-block relative flex w-full min-w-0 flex-col overflow-hidden', CODE_BLOCK_VARIANTS[opts.variant ?? 'default']); +export function codeBlockClass(opts: { variant?: CodeBlockVariant } & { className?: string } = {}): string { + return cn('cn-code-block group/code-block relative flex w-full min-w-0 flex-col overflow-hidden', CODE_BLOCK_VARIANTS[opts.variant ?? 'default'], opts.className); } /** shadcn's name for {@link codeBlockClass}. Like cva, it merges a `className`. */ export function codeBlockVariants(opts: { variant?: CodeBlockVariant; className?: string } = {}): string { - return cn(codeBlockClass(opts), opts.className); + return codeBlockClass(opts); } /** The header row. */ @@ -100,16 +100,17 @@ const CODE_BLOCK_LINE_VARIANTS = { export type CodeBlockLineVariant = keyof typeof CODE_BLOCK_LINE_VARIANTS; /** One line's classes. */ -export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } = {}): string { +export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } & { className?: string } = {}): string { return cn( "cn-code-block-line relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']", CODE_BLOCK_LINE_VARIANTS[opts.variant ?? 'default'], + opts.className, ); } /** shadcn's name for {@link codeBlockLineClass}. Like cva, it merges a `className`. */ export function codeBlockLineVariants(opts: { variant?: CodeBlockLineVariant; className?: string } = {}): string { - return cn(codeBlockLineClass(opts), opts.className); + return codeBlockLineClass(opts); } /** The footer row. */ diff --git a/packages/ui/packages/registry/components/input-group.ts b/packages/ui/packages/registry/components/input-group.ts index 3bc89ba72..060483f30 100644 --- a/packages/ui/packages/registry/components/input-group.ts +++ b/packages/ui/packages/registry/components/input-group.ts @@ -55,8 +55,8 @@ const INPUT_GROUP_ADDON_ALIGNS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } = {}): string { - return cn(INPUT_GROUP_ADDON_BASE, INPUT_GROUP_ADDON_ALIGNS[opts.align ?? 'inline-start']); +export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } & { className?: string } = {}): string { + return cn(INPUT_GROUP_ADDON_BASE, INPUT_GROUP_ADDON_ALIGNS[opts.align ?? 'inline-start'], opts.className); } /** @@ -64,7 +64,7 @@ export function inputGroupAddonClass(opts: { align?: keyof typeof INPUT_GROUP_AD * it merges a `className` into the result. */ export function inputGroupAddonVariants(opts: { align?: keyof typeof INPUT_GROUP_ADDON_ALIGNS } & { className?: string } = {}): string { - return cn(inputGroupAddonClass(opts), opts.className); + return inputGroupAddonClass(opts); } const INPUT_GROUP_BUTTON_BASE = @@ -84,8 +84,8 @@ const INPUT_GROUP_BUTTON_SIZES = { * with these classes on top, so the button's own classes come first and the * group's size wins a conflict. */ -export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } = {}): string { - return cn(buttonClass({ variant: opts.variant ?? 'ghost' }), INPUT_GROUP_BUTTON_BASE, INPUT_GROUP_BUTTON_SIZES[opts.size ?? 'xs']); +export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } & { className?: string } = {}): string { + return cn(buttonClass({ variant: opts.variant ?? 'ghost' }), INPUT_GROUP_BUTTON_BASE, INPUT_GROUP_BUTTON_SIZES[opts.size ?? 'xs'], opts.className); } /** @@ -93,7 +93,7 @@ export function inputGroupButtonClass(opts: { size?: keyof typeof INPUT_GROUP_BU * it merges a `className` into the result. */ export function inputGroupButtonVariants(opts: { size?: keyof typeof INPUT_GROUP_BUTTON_SIZES; variant?: ButtonVariant } & { className?: string } = {}): string { - return cn(inputGroupButtonClass(opts), opts.className); + return inputGroupButtonClass(opts); } /** A part with no `data-slot` of its own. */ diff --git a/packages/ui/packages/registry/components/item.ts b/packages/ui/packages/registry/components/item.ts index 2cfb39a27..195f98591 100644 --- a/packages/ui/packages/registry/components/item.ts +++ b/packages/ui/packages/registry/components/item.ts @@ -69,8 +69,8 @@ const ITEM_SIZES = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } = {}): string { - return cn(ITEM_BASE, ITEM_VARIANTS[opts.variant ?? 'default'], ITEM_SIZES[opts.size ?? 'default']); +export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string { + return cn(ITEM_BASE, ITEM_VARIANTS[opts.variant ?? 'default'], ITEM_SIZES[opts.size ?? 'default'], opts.className); } /** @@ -78,7 +78,7 @@ export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: k * it merges a `className` into the result. */ export function itemVariants(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string { - return cn(itemClass(opts), opts.className); + return itemClass(opts); } const ITEM_MEDIA_BASE = @@ -91,8 +91,8 @@ const ITEM_MEDIA_VARIANTS = { } as const; /** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */ -export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } = {}): string { - return cn(ITEM_MEDIA_BASE, ITEM_MEDIA_VARIANTS[opts.variant ?? 'default']); +export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string { + return cn(ITEM_MEDIA_BASE, ITEM_MEDIA_VARIANTS[opts.variant ?? 'default'], opts.className); } /** @@ -100,7 +100,7 @@ export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANT * it merges a `className` into the result. */ export function itemMediaVariants(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string { - return cn(itemMediaClass(opts), opts.className); + return itemMediaClass(opts); } /** Set `data-slot="item-content"` on the element. */ diff --git a/packages/ui/packages/registry/components/marker.ts b/packages/ui/packages/registry/components/marker.ts index 14303a62f..9e2366d0e 100644 --- a/packages/ui/packages/registry/components/marker.ts +++ b/packages/ui/packages/registry/components/marker.ts @@ -40,8 +40,8 @@ const VARIANTS = { export type MarkerVariant = keyof typeof VARIANTS; /** The marker row. Pair with `data-variant` set to the same variant. */ -export function markerClass(opts: { variant?: MarkerVariant } = {}): string { - return cn(BASE, VARIANTS[opts.variant ?? 'default']); +export function markerClass(opts: { variant?: MarkerVariant } & { className?: string } = {}): string { + return cn(BASE, VARIANTS[opts.variant ?? 'default'], opts.className); } /** @@ -49,7 +49,7 @@ export function markerClass(opts: { variant?: MarkerVariant } = {}): string { * cva, it merges a `className` into the result. */ export function markerVariants(opts: { variant?: MarkerVariant } & { className?: string } = {}): string { - return cn(markerClass(opts), opts.className); + return markerClass(opts); } /** The leading icon. */ diff --git a/packages/ui/packages/registry/components/sidebar.ts b/packages/ui/packages/registry/components/sidebar.ts index d88a9949f..7e1503c8e 100644 --- a/packages/ui/packages/registry/components/sidebar.ts +++ b/packages/ui/packages/registry/components/sidebar.ts @@ -164,17 +164,18 @@ export type SidebarMenuButtonVariant = keyof typeof MENU_BUTTON_VARIANTS; export type SidebarMenuButtonSize = keyof typeof MENU_BUTTON_SIZES; /** A menu button (an <a> or a <button>); mark the current one `data-active="true"`. */ -export function sidebarMenuButtonClass(opts: { variant?: SidebarMenuButtonVariant; size?: SidebarMenuButtonSize } = {}): string { +export function sidebarMenuButtonClass(opts: { variant?: SidebarMenuButtonVariant; size?: SidebarMenuButtonSize } & { className?: string } = {}): string { return cn( 'cn-sidebar-menu-button peer/menu-button group/menu-button flex w-full items-center overflow-hidden outline-hidden disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0 [&>span:last-child]:truncate', MENU_BUTTON_VARIANTS[opts.variant ?? 'default'], MENU_BUTTON_SIZES[opts.size ?? 'default'], + opts.className, ); } /** shadcn's name for {@link sidebarMenuButtonClass}. Like cva, it merges a `className`. */ export function sidebarMenuButtonVariants(opts: { variant?: SidebarMenuButtonVariant; size?: SidebarMenuButtonSize; className?: string } = {}): string { - return cn(sidebarMenuButtonClass(opts), opts.className); + return sidebarMenuButtonClass(opts); } /** A menu item's action button; `showOnHover` hides it until the item is hovered or focused. */ diff --git a/packages/ui/packages/registry/components/tabs.ts b/packages/ui/packages/registry/components/tabs.ts index 9fe334f35..63ee460ec 100644 --- a/packages/ui/packages/registry/components/tabs.ts +++ b/packages/ui/packages/registry/components/tabs.ts @@ -101,8 +101,8 @@ export function tabsListVariant(variant: TabsListVariant | string | null | undef } /** Optional helper exposing the tabs-list class for advanced overrides. */ -export function tabsListClass(opts: { variant?: TabsListVariant } = {}): string { - return cn(TABS_LIST_BASE, TABS_LIST_VARIANTS[tabsListVariant(opts.variant)]); +export function tabsListClass(opts: { variant?: TabsListVariant } & { className?: string } = {}): string { + return cn(TABS_LIST_BASE, TABS_LIST_VARIANTS[tabsListVariant(opts.variant)], opts.className); } /** @@ -111,7 +111,7 @@ export function tabsListClass(opts: { variant?: TabsListVariant } = {}): string * merges a `className` into the result. */ export function tabsListVariants(opts: { variant?: TabsListVariant } & { className?: string } = {}): string { - return cn(tabsListClass(opts), opts.className); + return tabsListClass(opts); } // The trigger is rendered as a native <button role="tab">, which gives diff --git a/packages/ui/packages/registry/components/toggle.ts b/packages/ui/packages/registry/components/toggle.ts index cbb863f23..1e30de149 100644 --- a/packages/ui/packages/registry/components/toggle.ts +++ b/packages/ui/packages/registry/components/toggle.ts @@ -92,8 +92,8 @@ const SIZES = { export type ToggleVariant = keyof typeof VARIANTS; export type ToggleSize = keyof typeof SIZES; -export function toggleClass(opts: { variant?: ToggleVariant; size?: ToggleSize } = {}): string { - return cn(BASE, VARIANTS[opts.variant ?? 'default'], SIZES[opts.size ?? 'default']); +export function toggleClass(opts: { variant?: ToggleVariant; size?: ToggleSize } & { className?: string } = {}): string { + return cn(BASE, VARIANTS[opts.variant ?? 'default'], SIZES[opts.size ?? 'default'], opts.className); } /** @@ -102,7 +102,7 @@ export function toggleClass(opts: { variant?: ToggleVariant; size?: ToggleSize } * merges a `className` into the result. */ export function toggleVariants(opts: { variant?: ToggleVariant; size?: ToggleSize } & { className?: string } = {}): string { - return cn(toggleClass(opts), opts.className); + return toggleClass(opts); } // -------------------------------------------------------------------------- diff --git a/packages/ui/packages/registry/lib/utils.ts b/packages/ui/packages/registry/lib/utils.ts index 435d40050..72adfe85e 100644 --- a/packages/ui/packages/registry/lib/utils.ts +++ b/packages/ui/packages/registry/lib/utils.ts @@ -1,23 +1,7 @@ /** - * Tiny class-name merger. Drop-in replacement for the clsx + tailwind-merge - * pair used in shadcn. - * - * - Concatenates truthy arguments separated by spaces. - * - Later Tailwind utilities win when they target the same property, mimicking - * `tailwind-merge`'s behaviour for the cases components actually hit - * (background colour, image, clip, origin, blend mode, position, size, - * repeat, attachment; text colour, size, alignment, wrapping, overflow; - * box-shadow and text-shadow, each split into size and colour; padding, - * margin, width, height, border, rounded, opacity, display). - * - * For projects that want the full tailwind-merge behaviour, install - * `clsx` + `tailwind-merge` and replace this file: - * - * import { clsx, type ClassValue } from 'clsx'; - * import { twMerge } from 'tailwind-merge'; - * export function cn(...inputs: ClassValue[]) { - * return twMerge(clsx(inputs)); - * } + * `cn()`, shadcn's clsx + tailwind-merge in one: joins the truthy arguments, + * and a later utility wins over an earlier one for the same CSS property. + * Below it are the layout and typography class helpers. */ export type ClassValue = string | number | null | false | undefined | ClassValue[] | Record<string, unknown>; @@ -44,64 +28,35 @@ function walk(value: ClassValue, out: string[]): void { } } -// Conflict groups: classes with the same group key: last one wins. -// Covers ~95% of in-component overrides the registry exposes. -// -// IMPORTANT: text-size (text-sm, text-xs, text-base, text-lg, …) and -// text-color (text-primary, text-foreground, …) are DIFFERENT properties -// and must be in different groups. Same for bg-size vs bg-color etc. -// Built on FIRST USE, not at module load, so a module that imports `cn` does no -// work at load and a page that never merges a class never builds the table -// (#1320). +// The merger. One group per CSS property (never per class prefix); a later +// class evicts an earlier one in its group. Built on first use (#1320). let _groups: Array<[RegExp, string]> | undefined; function GROUPS(): Array<[RegExp, string]> { return (_groups ??= [ [/^p-/, 'p'], [/^px-/, 'px'], [/^py-/, 'py'], [/^pt-/, 'pt'], [/^pr-/, 'pr'], [/^pb-/, 'pb'], [/^pl-/, 'pl'], [/^ps-/, 'ps'], [/^pe-/, 'pe'], [/^m-/, 'm'], [/^mx-/, 'mx'], [/^my-/, 'my'], [/^mt-/, 'mt'], [/^mr-/, 'mr'], [/^mb-/, 'mb'], [/^ml-/, 'ml'], [/^ms-/, 'ms'], [/^me-/, 'me'], [/^w-/, 'w'], [/^h-/, 'h'], [/^size-/, 'size'], - // A `bg-[url(…)]` / `bg-[linear-gradient(…)]` background image is classified - // by its FUNCTION, since it carries no type hint to classify it by. The - // hinted forms are handled centrally, in `hintedGroup`. [/^bg-\[(url\(|linear-gradient|radial-gradient|conic-gradient)/, 'bg-image'], [/^bg-(linear|gradient|conic|radial|none)/, 'bg-image'], [/^bg-(no-repeat|repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/, 'bg-repeat'], [/^bg-(fixed|local|scroll)$/, 'bg-attach'], [/^bg-(auto|cover|contain)$/, 'bg-size'], [/^bg-size-/, 'bg-size'], - // Two entries rather than one alternation: the first covers the live v4 - // compounds (`bg-top-left`), the second the bare keywords plus the v4.1 - // deprecated reversed compounds (`bg-left-top`), which tailwind-merge still - // carries. An unmatched `bg-*` token falls into the colour catch-all below and - // evicts a real colour, so admitting a dead spelling is the safe direction. [/^bg-(top|bottom)(-(left|right))?$/, 'bg-position'], [/^bg-(left|right|center)(-(top|bottom))?$/, 'bg-position'], [/^bg-position-/, 'bg-position'], - // Clip, origin, and blend mode are three more properties under the same - // prefix. Each sat in `bg-color` before, so `bg-clip-text` evicted a real - // background colour (the gradient-text idiom lost its clip silently). [/^bg-clip-(border|padding|content|text)$/, 'bg-clip'], [/^bg-origin-(border|padding|content)$/, 'bg-origin'], [/^bg-blend-(normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity)$/, 'bg-blend'], [/^bg-/, 'bg-color'], - // text-shadow is its own property, and its size scale and its colour are two - // properties again. All three entries precede the text- patterns below, which - // is what keeps a `text-shadow-*` token out of `text-size` and `text-color`. [/^text-shadow(-(2xs|xs|sm|md|lg|none))?(\/([\d.]+|\[[^\]]*\]))?$/, 'text-shadow'], [/^text-shadow-(\[(inset|-|\.|\d|var\()|\(--)/, 'text-shadow'], [/^text-shadow-/, 'text-shadow-color'], - // Font size: explicit list of Tailwind size scale. [/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/, 'text-size'], - // Alignment, wrapping, and overflow are three more properties under the same - // prefix. Each was previously excluded from text-color by a lookahead and then - // matched nothing at all, so two alignments never collapsed. [/^text-(left|center|right|justify|start|end)$/, 'text-align'], [/^text-(wrap|nowrap|balance|pretty)$/, 'text-wrap'], [/^text-(ellipsis|clip)$/, 'text-overflow'], - // Text color: anything else under the prefix. The specific groups above are - // the whole carve-out, so no negative lookahead is needed here as well. [/^text-/, 'text-color'], - // Border sub-properties that are neither a width nor a colour. These come - // FIRST so the width / colour classifier below never sees them. [/^border-(collapse|separate)$/, 'border-collapse'], [/^border-spacing(-[xy])?-/, 'border-spacing'], [/^border-(solid|dashed|dotted|double|hidden|none)$/, 'border-style'], @@ -111,47 +66,20 @@ function GROUPS(): Array<[RegExp, string]> { [/^opacity-/, 'opacity'], [/^leading-/, 'leading'], [/^font-(thin|light|normal|medium|semibold|bold|black|extralight|extrabold)$/, 'font-weight'], - // Box-shadow SIZE and box-shadow COLOUR are two properties (`box-shadow` and - // `--tw-shadow-color`), so they need two groups. `shadow-none` is a size, - // `shadow-inherit` / `shadow-initial` are colours, and Tailwind accepts an - // alpha modifier on a size as well as on a colour, so `shadow-lg/25` has to - // stay on the size side. An unhinted arbitrary value is a SIZE when it opens - // with `inset`, a sign, a dot, or a digit (a shadow offset list) and also - // when it is a bare `var()` or the `(--x)` variable shorthand: Tailwind - // itself resolves an ambiguous arbitrary shadow to `box-shadow` unless the - // value is provably a colour, and `shadow-[var(--shadow-glow)]` is the normal - // way to write a design-token shadow. This is the one place the - // `borderGroups()` convention inverts, because a bare `border-[var(--x)]` is - // far more often a colour while a bare `shadow-[var(--x)]` is far more often - // a shadow. The size entries must precede the colour catch-all, or every - // size lands in the colour group and the bug inverts rather than being fixed. + // Shadow size and shadow colour are two properties; an unhinted arbitrary + // value is a size when it opens like an offset list or is a bare var(). [/^shadow(-(2xs|xs|sm|md|lg|xl|2xl|inner|none))?(\/([\d.]+|\[[^\]]*\]))?$/, 'shadow'], [/^shadow-(\[(inset|-|\.|\d|var\()|\(--)/, 'shadow'], - // A bare name the size scale does not list reads as a colour, because - // `shadow-primary` is overwhelmingly more common than a `@theme`-extended - // `--shadow-card`. A project that adds a custom shadow NAME is the residual - // gap, and the docs say so rather than claiming the split is total. [/^shadow-/, 'shadow-color'], [/^z-/, 'z'], - // A bare `flex` / `grid` is a DISPLAY value, not a member of the flex / grid - // sub-property groups below, so it must never dedupe against them: an element - // can be both a flex container and a flex child (`class="flex flex-1"`), and - // collapsing the two silently drops `display:flex`. It still belongs to a - // group of its own, alongside every other display keyword, so a repeated one - // collapses and `cn('hidden', open && 'flex')` resolves to one display. + // Display keywords, apart from the flex / grid sub-properties below. [/^(inline-block|inline-flex|inline-grid|inline-table|inline|block|flex|grid|flow-root|contents|hidden|list-item|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table)$/, 'display'], - // Each sub-utility below gets the group of the real CSS property it sets, so - // none of them collapses against the display value or against each other. [/^flex-(row|row-reverse|col|col-reverse)$/, 'flex-direction'], [/^flex-(wrap|wrap-reverse|nowrap)$/, 'flex-wrap'], [/^flex-(\d+|auto|initial|none|\[[^\]]*\])$/, 'flex'], [/^grid-cols-/, 'grid-cols'], [/^grid-rows-/, 'grid-rows'], [/^grid-flow-/, 'grid-flow'], - // Flex basis and the alignment properties, one group per property: - // `justify-items-*` and `justify-self-*` precede `justify-*`, which is - // justify-content, and likewise `self-*` is align-self, apart from - // `items-*` (align-items). [/^basis-/, 'basis'], [/^justify-items-/, 'justify-items'], [/^justify-self-/, 'justify-self'], @@ -162,34 +90,12 @@ function GROUPS(): Array<[RegExp, string]> { } /** - * Border WIDTH and border COLOUR share the `border-` prefix but are different - * CSS properties, so they need different groups: `cn('border-2', - * 'border-primary')` must keep BOTH, while `cn('border-border', - * 'border-accent')` must keep only the later colour (today the winner is - * decided by compiled stylesheet order, which silently loses whenever the - * override sorts alphabetically earlier). - * - * Classification, after an optional side / axis segment: a bare or numeric - * value is a width (`border`, `border-2`, `border-t-4`), an arbitrary value - * that opens with a digit, a dot, or `length:` is a width (`border-[3px]`, - * `border-[length:var(--w)]`, and the v4 paren spelling - * `border-(length:--w)`), and everything else is a colour - * (`border-primary`, `border-red-500/50`, `border-[#fff]`). An ambiguous - * `border-[var(--x)]`, or its paren spelling `border-(--x)`, falls to colour, - * which is the far more common intent. - * - * Each side is its own group so a per-side utility only overrides its own side, - * and the shorthand / axis subsumption is declared in CONFLICTS below, exactly - * like padding and margin. The logical inline sides (`border-s-*`, - * `border-e-*`) get their own groups but are subsumed only by the all-sides - * shorthand, never by `border-x-*`: which physical side they land on depends on - * the writing direction, so an axis override there would be a guess. + * Border width and colour groups, one per side. A bare or numeric value, or an + * arbitrary length, is a width; anything else is a colour. */ function borderGroups(): Array<[RegExp, string]> { const width = '(\\d+(\\.\\d+)?|\\[(length:|\\d|\\.)[^\\]]*\\]|\\(length:[^)]*\\))'; const out: Array<[RegExp, string]> = []; - // Sides before the bare form: `border-t-primary` must match the `t` colour - // group, not be swallowed by the side-less `^border-` colour pattern. const sides = ['x', 'y', 't', 'r', 'b', 'l', 's', 'e', '']; for (const side of sides) { const seg = side ? `-${side}` : ''; @@ -203,34 +109,9 @@ function borderGroups(): Array<[RegExp, string]> { } /** - * An arbitrary value may carry a Tailwind TYPE HINT: `bg-[image:var(--g)]`, - * `text-[length:14px]`, `shadow-[color:red]`, and in the v4 paren shorthand - * `bg-(image:--g)`, `shadow-(color:--x)`. The hint exists precisely because - * the utility prefix is ambiguous, so the PREFIX cannot decide the group and - * the hint must. Letting a hinted value fall into the prefix's default group - * evicts a class that sets an entirely different property (`shadow-[color:red]` - * would eat `shadow-lg`). - * - * Every `<prefix>:<hint>` pair listed here names the group it belongs to; an - * empty string means the hint names the prefix's OWN default property, so the - * GROUPS table above is already right for it and matching falls through. A pair - * that is NOT listed gets a group of its own, so it can only ever collide with - * the identical hint under the identical prefix, never with the prefix's - * default. That is the safe direction to fail: an extra class renders, a - * dropped one does not. - * - * This is central rather than per-prefix on purpose. Handling only the prefixes - * that came to mind is how `shadow-[color:red]` was left evicting `shadow-lg` - * while `bg-` and `text-` were correct. - * - * These reach the matcher at all only because `variantPrefix` splits on the - * last colon OUTSIDE brackets AND parentheses; see the comment there. - * - * Both spellings of one hint produce the identical `<prefix>:<hint>` key, so - * the map needs no paren-specific entries. The closing delimiter is - * deliberately not validated: the hint names the CSS property, and how the - * value terminates cannot change which property that is (the bracket branch - * has never validated its own close either). + * A type-hinted arbitrary value (`bg-[image:...]`, `shadow-(color:--x)`) is + * grouped by its hint. '' means the prefix's own default property; an unlisted + * pair gets a group of its own. */ const HINTED_GROUPS: Record<string, string> = { 'bg:color': '', @@ -240,10 +121,6 @@ const HINTED_GROUPS: Record<string, string> = { 'bg:length': 'bg-size', 'text:color': '', 'text:length': 'text-size', - // Both shadow prefixes carry a colour that is a DIFFERENT property from the - // prefix's own default (the size), so the hint has a named group to point at - // and must, or `shadow-[color:red]` keeps an isolated bucket and stops - // deduping against `shadow-red-500`, which sets the identical property. 'shadow:color': 'shadow-color', 'text-shadow:color': 'text-shadow-color', }; @@ -259,22 +136,12 @@ function hintedGroup(bare: string): string | null | undefined { const hint = m[2]; const key = `${prefix}:${hint}`; if (key in HINTED_GROUPS) return HINTED_GROUPS[key] || null; - // A border width or colour hint is read by `borderGroups()`'s value parser, - // which already classifies `border-[length:2px]` as a width and everything - // else after `border-` as a colour. The side list MUST match the one - // `borderGroups()` enumerates, logical inline sides included, or the hinted - // and plain spellings of one utility land in different groups. if (/^border(-[xytrbles])?$/.test(prefix) && (hint === 'length' || hint === 'color')) return null; return `hint:${key}`; } -// Directional shorthand conflicts (the tailwind-merge model). A shorthand -// utility invalidates the axis / side utilities it SUBSUMES, because Tailwind's -// cascade makes the shorthand win: `p-0` after `px-4 py-2` drops both, but -// `px-4` after `p-2` refines only the x-axis so BOTH survive (the conflict is -// directional, not symmetric). Keyed by the group a NEWLY-seen token belongs to; -// the value lists the EARLIER groups whose survivors it removes (its own group -// is always removed too, handled below). +// A shorthand evicts the sides it subsumes (`p-0` drops an earlier `px-4`), not +// the other way round. const CONFLICTS: Record<string, string[]> = { p: ['px', 'py', 'pt', 'pr', 'pb', 'pl', 'ps', 'pe'], px: ['pl', 'pr'], @@ -298,14 +165,9 @@ function dedupeUtilities(input: string): string { const result: Array<string | null> = []; for (const token of tokens) { - // Strip variant prefix (`hover:`, `dark:md:`, …) before testing each dedupe - // regex so `hover:bg-red-500` still matches the `bg-color` group. Conflicts - // only apply WITHIN the same variant (`px-4 hover:p-0` keeps both). + // Conflicts apply within one variant set (`px-4 hover:p-0` keeps both). const prefix = variantPrefix(token); const bare = prefix ? token.slice(prefix.length) : token; - // A type-hinted arbitrary value is classified by its HINT, which overrides - // the prefix-keyed table below (`hintedGroup` returns null when the hint - // names the prefix's own default property and the table is already right). const hinted = hintedGroup(bare); let gk: string | null = hinted ?? null; if (hinted === undefined || hinted === null) { @@ -314,7 +176,6 @@ function dedupeUtilities(input: string): string { } } if (gk) { - // Remove earlier survivors in this group AND in every group it subsumes. for (const g of [gk, ...(CONFLICTS[gk] ?? [])]) { const k = `${prefix}::${g}`; const idx = lastByKey.get(k); @@ -328,23 +189,8 @@ function dedupeUtilities(input: string): string { } function variantPrefix(token: string): string { - // Capture leading variants like `hover:`, `dark:`, `md:`: overrides only - // conflict within the same variant set. The split is the last colon at top - // level, meaning outside BOTH square brackets and parentheses, because an - // arbitrary value can contain a colon of its own in either delimiter - // (`border-[length:2px]`, `bg-[url(https://x/y.png)]`, `text-[color:var(--c)]`, - // and the v4 paren spelling `shadow-(color:--x)`, `bg-(image:--g)`). - // Splitting on the last colon anywhere hands the group matcher a fragment - // like `2px]` or `--x)`, which matches nothing, so the utility silently - // stops deduping against its own property. - // - // TWO counters, both required to be zero, rather than one shared counter. - // Tailwind's own top-level splitter (`segment()`, in the upstream - // tailwindlabs/tailwindcss repo at packages/tailwindcss/src/utils/segment.ts, - // NOT a path in this repo) is a MATCHED-PAIR stack, so a - // stray closer never cancels a live opener of the other kind. A single - // shared counter would let `)` cancel `[` and read `x-[y)-z:w` as having a - // top-level colon, which is the fragment bug above wearing a different hat. + // The variants end at the last colon outside both brackets and parens, each + // counted on its own, since an arbitrary value has colons of its own. let bracketDepth = 0; let parenDepth = 0; let i = -1; @@ -359,15 +205,8 @@ function variantPrefix(token: string): string { return i === -1 ? '' : token.slice(0, i + 1); } -// --------------------------------------------------------------------------- -// Stable DOM ids for wiring ARIA relationships (aria-controls / -// aria-labelledby / aria-describedby) between sibling light-DOM nodes. -// A monotonic counter is fine for uniqueness within a document: the id is -// only consumed as an attribute value, never persisted. When SSR emits an -// id on a host element, the upgraded element reuses it (ensureId is a no-op -// when an id is already present), so the server and client agree. -// --------------------------------------------------------------------------- - +// Stable DOM ids for ARIA wiring between light-DOM nodes. An id already on +// the element (author-set, or from SSR) is kept, so server and client agree. let _idSeq = 0; /** A fresh, document-unique id string with a readable prefix. */ @@ -395,18 +234,10 @@ export type ClassHost = { }; /** - * The class an author wrote on a Tier-2 part's host, which is shadcn's - * `className` and belongs on the element the part renders. Read once per - * element, then `hostClass` replaces it on the host (`null` removes the - * class, `undefined` leaves the attribute to the caller, for a host that - * styles itself). - * - * The first read records the class in `data-authored-class`, which the server - * serves, because the class attribute cannot be trusted on hydration: the - * server sends the class a tag was written with, and a host written with none - * is sent the class the element gave it (`contents`, its own classes). The - * element that upgrades the served markup is a fresh instance, so without the - * record it would read that class back as the author's. + * The class an author wrote on a Tier-2 part's host (shadcn's `className`), + * recorded in `data-authored-class` on first read so a hydrating instance + * reads the author's class, not the one the element served. `hostClass` + * replaces it on the host (`null` removes it). */ export function takeAuthoredClass(host: ClassHost, hostClass?: string | null): string | null { if (host._authoredClass === undefined) { @@ -420,18 +251,7 @@ export function takeAuthoredClass(host: ClassHost, hostClass?: string | null): s return host._authoredClass; } -// NOTE: the old `HTMLElement`-era `Base` / `defineElement` / SSR-stub helpers -// were removed. The ui registry components extend `WebComponent` from -// `@webjsdev/core` now, so those helpers were dead code, and referencing -// `HTMLElement` / `customElements` at module scope marked this util (and any -// page that imports `cn`) as client-effecting. Everything below is pure or -// SSR-safe, so importing `cn` no longer pins a page to the browser (#819). - -// --------------------------------------------------------------------------- -// Layout helpers: encode the design-system rhythm (spacing between label / -// input / hint, between form fields, between sections). Change one helper to -// retune the whole app: call sites stay readable inline Tailwind. -// --------------------------------------------------------------------------- +// Layout helpers: the design system's spacing rhythm, in one place. /** Vertical rhythm inside a single form field: label ↔ control ↔ hint/error. */ export const fieldClass = () => 'grid gap-2'; @@ -442,13 +262,7 @@ export const fieldRowClass = () => 'flex items-center gap-3'; /** Gap step for `stackClass({ gap })`. */ export type StackGap = 'sm' | 'md' | 'lg'; -/** - * Stack of form fields. `sm` for tight groupings, `lg` for spaced-out sections. - * - * Object-arg shape matches the rest of the kit (`buttonClass({ variant, size })`, - * `badgeClass({ variant })`, etc.): predictable across all helpers and - * extensible if a second dimension (e.g. `direction`) is ever added. - */ +/** Stack of form fields: `sm` tight, `lg` spaced out. */ export const stackClass = (opts: { gap?: StackGap } = {}): string => { const gap = opts.gap ?? 'md'; return gap === 'sm' ? 'grid gap-3' : gap === 'lg' ? 'grid gap-8' : 'grid gap-6'; @@ -460,9 +274,7 @@ export const formClass = () => 'grid gap-6'; /** Top-level section separation (between form groups, between sections of a page). */ export const sectionClass = () => 'grid gap-8'; -// --------------------------------------------------------------------------- -// Typography helpers: fixed text styles used across the design system. -// --------------------------------------------------------------------------- +// Typography helpers. /** Form-field label: `<label>` text style. */ export const fieldLabelClass = () => diff --git a/packages/ui/test/class-helpers.test.js b/packages/ui/test/class-helpers.test.js index a70dcdf4e..4ebf1e6d5 100644 --- a/packages/ui/test/class-helpers.test.js +++ b/packages/ui/test/class-helpers.test.js @@ -359,6 +359,29 @@ test('the shadcn style-function aliases return the helper output, plus a merged } }); +// #1697: an eval agent wrote `buttonClass({ variant: 'link', className })`, +// the shadcn `buttonVariants` habit under the kit's own name, and spent a +// typecheck round on it. Every helper that has a shadcn alias takes it too. +test('a helper with a shadcn alias takes className itself, and is unchanged without it', { skip }, async () => { + const { readdirSync, readFileSync } = await import('node:fs'); + const files = readdirSync(COMPONENTS_DIR).filter((f) => f.endsWith('.ts')); + let checked = 0; + for (const file of files) { + const src = readFileSync(join(COMPONENTS_DIR, file), 'utf8'); + const mod = await import(join(COMPONENTS_DIR, file)); + for (const [, base] of src.matchAll(/export function ([a-zA-Z]+)Variants\(/g)) { + const helper = mod[`${base}Class`]; + assert.equal(typeof helper, 'function', `${base}Class is exported beside ${base}Variants`); + const plain = helper(); + assert.equal(helper({ className: '' }), plain, `${base}Class with an empty className is unchanged`); + assert.match(helper({ className: 'wj-extra' }), /(^|\s)wj-extra(\s|$)/, `${base}Class merges className`); + assert.equal(helper({ className: 'wj-extra' }), mod[`${base}Variants`]({ className: 'wj-extra' }), `${base}Class matches its alias`); + checked += 1; + } + } + assert.ok(checked >= 17, `checked ${checked} helpers`); +}); + test('alertDialogMediaClass: the header media slot', { skip }, async () => { const { alertDialogMediaClass } = await import(join(COMPONENTS_DIR, 'alert-dialog.ts')); const s = alertDialogMediaClass(); diff --git a/scripts/agent-eval/README.md b/scripts/agent-eval/README.md index 50e433a11..e7e1f7dde 100644 --- a/scripts/agent-eval/README.md +++ b/scripts/agent-eval/README.md @@ -72,7 +72,10 @@ above it is refused: Claude Code loads those from every ancestor, so a build under `~/.claude/` would follow the machine owner's own instructions. The app's `node_modules` links the framework checkout's entries except the in-repo apps (`@webjsdev/example-blog`, `gallery`, `website`), which no real install has. The transcript is stream-json, so `replay.mjs` -reads it as it is. +reads it as it is. Each build gets a dev-server port from the OS (pin them with +`--port-base <n>`) and its own short temp directory under `/tmp`, linked from +`<build>/tmp`, so two arms run at once never share a port, a database or a +cookie jar, and Playwright's socket path stays under the Unix limit. ```sh node scripts/agent-eval/build.mjs --spec roomly # 1 build, Haiku diff --git a/scripts/agent-eval/build.mjs b/scripts/agent-eval/build.mjs index af2c5c3f2..66e65778b 100644 --- a/scripts/agent-eval/build.mjs +++ b/scripts/agent-eval/build.mjs @@ -28,7 +28,8 @@ * * Local only: it calls a model and costs money per build. */ -import { mkdirSync, writeFileSync, readFileSync, existsSync, symlinkSync, readdirSync, createWriteStream } from 'node:fs'; +import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, existsSync, symlinkSync, readdirSync, readlinkSync, lstatSync, unlinkSync, rmSync, createWriteStream } from 'node:fs'; +import { createServer } from 'node:net'; import { parse as parsePath } from 'node:path'; import { spawn, spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; @@ -54,7 +55,7 @@ Work ONLY inside that directory. Start by reading its AGENTS.md. Dependencies ar ${spec.trim()} -When done, verify it yourself: \`npx webjs check\` must report no violations, \`npx webjs typecheck\` must pass, \`npm test\` must pass, and the app must boot (\`npx webjs dev --port ${port}\`, then exercise the routes with curl, then STOP the server). Do not leave any server running. +When done, verify it yourself: \`npx webjs check\` must report no violations, \`npx webjs typecheck\` must pass, \`npm test\` must pass, and the app must boot and serve its routes. If you start a server, use port ${port}, and stop it before you finish: leave no server running. Then reply with a short report: what you built, the verification results, and every point of friction (anything in WebJs that did not work the way your Lit / Next.js habits expected).`; } @@ -69,19 +70,36 @@ export function metricsOf(transcriptPath) { let toolCalls = 0; let inputTokens = 0; let outputTokens = 0; + let costUsd = null; + // stream-json repeats one API message once per content block (thinking, + // text, tool_use), each carrying the same id, so usage is counted once per + // message id. Counting it per event inflated input 2.2 to 2.9 times and + // tracked how much an agent narrated (#1697). A later event of a message can + // report more output than the first (it is written as the message streams), + // so each field keeps its largest value seen for the id. + /** @type {Map<string, { input: number, output: number }>} */ + const perMessage = new Map(); let durationMs = 0; let resultText = ''; for (const line of readFileSync(transcriptPath, 'utf8').split('\n')) { if (!line) continue; let e; try { e = JSON.parse(line); } catch { continue; } - if (e.type === 'result') { durationMs = e.duration_ms || 0; resultText = e.result || ''; continue; } + if (e.type === 'result') { durationMs = e.duration_ms || 0; resultText = e.result || ''; costUsd = e.total_cost_usd ?? null; continue; } const content = e.message?.content; if (!Array.isArray(content)) continue; if (e.type === 'assistant') { const u = e.message.usage || {}; - inputTokens += (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0); - outputTokens += u.output_tokens || 0; + const input = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0); + const output = u.output_tokens || 0; + const id = e.message.id; + if (!id) { + inputTokens += input; + outputTokens += output; + } else { + const seen = perMessage.get(id) || { input: 0, output: 0 }; + perMessage.set(id, { input: Math.max(seen.input, input), output: Math.max(seen.output, output) }); + } for (const c of content) { if (c?.type !== 'tool_use') continue; toolCalls++; @@ -106,7 +124,8 @@ export function metricsOf(transcriptPath) { } } } - return { firsts, rework, toolCalls, inputTokens, outputTokens, minutes: Math.round(durationMs / 600) / 100, report: resultText }; + for (const m of perMessage.values()) { inputTokens += m.input; outputTokens += m.output; } + return { firsts, rework, toolCalls, inputTokens, outputTokens, costUsd, minutes: Math.round(durationMs / 600) / 100, report: resultText }; } function grade(appDir, cli) { @@ -146,22 +165,59 @@ export async function prepareApp({ framework, parent, appName, template = 'full- /** * The environment a headless agent runs in: none of this session's markers, - * and, given a build directory, a temp directory of its own inside it. - * Concurrent builds shared /tmp, so one build's curl cookie jar was read by - * another, which then chased a session it never created for about 45 turns. + * and, given a build directory, a temp directory of its own. Concurrent builds + * shared /tmp, so one build's curl cookie jar was read by another, which then + * chased a session it never created for about 45 turns. The directory is a + * short one under /tmp, linked from `<buildDir>/tmp`: inside the build + * directory its path was long enough that Playwright's socket under it passed + * the 108-byte Unix socket limit, and the browser never launched (#1697, nine + * turns over four builds). * @param {string} [buildDir] */ export function agentEnv(buildDir) { const env = { ...process.env }; for (const k of Object.keys(env)) if (k.startsWith('CLAUDE_CODE') || k === 'CLAUDECODE') delete env[k]; if (buildDir) { - const tmp = join(buildDir, 'tmp'); - mkdirSync(tmp, { recursive: true }); + mkdirSync(buildDir, { recursive: true }); + const tmp = mkdtempSync(join(existsSync('/tmp') ? '/tmp' : tmpdir(), 'wje-')); + // A re-run into the same build dir finds the previous link: lstat sees it + // even when its /tmp target is gone (existsSync follows it and says no, + // so symlinkSync then threw EEXIST). It is replaced, and the previous + // run's temp dir removed, so the link always names this run's TMPDIR + // and old wje-* dirs do not pile up. A real directory (a build dir from + // before the link) is left alone. + const link = join(buildDir, 'tmp'); + let previous = null; + try { previous = lstatSync(link); } catch { /* none yet */ } + if (previous?.isSymbolicLink()) { + const old = readlinkSync(link); + unlinkSync(link); + if (/\/wje-[^/]+$/.test(old)) rmSync(old, { recursive: true, force: true }); + previous = null; + } + if (!previous) symlinkSync(tmp, link); env.TMPDIR = env.TMP = env.TEMP = tmp; } return env; } +/** + * A port nothing is listening on, from the OS. Builds started as separate + * runs used the same fixed port base, so two dev servers met on one port and + * an agent wrote into another build's database (#1697, eleven turns). + * @returns {Promise<number>} + */ +export function freePort() { + return new Promise((ok, fail) => { + const srv = createServer(); + srv.once('error', fail); + srv.listen(0, '127.0.0.1', () => { + const { port } = /** @type {import('node:net').AddressInfo} */ (srv.address()); + srv.close(() => ok(port)); + }); + }); +} + /** Where the eval host keeps a system Chromium, which Playwright's MCP cannot find on its own. */ export const SYSTEM_CHROMIUM = '/usr/bin/chromium'; @@ -231,11 +287,12 @@ const WORKSPACE_APPS = new Set(['example-blog', 'gallery', 'website']); * the workspace apps. * @param {string} framework @param {string} app */ -function linkNodeModules(framework, app) { +export function linkNodeModules(framework, app) { const src = join(framework, 'node_modules'); const dst = join(app, 'node_modules'); mkdirSync(dst); for (const name of readdirSync(src)) { + if (name === '.bin') { linkBin(join(src, name), join(dst, name)); continue; } if (name !== '@webjsdev') { symlinkSync(join(src, name), join(dst, name)); continue; } mkdirSync(join(dst, name)); for (const pkg of readdirSync(join(src, name))) { @@ -245,6 +302,27 @@ function linkNodeModules(framework, app) { } } +/** + * `node_modules/.bin`, entry by entry. npm writes each bin as a relative link + * (`../@webjsdev/cli/bin/webjs.js`), and linking the directory whole resolved + * those against the checkout it physically lives in, so in a linked worktree + * every eval app's `npx webjs` ran the PRIMARY checkout's CLI instead of the + * framework under test (#1697). A framework package's bin keeps its relative + * target, which now lands on the app's own link to that package; any other + * bin links to the original entry. + * @param {string} srcBin @param {string} dstBin + */ +function linkBin(srcBin, dstBin) { + mkdirSync(dstBin); + for (const entry of readdirSync(srcBin)) { + const from = join(srcBin, entry); + let target = null; + try { target = readlinkSync(from); } catch { /* a real file */ } + if (target && target.startsWith('../@webjsdev/')) symlinkSync(target, join(dstBin, entry)); + else symlinkSync(from, join(dstBin, entry)); + } +} + /** * A framework package as npm would install it: its `package.json` and the * entries its `files` list publishes (plus its own nested `node_modules`), each @@ -289,10 +367,10 @@ export function assertNoAncestorInstructions(out) { const yn = (v) => (v === true ? 'pass' : v === false ? 'FAIL' : '-'); function printTable(results) { - console.log('build first: check type test | draft: check type test | final: check type test | rework calls in(M) min'); + console.log('build first: check type test | draft: check type test | final: check type test | rework calls in(M) cost min'); for (const r of results) { const f = r.firsts || {}; - console.log(`${r.name.padEnd(21)} ${yn(f.check).padEnd(5)} ${yn(f.typecheck).padEnd(4)} ${yn(f.test).padEnd(4)} | ${yn(r.draft?.check).padEnd(5)} ${yn(r.draft?.typecheck).padEnd(4)} ${yn(r.draft?.test).padEnd(4)} | ${yn(r.final?.check).padEnd(5)} ${yn(r.final?.typecheck).padEnd(4)} ${yn(r.final?.test).padEnd(4)} | ${String(r.rework).padEnd(6)} ${String(r.toolCalls).padEnd(5)} ${(r.inputTokens / 1e6).toFixed(1).padEnd(5)} ${r.wallMinutes}`); + console.log(`${r.name.padEnd(21)} ${yn(f.check).padEnd(5)} ${yn(f.typecheck).padEnd(4)} ${yn(f.test).padEnd(4)} | ${yn(r.draft?.check).padEnd(5)} ${yn(r.draft?.typecheck).padEnd(4)} ${yn(r.draft?.test).padEnd(4)} | ${yn(r.final?.check).padEnd(5)} ${yn(r.final?.typecheck).padEnd(4)} ${yn(r.final?.test).padEnd(4)} | ${String(r.rework).padEnd(6)} ${String(r.toolCalls).padEnd(5)} ${(r.inputTokens / 1e6).toFixed(1).padEnd(5)} ${(r.costUsd == null ? '-' : '$' + r.costUsd.toFixed(2)).padEnd(5)} ${r.wallMinutes}`); } const all3 = (o) => o && o.check === true && o.typecheck === true && o.test === true; console.log(`first attempt all three: ${results.filter((r) => all3(r.firsts)).length}/${results.length}; draft all three: ${results.filter((r) => all3(r.draft)).length}/${results.length}; final all three: ${results.filter((r) => all3(r.final)).length}/${results.length}`); @@ -306,21 +384,22 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1 process.exit(0); } const specName = arg('spec'); - if (!specName) { console.error('usage: build.mjs --spec <roomly|pollster|trackr|inbox> [--runs N] [--jobs N] [--model haiku] [--framework <checkout>] [--label after] [--out <dir>] [--port-base 8900]'); process.exit(2); } + if (!specName) { console.error('usage: build.mjs --spec <roomly|pollster|trackr|inbox> [--runs N] [--jobs N] [--model haiku] [--framework <checkout>] [--label after] [--out <dir>] [--port-base <n>]'); process.exit(2); } const spec = readFileSync(join(HERE, 'specs', `${specName}.md`), 'utf8'); const runs = Number(arg('runs', '1')); const jobs = Number(arg('jobs', '3')); const out = resolve(arg('out', join('/var/tmp', 'webjs-builds'))); assertNoAncestorInstructions(out); const opts = { spec, specName, out, framework: resolve(arg('framework', REPO)), model: arg('model', 'haiku'), label: arg('label', 'after'), timeoutS: Number(arg('timeout', '5400')) }; - // A distinct --port-base per concurrent invocation keeps two arms' dev servers apart. - const portBase = Number(arg('port-base', '8900')); + // Each build asks the OS for a free port; --port-base pins them instead. + const portBase = arg('port-base') ? Number(arg('port-base')) : null; const results = []; let next = 0; await Promise.all(Array.from({ length: Math.min(jobs, runs) }, async (_, w) => { while (next < runs) { const index = ++next; - results.push(await oneBuild({ ...opts, index, port: portBase + index * 10 + w })); + const port = portBase === null ? await freePort() : portBase + index * 10 + w; + results.push(await oneBuild({ ...opts, index, port })); } })); results.sort((a, b) => a.name.localeCompare(b.name)); diff --git a/test/agent-eval/build-metrics.test.mjs b/test/agent-eval/build-metrics.test.mjs index 45c917851..961fe32da 100644 --- a/test/agent-eval/build-metrics.test.mjs +++ b/test/agent-eval/build-metrics.test.mjs @@ -10,7 +10,10 @@ import { mkdtempSync, writeFileSync, rmSync, mkdirSync, readFileSync, existsSync import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { metricsOf, promptFor, agentEnv, evalMcpConfig } from '../../scripts/agent-eval/build.mjs'; +import { realpathSync } from 'node:fs'; +import { createServer } from 'node:net'; +import { symlinkSync } from 'node:fs'; +import { metricsOf, promptFor, agentEnv, evalMcpConfig, freePort, linkNodeModules } from '../../scripts/agent-eval/build.mjs'; /** A stream-json transcript from a list of events. */ function transcript(events) { @@ -54,7 +57,11 @@ test('the prompt carries the spec and names no WebJs API beyond its CLI', () => const p = promptFor('Build "X", a thing.', '/tmp/app', 8900); assert.match(p, /Build "X", a thing\./); assert.match(p, /\/tmp\/app/); - assert.match(p, /webjs dev --port 8900/); + // #1697: the app must boot and serve its routes, and the prompt does not + // say how (a dev server plus curl was a loop no real user asks for). + assert.match(p, /boot and serve its routes/); + assert.match(p, /use port 8900/); + assert.doesNotMatch(p, /curl/); assert.doesNotMatch(p, /WebComponent|createAuth|html`|'use server'/, 'the frame teaches nothing the brief should'); }); @@ -62,15 +69,29 @@ test('each build gets a temp directory of its own, so concurrent builds never sh const dir = mkdtempSync(join(tmpdir(), 'eval-env-')); try { const env = agentEnv(dir); - assert.equal(env.TMPDIR, join(dir, 'tmp')); assert.equal(env.TMP, env.TMPDIR); assert.ok(existsSync(env.TMPDIR), 'and it exists'); - assert.notEqual(agentEnv(join(dir, 'b')).TMPDIR, env.TMPDIR, 'a second build gets another'); + assert.equal(realpathSync(join(dir, 'tmp')), realpathSync(env.TMPDIR), 'linked from the build directory'); + // #1697: Playwright puts a Unix socket under TMPDIR, and a socket path + // has a 108-byte limit, so the directory has to be short. + assert.ok(env.TMPDIR.length < 32, `a short path (${env.TMPDIR})`); + const other = agentEnv(join(dir, 'b')); + assert.notEqual(other.TMPDIR, env.TMPDIR, 'a second build gets another'); + rmSync(env.TMPDIR, { recursive: true, force: true }); + rmSync(other.TMPDIR, { recursive: true, force: true }); } finally { rmSync(dir, { recursive: true, force: true }); } }); +test('freePort hands out a port nothing is listening on', async () => { + const port = await freePort(); + assert.ok(port > 0); + const srv = createServer(); + await new Promise((ok, fail) => { srv.once('error', fail); srv.listen(port, '127.0.0.1', ok); }); + await new Promise((ok) => srv.close(ok)); +}); + test('the agent MCP config is a copy pointing Playwright at the system Chromium', () => { const dir = mkdtempSync(join(tmpdir(), 'eval-mcp-')); try { @@ -90,3 +111,90 @@ test('the agent MCP config is a copy pointing Playwright at the system Chromium' rmSync(dir, { recursive: true, force: true }); } }); + +// #1697: a framework checkout whose node_modules is a link into another +// checkout (a linked worktree) must still hand the app ITS CLI through npx. +test('an eval app runs the framework under test through npx, not the checkout its .bin lives in', () => { + const root = mkdtempSync(join(tmpdir(), 'eval-bin-')); + try { + const mk = (dir, ver) => { + mkdirSync(join(dir, 'packages/cli/bin'), { recursive: true }); + writeFileSync(join(dir, 'packages/cli/package.json'), JSON.stringify({ name: '@webjsdev/cli', files: ['bin'] })); + writeFileSync(join(dir, 'packages/cli/bin/webjs.js'), `// ${ver}\n`); + }; + const primary = join(root, 'primary'); + const worktree = join(root, 'worktree'); + mk(primary, 'primary'); + mk(worktree, 'worktree'); + // The primary's install: npm's relative bin link and a workspace link. + mkdirSync(join(primary, 'node_modules/.bin'), { recursive: true }); + mkdirSync(join(primary, 'node_modules/@webjsdev'), { recursive: true }); + symlinkSync('../../packages/cli', join(primary, 'node_modules/@webjsdev/cli')); + symlinkSync('../@webjsdev/cli/bin/webjs.js', join(primary, 'node_modules/.bin/webjs')); + mkdirSync(join(primary, 'node_modules/left-pad')); + // The worktree: .bin linked whole into the primary, @webjsdev its own. + mkdirSync(join(worktree, 'node_modules/@webjsdev'), { recursive: true }); + symlinkSync(join(primary, 'node_modules/.bin'), join(worktree, 'node_modules/.bin')); + symlinkSync(join(primary, 'node_modules/left-pad'), join(worktree, 'node_modules/left-pad')); + symlinkSync(join(worktree, 'packages/cli'), join(worktree, 'node_modules/@webjsdev/cli')); + const app = join(root, 'app'); + mkdirSync(app); + linkNodeModules(worktree, app); + assert.match(readFileSync(join(app, 'node_modules/.bin/webjs'), 'utf8'), /worktree/, 'the bin resolves to the worktree CLI'); + assert.ok(existsSync(join(app, 'node_modules/left-pad')), 'other packages are still linked'); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); + +// #1697: stream-json writes one event per content block of a message, each +// with the message's full usage, so summing per event counted it 2 to 3 times. +test('usage is counted once per API message, however many blocks it has', () => { + const block = (type) => ({ type: 'assistant', message: { id: 'msg_1', usage: { input_tokens: 10, cache_read_input_tokens: 990, output_tokens: 5 }, content: [{ type }] } }); + const { file, dir } = transcript([ + block('thinking'), block('text'), + { type: 'assistant', message: { id: 'msg_1', usage: { input_tokens: 10, cache_read_input_tokens: 990, output_tokens: 5 }, content: [{ type: 'tool_use', id: 'b1', name: 'Bash', input: { command: 'ls' } }] } }, + { type: 'assistant', message: { id: 'msg_2', usage: { input_tokens: 20, cache_read_input_tokens: 1980, output_tokens: 7 }, content: [{ type: 'text' }] } }, + { type: 'result', duration_ms: 60_000, result: 'ok', total_cost_usd: 0.42 }, + ]); + try { + const m = metricsOf(file); + assert.equal(m.inputTokens, 3000, 'msg_1 once (1000) plus msg_2 (2000), not msg_1 three times'); + assert.equal(m.outputTokens, 12); + assert.equal(m.toolCalls, 1); + assert.equal(m.costUsd, 0.42, 'the run cost from the result event'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +// A review of #1698: a message's later events can report more output than its +// first, since usage is written as the message streams. +test('each message keeps the largest usage any of its events reports', () => { + const ev = (out) => ({ type: 'assistant', message: { id: 'msg_1', usage: { input_tokens: 10, cache_read_input_tokens: 990, output_tokens: out }, content: [{ type: 'text' }] } }); + const { file, dir } = transcript([ev(2), ev(40), ev(15)]); + try { + const m = metricsOf(file); + assert.equal(m.inputTokens, 1000); + assert.equal(m.outputTokens, 40, 'the largest output the message reported, not its first'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +// A review of #1698: re-running into the same build dir after /tmp was +// cleaned left a dangling link, and symlinkSync threw EEXIST. +test('a re-run into the same build dir replaces the previous temp link', () => { + const dir = mkdtempSync(join(tmpdir(), 'eval-rerun-')); + try { + const first = agentEnv(dir); + rmSync(first.TMPDIR, { recursive: true, force: true }); + const second = agentEnv(dir); + assert.equal(realpathSync(join(dir, 'tmp')), realpathSync(second.TMPDIR), 'the link names the new run'); + const third = agentEnv(dir); + assert.ok(!existsSync(second.TMPDIR), 'and the previous run\'s temp dir is removed'); + rmSync(third.TMPDIR, { recursive: true, force: true }); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/bun/action-control-flow-rpc.mjs b/test/bun/action-control-flow-rpc.mjs new file mode 100644 index 000000000..5be2cbe23 --- /dev/null +++ b/test/bun/action-control-flow-rpc.mjs @@ -0,0 +1,63 @@ +/** + * Cross-runtime proof that notFound() / forbidden() / unauthorized() in a + * server action called over RPC answer 404 / 403 / 401 through the real + * listener, with the kind in x-webjs-control, the same status the no-JS form + * path renders (#1697). They used to answer a logged 500. + * + * node test/bun/action-control-flow-rpc.mjs + * bun test/bun/action-control-flow-rpc.mjs + */ +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CORE = pathToFileURL(resolve(__dirname, '../../packages/core/index.js')).toString(); +const { startServer } = await import(pathToFileURL(resolve(__dirname, '../../packages/server/index.js')).toString()); +const { stringify } = await import(pathToFileURL(resolve(__dirname, '../../packages/core/src/serialize.js')).toString()); +const runtime = process.versions.bun ? `bun ${process.versions.bun}` : `node ${process.versions.node}`; +const errors = []; +const quiet = { info() {}, warn() {}, error(...a) { errors.push(a.join(' ')); }, debug() {} }; + +const dir = mkdtempSync(join(tmpdir(), 'wj-act-control-')); +const w = (rel, body) => { const abs = join(dir, rel); mkdirSync(dirname(abs), { recursive: true }); writeFileSync(abs, body); }; +let close; +let failure = null; +try { + writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'ac', type: 'module' })); + w('modules/guard.server.ts', `'use server';\nimport { notFound, forbidden, unauthorized } from ${JSON.stringify(CORE)};\nexport async function denied() { forbidden(); }\nexport async function missing() { notFound(); }\nexport async function anon() { unauthorized(); }\n`); + w('app/page.ts', `import { html } from ${JSON.stringify(CORE)};\nimport { denied } from '../modules/guard.server.ts';\nexport default () => html\`<form action=\${denied}></form>\`;\n`); + + let server; + ({ server, close } = await startServer({ appDir: dir, dev: false, port: 0, logger: quiet })); + const port = typeof server.port === 'number' ? server.port : server.address().port; + const base = `http://localhost:${port}`; + const html = await (await fetch(`${base}/`)).text(); + const id = /name="__webjs_action" value="([^"]+)"/.exec(html)?.[1]; + assert.ok(id, `the form renders an identity on ${runtime}`); + const hash = id.split('/')[0]; + + for (const [fn, status, kind] of [['denied', 403, 'forbidden'], ['missing', 404, 'not-found'], ['anon', 401, 'unauthorized']]) { + const rpc = await fetch(`${base}/__webjs/action/${hash}/${fn}`, { + method: 'POST', + headers: { 'content-type': 'application/vnd.webjs+json', 'sec-fetch-site': 'same-origin' }, + body: await stringify([]), + }); + await rpc.text(); + assert.equal(rpc.status, status, `${fn}() over RPC is a ${status} on ${runtime}`); + assert.equal(rpc.headers.get('x-webjs-control'), kind); + } + assert.deepEqual(errors.filter((e) => /action threw/.test(e)), [], `no sentinel is logged as an action error on ${runtime}`); + console.log(`ok action control flow over RPC on ${runtime}`); +} catch (e) { + failure = e; +} finally { + if (close) await close(); + rmSync(dir, { recursive: true, force: true }); +} +if (failure) { + console.error(failure); + process.exit(1); +} diff --git a/test/cli/test-db.test.mjs b/test/cli/test-db.test.mjs index afbec6900..f167b15c4 100644 --- a/test/cli/test-db.test.mjs +++ b/test/cli/test-db.test.mjs @@ -10,7 +10,7 @@ */ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, existsSync } from 'node:fs'; +import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync, existsSync, readFileSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; @@ -102,6 +102,14 @@ test('a row round-trips through the app db', async () => { // A second run starts empty again: the row count assertion would fail on a reused database. assert.equal(run({}).status, 0, 'each run gets its own database'); + // #1697: test files run in parallel processes, and on one shared file they + // hit `database is locked`. Each file gets its own copy, so a second file + // inserting the same unique email still sees exactly one row. + writeFileSync(join(app, 'test', 'users', 'again.test.ts'), + readFileSync(join(app, 'test', 'users', 'users.test.ts'), 'utf8')); + const pair = run({}); + assert.equal(pair.status, 0, 'two files writing the same unique row each have their own database\n' + pair.stdout + pair.stderr); + // Counterfactual: opted out, the test runs against the unmigrated dev database and fails. assert.notEqual(run({ WEBJS_TEST_DB: '0' }).status, 0, 'without the test database the table does not exist'); } finally { diff --git a/test/cli/verify.test.mjs b/test/cli/verify.test.mjs new file mode 100644 index 000000000..8a5a4106f --- /dev/null +++ b/test/cli/verify.test.mjs @@ -0,0 +1,125 @@ +/** + * `webjs verify` (#1697): check and typecheck in parallel, then test, then the + * app's dev before-steps and an in-process boot of every route, in one call + * on the `webjs ci` engine. Eval agents spent about 19 late turns per build + * starting a dev server, curling and stopping it. The engine's spawn is + * injected, so nothing real runs. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { PassThrough } from 'node:stream'; + +import { runVerify, verifySteps, tail } from '../../packages/cli/lib/verify.js'; + +/** + * A fake spawn: each command resolves to { code, output, late }, where `late` + * is written after 'exit' and before 'close', as a real child's last stdio + * chunks can be. + */ +function fakeSpawn(results, log) { + return (cmd, opts) => { + const child = new EventEmitter(); + child.stdout = new PassThrough(); + child.stderr = new PassThrough(); + child.pid = 1; + child.kill = () => {}; + const key = Object.keys(results).find((k) => cmd.endsWith(k)); + const r = (key && results[key]) || { code: 0, output: '' }; + log.push({ cmd, env: opts.env, at: log.length }); + setImmediate(() => { + if (r.output) child.stdout.write(r.output); + child.emit('exit', r.code, null); + setImmediate(() => { + if (r.late) child.stdout.write(r.late); + setImmediate(() => child.emit('close', r.code, null)); + }); + }); + return child; + }; +} + +const run = (results, extra = {}) => { + const log = []; + const lines = []; + const p = runVerify({ appDir: '/app', cli: 'CLI', spawn: fakeSpawn(results, log), out: (s) => lines.push(s), env: {}, ...extra }); + return p.then((code) => ({ code, log, lines })); +}; + +test('the steps: check and typecheck in one parallel group, then test, prepare and boot', () => { + const nodes = verifySteps('CLI', ['webjs db migrate', 'webjs regenerate']); + assert.equal(nodes[0].kind, 'group'); + assert.equal(nodes[0].parallel, 2); + assert.deepEqual(nodes[0].steps.map((s) => s.run), ['CLI check', 'CLI typecheck']); + assert.deepEqual(nodes.slice(1).map((s) => s.run), ['CLI test', 'webjs db migrate && webjs regenerate', 'CLI status --boot']); + assert.deepEqual(verifySteps('CLI', []).map((n) => n.title), ['checks', 'test', 'boot'], 'no prepare step without before-steps'); +}); + +test('every step passes: one line each and exit 0', async () => { + const { code, lines, log } = await run({}, { beforeSteps: ['webjs db migrate'] }); + assert.equal(code, 0); + assert.deepEqual(lines.slice(0, 5).map((l) => l.split(/\s+/)[1]), ['check', 'typecheck', 'test', 'prepare', 'boot']); + assert.match(lines.at(-1), /all 5 steps passed/); + assert.equal(log.length, 5); +}); + +test('check and typecheck start before either finishes', async () => { + const { log } = await run({}); + assert.deepEqual(log.slice(0, 2).map((l) => l.cmd), ['CLI check', 'CLI typecheck'], 'both spawned first, in the same group'); +}); + +test('a failing step prints its output tail, the rest still run, and the exit is 1', async () => { + const { code, lines } = await run({ + 'CLI typecheck': { code: 2, output: 'app/page.ts(3,1): error TS2322: nope\n' }, + 'CLI status --boot': { code: 1, output: 'GET /polls 500\n Error: no such table: polls\n' }, + }); + assert.equal(code, 1); + const text = lines.join('\n'); + assert.match(text, /FAIL {2}typecheck .*exit 2/); + assert.match(text, /error TS2322: nope/); + assert.match(text, /ok {4}test/, 'a later step still ran after the failure'); + assert.match(text, /no such table: polls/); + assert.match(lines.at(-1), /2 of 4 steps failed/); +}); + +// The review's first finding: output written after 'exit' and before 'close' +// is the failing assertion and the run's summary, the part the tail exists for. +test('output a step writes after it exits is still in the report', async () => { + const { lines } = await run({ 'CLI test': { code: 1, output: 'running 3 tests\n', late: 'not ok 2 - votes are counted\n# fail 1\n' } }); + const text = lines.join('\n'); + assert.match(text, /not ok 2 - votes are counted/); + assert.match(text, /# fail 1/); +}); + +// A review of #1698: the ci engine sets CI=true on every step, which made an +// app's tests and boot run as CI during a local loop. +test('steps run without CI=true, unless the shell set it', async () => { + const plain = await run({}, { env: { KEEP: '1' } }); + for (const l of plain.log) assert.equal(l.env.CI, undefined); + const inCi = await run({}, { env: { CI: '1' } }); + for (const l of inCi.log) assert.equal(l.env.CI, '1', 'a real CI shell keeps its own value'); +}); + +test('no step inherits a parent node --test context', async () => { + const { log } = await run({}, { env: { NODE_TEST_CONTEXT: 'child-v8', KEEP: '1' } }); + for (const l of log) { + assert.equal(l.env.NODE_TEST_CONTEXT, undefined); + assert.equal(l.env.KEEP, '1'); + } +}); + +test('tail keeps the last lines and strips colour codes', () => { + const out = Array.from({ length: 50 }, (_, i) => `\x1b[31mline ${i}\x1b[0m`).join('\n'); + assert.deepEqual(tail(out, 3).split('\n'), ['...', 'line 47', 'line 48', 'line 49']); +}); + +test('tail drops stack frames, which the code frame already locates', () => { + const out = 'Error: kaboom\n at Broken (file:///app/page.ts:1:42)\n at async render (x.js:9:1)\n GET /broken 500'; + assert.equal(tail(out), 'Error: kaboom\n GET /broken 500'); +}); + +// A review of #1698: the filter dropped every line starting with "at". +test('tail keeps a message line that starts with "at"', () => { + const out = 'not ok 1 - rows\n at least one row expected\n at Test.run (node:internal/test_runner/test:1409:7)\n at <anonymous>'; + assert.equal(tail(out), 'not ok 1 - rows\n at least one row expected'); +}); diff --git a/test/repo-health/gallery-theme-key.test.mjs b/test/repo-health/gallery-theme-key.test.mjs index 0b1f4e534..0d1537b07 100644 --- a/test/repo-health/gallery-theme-key.test.mjs +++ b/test/repo-health/gallery-theme-key.test.mjs @@ -68,8 +68,9 @@ test('the gallery bootstrap and toggle agree on one theme storage key', () => { test('the shared theme key matches every other app in the repo', () => { // The gallery is the reference a scaffolded app is grown from, so a private // key here would teach the wrong convention even though nothing would break. + // The scaffold (packages/cli/lib/create.js) is not listed: since #1697 it + // ships no theme toggle and stores no choice, its dark mode following the OS. for (const [rel, expected] of [ - ['packages/cli/lib/create.js', 'webjs_theme'], ['examples/blog/components/theme-toggle.ts', 'webjs_theme'], ]) { assert.ok( diff --git a/test/scaffolds/gallery-coverage.json b/test/scaffolds/gallery-coverage.json index 12f74e7e2..d7519ca5f 100644 --- a/test/scaffolds/gallery-coverage.json +++ b/test/scaffolds/gallery-coverage.json @@ -744,7 +744,7 @@ "demoed": true }, "setOnError": { - "demoed": true + "exempt": "deferred: agent-facing (the APM hook an app's instrumentation.ts registers, documented on the docs-site error-handling page); the scaffold dropped its optional instrumentation.ts to stay minimal (#1697)" }, "setSerializer": { "exempt": "internal: framework/CLI plumbing" diff --git a/test/scaffolds/scaffold-integration.test.js b/test/scaffolds/scaffold-integration.test.js index ded81cab1..eea4f0642 100644 --- a/test/scaffolds/scaffold-integration.test.js +++ b/test/scaffolds/scaffold-integration.test.js @@ -129,38 +129,28 @@ test('scaffoldApp full-stack: writes the canonical full-stack app layout', async // Full-stack template-specific assert.ok(existsSync(join(appDir, 'app', 'layout.ts')), 'layout.ts written'); assert.ok(existsSync(join(appDir, 'app', 'page.ts')), 'page.ts written'); - assert.ok(existsSync(join(appDir, 'components', 'theme-toggle.ts')), 'theme-toggle written'); - - // Dark-mode wiring: the head init script (in layout) AND the theme-toggle - // must toggle the shadcn `.dark` class, not only the `data-theme` - // attribute. Without `.dark`, the theme (and the copied components/ui/*) - // render light tokens on the dark chrome (white buttons/cards, invisible text). Light - // mode hides this, so guard it here. See https://webjs.dev/docs/styling. + // #1697: the scaffold ships no theme toggle and no kit code. Dark mode + // follows the OS from the layout's pre-paint script, on the shadcn .dark + // class the kit's tokens switch on; without .dark the theme renders light + // tokens on dark chrome. + assert.ok(!existsSync(join(appDir, 'components', 'theme-toggle.ts')), 'no theme toggle'); + assert.ok(!existsSync(join(appDir, 'components', 'ui')), 'no pre-installed kit components'); + assert.ok(!existsSync(join(appDir, 'lib', 'utils', 'cn.ts')), 'no pre-written cn(): the first ui add writes it'); + assert.ok(!existsSync(join(appDir, 'instrumentation.ts')), 'no optional instrumentation hook'); const layoutSrc = readFileSync(join(appDir, 'app', 'layout.ts'), 'utf8'); - const toggleSrc = readFileSync(join(appDir, 'components', 'theme-toggle.ts'), 'utf8'); - assert.match(layoutSrc, /classList\.toggle\(['"]dark['"]/, - 'layout head script must toggle the .dark class (shadcn dark-mode signal)'); - assert.match(toggleSrc, /classList\.toggle\(['"]dark['"]/, - 'theme-toggle must toggle the .dark class (shadcn dark-mode signal)'); - assert.doesNotMatch(toggleSrc, /\sstyle="/, 'the toggle carries no inline style (its icons use SVG attributes)'); - assert.doesNotMatch(toggleSrc, /document\.(getElementById|querySelector)/, 'and no document query'); - // The head script only applies the theme before paint; following the OS is - // the toggle's job, on Lit's lifecycle (#1686). - assert.doesNotMatch(layoutSrc, /addEventListener/, 'the pre-paint script attaches no listener'); - assert.match(toggleSrc, /connectedCallback\(\) \{[\s\S]*?matchMedia\('\(prefers-color-scheme: dark\)'\)[\s\S]*?addEventListener\('change'/, 'the toggle follows the OS from connectedCallback'); - assert.match(toggleSrc, /disconnectedCallback\(\) \{[\s\S]*?removeEventListener\('change'/, 'and stops in disconnectedCallback'); - // The toggle is the UI kit's own Button (the AGENTS.md rule), which also - // gives it the pointer cursor Tailwind v4's reset takes from a button. - assert.match(toggleSrc, /import \{ buttonClass \} from '#components\/ui\/button\.ts'/, 'the toggle uses the kit Button'); - assert.match(toggleSrc, /class=\$\{buttonClass\(\{ variant: 'ghost', size: 'icon' \}\)\}/, 'as a ghost icon button'); - assert.match(readFileSync(join(appDir, 'components', 'ui', 'button.ts'), 'utf8'), /\bcursor-pointer\b/, 'whose classes carry the pointer cursor'); - assert.match(toggleSrc, /static properties = \{ theme: \{ state: true \} \};/, 'its theme is Lit reactive state'); + assert.match(layoutSrc, /classList\.toggle\(['"]dark['"], m\.matches\)/, + 'layout head script toggles the .dark class (shadcn dark-mode signal) from the OS'); + assert.match(layoutSrc, /matchMedia\('\(prefers-color-scheme: dark\)'\)/, 'following prefers-color-scheme'); + assert.doesNotMatch(layoutSrc, /theme-toggle|components\/ui/, 'the layout imports no component'); // The shell wears the webjs.dev/ui theme (shadcn's neutral palette and - // Geist), with a floating top navbar and a main that fills the viewport - // minus the navbar. - assert.match(layoutSrc, /<main class="min-h-\[calc\(100dvh-var\(--header-h\)\)\][^"]*">/, - 'layout main fills the viewport minus the navbar'); + // Geist), with a floating top navbar and a container that fills the + // viewport minus the navbar. The page renders its own <main>, as a + // create-next-app page does (#1697: agents nested one inside the layout's). + assert.match(layoutSrc, /<div class="min-h-\[calc\(100dvh-var\(--header-h\)\)\][^"]*">/, + 'layout container fills the viewport minus the navbar'); + assert.doesNotMatch(layoutSrc, /<main\b/, 'the layout leaves <main> to the page'); + assert.match(readFileSync(join(appDir, 'app', 'page.ts'), 'utf8'), /<main\b/, 'the home page renders its own <main>'); assert.match(layoutSrc, /<header\b/, 'the shell ships a floating top navbar'); // #1660: the navbar is sized by --header-h and nothing measures it, so a // client-router swap that replaces the header cannot zero the offset. @@ -218,26 +208,15 @@ test('scaffoldApp full-stack: writes the canonical full-stack app layout', async // The home page is a minimal starting point that imports nothing from a // gallery, and the navbar links the docs and the source. const pageSrc = readFileSync(join(appDir, 'app', 'page.ts'), 'utf8'); - // The home is a thin route over the example module (modules/users/). - assert.match(pageSrc, /from '#modules\/users\/actions\/add-user\.server\.ts'/, 'the home binds the example module\'s action'); - assert.match(pageSrc, /from '#modules\/users\/queries\/list-users\.server\.ts'/, 'and reads its query'); - assert.match(pageSrc, /<form action=\$\{addUser\}/, 'as a bound form'); - assert.match(pageSrc, /<user-list \.users=\$\{latest\}><\/user-list>/, 'and renders the users with the module\'s component'); - const listSrc = readFileSync(join(appDir, 'modules', 'users', 'components', 'user-list.ts'), 'utf8'); - assert.match(listSrc, /static properties = \{ users: \{ type: Array \} \};/, 'a Lit-style reactive property'); - assert.match(listSrc, /UserList\.register\('user-list'\)/, 'registered under its tag'); - assert.match(pageSrc, /<form action=\$\{clearUsers\}>/, 'and a Clear list button bound to its clear action'); - assert.match(readFileSync(join(appDir, 'modules', 'users', 'actions', 'clear-users.server.ts'), 'utf8'), /^'use server';/, 'which is a server action'); - // The example agents copy: only a duplicate is a field error, every other - // database error throws (no catch that relabels it). - const addSrc = readFileSync(join(appDir, 'modules', 'users', 'actions', 'add-user.server.ts'), 'utf8'); - assert.match(addSrc, /\.onConflictDoNothing\(\)\.returning\(\)/, 'a duplicate is detected by the insert itself'); - assert.doesNotMatch(addSrc, /catch\s*[{(]/, 'and no catch turns other errors into a duplicate message'); - assert.ok(existsSync(join(appDir, 'test', 'users', 'users.test.ts')), 'the module ships its own test'); + // #1697: no example module. modules/ is a placeholder; AGENTS.md carries + // the layout and the source guides the worked examples. + assert.doesNotMatch(pageSrc, /#modules\//, 'the home imports no module'); + assert.deepEqual(readdirSync(join(appDir, 'modules')), ['.gitkeep'], 'modules/ is an empty placeholder'); + assert.ok(!existsSync(join(appDir, 'test', 'users')), 'and no example test'); assert.match(pageSrc, /Edit app\/page\.ts/, 'the home points at the file to edit'); assert.match(layoutSrc, /webjs\.dev\/docs/, 'the navbar links the docs'); assert.match(layoutSrc, /github\.com\/webjsdev\/webjs/, 'the navbar links the source'); - assert.doesNotMatch(layoutSrc + toggleSrc, /#modules\//, 'the shell imports no demo module'); + assert.doesNotMatch(layoutSrc, /#modules\//, 'the shell imports no demo module'); // Drizzle db layer wired up assert.ok(existsSync(join(appDir, 'db', 'schema.server.ts')), 'db/schema.server.ts written'); @@ -506,6 +485,38 @@ test('scaffoldApp full-stack: writes the canonical full-stack app layout', async } }); +// #1697: an agent's first move on a fresh app is one `cat` of the source it +// will build on. Eval agents read 26 to 58K characters that way, went past the +// tool-output limit, and re-read file by file, after which the text sat in +// context for the rest of the run. Most of it was UI kit library code (cn(), +// the Button, Input and Label, the theme toggle) no agent needed to read, so +// the scaffold no longer ships it. +test('scaffoldApp full-stack: the source an agent reads first fits one tool call', async () => { + const cwd = await mkdtemp(join(tmpdir(), 'webjs-first-read-')); + try { + await scaffoldApp('first-read', cwd, { template: 'full-stack' }); + const appDir = join(cwd, 'first-read'); + const sizes = []; + const walk = (rel) => { + const abs = join(appDir, rel); + if (!existsSync(abs)) return; + if (statSync(abs).isDirectory()) { + for (const e of readdirSync(abs)) walk(join(rel, e)); + } else if (/\.(ts|js)$/.test(rel)) { + sizes.push([rel, statSync(abs).size]); + } + }; + for (const rel of ['app', 'db', 'modules', 'test/users', 'components', 'lib', 'drizzle.config.ts', 'instrumentation.ts']) walk(rel); + const total = sizes.reduce((n, [, s]) => n + s, 0); + const largest = sizes.sort((a, b) => b[1] - a[1]).slice(0, 3).map(([f, s]) => `${f} ${s}`).join(', '); + // The real tool-output limit is about 30K characters (round 9 builds + // overflowed at 31K and fit at 28K), so the read stays well under it. + assert.ok(total < 20_000, `the first-read source totals ${total} bytes, over 20 KB (largest: ${largest})`); + } finally { + await rm(cwd, { recursive: true, force: true }); + } +}); + test('scaffoldApp api: writes API-only template (no layout, no components)', async () => { const cwd = await tempCwd(); const restore = muteConsole(); @@ -860,7 +871,13 @@ test('scaffoldApp: AGENTS.md is the brief alone, the same for both templates', a await scaffoldApp('api-app', cwd, { template: 'api' }); const fs = readFileSync(join(cwd, 'fs-app', 'AGENTS.md'), 'utf8'); const api = readFileSync(join(cwd, 'api-app', 'AGENTS.md'), 'utf8'); - assert.equal(fs.replace('fs-app', 'X'), api.replace('api-app', 'X'), 'one AGENTS.md for both templates'); + // One AGENTS.md for both templates, save the line that names the api + // template's users module as an example to replace (#1697): the + // full-stack app ships no example module, so it has no such line. + const exampleLine = '`modules/users/` with `app/api/users/` is an example of that layout: replace it with the app\'s own features.\n'; + assert.ok(api.includes(exampleLine), 'the api AGENTS.md names its example module'); + assert.ok(!fs.includes('modules/users'), 'the full-stack AGENTS.md names none'); + assert.equal(fs.replace('fs-app', 'X'), api.replace('api-app', 'X').replace(exampleLine, ''), 'otherwise one AGENTS.md for both templates'); assert.doesNotMatch(fs, /\{\{[A-Z_]+\}\}/, 'no leftover placeholder'); assert.match(fs, /## The WebJs brief/, 'opens with the brief'); assert.match(fs, /node_modules\/@webjsdev\/\*/, 'points at the framework source'); @@ -869,7 +886,14 @@ test('scaffoldApp: AGENTS.md is the brief alone, the same for both templates', a assert.match(fs, /document\.getElementById/, 'naming the raw DOM calls to avoid'); assert.match(fs, /Style with Tailwind utilities on the kit's design tokens/, 'steers styling to Tailwind on the kit tokens'); assert.match(fs, /npx webjs ui init --preset/, 'and theming to a kit preset'); - assert.match(fs, /`modules\/users\/` is an example of that shape: read it, then\ndelete it, its test and whatever uses it before you build the app\./, 'tells the agent to delete the example module before building'); + // #1697: the module layout itself, every folder a module holds, since the + // scaffold no longer ships an example module to copy. + for (const dir of ['actions', 'queries', 'components', 'utils']) { + assert.match(fs, new RegExp(`modules/<feature>/${dir}/`), `names the module's ${dir}/ folder`); + } + assert.match(fs, /modules\/<feature>\/types\.ts/, 'and its types.ts'); + assert.match(fs, /`npx webjs source modules` prints a worked module/, 'and where the worked example is'); + assert.doesNotMatch(fs, /modules\/users/, 'and names no example module'); assert.match(fs, /\n## This app\n\nReplace this paragraph with what /, 'ends with a This app section the agent fills in'); assert.match(fs, /`CLAUDE\.md` imports this file, so notes go here\./, 'which says app notes live in AGENTS.md, not CLAUDE.md'); // The brief plus the scaffold's rules plus the This app stub: still short, @@ -879,7 +903,9 @@ test('scaffoldApp: AGENTS.md is the brief alone, the same for both templates', a // the file says it: check-on-edit, the refusals, and the soft flags. assert.match(fs, /Hooks, so you need not open them: each edit returns that file's `webjs check` and type/, 'summarises the shipped hooks'); assert.match(fs, /`extends HTMLElement`, an em-dash/, 'naming what they refuse'); - assert.ok(fs.split('\n').length < 70, `AGENTS.md stays short (${fs.split('\n').length} lines)`); + // 75 since #1697: the module layout's eight lines replaced the example + // module (about 5 KB of code an agent read on its first look). + assert.ok(fs.split('\n').length < 75, `AGENTS.md stays short (${fs.split('\n').length} lines)`); for (const dir of ['fs-app', 'api-app']) { assert.ok(!existsSync(join(cwd, dir, '.agents')), `${dir}: no .agents rules or skills`); } diff --git a/test/scaffolds/scaffold-ui-integration.test.js b/test/scaffolds/scaffold-ui-integration.test.js index 7e09d6a70..21857347c 100644 --- a/test/scaffolds/scaffold-ui-integration.test.js +++ b/test/scaffolds/scaffold-ui-integration.test.js @@ -31,18 +31,16 @@ test('full-stack scaffold pre-initialises the Webjs UI kit', async () => { await scaffoldApp('demo', cwd, { template: 'full-stack' }); const appDir = join(cwd, 'demo'); - // Bootstrap for `webjs ui add`: the config + cn() helper + theme ship, so an - // app can add components on demand. No component ships until it is added. + // Bootstrap for `webjs ui add`: the config + theme ship, so an app can add + // components on demand. No kit code ships until it is added (#1697): the + // first add writes cn() as a registry dependency. assert.ok(await exists(join(appDir, 'components.json')), 'components.json should exist'); - assert.ok(await exists(join(appDir, 'lib', 'utils', 'cn.ts')), 'lib/utils/cn.ts should exist'); + assert.equal(existsSync(join(appDir, 'lib', 'utils', 'cn.ts')), false, 'lib/utils/cn.ts is not pre-written'); assert.ok(await exists(join(appDir, 'styles', 'globals.css')), 'styles/globals.css should exist'); assert.equal(existsSync(join(appDir, 'app', 'globals.css')), false, 'globals.css must not be in routing-only app/'); - // The kit's Button, which the theme toggle uses, and nothing else. - // The kit components the shell uses (the toggle's Button, the home form's - // Input and Label), and nothing else. - assert.deepEqual(readdirSync(join(appDir, 'components', 'ui')).sort(), ['button.ts', 'input.ts', 'label.ts'], 'components/ui holds the kit components the shell uses'); + assert.equal(existsSync(join(appDir, 'components', 'ui')), false, 'no kit component is pre-installed'); // One example module, the modules/<feature>/ convention AGENTS.md names. - assert.deepEqual(readdirSync(join(appDir, 'modules')), ['users'], 'modules/ ships the one example module'); + assert.deepEqual(readdirSync(join(appDir, 'modules')), ['.gitkeep'], 'modules/ is an empty placeholder (#1697)'); // The scaffold and `webjsui init` must emit the SAME components.json, so // that initialising a bare app and scaffolding a new one land on one @@ -149,10 +147,13 @@ test('api scaffold route imports resolve to real modules/ files', async () => { } }); -test('lib/utils/cn.ts ships the pure cn() helper; onBeforeCache is in lib/utils/dom.ts (#819)', async () => { +test('the first ui add writes the pure cn() helper, and onBeforeCache in lib/utils/dom.ts (#819, #1697)', async () => { const cwd = await tempCwd(); try { await scaffoldApp('demo', cwd, { template: 'full-stack' }); + // The scaffold pre-writes neither; the kit installs them as registry + // dependencies of the first component that needs them. + await add.parseAsync(['dialog', '--cwd', join(cwd, 'demo'), '--yes', '--no-deps'], { from: 'user' }); const utils = await readFile(join(cwd, 'demo', 'lib', 'utils', 'cn.ts'), 'utf8'); assert.match(utils, /export function cn/); assert.match(utils, /ClassValue/); @@ -225,25 +226,19 @@ function tsFiles(dir) { e.isDirectory() ? tsFiles(join(dir, e.name)) : e.name.endsWith('.ts') ? [join(dir, e.name)] : []); } -test('webjs ui add --overwrite in a fresh app keeps the shell working', async () => { - // A fresh app's `add dialog` pulls the kit's card, input, button and badge - // into components/ui/, overwriting the Button the theme toggle uses. The - // shell imports only the kit's public helper (buttonClass), so it keeps - // resolving; nothing else in the shell imports from components/ui/. +test('the scaffold shell imports no kit component, so any ui add leaves it working', async () => { + // #1697: the shell (the layout and the home page) uses plain Tailwind on the + // kit's tokens, so an `add --overwrite` of any component cannot break it. const cwd = await tempCwd(); try { await scaffoldApp('demo', cwd, { template: 'full-stack' }); const appDir = join(cwd, 'demo'); - const shell = [...tsFiles(join(appDir, 'app')), ...tsFiles(join(appDir, 'components'))]; + const shell = tsFiles(join(appDir, 'app')); await add.parseAsync(['dialog', 'card', 'input', 'button', 'badge', '--cwd', appDir, '--overwrite', '--yes', '--no-deps'], { from: 'user' }); assert.ok(existsSync(join(appDir, 'components', 'ui', 'card.ts')), 'the kit card landed where add writes'); + assert.ok(existsSync(join(appDir, 'lib', 'utils', 'cn.ts')), 'and cn() came with it'); for (const file of shell) { - const src = await readFile(file, 'utf8'); - for (const m of src.matchAll(/from '#components\/ui\/([\w-]+)\.ts'/g)) { - const helper = { button: 'buttonClass', input: 'inputClass', label: 'labelClass' }[m[1]]; - assert.ok(helper, `${file} imports only the kit components the scaffold installs (got ${m[1]})`); - assert.match(await readFile(join(appDir, 'components', 'ui', `${m[1]}.ts`), 'utf8'), new RegExp(`export function ${helper}\\(`), `${m[1]}.ts still exports ${helper} after the overwrite`); - } + assert.doesNotMatch(await readFile(file, 'utf8'), /#components\/ui\//, `${file} imports no kit component`); } } finally { await rm(cwd, { recursive: true, force: true }); diff --git a/website/app/(site)/docs/ai-first/page.ts b/website/app/(site)/docs/ai-first/page.ts index c00e3aa95..a1f70f994 100644 --- a/website/app/(site)/docs/ai-first/page.ts +++ b/website/app/(site)/docs/ai-first/page.ts @@ -23,7 +23,7 @@ export default function AIFirst() { <h3>1. AGENTS.md: The Machine-Readable Contract</h3> <p>Every WebJs app has an <code>AGENTS.md</code> at the root, and it is short on purpose. WebJs follows Next.js App Router routing and Lit's component APIs, so an agent's existing habits already write most of an app correctly. The file holds only what differs:</p> <ul> - <li><strong>The WebJs brief</strong>: the handful of places WebJs departs from Next.js and Lit (light DOM by default, erasable TypeScript, server code in <code>*.server.ts</code>, imports from <code>@webjsdev/*</code>), and the instruction to run <code>webjs check</code> and <code>webjs status</code> after each edit.</li> + <li><strong>The WebJs brief</strong>: the handful of places WebJs departs from Next.js and Lit (light DOM by default, erasable TypeScript, server code in <code>*.server.ts</code>, imports from <code>@webjsdev/*</code>), the instruction to run <code>webjs check</code> after each edit, and <code>webjs verify</code> to check, typecheck, test and boot every route in one call.</li> <li><strong>A build checklist</strong> for the template the app was created from.</li> <li><strong>Types and data</strong>: derive every type from its source, and keep data in the database.</li> </ul> diff --git a/website/app/(site)/docs/conventions/page.ts b/website/app/(site)/docs/conventions/page.ts index 349499e3a..e813b6e96 100644 --- a/website/app/(site)/docs/conventions/page.ts +++ b/website/app/(site)/docs/conventions/page.ts @@ -149,8 +149,8 @@ cd my-app && npm run dev</code-block> <p>This generates:</p> <ul> <li><code>app/</code> with root layout + page</li> - <li><code>modules/users/</code>, one example feature module (a <code>'use server'</code> action in <code>actions/</code>, a query in <code>queries/</code>, a component in <code>components/</code>, <code>types.ts</code>) that the home page uses, to copy for your own features and then delete</li> - <li><code>components/</code> with a theme toggle component and the UI kit's Button, Input and Label in <code>components/ui/</code></li> + <li><code>modules/</code>, empty: each feature goes in <code>modules/<feature>/</code> with its <code>'use server'</code> actions in <code>actions/</code>, server-only reads in <code>queries/</code>, components in <code>components/</code>, pure helpers in <code>utils/</code> and <code>types.ts</code>, the layout <code>AGENTS.md</code> describes and <code>npx webjs source modules</code> shows worked</li> + <li><code>components.json</code> and <code>styles/globals.css</code>, the UI kit's config and theme, with no kit component pre-installed: <code>npx webjs ui add <name></code> copies one (and its <code>cn()</code> helper) into the app when you need it</li> <li><code>db/schema.server.ts</code>: the Drizzle schema, SQLite by default, example <code>User</code> model. <code>db/connection.server.ts</code> exports the <code>db</code> connection.</li> <li><code>test/<feature>/</code> with example tests, and <code>browser/</code> and <code>e2e/</code> subfolders</li> <li><code>AGENTS.md</code>: the WebJs brief (what differs from Next.js routing and Lit components), a few scaffold rules, and a "This app" section the agent fills in and keeps current as it builds</li> diff --git a/website/app/(site)/docs/deployment/page.ts b/website/app/(site)/docs/deployment/page.ts index 89a8efa9c..7a75f32f4 100644 --- a/website/app/(site)/docs/deployment/page.ts +++ b/website/app/(site)/docs/deployment/page.ts @@ -199,7 +199,7 @@ const app = await createRequestHandler({ });</code-block> <p><strong>The contract is best-effort.</strong> A throwing <code>onError</code> is caught and ignored so it can never crash the response, and the hook is purely additive: webjs's existing behavior (the sanitized 500, with only <code>error.message</code> in prod and never the stack) is unchanged. The hook fires BEFORE the sanitized response is sent, so the sink always sees the real error.</p> - <p>To register the sink from the app rather than the server entry, call <code>setOnError(fn)</code> from <code>@webjsdev/server</code> inside the <code>register()</code> export of an app-root <code>instrumentation.ts</code>, which runs once at boot. The scaffold ships that file with the call in place.</p> + <p>To register the sink from the app rather than the server entry, call <code>setOnError(fn)</code> from <code>@webjsdev/server</code> inside the <code>register()</code> export of an app-root <code>instrumentation.ts</code>, which runs once at boot. Create that file when the app needs it; the scaffold does not ship one.</p> <p><strong>Two framework diagnostics ride the same hook</strong>, and neither is a request failure, so both carry an <code>err.code</code> you can group or filter on. <code>WEBJS_FORM_SUBMITTED_AS_GET</code> fires on a page GET carrying the reserved <code>__webjs_action</code> field in its query string, which means a submission holding a bound action's identity went out as a GET, so the action never ran and the page still rendered a 200. A bound submitter carries its own <code>formmethod="post"</code>, so what reaches this is an explicit <code>formmethod="get"</code> or <code>method="get"</code> the author wrote and the renderer deliberately honours rather than refuses. It is the production counterpart to the dev-time console error the client router logs at submit time. <code>WEBJS_FORM_ACTION_MISSING</code> fires when a parseable form body carries no identity at all, the case answered with a 405. (An <code>enctype="text/plain"</code> submission is answered before its body is read, so that one stays a bare 405.) Both are detect-only, so neither changes the status; each carries <code>method</code> and <code>pathname</code>, plus the submitted field NAMES for the second (template constants that identify WHICH form posted nowhere, never the values, which are user data); and each is deduplicated per process on the code, the method, and the matched ROUTE (not the request pathname, so crafted urls on a dynamic route cannot exhaust the 256-entry cap and silence the diagnostics), because both are reachable by an unauthenticated request and an uncapped report would be a free amplifier into a paid sink. In dev the same two detections also log a warning, which is what makes the no-JS write path visible without an APM wired. See <a href="/docs/troubleshooting">Troubleshooting</a>.</p> diff --git a/website/app/(site)/docs/error-handling/page.ts b/website/app/(site)/docs/error-handling/page.ts index 794e1cf49..4b0033c0f 100644 --- a/website/app/(site)/docs/error-handling/page.ts +++ b/website/app/(site)/docs/error-handling/page.ts @@ -102,7 +102,7 @@ export default async function AdminPage() { return html${'`'}...${'`'}; }</code-block> - <p>Inside a <code>'use server'</code> RPC action (one a client component calls), return a <code>{ success: false, error, status }</code> <code>ActionResult</code> for an auth failure rather than throwing <code>forbidden()</code> / <code>unauthorized()</code>. The boundary render is a page-routing concern, the same guidance as for <code>notFound()</code> / <code>redirect()</code>.</p> + <p>Inside a <code>'use server'</code> action a client component calls, a thrown <code>notFound()</code>, <code>forbidden()</code> or <code>unauthorized()</code> answers the same 404, 403 or 401 the no-JS form path renders, and the call rejects with that sentinel, so the caller tests it with <code>isForbidden(err)</code> (and <code>invokeActionForTest</code> rejects the same way). It is never logged as an error. When the component should show a message instead, return a <code>{ success: false, error, status }</code> <code>ActionResult</code>.</p> <h2>global-error.ts and global-not-found.ts</h2> <p>Two root-only boundaries (in <code>app/</code> exactly). <code>global-error.ts</code> is the app-wide catch-all, tried after the nested <code>error.ts</code> boundaries are exhausted, and it renders its OWN full document (a root-layout failure is when it fires):</p> @@ -149,7 +149,7 @@ export default function GlobalError({ error }: { error: Error }) { <p>Tearing content back out is covered too, and it has to be, because a teardown has no next render to repair it. Unbinding a <code>ref</code> while a row is removed can never abort the removal of the rest of the list, and <code>repeat()</code> drops each leftover key from its map before touching that row, so the map never describes a row that has already been removed. Without that, a throw part-way through left the row you had DELETED on screen, reordered the survivors, and let a later render that re-added the key reinsert the disposed instance. The cost is that a <code>ref</code> whose object <code>value</code> setter throws is swallowed on teardown, matching the ref callback, which was already swallowed everywhere (lit guards neither and propagates from both, so this is a deliberate divergence). It applies to teardown only: on the COMMIT path a throwing object-ref setter still reaches <code>renderError()</code>. Covered also means a removal takes the row's own boundary markers with it, so a list that grows and shrinks all day is net zero on the nodes the renderer added, rather than accruing one invisible comment per removed row for the life of the region.</p> <h2>Server action errors</h2> - <p>Errors thrown from server actions are sanitized in production: the client gets a generic <code>"Internal server error"</code> message plus a short <code>digest</code>, never the raw thrown message or the stack trace. The full error is logged server-side keyed by that digest, so a client-reported digest maps back to the server log line. A <code>redirect()</code> / <code>notFound()</code> control-flow throw passes through. To surface a specific user-facing message, return an <code>ActionResult</code> <code>{ success: false, error }</code> envelope instead of throwing.</p> + <p>Errors thrown from server actions are sanitized in production: the client gets a generic <code>"Internal server error"</code> message plus a short <code>digest</code>, never the raw thrown message or the stack trace. The full error is logged server-side keyed by that digest, so a client-reported digest maps back to the server log line. A <code>redirect()</code>, <code>notFound()</code>, <code>forbidden()</code> or <code>unauthorized()</code> throw passes through with its own status. To surface a specific user-facing message, return an <code>ActionResult</code> <code>{ success: false, error }</code> envelope instead of throwing.</p> <h2 id="on-request-error">Reporting errors with onRequestError</h2> <p>An app-root <code>instrumentation.ts</code> may export Next.js's <code>onRequestError</code>. The server calls it for every error a request hits on the server: a page or layout render, a metadata route, a <code>route.ts</code> handler, a server action, or middleware. It receives the same three arguments Next passes, so an existing Sentry or OpenTelemetry reporter works unchanged.</p> diff --git a/website/app/(site)/docs/getting-started/page.ts b/website/app/(site)/docs/getting-started/page.ts index 88bd0a264..4e73d5eed 100644 --- a/website/app/(site)/docs/getting-started/page.ts +++ b/website/app/(site)/docs/getting-started/page.ts @@ -34,11 +34,11 @@ webjs create my-api --template api</code-block> <p><strong>Naming the app.</strong> The name you pass becomes three things at once: the new directory, the <code>name</code> field of the generated <code>package.json</code>, and a value the scaffold writes into generated source (the home page's <code>metadata.title</code>, for one). So it has to be a valid package name: letters, digits, and the separators <code>-</code>, <code>.</code> and <code>_</code>, starting with a letter or a digit, at most 214 characters, and not <code>node_modules</code> or <code>favicon.ico</code>, which npm reserves. Anything else is refused before a single file is written, with a message naming the offending character, so <code>webjs create "my app"</code> is an error while <code>webjs create my-app</code> and <code>webjs create MyApp</code> both work.</p> - <p><strong>For AI agents:</strong> only those two templates exist, and the CLI rejects any other <code>--template</code> value. Default to full-stack with Drizzle + SQLite for any product app (todo, blog, dashboard, marketplace, social, e-commerce, a SaaS with accounts…). Pick <code>--template api</code> only if the user explicitly asks for a backend-only API with no UI. The scaffold is a starting point. Its one example feature (<code>modules/users/</code>, <code>test/users/</code> and the home page's form) shows the module shape: read it, then delete it and replace the example page and <code>User</code> model with the app the user actually asked for. Use Drizzle for any persisted data, never JSON files, in-memory arrays, or localStorage. When AGENTS.md doesn't cover what you need, the full hosted docs are at <a href="/docs">the rest of these docs</a>.</p> + <p><strong>For AI agents:</strong> only those two templates exist, and the CLI rejects any other <code>--template</code> value. Default to full-stack with Drizzle + SQLite for any product app (todo, blog, dashboard, marketplace, social, e-commerce, a SaaS with accounts…). Pick <code>--template api</code> only if the user explicitly asks for a backend-only API with no UI. The scaffold is a starting point: put each feature in <code>modules/<feature>/</code> (its <code>actions/</code>, <code>queries/</code>, <code>components/</code>, <code>utils/</code> and <code>types.ts</code>), which <code>AGENTS.md</code> lays out and <code>npx webjs source modules</code> shows worked, and replace the example page and <code>User</code> model with the app the user actually asked for. <code>npx webjs verify</code> then checks, typechecks, tests and boots every route in one call. Use Drizzle for any persisted data, never JSON files, in-memory arrays, or localStorage. When AGENTS.md doesn't cover what you need, the full hosted docs are at <a href="/docs">the rest of these docs</a>.</p> <p>The <code>--template api</code> scaffold generates thin route handlers that wrap typed server actions. Business logic lives in <code>modules/</code>. Routes just import and call the action/query, giving you file-based routing for URL structure plus type-safe server actions for logic.</p> - <p><strong>The scaffold is minimal, grown in place.</strong> The full-stack app ships a root layout with a neutral palette, a starting home page, a theme toggle, the database wiring, and one starter test; the api app ships the health and users endpoints over typed server actions. The framework context an agent needs is a short brief in <code>AGENTS.md</code>: WebJs follows Next.js App Router routing and Lit's component APIs, so the brief lists only what differs, and <code>webjs check</code> refuses the rest with the fix in the message. Build the app the user asked for on top of the scaffold, editing the home page, layout, and schema in place.</p> + <p><strong>The scaffold is minimal, grown in place.</strong> The full-stack app ships a root layout with a neutral palette, a starting home page, dark mode that follows the OS, the database wiring, and one starter test, with the UI kit configured but no kit code installed until you add a component; the api app ships the health and users endpoints over typed server actions. The framework context an agent needs is a short brief in <code>AGENTS.md</code>: WebJs follows Next.js App Router routing and Lit's component APIs, so the brief lists only what differs, and <code>webjs check</code> refuses the rest with the fix in the message. Build the app the user asked for on top of the scaffold, editing the home page, layout, and schema in place.</p> <p><strong>Runnable demos live in the gallery.</strong> Every feature (auth with a protected route, server actions, streaming, the client router, WebSockets, file storage and more) has a single-concept demo at <a href="https://gallery.webjs.dev">gallery.webjs.dev</a>, with its source in the repository's <code>gallery/</code> app. Copy from it when a demo matches what you are building; nothing from it ships in a new app.</p> diff --git a/website/app/(site)/docs/server-actions/page.ts b/website/app/(site)/docs/server-actions/page.ts index e0422e851..dcc5363fd 100644 --- a/website/app/(site)/docs/server-actions/page.ts +++ b/website/app/(site)/docs/server-actions/page.ts @@ -364,7 +364,7 @@ export async function createPost(input: { title: string }) { <p>When a server action throws (rather than returning an error envelope), WebJs catches the exception and returns a JSON error response:</p> <ul> <li><strong>Development:</strong> the response includes both the error message and the full stack trace, making debugging easy.</li> - <li><strong>Production:</strong> the client gets a generic <code>"Internal server error"</code> message plus a short <code>digest</code>, never the raw thrown message (a DB-driver message, an internal IP, or a file path is not author-controlled) and never the stack. The full error is logged server-side keyed by the same digest, so a client report maps to the server log. A <code>redirect()</code> / <code>notFound()</code> control-flow throw passes through. To show the user a specific message, return an <code>ActionResult</code> <code>{ success: false, error }</code> envelope instead of throwing.</li> + <li><strong>Production:</strong> the client gets a generic <code>"Internal server error"</code> message plus a short <code>digest</code>, never the raw thrown message (a DB-driver message, an internal IP, or a file path is not author-controlled) and never the stack. The full error is logged server-side keyed by the same digest, so a client report maps to the server log. A <code>redirect()</code>, <code>notFound()</code>, <code>forbidden()</code> or <code>unauthorized()</code> throw passes through with its own status (404, 403 or 401 for the last three, as on the no-JS form path). To show the user a specific message, return an <code>ActionResult</code> <code>{ success: false, error }</code> envelope instead of throwing.</li> </ul> <p>This prevents accidental leakage of file paths, database schemas, or other implementation details to end users.</p> diff --git a/website/app/(site)/docs/testing/page.ts b/website/app/(site)/docs/testing/page.ts index d32e1ee60..1726d9b4b 100644 --- a/website/app/(site)/docs/testing/page.ts +++ b/website/app/(site)/docs/testing/page.ts @@ -23,7 +23,7 @@ test('listPosts returns an array', async () => { const posts = await listPosts(); assert.ok(Array.isArray(posts)); });</code-block> - <p><strong>Server tests get their own database.</strong> For a SQLite app, <code>webjs test</code> creates a temporary database, applies the app's migrations to it with <code>webjs db migrate</code> (or, before the first migration exists, pushes the schema with <code>webjs db push</code>, as Rails loads its schema file), and runs the server tests with <code>DATABASE_URL</code> pointing there, the way Rails prepares a test database. So a test can import the app's <code>db</code> and write to it without touching <code>db/dev.db</code>, and every run starts empty (insert what a test needs; the seed file is not applied). A <code>DATABASE_URL</code> set in the shell is used as is (CI, or a Postgres test database), and <code>WEBJS_TEST_DB=0</code> turns it off.</p> + <p><strong>Server tests get their own database.</strong> For a SQLite app, <code>webjs test</code> creates a temporary database, applies the app's migrations to it with <code>webjs db migrate</code> (or, before the first migration exists, pushes the schema with <code>webjs db push</code>, as Rails loads its schema file), and runs the server tests with <code>DATABASE_URL</code> pointing there, the way Rails prepares a test database. So a test can import the app's <code>db</code> and write to it without touching <code>db/dev.db</code>, and every run starts empty (insert what a test needs; the seed file is not applied). On Node each test file runs in a process of its own with its own copy of that database, as Rails gives each parallel worker one, so two files writing at once never see each other's rows or a <code>database is locked</code> error. A <code>DATABASE_URL</code> set in the shell is used as is (CI, or a Postgres test database), and <code>WEBJS_TEST_DB=0</code> turns it off.</p> <h2>Renderer Tests</h2> <p>Test <code>renderToString</code> for SSR output. Import it from <code>@webjsdev/core/server</code>, not the root, so your test stays explicit about which side it runs on:</p> @@ -116,7 +116,7 @@ assert.match(await res.text(), /About/);</code-block> <p>A bare path (<code>/about</code>) is prefixed with a dummy origin (the pipeline only reads <code>pathname</code> + <code>search</code>). A full URL string or a pre-built <code>Request</code> works too. The optional third arg is a standard <code>RequestInit</code> (method, headers, body).</p> <h3>submitForm: the no-JS write path</h3> - <p>A form that binds an action (<code><form action=\${myAction}></code>) carries a hidden <code>__webjs_action</code> field naming the action, so a hand-written <code>POST</code> without it is answered <strong>405</strong>. <code>submitForm(app.handle, '/signup', fields)</code> renders the page, reuses the identity the server put there, and posts it back, exactly as a browser with JS off does: a success answers 303, a failure re-renders the same page at 422 with the result on <code>actionData</code>. Options: <code>cookies</code>, <code>match</code> or <code>index</code> (pick one of several forms; without <code>match</code> it chooses among the forms bound to an action, so a layout's plain logout or search form is skipped, and when several bound forms remain it posts the one whose inputs hold every submitted field, refusing with a list of the forms when the fields fit none or more than one), <code>submitPath</code>, <code>headers</code>, and <code>html</code>. Pass <code>html</code>, the page's HTML the test fetched earlier, to submit a form the page no longer renders, the way a tab left open still can: a vote on a poll closed since the page loaded is <code>submitForm(app.handle, '/p/1', fields, { html })</code>, where a fresh render would find no form. A <code>File</code> or <code>Blob</code> field value posts the form multipart, as a file input does, so an upload action can be tested the same way. A test may also import the action module at the top of the file to call an action directly: the form on the page still binds to it, even though the module loaded before the handler existed.</p> + <p>A form that binds an action (<code><form action=\${myAction}></code>) carries a hidden <code>__webjs_action</code> field naming the action, so a hand-written <code>POST</code> without it is answered <strong>405</strong>. <code>submitForm(app.handle, '/signup', fields)</code> renders the page, reuses the identity the server put there, and posts it back, exactly as a browser with JS off does: a success answers 303, a failure re-renders the same page at 422 with the result on <code>actionData</code>. Options: <code>cookies</code>, <code>match</code> or <code>index</code> (pick one of several forms; without <code>match</code> it chooses among the forms bound to an action, so a layout's plain logout or search form is skipped, and when several bound forms remain it posts the one whose inputs hold every submitted field, refusing with a list of the forms when the fields fit none or more than one, and refusing when the only bound form has no fields at all while the test submits some, which is a layout's logout button on a page that did not render the form the test means), <code>submitPath</code>, <code>headers</code>, and <code>html</code>. Pass <code>html</code>, the page's HTML the test fetched earlier, to submit a form the page no longer renders, the way a tab left open still can: a vote on a poll closed since the page loaded is <code>submitForm(app.handle, '/p/1', fields, { html })</code>, where a fresh render would find no form. A <code>File</code> or <code>Blob</code> field value posts the form multipart, as a file input does, so an upload action can be tested the same way. A test may also import the action module at the top of the file to call an action directly: the form on the page still binds to it, even though the module loaded before the handler existed.</p> <p>For a browser test that drives the app in a real DOM, <code>createBrowserTestHandler(appDir)</code> from <code>@webjsdev/server/testing</code> exposes the same <code>handle()</code> pipeline to the WTR Chromium session.</p> <h3>The auth/session helpers</h3> diff --git a/website/app/(site)/docs/troubleshooting/page.ts b/website/app/(site)/docs/troubleshooting/page.ts index 7dc101f24..7ae575fa1 100644 --- a/website/app/(site)/docs/troubleshooting/page.ts +++ b/website/app/(site)/docs/troubleshooting/page.ts @@ -83,6 +83,7 @@ export default function Troubleshooting() { <p><strong>Symptom:</strong> submitting a form returns <code>405 Method Not Allowed</code> with <code>Allow: GET, HEAD</code>, and the page itself renders fine on a GET.</p> <p><strong>Cause:</strong> the form binds no action. A page has no <code>action</code> export, so a bare <code><form method="post"></code> has nothing to run: the url exists and only renders, which is what the 405 says. The other way to get one is binding an action whose file declares <code>export const method = 'GET'</code>; a GET action rides its arguments in the url and skips the CSRF check, so it cannot answer a form POST. That case answers <code>Allow: GET</code>, and <code>webjs check</code>'s <code>form-action-not-a-get-action</code> rule catches it before it ships.</p> <p><strong>Fix:</strong> bind the action (<code><form action=\${submitFeedback}></code>), or drop the <code>method</code> export from the action's file so it is an ordinary POST.</p> + <p>Posting by hand (<code>curl</code>, a script) to a page whose form IS bound answers the same 405 when the request leaves out the form's hidden <code>__webjs_action</code> field, and in development the response body says so (production answers the bare status). Copy that field's value from the rendered form and send it with the others, or in a test use <code>submitForm()</code>, which reads it from the page for you.</p> <h2 id="a-button-submits-and-the-page-just-re-renders">A button submits and the page just re-renders</h2> <p><strong>Symptom:</strong> clicking a <code>formaction=\${action}</code> button reloads the same page with a 200, nothing was written, no error appears anywhere, and the address bar has grown a <code>?__webjs_action=</code> parameter.</p>