brustjs 0.1.24-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.
@@ -6,7 +6,7 @@
6
6
  // api.team({ id }).delete() → DELETE /_brust/action/team/{id}
7
7
 
8
8
  import { z } from 'zod'
9
- import { defineActions, ActionError } from 'brustjs'
9
+ import { cookies, defineActions, ActionError } from 'brustjs'
10
10
  import { MAX_TEAM, teamStore } from './lib/team-store'
11
11
 
12
12
  const TeamMemberInput = z.object({
@@ -28,11 +28,19 @@ export const actions = defineActions()
28
28
  }
29
29
  return { team: teamStore.list(), max: MAX_TEAM }
30
30
  },
31
- { body: TeamMemberInput },
31
+ { body: TeamMemberInput, errors: { TEAM_FULL: z.object({ max: z.number() }) } },
32
32
  )
33
33
  .delete('/team/{id}', ({ params }) => {
34
34
  teamStore.remove(Number(params.id))
35
35
  return { team: teamStore.list(), max: MAX_TEAM }
36
36
  })
37
+ .post(
38
+ '/theme',
39
+ ({ body }) => {
40
+ cookies.set('mode', body.mode, { path: '/', maxAge: 31536000, sameSite: 'Lax' })
41
+ return { mode: body.mode }
42
+ },
43
+ { body: z.object({ mode: z.enum(['dark', 'light']) }) },
44
+ )
37
45
 
38
46
  export type Actions = typeof actions
@@ -2,9 +2,9 @@
2
2
  PokéDex app.css — AssetsArt Design System (tokens + components) +
3
3
  a PokéDex (.dex-*) layer that replaces the prototype's inline styles.
4
4
  ---------------------------------------------------------------------
5
- NOTE: dark-mode only. The design's [data-mode="dark"] selectors are
6
- rewritten to .dark, set via <BrustPage className="dark"> (BrustPage
7
- only sets <html class>, not arbitrary data-* attrs see GAPS S8).
5
+ NOTE: light + dark. :root holds the LIGHT defaults; [data-mode="dark"]
6
+ remaps them. The mode is set on <html data-mode={mode}> via BrustPage's
7
+ data-* support, driven by the `mode` cookie + the native ThemeToggle.
8
8
  Remote @import of Google Fonts is dropped (the css pipeline runs through
9
9
  @tailwindcss/node); we rely on the system-font fallbacks in the stacks.
10
10
  ===================================================================== */
@@ -328,7 +328,7 @@
328
328
  The product (Cloud Server Portal) defaults to DARK; marketing + first-run
329
329
  default to LIGHT.
330
330
  ===================================================================== */
331
- .dark {
331
+ [data-mode="dark"] {
332
332
  --ink-0: #14171F;
333
333
  --ink-25: #181B25;
334
334
  --ink-50: #1C2030; /* card surface */
@@ -445,7 +445,7 @@ a:hover { text-decoration: underline; }
445
445
  code, pre { font-family: var(--font-mono); }
446
446
 
447
447
  ::selection { background: var(--primary-200); color: var(--primary-900); }
448
- .dark ::selection { background: rgba(127,63,151,0.45); color: #fff; }
448
+ [data-mode="dark"] ::selection { background: rgba(127,63,151,0.45); color: #fff; }
449
449
 
450
450
  /* =====================================================================
451
451
  TYPE UTILITIES — opt-in semantic typography classes
@@ -642,7 +642,7 @@ code, pre { font-family: var(--font-mono); }
642
642
  --_fg: var(--primary-500);
643
643
  --_border: var(--primary-500);
644
644
  }
645
- .dark .aa-btn--outline { --_fg: var(--purple-300); --_border: var(--purple-400); }
645
+ [data-mode="dark"] .aa-btn--outline { --_fg: var(--purple-300); --_border: var(--purple-400); }
646
646
  .aa-btn--danger {
647
647
  --_bg: var(--danger-600);
648
648
  --_bg-hover: var(--danger-700);
@@ -815,11 +815,11 @@ code, pre { font-family: var(--font-mono); }
815
815
  }
816
816
 
817
817
  /* dark-mode pill foreground gets lifted */
818
- .dark .aa-badge--success { color: #6BD9A4; }
819
- .dark .aa-badge--warning { color: #F0C76A; }
820
- .dark .aa-badge--danger { color: #F195B2; }
821
- .dark .aa-badge--info { color: #7BB6E2; }
822
- .dark .aa-badge--soft { color: #C9A4D8; }
818
+ [data-mode="dark"] .aa-badge--success { color: #6BD9A4; }
819
+ [data-mode="dark"] .aa-badge--warning { color: #F0C76A; }
820
+ [data-mode="dark"] .aa-badge--danger { color: #F195B2; }
821
+ [data-mode="dark"] .aa-badge--info { color: #7BB6E2; }
822
+ [data-mode="dark"] .aa-badge--soft { color: #C9A4D8; }
823
823
 
824
824
  /* Status dot pill (used in tables) */
825
825
  .aa-pill {
@@ -843,10 +843,10 @@ code, pre { font-family: var(--font-mono); }
843
843
  .aa-pill--muted { background: var(--ink-100); color: var(--text-tertiary); }
844
844
  .aa-pill--no-dot::before { display: none; }
845
845
 
846
- .dark .aa-pill--ok { color: #6BD9A4; }
847
- .dark .aa-pill--warn { color: #F0C76A; }
848
- .dark .aa-pill--err { color: #F195B2; }
849
- .dark .aa-pill--info { color: #7BB6E2; }
846
+ [data-mode="dark"] .aa-pill--ok { color: #6BD9A4; }
847
+ [data-mode="dark"] .aa-pill--warn { color: #F0C76A; }
848
+ [data-mode="dark"] .aa-pill--err { color: #F195B2; }
849
+ [data-mode="dark"] .aa-pill--info { color: #7BB6E2; }
850
850
 
851
851
  /* =====================================================================
852
852
  TABLE
@@ -903,8 +903,8 @@ code, pre { font-family: var(--font-mono); }
903
903
  .aa-tab[aria-selected="true"], .aa-tab.is-active {
904
904
  color: var(--primary-600); border-color: var(--primary-600); font-weight: var(--fw-semibold);
905
905
  }
906
- .dark .aa-tab[aria-selected="true"],
907
- .dark .aa-tab.is-active { color: var(--purple-300); border-color: var(--purple-400); }
906
+ [data-mode="dark"] .aa-tab[aria-selected="true"],
907
+ [data-mode="dark"] .aa-tab.is-active { color: var(--purple-300); border-color: var(--purple-400); }
908
908
 
909
909
  .aa-segmented {
910
910
  display: inline-flex; padding: 3px;
@@ -947,10 +947,10 @@ code, pre { font-family: var(--font-mono); }
947
947
  .aa-alert--danger .aa-alert__icon { color: var(--danger-600); }
948
948
 
949
949
  /* dark-mode alert text */
950
- .dark .aa-alert--info { color: #9DC4E6; }
951
- .dark .aa-alert--success { color: #93D6B0; }
952
- .dark .aa-alert--warning { color: #EFCC74; }
953
- .dark .aa-alert--danger { color: #F195B2; }
950
+ [data-mode="dark"] .aa-alert--info { color: #9DC4E6; }
951
+ [data-mode="dark"] .aa-alert--success { color: #93D6B0; }
952
+ [data-mode="dark"] .aa-alert--warning { color: #EFCC74; }
953
+ [data-mode="dark"] .aa-alert--danger { color: #F195B2; }
954
954
 
955
955
  /* =====================================================================
956
956
  AVATAR
@@ -972,7 +972,7 @@ code, pre { font-family: var(--font-mono); }
972
972
  .aa-avatar--sm { width: 28px; height: 28px; font-size: var(--text-3xs); }
973
973
  .aa-avatar--lg { width: 44px; height: 44px; font-size: var(--text-md); }
974
974
  .aa-avatar--xl { width: 64px; height: 64px; font-size: var(--text-lg); }
975
- .dark .aa-avatar { color: var(--purple-200); }
975
+ [data-mode="dark"] .aa-avatar { color: var(--purple-200); }
976
976
 
977
977
  /* =====================================================================
978
978
  PROGRESS
@@ -1027,8 +1027,8 @@ code, pre { font-family: var(--font-mono); }
1027
1027
  .aa-kpi__delta--up { color: var(--success-600); }
1028
1028
  .aa-kpi__delta--down { color: var(--danger-600); }
1029
1029
  .aa-kpi__delta--neutral { color: var(--text-tertiary); }
1030
- .dark .aa-kpi__delta--up { color: #6BD9A4; }
1031
- .dark .aa-kpi__delta--down { color: #F195B2; }
1030
+ [data-mode="dark"] .aa-kpi__delta--up { color: #6BD9A4; }
1031
+ [data-mode="dark"] .aa-kpi__delta--down { color: #F195B2; }
1032
1032
  .aa-kpi__meta {
1033
1033
  display: inline-flex; align-items: center; gap: 6px;
1034
1034
  font-size: var(--text-xs);
@@ -1092,7 +1092,7 @@ code, pre { font-family: var(--font-mono); }
1092
1092
  letter-spacing: 0.08em;
1093
1093
  margin-left: auto;
1094
1094
  }
1095
- .dark .aa-sidebar__env { color: #93D6B0; }
1095
+ [data-mode="dark"] .aa-sidebar__env { color: #93D6B0; }
1096
1096
 
1097
1097
  .aa-sidebar__nav {
1098
1098
  flex: 1;
@@ -1131,7 +1131,7 @@ code, pre { font-family: var(--font-mono); }
1131
1131
  color: var(--primary-700);
1132
1132
  font-weight: var(--fw-semibold);
1133
1133
  }
1134
- .dark .aa-nav-item.is-active { color: #C9A4D8; }
1134
+ [data-mode="dark"] .aa-nav-item.is-active { color: #C9A4D8; }
1135
1135
  .aa-nav-item svg { width: 16px; height: 16px; flex: none; stroke-width: 1.75; }
1136
1136
  .aa-nav-item__count {
1137
1137
  margin-left: auto;
@@ -1146,7 +1146,7 @@ code, pre { font-family: var(--font-mono); }
1146
1146
  }
1147
1147
  .aa-nav-item.is-active .aa-nav-item__count { background: var(--primary-100); color: var(--primary-700); }
1148
1148
  .aa-nav-item__count--alert { background: var(--danger-50); color: var(--danger-700); }
1149
- .dark .aa-nav-item__count--alert { color: #F195B2; }
1149
+ [data-mode="dark"] .aa-nav-item__count--alert { color: #F195B2; }
1150
1150
 
1151
1151
  .aa-sidebar__user {
1152
1152
  padding: 12px;
@@ -1302,7 +1302,7 @@ code, pre { font-family: var(--font-mono); }
1302
1302
  }
1303
1303
  .aa-toolbar__filter:hover { border-color: var(--ink-300); }
1304
1304
  .aa-toolbar__filter.is-active { border-color: var(--primary-500); background: var(--primary-50); color: var(--primary-700); }
1305
- .dark .aa-toolbar__filter.is-active { color: #C9A4D8; }
1305
+ [data-mode="dark"] .aa-toolbar__filter.is-active { color: #C9A4D8; }
1306
1306
  .aa-toolbar__filter svg { width: 12px; height: 12px; stroke: currentColor; fill: none; stroke-width: 2; }
1307
1307
 
1308
1308
  /* Service / category chip */
@@ -1656,8 +1656,8 @@ code, pre { font-family: var(--font-mono); }
1656
1656
  .dex-tc__cell--weak { background: var(--danger-50); color: var(--danger-700); }
1657
1657
  .dex-tc__cell--none { background: var(--ink-100); color: var(--text-muted); }
1658
1658
  .dex-tc__swatch { min-height: auto; width: 22px; height: 22px; border-radius: 4px; border: none; }
1659
- .dark .dex-tc__cell--super { color: #6BD9A4; }
1660
- .dark .dex-tc__cell--weak { color: #F195B2; }
1659
+ [data-mode="dark"] .dex-tc__cell--super { color: #6BD9A4; }
1660
+ [data-mode="dark"] .dex-tc__cell--weak { color: #F195B2; }
1661
1661
 
1662
1662
  /* not found */
1663
1663
  .dex-notfound { display: grid; place-items: center; padding: 80px 20px; text-align: center; }
@@ -8,7 +8,6 @@
8
8
  // The behavior is react-free: `signal`/`computed` from brustjs/store (the window
9
9
  // singleton on the client), `client` from brustjs/client (the treaty action
10
10
  // client — also react-free), and the shared teamStore. NO react imports.
11
- import type { ActionErrorBody } from 'brustjs'
12
11
  import { client } from 'brustjs/client'
13
12
  import { computed, signal } from 'brustjs/store'
14
13
  import type { Actions } from '../actions'
@@ -57,7 +56,7 @@ export const behavior = ({ props }: { props: AddToTeamProps }) => {
57
56
  if (data) {
58
57
  full.set(false)
59
58
  teamStore.members.set(data.team)
60
- } else if ((error?.value as ActionErrorBody)?.code === 'TEAM_FULL') {
59
+ } else if (error?.value.code === 'TEAM_FULL') {
61
60
  full.set(true) // server rejected — team full; surface instead of silent no-op
62
61
  }
63
62
  }
@@ -17,22 +17,25 @@
17
17
  import { BrustPage, Island, Outlet } from 'brustjs'
18
18
  import type { TeamMember } from '../lib/types'
19
19
  import TeamBuilder from './TeamBuilder'
20
+ import ThemeToggle from './ThemeToggle'
20
21
 
21
22
  export default function AppLayout({
22
23
  title,
23
24
  active,
24
25
  crumb,
25
26
  teamProps,
27
+ mode,
26
28
  }: {
27
29
  title: string
28
30
  active: 'list' | 'typechart'
29
31
  crumb: string
30
32
  teamProps: { teamInitial: TeamMember[] }
33
+ mode: 'dark' | 'light'
31
34
  }) {
32
35
  return (
33
36
  <BrustPage
34
37
  lang="en"
35
- className="dark"
38
+ data-mode={mode}
36
39
  title={title}
37
40
  head={[{ tag: 'link', rel: 'icon', href: '/favicon.svg' }]}
38
41
  >
@@ -87,6 +90,7 @@ export default function AppLayout({
87
90
  <span className="dex-crumb__sep">›</span>
88
91
  <b>{crumb}</b>
89
92
  </div>
93
+ <ThemeToggle native />
90
94
  </header>
91
95
 
92
96
  <div className="aa-content">
@@ -0,0 +1,51 @@
1
+ // NATIVE INTERACTIVE COMPONENT (B4 dogfood) — the dark/light theme toggle in
2
+ // the topbar. Single-file native directive component: a co-located
3
+ // `export const behavior` (client logic, react-free) + a JSX `default` export
4
+ // (the native template the compiler lowers to minijinja). The build bundles
5
+ // ONLY `behavior` into _directives.js, registered as "themeToggle" (camelCase
6
+ // filename); the JSX default is tree-shaken out so react never leaks client-side.
7
+ //
8
+ // react-free: `signal`/`computed` from brustjs/store (the window singleton on
9
+ // the client), `client` from brustjs/client (the treaty action client). The
10
+ // toggle flips <html data-mode> immediately (no reload) AND persists via the
11
+ // /theme action which sets the `mode` cookie — so SSR matches on the next load.
12
+ import { client } from 'brustjs/client'
13
+ import { computed, signal } from 'brustjs/store'
14
+ import type { Actions } from '../actions'
15
+
16
+ const api = client<Actions>()
17
+
18
+ // behavior → client bundle, registered as "themeToggle". Reads the initial mode
19
+ // straight off <html data-mode> (server already set it from the cookie).
20
+ export const behavior = () => {
21
+ const mode = signal(
22
+ typeof document !== 'undefined' ? (document.documentElement.dataset.mode ?? 'dark') : 'dark',
23
+ )
24
+ const label = computed(() => (mode() === 'dark' ? '☀ Light' : '🌙 Dark'))
25
+
26
+ async function toggle() {
27
+ const next = mode() === 'dark' ? 'light' : 'dark'
28
+ document.documentElement.dataset.mode = next // flip the theme immediately
29
+ mode.set(next)
30
+ await api.theme.post({ mode: next }) // persist via cookie for the next SSR
31
+ }
32
+
33
+ return { toggle, label }
34
+ }
35
+
36
+ // default → jinja (server). The x-* directives are static string attributes the
37
+ // native compiler passes straight through; the directive runtime binds them to
38
+ // the behavior instance on the client.
39
+ export default function ThemeToggle() {
40
+ return (
41
+ <button
42
+ type="button"
43
+ x-data="themeToggle"
44
+ x-text="label"
45
+ x-on-click="toggle"
46
+ className="aa-btn aa-btn--outline aa-btn--sm"
47
+ >
48
+ 🌙 Dark
49
+ </button>
50
+ )
51
+ }
@@ -87,12 +87,17 @@ export async function listLoader({ req }: LoaderCtx): Promise<ListData> {
87
87
  active: 'list',
88
88
  crumb: 'All Pokémon',
89
89
  teamProps: { teamInitial: teamStore.list() },
90
+ mode: req.cookies.mode === 'light' ? 'light' : 'dark',
90
91
  }
91
92
  }
92
93
 
93
- export async function detailLoader({ params }: LoaderCtx): Promise<DetailData | NativeVerdict> {
94
+ export async function detailLoader({
95
+ params,
96
+ req,
97
+ }: LoaderCtx): Promise<DetailData | NativeVerdict> {
94
98
  const name = params?.name ?? ''
95
- const empty = emptyDetail(name)
99
+ const mode = req.cookies.mode === 'light' ? 'light' : 'dark'
100
+ const empty = emptyDetail(name, mode)
96
101
 
97
102
  const p = await fetchPokemon(name)
98
103
  // GAP S9 (FIXED): native loaders can now `return notFound(data)` to render the
@@ -153,6 +158,7 @@ export async function detailLoader({ params }: LoaderCtx): Promise<DetailData |
153
158
  title: `${cap(p.name)} · PokéDex`,
154
159
  active: 'list',
155
160
  crumb: cap(p.name),
161
+ mode,
156
162
  name: p.name,
157
163
  id: p.id,
158
164
  displayName: cap(p.name),
@@ -186,13 +192,14 @@ export async function detailLoader({ params }: LoaderCtx): Promise<DetailData |
186
192
  }
187
193
  }
188
194
 
189
- function emptyDetail(name: string): DetailData {
195
+ function emptyDetail(name: string, mode: 'dark' | 'light'): DetailData {
190
196
  return {
191
197
  notFound: true,
192
198
  // Chrome fields (ChromeData) read by AppLayout from the merged context.
193
199
  title: `${cap(name)} · PokéDex`,
194
200
  active: 'list',
195
201
  crumb: cap(name),
202
+ mode,
196
203
  name,
197
204
  id: 0,
198
205
  displayName: cap(name),
@@ -244,9 +251,9 @@ const SHORT: Record<string, string> = {
244
251
  fairy: 'FAI',
245
252
  }
246
253
 
247
- export async function typeChartLoader(): Promise<TypeChartData> {
248
- // GAP S2: no loader-level batch/parallel helper or request-scoped cache we
249
- // fan out 18 fetches by hand with Promise.all (and there is no dedupe).
254
+ export async function typeChartLoader({ req }: LoaderCtx): Promise<TypeChartData> {
255
+ // Fan out 18 distinct type fetches with Promise.all; each goes through
256
+ // cachedFetch (S2), so duplicate in-flight GETs within the request dedupe.
250
257
  const relations = await Promise.all(ALL_TYPES.map((t) => fetchTypeRelations(t)))
251
258
 
252
259
  // Build the 19×19 grid as nested rows (header row + one row per attacking
@@ -327,5 +334,6 @@ export async function typeChartLoader(): Promise<TypeChartData> {
327
334
  active: 'typechart',
328
335
  crumb: 'Type chart',
329
336
  teamProps: { teamInitial: teamStore.list() },
337
+ mode: req.cookies.mode === 'light' ? 'light' : 'dark',
330
338
  }
331
339
  }
@@ -4,6 +4,8 @@
4
4
  // constraint). Their job is to fetch from PokeAPI and return fully render-ready
5
5
  // view-models so the native (jinja) page templates only interpolate fields.
6
6
 
7
+ import { cachedFetch } from 'brustjs'
8
+
7
9
  export const API = 'https://pokeapi.co/api/v2'
8
10
 
9
11
  export const idFromUrl = (url: string): number => Number((url.match(/\/pokemon\/(\d+)\//) || [])[1])
@@ -79,7 +81,7 @@ export interface RawEvolutionStage {
79
81
  }
80
82
 
81
83
  export async function fetchList(offset: number, limit: number) {
82
- const res = await fetch(`${API}/pokemon?limit=${limit}&offset=${offset}`)
84
+ const res = await cachedFetch(`${API}/pokemon?limit=${limit}&offset=${offset}`)
83
85
  if (!res.ok) throw new Error(`PokeAPI list ${res.status}`)
84
86
  const page = (await res.json()) as {
85
87
  count: number
@@ -92,7 +94,7 @@ export async function fetchList(offset: number, limit: number) {
92
94
  }
93
95
 
94
96
  export async function fetchPokemon(name: string): Promise<RawPokemon | null> {
95
- const res = await fetch(`${API}/pokemon/${name}`)
97
+ const res = await cachedFetch(`${API}/pokemon/${name}`)
96
98
  if (!res.ok) return null
97
99
  const p = (await res.json()) as any
98
100
  return {
@@ -108,7 +110,7 @@ export async function fetchPokemon(name: string): Promise<RawPokemon | null> {
108
110
  }
109
111
 
110
112
  export async function fetchSpecies(id: number): Promise<RawSpecies> {
111
- const res = await fetch(`${API}/pokemon-species/${id}`)
113
+ const res = await cachedFetch(`${API}/pokemon-species/${id}`)
112
114
  const s = (await res.json()) as any
113
115
  const flavor = s.flavor_text_entries?.find((e: any) => e.language.name === 'en')?.flavor_text as
114
116
  | string
@@ -124,7 +126,7 @@ export async function fetchSpecies(id: number): Promise<RawSpecies> {
124
126
  * flattened to the first branch — noted as an open question in the design. */
125
127
  export async function fetchEvolution(url: string): Promise<RawEvolutionStage[]> {
126
128
  if (!url) return []
127
- const res = await fetch(url)
129
+ const res = await cachedFetch(url)
128
130
  if (!res.ok) return []
129
131
  const data = (await res.json()) as any
130
132
  const stages: RawEvolutionStage[] = []
@@ -162,7 +164,7 @@ export const ALL_TYPES = [
162
164
 
163
165
  /** Fetch one type's damage relations → a map of defendingType → multiplier. */
164
166
  export async function fetchTypeRelations(type: string): Promise<Record<string, number>> {
165
- const res = await fetch(`${API}/type/${type}`)
167
+ const res = await cachedFetch(`${API}/type/${type}`)
166
168
  if (!res.ok) return {}
167
169
  const d = (await res.json()) as any
168
170
  const rel = d.damage_relations
@@ -18,6 +18,7 @@ export interface ChromeData {
18
18
  active: 'list' | 'typechart' // which sidebar nav item gets is-active (S11 conditional)
19
19
  crumb: string // topbar breadcrumb leaf label
20
20
  teamProps: { teamInitial: TeamMember[] } // floating team-dock island initial state
21
+ mode: 'dark' | 'light' // theme, read from the `mode` cookie → <html data-mode={mode}>
21
22
  }
22
23
 
23
24
  /** A single list cell — derived from the list endpoint alone (no detail fetch,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brustjs",
3
- "version": "0.1.24-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.24-alpha",
44
- "brustjs-darwin-arm64": "0.1.24-alpha",
45
- "brustjs-linux-x64-gnu": "0.1.24-alpha",
46
- "brustjs-linux-arm64-gnu": "0.1.24-alpha",
47
- "brustjs-linux-x64-musl": "0.1.24-alpha",
48
- "brustjs-linux-arm64-musl": "0.1.24-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,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 {