brustjs 0.1.23-alpha → 0.1.25-alpha

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,12 +1,12 @@
1
- // Route "/" — the Pokédex list. NATIVE route: this whole tree is compiled to a
2
- // minijinja template and rendered in Rust (no React on the server). The only
3
- // non-host tags are <BrustPage> (the document shell) and <Island> (the floating
4
- // team dock)both intercepted by the compiler.
1
+ // Route "/" — the Pokédex list. NATIVE leaf route: compiled to a minijinja
2
+ // template and rendered into AppLayout's <Outlet/> slot (chrome lives in
3
+ // AppLayout, nested as the parent in routes.tsx). The page therefore returns
4
+ // JUST its inner aa-content fragment no <BrustPage>, no <main>: AppLayout owns
5
+ // the document shell and the single <main>.
5
6
  //
6
7
  // Native route components support `.map()` AND conditionals (S11): pagination
7
8
  // "disabled" state is a real `{hasPrev ? <a/> : <span/>}` branch, not a
8
9
  // precomputed hide-class. See ../FRAMEWORK-GAPS.md S11.
9
- import PageLayout from '../components/PageLayout'
10
10
  import type { ListData } from '../lib/types'
11
11
 
12
12
  export default function ListPage({
@@ -19,16 +19,9 @@ export default function ListPage({
19
19
  hasNext,
20
20
  prevHref,
21
21
  nextHref,
22
- teamProps,
23
22
  }: ListData) {
24
23
  return (
25
- <PageLayout
26
- native
27
- title="PokéDex · brust example"
28
- active="list"
29
- crumb="All Pokémon"
30
- teamProps={teamProps}
31
- >
24
+ <>
32
25
  <div className="aa-page-header">
33
26
  <div>
34
27
  <h1 className="aa-page-header__title">Pokédex</h1>
@@ -78,6 +71,6 @@ export default function ListPage({
78
71
  )}
79
72
  </div>
80
73
  </div>
81
- </PageLayout>
74
+ </>
82
75
  )
83
76
  }
@@ -1,19 +1,14 @@
1
- // Route "/type-chart" — NATIVE route. A static 18×18 type-effectiveness matrix:
2
- // pure read-only data, the ideal native page (compiled to jinja, rendered in
3
- // Rust, zero React on the server). The 19×19 grid uses nested `.map()` on the
4
- // native path: rows.map(r => r.cells.map(c => …)) into a CSS grid.
5
- import PageLayout from '../components/PageLayout'
1
+ // Route "/type-chart" — NATIVE leaf route, rendered into AppLayout's <Outlet/>
2
+ // slot (chrome lives in AppLayout). Returns JUST its inner aa-content fragment.
3
+ // A static 18×18 type-effectiveness matrix: pure read-only data, the ideal
4
+ // native page (compiled to jinja, rendered in Rust, zero React on the server).
5
+ // The 19×19 grid uses nested `.map()` on the native path: rows.map(r =>
6
+ // r.cells.map(c => …)) into a CSS grid.
6
7
  import type { TypeChartData } from '../lib/types'
7
8
 
8
- export default function TypeChart({ rows, teamProps }: TypeChartData) {
9
+ export default function TypeChart({ rows }: TypeChartData) {
9
10
  return (
10
- <PageLayout
11
- native
12
- title="PokéDex · type chart"
13
- active="typechart"
14
- crumb="Type chart"
15
- teamProps={teamProps}
16
- >
11
+ <>
17
12
  <div className="aa-page-header">
18
13
  <div>
19
14
  <h1 className="aa-page-header__title">Type chart</h1>
@@ -49,6 +44,6 @@ export default function TypeChart({ rows, teamProps }: TypeChartData) {
49
44
  ))}
50
45
  </div>
51
46
  </div>
52
- </PageLayout>
47
+ </>
53
48
  )
54
49
  }
@@ -1,4 +1,5 @@
1
1
  import { defineRoutes } from 'brustjs/routes'
2
+ import AppLayout from './components/AppLayout'
2
3
  import { detailLoader, listLoader, typeChartLoader } from './lib/loaders'
3
4
  import DetailPage from './pages/DetailPage'
4
5
  import ListPage from './pages/ListPage'
@@ -9,13 +10,27 @@ import TypeChart from './pages/TypeChart'
9
10
  // runs in a Bun worker and its return value becomes the template scope. The only
10
11
  // React that ever boots in the browser is the islands (TeamBuilder /
11
12
  // AddToTeamButton). See ./FRAMEWORK-GAPS.md for what this costs.
13
+ //
14
+ // ROUTER-LEVEL LAYOUT (Approach a): the chrome (sidebar / topbar / team-dock) is
15
+ // written ONCE in AppLayout, nested as the parent of the three leaf routes. Each
16
+ // leaf renders into AppLayout's <Outlet/> slot. The compiler builds the synth
17
+ // wrapper `<AppLayout native><Leaf native/></AppLayout>` per leaf and runs the
18
+ // chain loaders top-down, shallow-merging into one flat jinja context. The leaf
19
+ // loaders therefore also return the chrome fields (title/active/crumb/teamProps)
20
+ // that AppLayout reads — see lib/loaders.ts and components/AppLayout.tsx.
12
21
  export const routes = defineRoutes([
13
- // List + pagination (query string via req.search, validated by hand in the loader).
14
- { path: '/', Component: ListPage, native: true, loader: listLoader },
22
+ {
23
+ Component: AppLayout,
24
+ native: true,
25
+ children: [
26
+ // List + pagination (query string via req.search, validated by hand in the loader).
27
+ { path: '/', Component: ListPage, native: true, loader: listLoader },
15
28
 
16
- // Dynamic param {name} + a (non-streamed) evolution chain loaded in the loader.
17
- { path: '/pokemon/{name}', Component: DetailPage, native: true, loader: detailLoader },
29
+ // Dynamic param {name} + a (non-streamed) evolution chain loaded in the loader.
30
+ { path: '/pokemon/{name}', Component: DetailPage, native: true, loader: detailLoader },
18
31
 
19
- // Static 18×18 effectiveness matrix — the ideal native page.
20
- { path: '/type-chart', Component: TypeChart, native: true, loader: typeChartLoader },
32
+ // Static 18×18 effectiveness matrix — the ideal native page.
33
+ { path: '/type-chart', Component: TypeChart, native: true, loader: typeChartLoader },
34
+ ],
35
+ },
21
36
  ])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brustjs",
3
- "version": "0.1.23-alpha",
3
+ "version": "0.1.25-alpha",
4
4
  "description": "Bun + Rust SSR framework — React on the server, Rust everywhere else (napi cdylib + per-worker SharedArrayBuffer).",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -40,12 +40,12 @@
40
40
  "typescript": "^6.0.3"
41
41
  },
42
42
  "optionalDependencies": {
43
- "brustjs-darwin-x64": "0.1.23-alpha",
44
- "brustjs-darwin-arm64": "0.1.23-alpha",
45
- "brustjs-linux-x64-gnu": "0.1.23-alpha",
46
- "brustjs-linux-arm64-gnu": "0.1.23-alpha",
47
- "brustjs-linux-x64-musl": "0.1.23-alpha",
48
- "brustjs-linux-arm64-musl": "0.1.23-alpha"
43
+ "brustjs-darwin-x64": "0.1.25-alpha",
44
+ "brustjs-darwin-arm64": "0.1.25-alpha",
45
+ "brustjs-linux-x64-gnu": "0.1.25-alpha",
46
+ "brustjs-linux-arm64-gnu": "0.1.25-alpha",
47
+ "brustjs-linux-x64-musl": "0.1.25-alpha",
48
+ "brustjs-linux-arm64-musl": "0.1.25-alpha"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "react": "^19.2.6",
@@ -98,6 +98,7 @@
98
98
  "lint": "biome lint .",
99
99
  "check": "biome check .",
100
100
  "check:fix": "biome check --write .",
101
- "ci": "biome ci ."
101
+ "ci": "biome ci .",
102
+ "typecheck:treaty": "cd runtime && bunx tsc -p tsconfig.typecheck.json --noEmit"
102
103
  }
103
104
  }
@@ -0,0 +1,31 @@
1
+ // Typed domain error for treaty actions. `throw new ActionError(status, code, { data })`
2
+ // from a handler (or nested business logic) → dispatchAction maps it to an HTTP
3
+ // non-2xx with a flat body `{ code, message, data }`. Branded with Symbol.for so the
4
+ // guard survives the class being duplicated across bundles (user code → framework).
5
+ const ACTION_ERROR: unique symbol = Symbol.for('brust.actionError')
6
+
7
+ export interface ActionErrorBody {
8
+ code: string
9
+ message: string
10
+ data?: unknown
11
+ }
12
+
13
+ export class ActionError extends Error {
14
+ readonly [ACTION_ERROR] = true as const
15
+ readonly status: number
16
+ readonly code: string
17
+ readonly data?: unknown
18
+ constructor(status: number, code: string, opts?: { message?: string; data?: unknown }) {
19
+ super(opts?.message ?? code)
20
+ this.name = 'ActionError'
21
+ this.status = status
22
+ this.code = code
23
+ this.data = opts?.data
24
+ }
25
+ }
26
+
27
+ export function isActionError(v: unknown): v is ActionError {
28
+ return (
29
+ typeof v === 'object' && v !== null && (v as Record<symbol, unknown>)[ACTION_ERROR] === true
30
+ )
31
+ }
@@ -328,7 +328,10 @@ export async function runBuild(args: string[]): Promise<void> {
328
328
  // an empty importMap (no native routes to emit anyway).
329
329
  await emitNativeTemplates({
330
330
  entryFile: existsSync(routesFile) ? routesFile : entry,
331
- flatRoutes: (loadedRoutes ?? []) as { nativeTemplate?: string }[],
331
+ flatRoutes: (loadedRoutes ?? []) as {
332
+ nativeTemplate?: string
333
+ chain?: Array<{ Component?: { name?: string } }>
334
+ }[],
332
335
  outDir: jinjaDir,
333
336
  repoRoot: REPO_ROOT,
334
337
  })
@@ -82,7 +82,10 @@ export async function runDev(args: string[]): Promise<void> {
82
82
  const jinjaDir = path.join(process.cwd(), '.brust/jinja')
83
83
  const emitOpts = {
84
84
  entryFile: existsSync(routesFile) ? routesFile : entry,
85
- flatRoutes: loadedRoutes as { nativeTemplate?: string }[],
85
+ flatRoutes: loadedRoutes as {
86
+ nativeTemplate?: string
87
+ chain?: Array<{ Component?: { name?: string } }>
88
+ }[],
86
89
  outDir: jinjaDir,
87
90
  repoRoot: REPO_ROOT,
88
91
  }
@@ -83,6 +83,125 @@ export function gatherComponentSources(pageSourcePath: string): {
83
83
  return { sources, mergedImports }
84
84
  }
85
85
 
86
+ /** T2 / B1 fix — gather component sources for an ENTIRE native chain.
87
+ *
88
+ * The leaf of a composed chain is a bare fragment that no longer imports its
89
+ * ancestors, so seeding `gatherComponentSources` from the leaf alone would
90
+ * leave every ancestor's source ABSENT — `<AppLayout native>` would then
91
+ * silently soft-fall to an SsrComponent (React render) and break native. This
92
+ * unions `gatherComponentSources` over EVERY chain component's resolved source
93
+ * file (resolved name→file via the entry's `importMap`), then injects each
94
+ * chain component's OWN source keyed by its ident.
95
+ *
96
+ * Returns the merged `sources` map and `mergedImports` (ident→absolute path).
97
+ * Post-condition: `sources` has a key for every chain component name. Throws if
98
+ * a chain component name can't be resolved to a source file via `importMap`. */
99
+ export function gatherChainSources(
100
+ chainNames: string[],
101
+ importMap: Map<string, string>,
102
+ ): { sources: Record<string, string>; mergedImports: Map<string, string> } {
103
+ const sources: Record<string, string> = {}
104
+ const mergedImports = new Map<string, string>()
105
+
106
+ for (const compName of chainNames) {
107
+ const compPath = importMap.get(compName)
108
+ if (!compPath) {
109
+ throw new Error(
110
+ `native chain component "${compName}" has no matching import in the routes entry ` +
111
+ `(expected \`import ${compName} from "..."\`)`,
112
+ )
113
+ }
114
+
115
+ // Union the transitive sources reachable from THIS chain component.
116
+ const { sources: subSources, mergedImports: subImports } = gatherComponentSources(compPath)
117
+ for (const [ident, src] of Object.entries(subSources)) {
118
+ if (ident in sources && sources[ident] !== src) {
119
+ throw new Error(
120
+ `native build: ambiguous component ident "${ident}" — two different sources in one chain`,
121
+ )
122
+ }
123
+ sources[ident] = src
124
+ }
125
+ for (const [ident, p] of subImports) {
126
+ const existing = mergedImports.get(ident)
127
+ if (existing !== undefined && existing !== p) {
128
+ throw new Error(
129
+ `native build: ambiguous component ident "${ident}" resolves to two paths: ${existing} and ${p}`,
130
+ )
131
+ }
132
+ mergedImports.set(ident, p)
133
+ }
134
+
135
+ // Inject the chain component's OWN source keyed by its ident — it is the
136
+ // route source for `gatherComponentSources(compPath)` (which seeds from the
137
+ // file's imports, not the file itself), so it would otherwise be missing.
138
+ const ownSrc = readFileSync(compPath, 'utf8')
139
+ if (compName in sources && sources[compName] !== ownSrc) {
140
+ throw new Error(
141
+ `native build: ambiguous component ident "${compName}" — two different sources in one chain`,
142
+ )
143
+ }
144
+ sources[compName] = ownSrc
145
+ mergedImports.set(compName, compPath)
146
+ }
147
+
148
+ return { sources, mergedImports }
149
+ }
150
+
151
+ /** T2 — build the synthetic wrapper SOURCE STRING for a native route chain.
152
+ *
153
+ * Given the component identifiers parent→leaf (e.g. `['AppLayout', 'Leaf']`),
154
+ * emit a default-exported function whose body nests every component, leaf
155
+ * innermost, with the `native` attribute on EVERY tag:
156
+ *
157
+ * export default function Leaf__chain() { return <AppLayout native><Leaf native/></AppLayout>; }
158
+ *
159
+ * Load-bearing details:
160
+ * - `export default function` is required — the Rust compiler's
161
+ * `find_default_export` only matches that exact form.
162
+ * - `native` on every tag — without it a nested component lowers to an
163
+ * SsrComponent (React render) instead of being inlined into the chain.
164
+ * - The leaf tag is self-closing; each ancestor wraps the next via `<Outlet/>`
165
+ * inside the ancestor's own source (the compiler substitutes the children
166
+ * slot for `<Outlet/>`).
167
+ *
168
+ * The wrapper function name is `${leafName}__chain` — purely cosmetic (the
169
+ * compiler keys off the default export, not the name). */
170
+ export function buildChainWrapperSource(chainNames: string[]): string {
171
+ if (chainNames.length < 2) {
172
+ throw new Error(
173
+ `buildChainWrapperSource requires a chain of length >= 2 (got ${chainNames.length})`,
174
+ )
175
+ }
176
+ // The names are interpolated raw into a JSX source string fed to the compiler.
177
+ // They come from `Component.name` (build-time idents) so injection isn't a real
178
+ // attack surface, but a pathological name would emit malformed JSX (a confusing
179
+ // compiler parse error) — reject anything that isn't a valid component identifier.
180
+ for (const name of chainNames) {
181
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) {
182
+ throw new Error(
183
+ `native chain component name is not a valid identifier: ${JSON.stringify(name)}`,
184
+ )
185
+ }
186
+ }
187
+ const leafName = chainNames[chainNames.length - 1]!
188
+ // Build nested JSX inner→outer: <Leaf native/> wrapped by each ancestor.
189
+ let jsx = `<${leafName} native/>`
190
+ for (let i = chainNames.length - 2; i >= 0; i--) {
191
+ const name = chainNames[i]!
192
+ jsx = `<${name} native>${jsx}</${name}>`
193
+ }
194
+ return `export default function ${leafName}__chain() { return ${jsx}; }`
195
+ }
196
+
197
+ /** Count opening `<main>` tags in a compiled template. SPA navigation extracts
198
+ * the FIRST `<main>…</main>` block (routes.ts), so a composed native template
199
+ * must contain exactly one `<main>` — the layout owns it and leaf fragments must
200
+ * not add their own. More than one silently truncates the SPA-nav payload. */
201
+ export function countMainTags(template: string): number {
202
+ return (template.match(/<main[\s/>]/g) ?? []).length
203
+ }
204
+
86
205
  /** Dev-only: splice the /_brust/dev WS client `<script>` into a compiled native
87
206
  * template so `native: true` (jinja) routes auto-reload like React-SSR routes.
88
207
  *
@@ -133,8 +252,13 @@ export interface NativeRouteEmitOpts {
133
252
  /** User's routes entry file (absolute path). Scanned for ImportDeclarations
134
253
  * to resolve each native: true route's Component to its source .tsx. */
135
254
  entryFile: string
136
- /** Flat routes array; only entries with `nativeTemplate` are emitted. */
137
- flatRoutes: { nativeTemplate?: string }[]
255
+ /** Flat routes array; only entries with `nativeTemplate` are emitted. The
256
+ * runtime objects are full FlatRoutes — `chain` (parent→leaf route nodes,
257
+ * each carrying its `Component`) drives T2 native-chain composition. */
258
+ flatRoutes: {
259
+ nativeTemplate?: string
260
+ chain?: Array<{ Component?: { name?: string } }>
261
+ }[]
138
262
  /** `.brust/jinja` absolute output dir. Created if missing. */
139
263
  outDir: string
140
264
  /** Repo root. Retained for call-site compatibility; native compilation now
@@ -364,21 +488,69 @@ export async function emitNativeTemplates(opts: NativeRouteEmitOpts): Promise<vo
364
488
  }
365
489
  const outPath = resolve(opts.outDir, `${name}.jinja`)
366
490
 
367
- // Gather transitive component sources for native inlining and build the
368
- // merged import map that covers nested components (e.g. islands inside an
369
- // inlined native component that don't appear in the page's own imports).
370
- const { sources, mergedImports } = gatherComponentSources(sourcePath)
491
+ // T2 derive the route chain (parent→leaf component idents). A chain of
492
+ // length > 1 is a NESTED native route: synthesize a per-leaf wrapper that
493
+ // composes the whole chain into one native template, and gather sources for
494
+ // every chain component (B1 fix). Output stays under the LEAF's template
495
+ // name so the Rust route table is unchanged.
496
+ const chain = r.chain ?? []
497
+ const chainNames = chain
498
+ .map((node) => node.Component?.name)
499
+ .filter((n): n is string => typeof n === 'string' && n.length > 0)
500
+ // A nested route (chain.length > 1) whose names collapsed (anonymous/missing
501
+ // Component.name) must NOT silently fall through to the flat path — that would
502
+ // emit the leaf-only template and drop the layout. Fail loud instead.
503
+ if (chain.length > 1 && chainNames.length !== chain.length) {
504
+ throw new Error(
505
+ `native nested route "${name}" has ${chain.length} chain levels but only ${chainNames.length} named components — every level needs a named component`,
506
+ )
507
+ }
508
+
509
+ // Route source + sources map fed to the compiler. For a flat route
510
+ // (chain.length <= 1) this is the leaf source itself, seeded from its own
511
+ // imports — the EXISTING, untouched code path (no synth, no regression).
512
+ let routeSource: string
513
+ let routeSourcePath: string
514
+ let sources: Record<string, string>
515
+ let mergedImports: Map<string, string>
516
+ if (chainNames.length > 1) {
517
+ routeSource = buildChainWrapperSource(chainNames)
518
+ // Synthetic path: a placeholder under the leaf's dir. The compiler keys
519
+ // off the default export + componentSources, not a real file on disk.
520
+ routeSourcePath = resolve(dirname(sourcePath), `${name}__chain.tsx`)
521
+ ;({ sources, mergedImports } = gatherChainSources(chainNames, importMap))
522
+ } else {
523
+ // Gather transitive component sources for native inlining and build the
524
+ // merged import map that covers nested components (e.g. islands inside an
525
+ // inlined native component that don't appear in the page's own imports).
526
+ routeSource = readFileSync(sourcePath, 'utf8')
527
+ routeSourcePath = sourcePath
528
+ ;({ sources, mergedImports } = gatherComponentSources(sourcePath))
529
+ }
371
530
 
372
531
  let compiled: { template: string; islandsJson: string; warnings?: string[] }
373
532
  try {
374
- compiled = compileJsx!(readFileSync(sourcePath, 'utf8'), sourcePath, sources)
533
+ compiled = compileJsx!(routeSource, routeSourcePath, sources)
375
534
  } catch (e) {
376
- throw new Error(`native route "${name}" failed to compile (${sourcePath}):\n${String(e)}`)
535
+ throw new Error(
536
+ `native route "${name}" failed to compile (${routeSourcePath}):\n${String(e)}`,
537
+ )
377
538
  }
378
539
 
379
540
  // Print non-fatal compiler warnings to stderr.
380
541
  for (const w of compiled.warnings ?? []) process.stderr.write(`brust: ${w}\n`)
381
542
 
543
+ // SPA navigation extracts the FIRST <main>…</main> block, so a native route
544
+ // template must hold exactly one <main>. More than one (typically a leaf
545
+ // fragment adding its own under a layout that already owns one) silently
546
+ // truncates the nav payload — warn at build time (convention: layout owns <main>).
547
+ if (countMainTags(compiled.template) > 1) {
548
+ process.stderr.write(
549
+ `brust: native route "${name}" has more than one <main> — SPA navigation extracts only the first <main>…</main>. ` +
550
+ `Keep a single <main> (the layout owns it; leaf fragments must not add their own).\n`,
551
+ )
552
+ }
553
+
382
554
  // Dev-only: native routes don't pass through the React renderer's dev-client
383
555
  // injection, so splice the /_brust/dev WS script in here. reEmitJinja() runs
384
556
  // this on every hot reload, so the script is always present in dev.
@@ -0,0 +1,61 @@
1
+ import { __scope } from './request-context.ts'
2
+
3
+ export interface CookieOptions {
4
+ maxAge?: number
5
+ expires?: Date
6
+ path?: string
7
+ domain?: string
8
+ secure?: boolean
9
+ httpOnly?: boolean
10
+ sameSite?: 'Strict' | 'Lax' | 'None'
11
+ }
12
+
13
+ // RFC 6265 cookie-name is a token: no control chars, whitespace, or separators.
14
+ const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
15
+
16
+ /** Serialize a single Set-Cookie value. The value is URL-encoded; attributes
17
+ * are appended in a stable order. Mirrors the standard cookie attribute names.
18
+ *
19
+ * Hardening: the name is validated as an RFC 6265 token, and the final line is
20
+ * asserted CRLF-free — so a stray `\r\n` in a name/path/domain (which are NOT
21
+ * URL-encoded, unlike the value) can't smuggle an extra response header. */
22
+ export function serializeCookie(name: string, value: string, opts: CookieOptions = {}): string {
23
+ if (!COOKIE_NAME.test(name)) {
24
+ throw new Error(`invalid cookie name ${JSON.stringify(name)} (must be an RFC 6265 token)`)
25
+ }
26
+ let out = `${name}=${encodeURIComponent(value)}`
27
+ if (opts.maxAge !== undefined) out += `; Max-Age=${opts.maxAge}`
28
+ if (opts.expires !== undefined) out += `; Expires=${opts.expires.toUTCString()}`
29
+ if (opts.path !== undefined) out += `; Path=${opts.path}`
30
+ if (opts.domain !== undefined) out += `; Domain=${opts.domain}`
31
+ if (opts.secure) out += '; Secure'
32
+ if (opts.httpOnly) out += '; HttpOnly'
33
+ if (opts.sameSite !== undefined) out += `; SameSite=${opts.sameSite}`
34
+ if (/[\r\n]/.test(out)) {
35
+ throw new Error('cookie contains CR/LF — refusing to emit (header-injection guard)')
36
+ }
37
+ return out
38
+ }
39
+
40
+ /** Per-request cookie helper. `get` reads the incoming request cookies; `set`
41
+ * and `delete` stage a Set-Cookie onto the active request scope, flushed onto
42
+ * the response by routes.ts. Outside a request scope, `set`/`delete` are no-ops
43
+ * (dev-warn under BRUST_DEV). */
44
+ export const cookies = {
45
+ get(name: string): string | undefined {
46
+ return __scope()?.reqCookies[name]
47
+ },
48
+ set(name: string, value: string, opts?: CookieOptions): void {
49
+ const s = __scope()
50
+ if (!s) {
51
+ if (process.env.BRUST_DEV === '1') {
52
+ console.warn(`[brust] cookies.set('${name}') outside a request scope — no-op`)
53
+ }
54
+ return
55
+ }
56
+ s.setCookies.push(serializeCookie(name, value, opts))
57
+ },
58
+ delete(name: string, opts?: Pick<CookieOptions, 'path' | 'domain'>): void {
59
+ cookies.set(name, '', { ...opts, maxAge: 0 })
60
+ },
61
+ }
@@ -46,6 +46,10 @@ export interface EndpointOptions {
46
46
  middleware?: Middleware[]
47
47
  /** Build-time MCP tool description (read by the manifest extractor). */
48
48
  description?: string
49
+ /** Declared domain errors, keyed by code. Each value is a StandardSchema for
50
+ * the error's `data` payload. TYPE-ONLY: flows into the treaty client's typed
51
+ * error union; the runtime ignores it (handlers throw `ActionError`). */
52
+ errors?: Record<string, StandardSchemaV1>
49
53
  }
50
54
  export interface EndpointDef {
51
55
  method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'
@@ -72,8 +76,19 @@ type QueryOf<O> = O extends { query: infer S }
72
76
  ? InferOutput<S>
73
77
  : unknown
74
78
  : Record<string, string>
79
+ /** Discriminated error union derived from `opts.errors`. Each declared code maps
80
+ * to `{ code; message; data }` where `data` is the schema's inferred output. */
81
+ type ErrorOf<O> = O extends { errors: infer E }
82
+ ? {
83
+ [K in keyof E & string]: {
84
+ code: K
85
+ message: string
86
+ data: E[K] extends StandardSchemaV1 ? InferOutput<E[K]> : unknown
87
+ }
88
+ }[keyof E & string]
89
+ : never
75
90
 
76
- export type EndpointEntry = { input: unknown; output: unknown }
91
+ export type EndpointEntry = { input: unknown; output: unknown; error: unknown }
77
92
  export type EndpointMap = Record<string, Partial<Record<EndpointDef['method'], EndpointEntry>>>
78
93
 
79
94
  export function isValidEndpointPath(p: string): boolean {
@@ -88,32 +103,44 @@ export interface ActionsBuilder<Acc extends EndpointMap = {}> {
88
103
  path: P,
89
104
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
90
105
  opts?: O,
91
- ): ActionsBuilder<Acc & { [K in P]: { GET: { input: QueryOf<O>; output: Awaited<R> } } }>
106
+ ): ActionsBuilder<
107
+ Acc & { [K in P]: { GET: { input: QueryOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
108
+ >
92
109
  post<P extends string, O extends EndpointOptions, R>(
93
110
  path: P,
94
111
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
95
112
  opts?: O,
96
- ): ActionsBuilder<Acc & { [K in P]: { POST: { input: BodyOf<O>; output: Awaited<R> } } }>
113
+ ): ActionsBuilder<
114
+ Acc & { [K in P]: { POST: { input: BodyOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
115
+ >
97
116
  put<P extends string, O extends EndpointOptions, R>(
98
117
  path: P,
99
118
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
100
119
  opts?: O,
101
- ): ActionsBuilder<Acc & { [K in P]: { PUT: { input: BodyOf<O>; output: Awaited<R> } } }>
120
+ ): ActionsBuilder<
121
+ Acc & { [K in P]: { PUT: { input: BodyOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
122
+ >
102
123
  patch<P extends string, O extends EndpointOptions, R>(
103
124
  path: P,
104
125
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
105
126
  opts?: O,
106
- ): ActionsBuilder<Acc & { [K in P]: { PATCH: { input: BodyOf<O>; output: Awaited<R> } } }>
127
+ ): ActionsBuilder<
128
+ Acc & { [K in P]: { PATCH: { input: BodyOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
129
+ >
107
130
  delete<P extends string, O extends EndpointOptions, R>(
108
131
  path: P,
109
132
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
110
133
  opts?: O,
111
- ): ActionsBuilder<Acc & { [K in P]: { DELETE: { input: BodyOf<O>; output: Awaited<R> } } }>
134
+ ): ActionsBuilder<
135
+ Acc & { [K in P]: { DELETE: { input: BodyOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
136
+ >
112
137
  head<P extends string, O extends EndpointOptions, R>(
113
138
  path: P,
114
139
  handler: Handler<BodyOf<O>, Params<P>, QueryOf<O>, R>,
115
140
  opts?: O,
116
- ): ActionsBuilder<Acc & { [K in P]: { HEAD: { input: QueryOf<O>; output: Awaited<R> } } }>
141
+ ): ActionsBuilder<
142
+ Acc & { [K in P]: { HEAD: { input: QueryOf<O>; output: Awaited<R>; error: ErrorOf<O> } } }
143
+ >
117
144
  }
118
145
 
119
146
  export function defineActions(): ActionsBuilder {