@webjsdev/cli 0.10.12 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,404 +0,0 @@
1
- # AGENTS.md for webjs
2
-
3
- This file is the contract for **AI agents** (and humans) editing a webjs app.
4
- It describes file conventions, the public API, invariants to preserve, and
5
- recipes for common tasks. Keep it in sync whenever behaviour changes.
6
-
7
- **Detail docs**, loaded when relevant. They don't auto-load. This file stays
8
- lean on purpose; anything marked "see `agent-docs/<x>.md`" has the full
9
- reference there.
10
-
11
- | File | Topic |
12
- |---|---|
13
- | `agent-docs/metadata.md` | Full `metadata` / `generateMetadata` field reference |
14
- | `agent-docs/components.md` | WebComponent deep-dive (controllers, hooks, light/shadow DOM, slots) |
15
- | `agent-docs/styling.md` | Tailwind helpers + vanilla-CSS opt-out conventions |
16
- | `agent-docs/built-ins.md` | Auth, sessions, env vars, caching (cache(), HTTP cache, asset-hash, conditional GET), rate-limit, broadcast, file storage |
17
- | `agent-docs/configuration.md` | The `package.json` `"webjs"` block (security headers, CSP, redirects, trailing-slash, basePath, ingress caps) + observability |
18
- | `agent-docs/advanced.md` | Suspense streaming, performance, bundling, client router (prefetch, frames, view transitions, stream actions), WebSockets |
19
- | `agent-docs/typescript.md` | TS at runtime + full-stack type safety |
20
- | `agent-docs/deployment.md` | Production, runtime targets, embedded use |
21
- | `agent-docs/service-worker.md` | The opt-in progressive-enhancement service worker (`public/sw.js`) |
22
- | `agent-docs/testing.md` | Unit, browser, convention validation, the `handle()` test harness (`@webjsdev/server/testing`) |
23
- | `agent-docs/framework-dev.md` | Monorepo dev (only when editing webjs itself): commands, repo-health git config, changelog flow, dev error overlay |
24
- | `agent-docs/recipes.md` | Page / route / action / component recipes |
25
- | `agent-docs/lit-muscle-memory-gotchas.md` | **READ FIRST** when writing components. Lit patterns that break webjs SSR or reactivity, with the webjs-shaped fix for each |
26
-
27
- ---
28
-
29
- ## AI-driven development: guardrails for all agents
30
-
31
- **webjs is AI-first. These rules apply to ALL agents (Claude, Cursor, Copilot, Antigravity, Aider), enforced via per-agent config the scaffold ships** (`AGENTS.md` + `CONVENTIONS.md` + `CLAUDE.md`, `.claude/settings.json` hooks, `.cursorrules`, `.agents/rules/workflow.md`, `.github/copilot-instructions.md`, a PR template, `.editorconfig`), all carrying the same rules in each agent's format.
32
-
33
- ### Before starting ANY work: verify and sync the branch
34
-
35
- 1. `git branch --show-current`. If on `main` / `master`, **STOP** and `git checkout -b feature/<task-slug>`.
36
- 2. Verify the branch matches the task. Don't mix unrelated work.
37
- 3. Sync with parent: `git fetch origin && git log HEAD..origin/main --oneline`. If there are upstream commits, `git rebase origin/main` first.
38
-
39
- Claude Code enforces step 1 via `.claude/hooks/guard-branch-context.sh`. Other agents check manually.
40
-
41
- ### Skills are routed deterministically, never skipped
42
-
43
- A Skill is model-invoked, so it fires only when the model judges a match. The `.claude/hooks/route-skills.sh` `UserPromptSubmit` hook makes routing deterministic: it keyword-matches each prompt against every skill's documented triggers and injects a directive to invoke the matched skill before other work. Check the available skills and invoke a matching one before starting. Tests in `test/hooks/route-skills.test.mjs`.
44
-
45
- ### Autonomous mode (sandbox / bypass permissions)
46
-
47
- When interactive approval is disabled, never block on questions. Auto-decide: on `main`, auto-create `feature/<task-slug>`; auto-rebase if the parent moved; auto-merge when ready; **delete** feature/fix branches after merge but **keep** long-lived ones (dev, staging, release/*); auto-generate meaningful commit messages; fix failing tests / convention violations rather than asking. Autonomous mode is MORE disciplined, not less, with the same quality bar.
48
-
49
- ### Code workflow (mandatory)
50
-
51
- Every code change MUST include, automatically:
52
-
53
- 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). `npm test` does NOT run browser or e2e; run them yourself and report the result. Never report work done with failing or missing tests. See `agent-docs/testing.md`. Enforced by `.claude/hooks/require-tests-with-src.sh` (the scaffold variant WARNS unless `WEBJS_TEST_GATE=block`).
54
- 2. **Documentation.** Update `AGENTS.md` for new API surface, `CONVENTIONS.md` for new conventions, `docs/` or `website/` for user-facing features.
55
- 3. **Convention validation.** Run `webjs check` and fix violations.
56
-
57
- ### Git workflow (mandatory)
58
-
59
- Always work on a feature branch; commit + push freely there. The only gate is merging into main (needs user approval unless in bypass mode).
60
-
61
- 1. **Feature branch first;** never edit on main; never push to main.
62
- 2. **Commit per logical unit** (one feature, fix, rename, doc rewrite) as soon as it is complete and tests pass (`webjs test`); 5+ unstaged files across concerns means you waited too long. Push after each commit.
63
- 3. **Meaningful commit messages** (imperative, under 72 chars, body explains *why*). **No AI attribution** (no `Co-Authored-By: Claude`, `Generated by AI`).
64
- 4. **PRs via `gh`, always.** "merge to main" is ALWAYS `gh pr create`, confirm, `gh pr merge`, never a local `git merge` + push.
65
- 5. **Never merge without permission.** Ask exactly "Ready to merge `<branch>` into `<target>`? After merging, should `<branch>` be deleted or kept?" and wait for both answers.
66
-
67
- ---
68
-
69
- ## Working in the webjs framework repo itself
70
-
71
- When editing the framework monorepo (this repo, not a scaffolded app): **`packages/` is plain `.js` with JSDoc. Never add `.ts` files there** (the framework ships buildless). TypeScript is fine in `examples/`, `docs/`, `website/`.
72
-
73
- See `agent-docs/framework-dev.md` for monorepo commands, workspace layout, per-feature update checklists, the worktree-safe git config, the per-package auto-generated changelog flow, and the dev error overlay.
74
-
75
- ---
76
-
77
- ## What webjs is
78
-
79
- An **AI-first, web-components-first** framework inspired by NextJs, Lit, and Rails. The component runtime API matches lit (reactive `static properties`, the lit lifecycle hooks, ReactiveControllers, the `lit-html` directive set, `html` / `css` templates) so lit training data transfers directly, but webjs ships its own no-build implementation under `packages/core/src/`. Decorators are the one lit exception (invariant 10); use `declare` + `static properties`.
80
-
81
- - **No build step.** Source files are served as native ES modules. JSDoc `.js` is default; `.ts` / `.mts` is stripped via Node 24+'s `module.stripTypeScriptTypes` (invariant 10 + `agent-docs/typescript.md`). Node 24+ is required, enforced by an early `assertNodeVersion()` preflight.
82
- - **SSR + CSR by default.** Pages are server-rendered HTML; components render light DOM by default, shadow DOM opt-in via `static shadow = true` with DSD SSR.
83
- - **Progressive enhancement is the default architecture.** Pages and components are SSR'd; with JS off, content reads, `<a>` navigates, `<form>` server actions submit, display-only elements render. JS is opt-in *per interactive behaviour* (`@click`, a reactive property assignment, a signal mutation). Never write a first paint that depends on hydration; never use `fetch` + JS where a `<form>` + server action would do.
84
- - **Display-only components are elided from the browser.** A component with no interactivity signal renders identical HTML with or without its JS, so the framework strips its import (and any vendor reachable only through it, importmap entry included) from the served source. Automatic, conservative, verified differentially. Disable with `"webjs": { "elide": false }` or `WEBJS_ELIDE=0`. See `agent-docs/components.md`.
85
- - **Server actions with rich types.** A `*.server.{js,ts}` file with `'use server'` exports functions importable from the client (the import is rewritten to a typed RPC stub); the wire round-trips `Date` / `Map` / `Set` / `BigInt` / `Error` / typed arrays / `Blob` / `File` / `FormData` / Symbols / cycles. The source is never served to the browser (invariant 1).
86
- - **Only files reachable from a browser-bound entry are servable.** The dev server walks the static import graph from every page / layout / error / loading / not-found / component file (lazily on first request, re-derived after each `fs.watch` rebuild); that Set is the authorisation gate, so anything no client code imports returns 404.
87
- - **Sensible defaults, overridable.** Memory store in dev, Redis when configured. Built-in auth, sessions, caching, rate limiting, file storage (all pluggable). Tailwind is the default styling. See `agent-docs/built-ins.md`.
88
-
89
- ---
90
-
91
- ## Execution model (read this to avoid the RSC mental model)
92
-
93
- webjs has **no server/client component split.** There is no RSC render tree, no Flight protocol, no "use client" / "use server" component boundary.
94
-
95
- **Pages, layouts, and components are isomorphic modules** (same source both sides), but hydrate differently:
96
-
97
- - **Components hydrate.** The module loads in the browser, registers the custom element, the browser upgrades the SSR'd tag, and `render()` / lifecycle / `@event` / signals run client-side. Per-element, islands-style. **All interactivity lives here.**
98
- - **Pages and layouts do NOT hydrate.** Their function runs only on the server to produce HTML and is never re-invoked in the browser. So a page/layout cannot be interactive in its own markup (an `@click` in a page template is dropped at SSR; a signal read in a page body never re-renders). For interactivity, render a component's tag.
99
-
100
- A page/layout module still **loads** in the browser for its top-level side effects: registering imported components (so their tags upgrade) and, for a layout, enabling the client router via `import '@webjsdev/core/client-router'`. That load is also how its imports reach the client (`import dayjs` at the top of a page fetches dayjs when the module loads, not via hydration). An inert page/layout is dead weight, which is exactly when elision drops it.
101
-
102
- `route.{js,ts}` is the one routing file that is NOT isomorphic: a server-only HTTP handler (named `GET` / `POST` exports), the webjs equivalent of a Next route handler. It never ships to the client.
103
-
104
- **`.server.{js,ts}` is the one server boundary, an RPC + source-protection mechanism, NOT an RSC component.** With `'use server'` exports are RPC-callable (the browser import becomes a stub POSTing to `/__webjs/action/<hash>/<fn>`); without it the file is a server-only utility whose browser import **throws at module load** (Prisma, secrets, `node:*`, hashing). Consequence: **never import a no-`'use server'` util directly into a page, layout, or component** (it works at SSR but the client stub crashes on load); use it inside `'use server'` actions, `route.{js,ts}`, or `middleware`, and reach it from a page by importing a `'use server'` action (whose RPC stub loads safely client-side). This boundary, not a component annotation, is how a dependency is kept off the client (a date library used only during SSR belongs in `lib/format.server.ts`). See `agent-docs/components.md`.
105
-
106
- ---
107
-
108
- ## Framework source: where to find it
109
-
110
- Plain JS with JSDoc lives in `node_modules/@webjsdev/` (`core/`, `server/`, `cli/`, `ts-plugin/`, `ui/`); what you read is what runs. Starting points: SSR `@webjsdev/server/src/ssr.js`, client hydration `@webjsdev/core/src/render-client.js`, client router `@webjsdev/core/src/router-client.js`, convention rules `@webjsdev/server/src/check.js`. For UI debugging use the Playwright MCP server; for live introspection the scaffold wires a read-only `webjs mcp` server (`list_routes`, `list_actions`, `list_components`, `check`).
111
-
112
- ---
113
-
114
- ## App layout (cannot be renamed)
115
-
116
- ```
117
- app/ ROUTING ONLY (thin adapters importing from modules/; no helpers/constants here)
118
- layout.js root layout, wraps every page
119
- page.js /
120
- error.js nested error boundary
121
- not-found.js 404 page (only at app/ root; nested <segment>/not-found.js, nearest wins)
122
- <segment>/page.js /<segment>
123
- [param]/page.js dynamic route (`params.param`)
124
- [...rest]/ [[...rest]]/ catch-all / optional catch-all
125
- (group)/… route group (folder NOT in URL, still scopes layout/error)
126
- _private/… private folder (ignored by the router)
127
- <path>/route.js HTTP handler at /<path>
128
- <segment>/middleware.js per-segment middleware
129
- <segment>/loading.js auto Suspense boundary
130
- middleware.js root middleware (every request)
131
- readiness.js optional /__webjs/ready check (return false/throw = 503)
132
- env.js optional boot-time env validation (schema or validator fn; fails fast)
133
- sitemap.js robots.js manifest.js icon.js opengraph-image.js twitter-image.js apple-icon.js metadata routes
134
- lib/ app-wide code (lib/*.server.js infra, lib/utils/ browser-safe helpers)
135
- modules/<feature>/ feature-scoped: actions/ (mutations), queries/ (reads), components/, utils/, types.js
136
- components/*.js SHARED presentational primitives
137
- public/* static assets, served at /<name>
138
- prisma/schema.prisma data models
139
- ```
140
-
141
- Every file is a plain ES module.
142
-
143
- ---
144
-
145
- ## Public API of `@webjsdev/core`
146
-
147
- ```js
148
- import { html, css, WebComponent, render } from '@webjsdev/core';
149
- import { renderToString } from '@webjsdev/core/server';
150
- ```
151
-
152
- The bare `@webjsdev/core` specifier resolves to a BROWSER bundle dropping server-only modules (`render-server.js`, `expose.js`, `setCspNonceProvider`); `renderToString` / `renderToStream` live at `@webjsdev/core/server` for Node-side consumers.
153
-
154
- | Export | Purpose |
155
- |---|---|
156
- | `html` / `css` | Tagged template literals. `css` goes in `static styles`. |
157
- | `WebComponent` | Base class for interactive components. |
158
- | `register(tag, C)` | Tag binding. Auto-called by `Class.register('tag')`. |
159
- | `render(v, el)` | Client-side render into a DOM element. |
160
- | `renderToString` | Server-side async render to HTML with DSD (from `/server`). |
161
- | `notFound()` / `redirect(url)` | Throw to return 404, or 307/308 redirect. |
162
- | `expose(p, fn)` | Tag a server action ALSO reachable at a REST path. Server-side only. |
163
- | `validateInput(fn, validate)` | Attach an input validator running on BOTH the RPC and `expose()` REST paths (#245). Server-side only. See Server actions. |
164
- | `Suspense({fallback, children})` | Streaming boundary. `repeat` keyed-list directive is also re-exported. |
165
- | `connectWS(url, handlers)` / `richFetch<T>` | Client WebSocket (auto-reconnect, queued sends); content-negotiated rich-type fetch. |
166
- | `navigate(url, opts?)` / `revalidate(url?)` | Programmatic client-router nav; evict the BROWSER snapshot cache. |
167
- | `optimistic(signal, value, action)` | Set `signal` immediately, run `action`, roll back on error or `{ success: false }`. |
168
- | `renderStream(payload)` / `WebjsFrame` | `<webjs-stream>` element-level updates (#248); `<webjs-frame>` partial-swap regions (#253). See `agent-docs/advanced.md`. |
169
- | `Metadata` / `PageProps<R>` / `LayoutProps<R>` / `RouteHandlerContext<R>` / `WebjsConfig` (type-only) | Types for metadata, page/layout/route args (`R` narrows `params` against the `webjs types` route union), and the `webjs` config block. See `agent-docs/metadata.md` + `agent-docs/configuration.md`. |
170
-
171
- ### Directives, from `@webjsdev/core/directives`
172
-
173
- lit-html parity: `repeat` (keyed lists), `unsafeHTML(str)` (trusted raw HTML, **NEVER with user input**), `live`, `keyed`, `guard`, `templateContent`, `ref` + `createRef`, `cache`, `until`, `asyncAppend` / `asyncReplace`, and `watch(signal)` (fine-grained DOM swap). Prefer `Task` over `until` for component async data; `Suspense` for page-level streaming. Everything else (`classMap`, `styleMap`, `ifDefined`, `when`, `choose`, `map`, `join`, `range`) uses native JS. Context lives in `@webjsdev/core/context`, `Task` / `TaskStatus` in `@webjsdev/core/task`.
174
-
175
- ### `html` expression prefixes
176
-
177
- `<div>${x}</div>` text child; `class=${x}` attribute (escaped); `@click=${fn}` event listener (client-only, drops at SSR); `.value=${v}` DOM property (round-trips through SSR on custom elements via `data-webjs-prop-*`, drops on native elements); `?disabled=${b}` boolean attribute. Event/property/boolean holes **must be unquoted** (invariant 4). Every hole is identical server and client except `@event` and `.prop` on native elements.
178
-
179
- ---
180
-
181
- ## `WebComponent` essentials
182
-
183
- ```ts
184
- class MyThing extends WebComponent {
185
- static shadow = false; // default light DOM; true = scoped shadow DOM
186
- static lazy = false; // true = load module on viewport entry
187
- static properties = { count: { type: Number, reflect: true } };
188
- declare count: number; // TS only, typed accessor
189
- static styles = css`…`;
190
- render() { return html`…`; }
191
- }
192
- MyThing.register('my-thing');
193
- ```
194
-
195
- **Signals are the default state primitive.** Import `signal` / `computed` from `@webjsdev/core`, read with `signal.get()` inside `render()`, and the built-in `SignalWatcher` re-renders on change. Module-scope signals share state across components and survive navigations; instance signals (constructor) are component-local. `static properties` is reserved for values that ride an HTML attribute, reflect to one, or arrive via `.prop=${value}` SSR hydration. **Typed props in TS use the `declare` pattern** (a `student: Student = {…}` class-field initializer overwrites the reactive accessor after `super()` and breaks reactivity; instead declare the runtime in `static properties`, the type via `declare student: Student`, and set defaults in the constructor, enforced by `reactive-props-use-declare`). Property options: `type` (default `String`), `reflect`, `state`, `hasChanged`, `converter`.
196
-
197
- **Lifecycle (lit-aligned), in order:** `shouldUpdate`, `willUpdate`, controllers' `hostUpdate()`, `update` (calls `render()` + commits), controllers' `hostUpdated()`, `firstUpdated`, `updated`, `updateComplete`, each receiving a `changedProperties` Map. **SSR runs only the constructor, attribute application, the pre-render hooks (`willUpdate` / `hostUpdate`), `reflect: true` reflection, and `render()`; it does NOT call `connectedCallback`, `firstUpdated`, `updated`, or any browser-only hook.** So defaults for first paint go in the constructor; browser-only data (localStorage, viewport, `navigator.*`) goes in `connectedCallback` writing a signal; server-known data arrives via the page function. Never ship a placeholder first paint that fetches in `connectedCallback`. A browser-only global in the constructor/`render()` throws at SSR (flagged by `no-browser-globals-in-render`; attribute methods and `closest()` are shimmed).
198
-
199
- **Light DOM (default) vs Shadow DOM.** Light DOM applies global CSS and Tailwind directly (default; for Tailwind/global CSS + simple composition). Shadow DOM (`static shadow = true`) is for `static styles` scoped CSS and third-party isolation; `<slot>` works in either. A light-DOM component authoring custom CSS MUST prefix every class selector with its tag name (invariant 7); prefer Tailwind. Add `@webjsdev/ts-plugin` to `tsconfig.json` `plugins` for editor intelligence. Full deep-dive in `agent-docs/components.md` + `agent-docs/lit-muscle-memory-gotchas.md`.
200
-
201
- ---
202
-
203
- ## File conventions: the essentials
204
-
205
- ### Pages (`app/**/page.{js,ts}`)
206
-
207
- - Default export is a possibly-async function receiving `{ params, searchParams, url, actionData }`. Runs **only on the server**. Throw `notFound()` / `redirect(url)` to short-circuit.
208
- - Named exports: `metadata` (static), `generateMetadata(ctx)` (async, takes precedence). Type both with `Metadata`. See `agent-docs/metadata.md`.
209
- - Optional `export const revalidate` (seconds) opts into the server HTML response cache (#241). SAFETY: only on a page identical for every visitor (no `cookies()` / session / per-user data); keyed by URL only. See `agent-docs/built-ins.md`.
210
- - Optional `export const action`: a fn `({ request, params, searchParams, url, formData })` handling a non-GET submission to the page's own URL (the no-JS write-path, #244), returning an `ActionResult`. Success is a `303` (PRG); failure re-renders the SAME page at `422` with the result on `ctx.actionData`. See `agent-docs/recipes.md`.
211
- - Page modules also load on the client so imported components register; keep top-level imports browser-safe. **Server-only code goes only in `.server.{js,ts}`, `route.ts`, or `middleware.ts`. Never in pages, layouts, or components.**
212
-
213
- ### Layouts (`app/**/layout.{js,ts}`)
214
-
215
- Default export receives `{ children, params, searchParams, url }`, must embed `children`, nests by folder, and `metadata` merges (deepest wins). The framework auto-emits `<!doctype><html lang="en"><head></head><body>`; only the **root layout** (`app/layout.{js,ts}` exactly) MAY write its own shell (the framework splices in importmap, modulepreload, title, meta). Non-root layouts and pages MUST NOT (the `shell-in-non-root-layout` rule).
216
-
217
- ### Error / loading / metadata routes
218
-
219
- `error.{js,ts}` default-exports `({ error, ...ctx }) => TemplateResult` (catches sibling-page / deeper render errors, innermost wins, prod sends only `error.message`). `loading.{js,ts}` wraps the sibling page in `Suspense` with an immediately-flushed fallback. Metadata routes (`sitemap`, `robots`, `manifest`, `icon`, `apple-icon`, `opengraph-image`, `twitter-image`) live at app root or static segments only and default-export a possibly-async function; `sitemap(entries)` / `sitemapIndex(sitemaps)` from `@webjsdev/server` serialize spec-valid XML.
220
-
221
- ### Route handlers (`app/**/route.{js,ts}`)
222
-
223
- Named async exports per method (`GET`/`POST`/`PUT`/`PATCH`/`DELETE`), each `(Request, { params }) => Response | value` (value auto-JSONs). A folder cannot have both `page.js` and `route.js`. Export `WS(ws, req, { params })` from the same file for a WebSocket endpoint (in dev re-imported per connection; shared state on `globalThis`). See `agent-docs/advanced.md`.
224
-
225
- ### Middleware (`middleware.{js,ts}`)
226
-
227
- Optional top-level + per-segment. Default export `async (req, next) => Response`. Return a Response to short-circuit, or call `next()` then post-process. Per-segment applies to its subtree, outermost to innermost.
228
-
229
- ### Env validation (`env.{js,ts}`)
230
-
231
- Optional app-root file default-exporting a **schema object** (env-var names to a type `string` / `number` / `boolean` / `url` / `enum` or options object with `optional` / `default` / `minLength` / `pattern` / `values`) OR a **validator function** `(env) => void` (throw to fail boot). Runs at boot after `.env` loads, writes coerced values + defaults back to `process.env`, fails fast naming EVERY bad var. Opt-in.
232
-
233
- ### Server actions (`**/*.server.{js,ts}` + `'use server'`)
234
-
235
- | File | `'use server'`? | What it is |
236
- |---|---|---|
237
- | `*.server.ts` | yes | **Server action.** Source-protected AND RPC-callable; client imports become stubs POSTing to `/__webjs/action/<hash>/<fn>`. |
238
- | `*.server.ts` | no | **Server-only utility.** Source-protected; browser imports get a throw-at-load stub. |
239
- | Plain `.ts` | yes | **Lint violation** (`use-server-needs-extension`). Rename to add `.server.`. |
240
- | Plain `.ts` | no | Browser-safe; standard. |
241
-
242
- Server actions export named async functions whose args + returns round-trip through the serializer. **Importing from a client component IS the API** (rewritten to an RPC stub; never hand-write `fetch()`). **Expose as REST:** `expose('METHOD /path', fn, { validate? })`. **Input validation runs on BOTH call paths (#245),** declared via `validateInput(fn, validate)` or `expose(..., { validate })`; the framework only CALLS the validator (ships no validation library) and reads its return (`{ success: true, data? }` runs the action, `{ success: false, fieldErrors }` returns a `422` without running the body, a THROW is a sanitized error, any other value is transformed input). The validator stays server-side and receives the action's first argument. Full reference in `agent-docs/recipes.md`.
243
-
244
- ### RPC + expose security
245
-
246
- Client to action RPC posts `x-webjs-csrf` matching the cookie issued on first SSR (mismatch 403); prod errors are sanitized to `message` only. `expose()`d REST endpoints are NOT CSRF-protected: authenticate every mutating endpoint, use `validate`, log without secrets, rate-limit. For CORS use the `cors()` middleware from `@webjsdev/server`; **`credentials: true` REQUIRES an explicit origin allowlist, never `'*'`.** See `agent-docs/advanced.md`.
247
-
248
- ### Components (`components/*.{js,ts}`)
249
-
250
- One custom element per file; call `Class.register('tag')` at module top level. Styling via `static styles` (shadow) or Tailwind classes, not inline `style="…"`.
251
-
252
- ---
253
-
254
- ## Modules architecture (preferred for non-trivial apps)
255
-
256
- - **`modules/<feature>/actions/*.server.{js,ts}`** mutations, **`queries/*.server.{js,ts}`** reads (one function per file), **`components/*.{js,ts}`** feature-owned components (shared UI in top-level `components/`), **`utils/*.{js,ts}`** pure helpers (no `'use server'`, no DB), **`types.{js,ts}`** typedefs.
257
- - **`lib/`** cross-cutting: `lib/*.server.{js,ts}` server-only infra (Prisma, session, hashing), `lib/utils/*` browser-safe helpers, `lib/*.ts` app-wide values.
258
-
259
- ### The `ActionResult<T>` envelope
260
-
261
- ```ts
262
- type ActionResult<T> =
263
- | { success: true, data?: T, redirect?: string } // redirect MUST be a same-site local path
264
- | { success: false, error?: string, fieldErrors?: Record<string, string>,
265
- values?: Record<string, string>, status?: number };
266
- ```
267
-
268
- `fieldErrors` / `values` / `redirect` are additive. **Failure detection is robust:** a result is a FAILURE when `result.success === false`, OR `result.fieldErrors` is present, OR `result.error` is present and `result.success !== true`. **`result.redirect` must be a same-site local path** (a single leading `/`); other values are ignored (open-redirect guard), so throw `redirect(absoluteUrl)` for a real external redirect.
269
-
270
- **Rules:** routes stay thin (extract >~20 lines into a module action); client components import server modules via the normal path; server-only imports reach the client only through `.server.{js,ts}`; one module, one feature. See `agent-docs/recipes.md`.
271
-
272
- ---
273
-
274
- ## Styling: Tailwind-first
275
-
276
- **Tailwind is the strong default for pages AND light-DOM components.** The lit reflex to scope CSS in a shadow root with `static styles` is the habit to resist in light DOM. When a class bundle repeats, extract it into a `lib/utils/ui.ts` helper returning an `` html`...` `` fragment (SSR-time), NOT a CSS class (no `@apply`). Reserve raw CSS for what utilities cannot express (design tokens / `@theme`, `@property` + `@keyframes`, scrollbar, `prefers-reduced-motion`, complex `color-mix()` / gradients); in light DOM the tag-prefix invariant (#7) still holds, and shadow-DOM components legitimately use `static styles = css\`\``. See `agent-docs/styling.md`.
277
-
278
- ---
279
-
280
- ## Client navigation: automatic, nothing to opt into
281
-
282
- Nested layouts auto-emit `<!--wj:children:<segment-path>-->` markers; the client router walks both DOMs and replaces only the deepest shared layout's children slot, preserving outer-layout DOM identity. Form submissions ride the same pipeline (`data-no-router` opts out). Wire bytes are minimized via the `X-Webjs-Have` header (the server returns only the divergent fragment); scroll is restored on back/forward. A non-GET `<form>` whose target page exports an `action` is the no-JS write-path (with JS the router applies the response in place: a `422` swaps without reload, a `303` is followed via fetch). A failed navigation recovers in place (a cancelable `webjs:navigation-error` event, else a minimal in-place alert), never a destructive full reload.
283
-
284
- The advanced client-router surface is in `agent-docs/advanced.md`: **link prefetch** (on by default, `intent` strategy, per-link `data-prefetch`), **`<webjs-frame>`** partial-swap regions, **View Transitions** (opt-in via `<meta name="view-transition">`, plus `data-webjs-permanent` to persist a live element), and **stream actions** (`<webjs-stream>` element-level updates, #248). Production benefits from HTTP/2 at the edge; `npm run start` speaks plain HTTP/1.1 (put a reverse proxy in front for TLS + HTTP/2).
285
-
286
- ---
287
-
288
- ## Invariants (for both humans and agents)
289
-
290
- > Hit one of these as a runtime error? The [Troubleshooting page](https://docs.webjs.com/docs/troubleshooting) is keyed by symptom (the throw-at-load server import, the backtick-in-template 500, the TypeScript strip failure, the SSR browser-global crash, the missing-frame swap) and maps each back to the invariant and the `webjs check` rule below.
291
-
292
- 1. **Server-only code goes in `.server.{js,ts}` files, `route.ts` handlers, or `middleware.ts`. Never in pages, layouts, or components.** The `.server.{js,ts}` extension is the path-level boundary (the file router refuses to serve the source); a `'use server'` directive additionally makes exports RPC-callable, else the file is a server-only utility whose browser import is a throw-at-load stub. Importing `@prisma/client`, `node:*`, or any server-only dep from a component or an `app/**` page / layout / loading / error / not-found file crashes the browser at module load.
293
- 2. **Every `*.server.{js,ts}` file with `'use server'` exports must be `async` functions returning serializer-safe values.** Args and results round-trip via webjs's wire. Files without `'use server'` (server-only utilities) can export anything, including singletons.
294
- 3. **Custom element tag names must contain a hyphen** (HTML spec). Pass the tag to `Class.register('tag-name')`, not a static field. Any short-string quote works: `'tag-name'`, `"tag-name"`, or `` `tag-name` `` (single-line, no interpolation).
295
- 4. **Event (`@`), property (`.`), boolean (`?`) holes in `html` must be unquoted**, e.g. `@click=${fn}`, never `@click="${fn}"`.
296
- 5. **Signals are the default state primitive.** Import `signal` / `computed` from `@webjsdev/core` and read via `signal.get()` inside `render()`; the built-in SignalWatcher tracks the reads and re-renders. Module-scope signals share state across components; instance-scope signals (constructor) are component-local. `static properties` (with a sibling `declare`) is reserved for values riding an HTML attribute, reflected to one, or arriving via `.prop=${value}` SSR hydration. For fine-grained DOM swap use `${watch(signal)}` from `@webjsdev/core/directives`.
297
- 6. **Page and layout default exports must be functions.** They return a value (usually `TemplateResult`). They do not call `render()` themselves.
298
- 7. **Light-DOM components with custom CSS MUST prefix every class selector with their tag name.** Tailwind utilities are unique by construction, so prefer them.
299
- 8. **Non-root layouts and pages MUST NOT** write `<!doctype>` / `<html>` / `<head>` / `<body>`. Only the root layout may.
300
- 9. **No backtick characters inside `html\`...\`` template bodies**, even inside CSS / HTML comments. A nested backtick closes the literal at JS-parse time and 500s in prod.
301
- 10. **TypeScript must be erasable.** Set `compilerOptions.erasableSyntaxOnly: true`. No `enum`, no value `namespace`, no constructor parameter properties, no legacy decorators with `emitDecoratorMetadata`, no `import = require`. Types are stripped via Node 24+'s `module.stripTypeScriptTypes` (buildless, no bundler fallback); non-erasable syntax 500s at strip time. Enforced by `erasable-typescript-only` (tsconfig flag) and `no-non-erasable-typescript` (source scan). See `agent-docs/typescript.md`.
302
-
303
- 11. **No em-dashes (U+2014), no hyphen or semicolon used as pause-punctuation in prose, and no colon attached to a code-shaped LHS.** Banned as a pause: U+2014, a space-surrounded hyphen between words, a space-surrounded semicolon between words. Banned colon attachments: a colon-then-prose after `xyz()`, a `<my-tag>`, an `[expr]` subscript, or a `<code>foo()</code>` definition list (rephrase verb-led). Prefer a period, comma, a colon on a plain-noun LHS, parentheses, or a restructure. Plain hyphens stay fine in compound words, flags, filenames, ranges; semicolons and colons stay fine inside code / TS / JSON / CSS. Enforced via `.claude/hooks/block-prose-punctuation.sh`, which scans only NEW content (you can still edit an existing line to remove a glyph).
304
-
305
- ---
306
-
307
- ## Scaffolding
308
-
309
- Three scaffolds exist (do not invent template names): `webjs create <name>` (full-stack: layout, page, components, modules, Prisma+SQLite), `webjs create <name> --template api` (backend-only routes + modules + Prisma, no SSR), `webjs create <name> --template saas` (auth + login/signup + protected dashboard + User model). Pick from the request: default for any product with UI (todo, blog, dashboard, marketplace, social, e-commerce), `api` for an HTTP/JSON API with no UI, `saas` for accounts/login/signup; default to full-stack when ambiguous.
310
-
311
- Rules: **always scaffold via `webjs create`** (never hand-roll). **Default to a real database (Prisma + SQLite); NEVER use JSON files, in-memory arrays, or localStorage for persistence.** Update `prisma/schema.prisma` to real models FIRST, then `webjs db migrate <name>`, then build pages/actions/queries. **Treat the scaffold as REFERENCE, not the final product:** replace the example page / `User` model / components and adapt `app/layout.ts` (brand, nav, content width; the default `<main class="max-w-[760px]">` reading column needs widening for a full-bleed app). ENFORCED: examples carry a `webjs-scaffold-placeholder` comment and `no-scaffold-placeholder` fails until the content is replaced and the marker deleted. Docs at https://docs.webjs.com.
312
-
313
- ---
314
-
315
- ## CLI reference
316
-
317
- ```sh
318
- webjs dev [--port N] # dev server with live reload
319
- webjs start [--port N] # prod server; source IS the runtime, plain HTTP/1.1 (reverse-proxy for TLS + HTTP/2)
320
- webjs test [--server] [--browser] [--watch]
321
- webjs check [--rules] [--json] # correctness validator (report-only, no autofix); --json for an agent loop
322
- webjs mcp # read-only MCP: routes, actions (RPC hashes), components, check
323
- webjs doctor # project-health checklist; non-zero exit on a hard fail
324
- webjs types # generate .webjs/routes.d.ts (typed Route union + per-route params, #258)
325
- webjs typecheck [tsc args...] # the project's own tsc --noEmit
326
- webjs create <name> [--template api|saas]
327
- webjs db <prisma-subcommand> [...]
328
- webjs ui init | add <names...> | list | view <name>
329
- webjs vendor pin|unpin|list|audit|outdated|update [--from PROVIDER] # importmap pinning, .webjs/vendor/importmap.json
330
- ```
331
-
332
- `--from PROVIDER` accepts `jspm` (default), `jsdelivr`, `unpkg`, `skypack` and is persisted in the pin file. `PORT` is honoured when `--port` is absent; `webjs dev` emits `routes.d.ts` automatically. Running this repo's own apps (`website/`, `docs/`, `examples/blog/`, `packages/ui/packages/website/`): always `cd` in and use **its** `npm run dev` / `npm start`, never `webjs dev` / `webjs start` directly (each composes extra watchers via `npm`).
333
-
334
- ---
335
-
336
- ## Environment, server config, caching, observability
337
-
338
- - **Env vars.** `process.env.X` reads are server-only; `WEBJS_PUBLIC_`-prefixed names are exposed in the browser via an inline `<script>` (no build); `NODE_ENV` is defined both sides. See `agent-docs/built-ins.md`.
339
- - **The `package.json` `"webjs"` block.** Security headers (on by default, per-path `webjs.headers` overrides), CSP (opt-in nonce, `webjs.csp`), declarative `webjs.redirects` (#254), `webjs.trailingSlash` (#255), `webjs.basePath` (#256), and ingress caps (`maxBodyBytes` / `maxMultipartBytes` / server timeouts). Type it with `WebjsConfig` + the JSON Schema. See `agent-docs/configuration.md`.
340
- - **Caching + file storage** (`agent-docs/built-ins.md`). HTTP `Cache-Control`, the `cache()` query helper + `revalidateTag`, the server HTML response cache (`export const revalidate` + `revalidatePath`, #241), content-hash asset URLs (`?v=`, #243), conditional GET (ETag, #240), and `FileStore` + `diskStore` (streaming, traversal-safe, signed URLs, S3-pluggable, #247).
341
- - **Observability** (`agent-docs/configuration.md`). Access log, `requestId()` + `X-Request-Id`, the `onError` APM hook, `GET /__webjs/version` (#239).
342
-
343
- ---
344
-
345
- ## CONVENTIONS.md and webjs check: two surfaces, split by nature
346
-
347
- Every app ships a root `CONVENTIONS.md`; AI agents MUST read it before writing code. It is the source of truth for **project conventions** (modules layout, action placement, one-function-per-file, testing, styling, git workflow), which are guidance a reasonable project could do differently, customizable directly in the prose (`<!-- OVERRIDE -->` sections), not tool-enforced.
348
-
349
- **`webjs check` is a separate, narrower tool: correctness checks only.** Every rule catches code that is wrong to ship (a crash, a security leak, a build/type-strip failure), plus the sentinel `no-scaffold-placeholder` (unreplaced scaffold content). They run unconditionally with no per-project disabling. The dividing line: could a sensible app legitimately want this to pass? If yes it is a convention (prose), if no it is a check (the tool). `webjs check --rules` lists them.
350
-
351
- So: read `CONVENTIONS.md` and follow it by judgment; run `webjs check` and fix every violation (correctness bugs, not style); change a convention by editing the prose.
352
-
353
- ---
354
-
355
- ## Recipes: the essentials
356
-
357
- The full set lives in `agent-docs/recipes.md`. The most common patterns:
358
-
359
- ### Add a page
360
-
361
- ```ts
362
- // app/about/page.ts
363
- import { html } from '@webjsdev/core';
364
- export default function About() {
365
- return html`<h1>About</h1>`;
366
- }
367
- ```
368
-
369
- ### Add a dynamic route
370
-
371
- ```ts
372
- // app/users/[id]/page.ts
373
- export default async function User({ params }: { params: { id: string } }) {
374
- const user = await fetchUser(params.id); // via server action, NEVER import DB directly
375
- return html`<h1>${user.name}</h1>`;
376
- }
377
- ```
378
-
379
- ### Add a server action
380
-
381
- ```ts
382
- // modules/users/actions/update-profile.server.ts
383
- 'use server';
384
- import { prisma } from '../../../lib/prisma.server.ts';
385
- export async function updateProfile(input: { name: string }) {
386
- const name = String(input?.name || '').trim();
387
- if (!name) return { success: false, error: 'name required', status: 400 };
388
- const row = await prisma.user.update({ where: { id: me.id }, data: { name } });
389
- return { success: true, data: row };
390
- }
391
- ```
392
-
393
- Call it from a client component via a normal import (rewritten to an RPC stub). A component is one custom element per file (`class X extends WebComponent { render() { return html\`…\`; } }` then `X.register('x-tag')`). Full recipes, including the no-JS page-action form, are in `agent-docs/recipes.md`.
394
-
395
- ---
396
-
397
- ## Deliberately deferred
398
-
399
- Not in v1. Do not implement as part of other tasks:
400
-
401
- - **Bundling and per-route code splitting.** webjs is **no-build** (the Rails 7 + importmap model); prod perf comes from HTTP/2 multiplex + `<link rel="modulepreload">` hints, not concatenation. **Do not propose a bundler or `webjs build`.**
402
- - **Vite-grade HMR with state preservation.** Custom elements only `define` once, so full reload is necessary; data reloads are near-instant via `fs.watch` to SSE.
403
- - **React Server Components Flight.** Server actions + `Suspense` streaming cover the need.
404
- - **Edge-runtime bundling / full portability** (see `agent-docs/deployment.md`), **i18n, image optimization** (layer libraries on top).