brustjs 0.1.24-alpha → 0.1.26-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.
- package/example/pokedex/actions.ts +10 -2
- package/example/pokedex/app.css +56 -30
- package/example/pokedex/components/AddToTeamButton.tsx +1 -2
- package/example/pokedex/components/AppLayout.tsx +15 -27
- package/example/pokedex/components/NavLink.tsx +50 -0
- package/example/pokedex/components/NavPreloader.tsx +21 -0
- package/example/pokedex/components/ThemeToggle.tsx +51 -0
- package/example/pokedex/lib/loaders.ts +14 -6
- package/example/pokedex/lib/pokeapi.ts +7 -5
- package/example/pokedex/lib/types.ts +1 -0
- package/package.json +11 -9
- package/runtime/client/index.ts +4 -0
- package/runtime/cookies.ts +61 -0
- package/runtime/define-actions.ts +34 -7
- package/runtime/index.js +52 -52
- package/runtime/index.ts +9 -0
- package/runtime/islands/bootstrap.ts +10 -1
- package/runtime/islands/island.tsx +8 -4
- package/runtime/islands/native-render.ts +3 -1
- package/runtime/loader-cache.ts +42 -0
- package/runtime/navigation/active-nav.ts +75 -0
- package/runtime/navigation/index.ts +13 -0
- package/runtime/navigation/react.ts +24 -0
- package/runtime/navigation/store.ts +208 -0
- package/runtime/request-context.ts +35 -0
- package/runtime/routes.ts +96 -25
- package/runtime/treaty.ts +47 -10
- package/runtime/treaty.type-test.ts +69 -0
- package/runtime/tsconfig.typecheck.json +23 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// runtime/navigation/active-nav.ts
|
|
2
|
+
// The DOM consumer of the navigation store. Installs two effects:
|
|
3
|
+
// - nav.path → reconcile is-active/aria-current on links in [data-brust-active-nav]
|
|
4
|
+
// - nav.phase → mirror to <html data-brust-nav> for CSS-driven indicators
|
|
5
|
+
// Attribute name [data-brust-active-nav] is deliberately distinct from the
|
|
6
|
+
// <html data-brust-nav> phase attr so the reconciler never treats <html> as a
|
|
7
|
+
// container (which would toggle is-active on every <a> in the document).
|
|
8
|
+
import { effect } from '../store/signal.ts'
|
|
9
|
+
import { nav, type NavPhase } from './store.ts'
|
|
10
|
+
|
|
11
|
+
// The install guard lives on globalThis (like __BRUST_NAV__), NOT as a module
|
|
12
|
+
// `let`: every Bun.build island chunk inlines its own copy of this module, so a
|
|
13
|
+
// module-local flag would not stop a second chunk from installing a duplicate
|
|
14
|
+
// pair of effects (both resolve the same singleton signals → double reconcile).
|
|
15
|
+
interface ActiveNavState {
|
|
16
|
+
installed: boolean
|
|
17
|
+
disposers: Array<() => void>
|
|
18
|
+
}
|
|
19
|
+
const GA = globalThis as { __BRUST_ACTIVE_NAV__?: ActiveNavState }
|
|
20
|
+
function activeNavState(): ActiveNavState {
|
|
21
|
+
if (!GA.__BRUST_ACTIVE_NAV__) GA.__BRUST_ACTIVE_NAV__ = { installed: false, disposers: [] }
|
|
22
|
+
return GA.__BRUST_ACTIVE_NAV__
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function installActiveNav(): void {
|
|
26
|
+
const a = activeNavState()
|
|
27
|
+
if (a.installed) return
|
|
28
|
+
a.installed = true
|
|
29
|
+
// effect() runs eagerly once and re-runs whenever a signal it read changes;
|
|
30
|
+
// it returns a disposer we keep so __resetActiveNavForTest can unsubscribe.
|
|
31
|
+
a.disposers = [
|
|
32
|
+
effect(() => {
|
|
33
|
+
const path = nav.path()
|
|
34
|
+
reconcileActiveLinks(path)
|
|
35
|
+
}),
|
|
36
|
+
effect(() => {
|
|
37
|
+
const phase = nav.phase()
|
|
38
|
+
setHtmlNav(phase)
|
|
39
|
+
}),
|
|
40
|
+
]
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function setHtmlNav(phase: NavPhase): void {
|
|
44
|
+
if (typeof document === 'undefined' || !document.documentElement) return
|
|
45
|
+
// 'success' is a transient logical phase; the DOM attr returns to idle so
|
|
46
|
+
// loading indicators clear once committed.
|
|
47
|
+
document.documentElement.setAttribute('data-brust-nav', phase === 'success' ? 'idle' : phase)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function reconcileActiveLinks(currentPath: string): void {
|
|
51
|
+
if (typeof document === 'undefined') return
|
|
52
|
+
const containers = document.querySelectorAll<HTMLElement>('[data-brust-active-nav]')
|
|
53
|
+
for (const el of Array.from(containers)) {
|
|
54
|
+
const activeClass = el.dataset.brustActiveClass || 'is-active'
|
|
55
|
+
const prefix = el.dataset.brustActiveMatch === 'prefix'
|
|
56
|
+
const links = el.querySelectorAll<HTMLAnchorElement>('a[href]')
|
|
57
|
+
for (const a of Array.from(links)) {
|
|
58
|
+
const linkPath = new URL(a.href, location.href).pathname
|
|
59
|
+
const isActive = prefix
|
|
60
|
+
? currentPath === linkPath || currentPath.startsWith(`${linkPath.replace(/\/$/, '')}/`)
|
|
61
|
+
: currentPath === linkPath
|
|
62
|
+
a.classList.toggle(activeClass, isActive)
|
|
63
|
+
if (isActive) a.setAttribute('aria-current', 'page')
|
|
64
|
+
else a.removeAttribute('aria-current')
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Test-only: dispose the installed effects and clear the guard so a subsequent
|
|
70
|
+
// installActiveNav() rebinds to the fresh singleton (after __resetNavForTest).
|
|
71
|
+
export function __resetActiveNavForTest(): void {
|
|
72
|
+
const a = activeNavState()
|
|
73
|
+
for (const d of a.disposers) d()
|
|
74
|
+
GA.__BRUST_ACTIVE_NAV__ = undefined
|
|
75
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// runtime/navigation/index.ts — brustjs/navigation. React-free, DOM-free entry.
|
|
2
|
+
// (active-nav.ts uses DOM globals but imports no DOM module; it's re-exported for
|
|
3
|
+
// authors who add nav containers dynamically. bootstrap wires it automatically.)
|
|
4
|
+
export type { NavPhase, NavState, NavStore } from './store.ts'
|
|
5
|
+
export {
|
|
6
|
+
nav,
|
|
7
|
+
getNavState,
|
|
8
|
+
subscribe,
|
|
9
|
+
onBeforeNavigate,
|
|
10
|
+
onNavigate,
|
|
11
|
+
onNavigateError,
|
|
12
|
+
} from './store.ts'
|
|
13
|
+
export { installActiveNav } from './active-nav.ts'
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// React view-layer adapter for the navigation store. Lives OUTSIDE navigation/
|
|
2
|
+
// index.ts (which stays React-free + in the typecheck:treaty gate) and is reached
|
|
3
|
+
// only via brustjs/client, the browser/island entry. Uses useSyncExternalStore so
|
|
4
|
+
// a React island re-renders on every navigation transition; getNavState is
|
|
5
|
+
// version-memoized (store.ts) so the snapshot is referentially stable.
|
|
6
|
+
import { useSyncExternalStore } from 'react'
|
|
7
|
+
import { getNavState, subscribe, type NavState } from './store.ts'
|
|
8
|
+
|
|
9
|
+
/** Watch the navigation state from a React island.
|
|
10
|
+
*
|
|
11
|
+
* ```tsx
|
|
12
|
+
* import { useNav } from 'brustjs/client'
|
|
13
|
+
* function Crumb() {
|
|
14
|
+
* const { path, phase } = useNav()
|
|
15
|
+
* return <span>{phase === 'loading' ? 'Loading…' : path}</span>
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* The third arg (server snapshot) is the same getter — on the server the store
|
|
20
|
+
* holds its idle defaults (no `location`), so SSR renders the idle state and the
|
|
21
|
+
* client hydrates the real one on mount. */
|
|
22
|
+
export function useNav(): NavState {
|
|
23
|
+
return useSyncExternalStore(subscribe, getNavState, getNavState)
|
|
24
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// runtime/navigation/store.ts
|
|
2
|
+
// Client-side navigation state for brust, driven by the SPA navigator in
|
|
3
|
+
// runtime/islands/bootstrap.ts. Fully React-free AND DOM-free: __navInit takes
|
|
4
|
+
// the initial path/search as arguments (bootstrap reads location), so this module
|
|
5
|
+
// imports nothing web-API and unit-tests without a DOM. The DOM consumer (active
|
|
6
|
+
// links + html[data-brust-nav]) lives in ./active-nav.ts.
|
|
7
|
+
//
|
|
8
|
+
// The `nav` bag of signals is a singleton stashed on globalThis.__BRUST_NAV__:
|
|
9
|
+
// signals share their reactive tracker cross-chunk via Symbol.for (see
|
|
10
|
+
// store/signal.ts), but the bag OBJECT must also be shared or each Bun.build
|
|
11
|
+
// chunk would build its own — the stash gives one object identity for all chunks.
|
|
12
|
+
import { batch, signal, type Signal } from '../store/signal.ts'
|
|
13
|
+
|
|
14
|
+
export type NavPhase = 'idle' | 'loading' | 'success' | 'error'
|
|
15
|
+
|
|
16
|
+
export interface NavState {
|
|
17
|
+
path: string
|
|
18
|
+
search: string
|
|
19
|
+
phase: NavPhase
|
|
20
|
+
error: Error | null
|
|
21
|
+
from: string | null
|
|
22
|
+
to: string | null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface NavStore {
|
|
26
|
+
path: Signal<string>
|
|
27
|
+
search: Signal<string>
|
|
28
|
+
phase: Signal<NavPhase>
|
|
29
|
+
error: Signal<Error | null>
|
|
30
|
+
from: Signal<string | null>
|
|
31
|
+
to: Signal<string | null>
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type BeforeCb = (e: { from: string; to: string }) => void
|
|
35
|
+
type NavCb = (e: NavState) => void
|
|
36
|
+
type ErrorCb = (e: { to: string; error: Error }) => void
|
|
37
|
+
|
|
38
|
+
interface NavInternal extends NavStore {
|
|
39
|
+
_subs: Set<NavCb>
|
|
40
|
+
_before: Set<BeforeCb>
|
|
41
|
+
_success: Set<NavCb>
|
|
42
|
+
_error: Set<ErrorCb>
|
|
43
|
+
// version bumps once per committed transition (in emit); `_snap` memoizes the
|
|
44
|
+
// NavState for that version so getNavState() returns a referentially-stable
|
|
45
|
+
// object — required by React's useSyncExternalStore (a fresh object each call
|
|
46
|
+
// would infinite-loop "getSnapshot should be cached"). Mirrors defineStore.
|
|
47
|
+
_version: number
|
|
48
|
+
_snap: { value: NavState; version: number } | null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function createNav(): NavInternal {
|
|
52
|
+
return {
|
|
53
|
+
path: signal(''),
|
|
54
|
+
search: signal(''),
|
|
55
|
+
phase: signal<NavPhase>('idle'),
|
|
56
|
+
error: signal<Error | null>(null),
|
|
57
|
+
from: signal<string | null>(null),
|
|
58
|
+
to: signal<string | null>(null),
|
|
59
|
+
_subs: new Set(),
|
|
60
|
+
_before: new Set(),
|
|
61
|
+
_success: new Set(),
|
|
62
|
+
_error: new Set(),
|
|
63
|
+
_version: 0,
|
|
64
|
+
_snap: null,
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const G = globalThis as { __BRUST_NAV__?: NavInternal }
|
|
69
|
+
function store(): NavInternal {
|
|
70
|
+
if (!G.__BRUST_NAV__) G.__BRUST_NAV__ = createNav()
|
|
71
|
+
return G.__BRUST_NAV__
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Public reactive handle. A Proxy resolves the singleton on each property access
|
|
75
|
+
// so (a) every chunk's `nav` points at the one globalThis bag, and (b) tests that
|
|
76
|
+
// reset the singleton see the fresh signals.
|
|
77
|
+
export const nav: NavStore = new Proxy({} as NavStore, {
|
|
78
|
+
get(_t, prop: string | symbol) {
|
|
79
|
+
// Symbol keys (Symbol.toPrimitive, Symbol.for('brust.signal') brand probes,
|
|
80
|
+
// React DevTools, etc.) are never store fields — return undefined without
|
|
81
|
+
// forcing a lazy singleton init.
|
|
82
|
+
if (typeof prop !== 'string') return undefined
|
|
83
|
+
return (store() as unknown as Record<string, unknown>)[prop]
|
|
84
|
+
},
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
export function getNavState(): NavState {
|
|
88
|
+
const s = store()
|
|
89
|
+
// Return the memoized snapshot if no transition has happened since it was
|
|
90
|
+
// built (referential stability for useSyncExternalStore).
|
|
91
|
+
if (s._snap && s._snap.version === s._version) return s._snap.value
|
|
92
|
+
const value: NavState = {
|
|
93
|
+
path: s.path(),
|
|
94
|
+
search: s.search(),
|
|
95
|
+
phase: s.phase(),
|
|
96
|
+
error: s.error(),
|
|
97
|
+
from: s.from(),
|
|
98
|
+
to: s.to(),
|
|
99
|
+
}
|
|
100
|
+
s._snap = { value, version: s._version }
|
|
101
|
+
return value
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Bump the snapshot version immediately after a batch of signal writes so the
|
|
105
|
+
// NEXT getNavState() rebuilds (the lifecycle callbacks + emit must see committed
|
|
106
|
+
// state, not the stale memoized snapshot). Called once per transition, right
|
|
107
|
+
// after the batch and before any callback/getNavState read.
|
|
108
|
+
function bumpVersion(s: NavInternal): void {
|
|
109
|
+
s._version += 1
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function emit(s: NavInternal): void {
|
|
113
|
+
const snap = getNavState()
|
|
114
|
+
for (const cb of [...s._subs]) cb(snap)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function subscribe(cb: NavCb): () => void {
|
|
118
|
+
const s = store()
|
|
119
|
+
s._subs.add(cb)
|
|
120
|
+
return () => s._subs.delete(cb)
|
|
121
|
+
}
|
|
122
|
+
export function onBeforeNavigate(cb: BeforeCb): () => void {
|
|
123
|
+
const s = store()
|
|
124
|
+
s._before.add(cb)
|
|
125
|
+
return () => s._before.delete(cb)
|
|
126
|
+
}
|
|
127
|
+
export function onNavigate(cb: NavCb): () => void {
|
|
128
|
+
const s = store()
|
|
129
|
+
s._success.add(cb)
|
|
130
|
+
return () => s._success.delete(cb)
|
|
131
|
+
}
|
|
132
|
+
export function onNavigateError(cb: ErrorCb): () => void {
|
|
133
|
+
const s = store()
|
|
134
|
+
s._error.add(cb)
|
|
135
|
+
return () => s._error.delete(cb)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Each lifecycle mutator writes several signals. We wrap the writes in batch()
|
|
139
|
+
// so a consumer effect reading multiple fields (e.g. nav.path() + nav.phase())
|
|
140
|
+
// re-runs ONCE on the settled state instead of firing on each torn intermediate
|
|
141
|
+
// write. The lifecycle callbacks (_before/_success/_error) and emit() run AFTER
|
|
142
|
+
// the batch so they observe fully-committed state.
|
|
143
|
+
export function __navInit(path: string, search: string): void {
|
|
144
|
+
const s = store()
|
|
145
|
+
batch(() => {
|
|
146
|
+
s.path.set(path)
|
|
147
|
+
s.search.set(search)
|
|
148
|
+
s.phase.set('idle')
|
|
149
|
+
s.from.set(null)
|
|
150
|
+
s.to.set(null)
|
|
151
|
+
s.error.set(null)
|
|
152
|
+
})
|
|
153
|
+
bumpVersion(s)
|
|
154
|
+
emit(s)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// `toSearch` is intentionally unused during 'loading': search is part of the
|
|
158
|
+
// COMMITTED state and is written by __navCommit, not while the fetch is pending.
|
|
159
|
+
// Kept in the signature for call-site symmetry with __navCommit.
|
|
160
|
+
export function __navStart(toPath: string, _toSearch: string): void {
|
|
161
|
+
const s = store()
|
|
162
|
+
const from = s.path()
|
|
163
|
+
batch(() => {
|
|
164
|
+
s.from.set(from)
|
|
165
|
+
s.to.set(toPath)
|
|
166
|
+
s.error.set(null)
|
|
167
|
+
s.phase.set('loading')
|
|
168
|
+
})
|
|
169
|
+
bumpVersion(s)
|
|
170
|
+
for (const cb of [...s._before]) cb({ from, to: toPath })
|
|
171
|
+
emit(s)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function __navCommit(toPath: string, toSearch: string): void {
|
|
175
|
+
const s = store()
|
|
176
|
+
batch(() => {
|
|
177
|
+
s.path.set(toPath)
|
|
178
|
+
s.search.set(toSearch)
|
|
179
|
+
s.to.set(null)
|
|
180
|
+
s.error.set(null)
|
|
181
|
+
s.phase.set('success')
|
|
182
|
+
})
|
|
183
|
+
bumpVersion(s)
|
|
184
|
+
const snap = getNavState()
|
|
185
|
+
for (const cb of [...s._success]) cb(snap)
|
|
186
|
+
emit(s)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Accepts `unknown` because the only caller is bootstrap's catch block (err is
|
|
190
|
+
// `unknown` under strict TS); coerce non-Error throws (strings, DOMException)
|
|
191
|
+
// into an Error so consumers always get a stable shape.
|
|
192
|
+
export function __navError(toPath: string, error: unknown): void {
|
|
193
|
+
const s = store()
|
|
194
|
+
const err = error instanceof Error ? error : new Error(String(error))
|
|
195
|
+
batch(() => {
|
|
196
|
+
s.to.set(null)
|
|
197
|
+
s.error.set(err)
|
|
198
|
+
s.phase.set('error')
|
|
199
|
+
})
|
|
200
|
+
bumpVersion(s)
|
|
201
|
+
for (const cb of [...s._error]) cb({ to: toPath, error: err })
|
|
202
|
+
emit(s)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Test-only: drop the singleton so the next access rebuilds fresh signals.
|
|
206
|
+
export function __resetNavForTest(): void {
|
|
207
|
+
G.__BRUST_NAV__ = undefined
|
|
208
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// This module imports a Node builtin (node:async_hooks) and therefore must NOT
|
|
2
|
+
// be reachable from browser/island bundles (brustjs/client) or from the
|
|
3
|
+
// isomorphic store entry (brustjs/store). It mirrors store/server-context.ts:
|
|
4
|
+
// the server pulls it in via routes.ts, where each request is wrapped in a
|
|
5
|
+
// per-request scope. cookies.ts reaches the active scope through __scope().
|
|
6
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
7
|
+
|
|
8
|
+
interface RequestScope {
|
|
9
|
+
ctx: Map<string, unknown>
|
|
10
|
+
reqCookies: Record<string, string>
|
|
11
|
+
setCookies: string[]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const reqCtx = new AsyncLocalStorage<RequestScope>()
|
|
15
|
+
|
|
16
|
+
/** Open a per-request scope. `reqCookies` is the parsed incoming Cookie header
|
|
17
|
+
* (BrustRequest.cookies). Staged Set-Cookie strings accumulate in `setCookies`
|
|
18
|
+
* and are flushed by routes.ts onto the response headers. */
|
|
19
|
+
export function runInRequestScope<T>(reqCookies: Record<string, string>, fn: () => T): T {
|
|
20
|
+
return reqCtx.run({ ctx: new Map(), reqCookies, setCookies: [] }, fn)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Per-request scratch Map for apps building request-scoped state on top of the
|
|
24
|
+
* module-global store. Throws when called outside a request scope. */
|
|
25
|
+
export function getRequestContext(): Map<string, unknown> {
|
|
26
|
+
const s = reqCtx.getStore()
|
|
27
|
+
if (!s) throw new Error('getRequestContext() called outside a request scope')
|
|
28
|
+
return s.ctx
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Internal — the active scope (or undefined). Used by cookies.ts and the
|
|
32
|
+
* routes.ts flush. Not re-exported from the package entry. */
|
|
33
|
+
export function __scope(): RequestScope | undefined {
|
|
34
|
+
return reqCtx.getStore()
|
|
35
|
+
}
|
package/runtime/routes.ts
CHANGED
|
@@ -11,6 +11,8 @@ import { Buffer } from 'node:buffer'
|
|
|
11
11
|
import * as native from './index.js'
|
|
12
12
|
import { renderBranchStreaming } from './render/stream.ts'
|
|
13
13
|
import { runInStoreContext, collectSnapshot } from './store/server-context.ts'
|
|
14
|
+
import { runInRequestCache } from './loader-cache.ts'
|
|
15
|
+
import { runInRequestScope, __scope } from './request-context.ts'
|
|
14
16
|
import {
|
|
15
17
|
loadIslandManifest,
|
|
16
18
|
resolveIslandContext,
|
|
@@ -23,6 +25,16 @@ import type { EndpointDef } from './define-actions.ts'
|
|
|
23
25
|
import { isRespondSentinel, makeRespond } from './define-actions.ts'
|
|
24
26
|
import { validate } from './standard-schema.ts'
|
|
25
27
|
|
|
28
|
+
// S2 + B3 — unified per-request scope. The request scope (B3 cookies/context) is
|
|
29
|
+
// the OUTERMOST layer, then the request-scoped loader cache/dedupe (S2: one Map
|
|
30
|
+
// per request for `cachedFetch`/`dedupe` across loaders AND render), then the
|
|
31
|
+
// store scope (per-request store instance). `reqCookies` is the parsed incoming
|
|
32
|
+
// Cookie header so a loader's `cookies.get` reads it and `cookies.set` stages
|
|
33
|
+
// onto this scope (flushed onto response headers via flushSetCookie).
|
|
34
|
+
function runInRequestContext<T>(reqCookies: Record<string, string>, fn: () => T): T {
|
|
35
|
+
return runInRequestScope(reqCookies, () => runInRequestCache(() => runInStoreContext(fn)))
|
|
36
|
+
}
|
|
37
|
+
|
|
26
38
|
// Sub-project J — island ISR cache, backed by the Rust-side store (shared across
|
|
27
39
|
// the worker pool) via NAPI. napi-rs maps snake→camel: island_cache_get →
|
|
28
40
|
// islandCacheGet, island_cache_set → islandCacheSet. `as any` avoids depending on
|
|
@@ -725,7 +737,9 @@ export function makeRenderer(
|
|
|
725
737
|
// child loaders (one Map per request — NOT one per loader). No
|
|
726
738
|
// snapshot is collected and no <script> is injected on native paths —
|
|
727
739
|
// Spec B owns native store delivery (hard non-goal here).
|
|
728
|
-
chainResult = await
|
|
740
|
+
chainResult = await runInRequestContext(call.req?.cookies ?? {}, () =>
|
|
741
|
+
runNativeChainLoaders(flat.chain, ctx),
|
|
742
|
+
)
|
|
729
743
|
} catch (err) {
|
|
730
744
|
console.error(`[brust] loader failed for native route ${flat.fullPath}:`, err)
|
|
731
745
|
// FAST LANE: native routes take dispatch_single_chunk (no chunk
|
|
@@ -756,6 +770,13 @@ export function makeRenderer(
|
|
|
756
770
|
data = chainResult.data
|
|
757
771
|
}
|
|
758
772
|
const json = JSON.stringify(data)
|
|
773
|
+
// napiRenderJinja has no headers param — any Set-Cookie staged by a
|
|
774
|
+
// native loader is dropped on this path. Dev-warn so it's not silent.
|
|
775
|
+
if ((__scope()?.setCookies.length ?? 0) > 0 && process.env.BRUST_DEV === '1') {
|
|
776
|
+
console.warn(
|
|
777
|
+
`[brust] cookies.set in a native loader for "${flat.nativeTemplate}" is dropped — native render has no headers; use a React route to write cookies`,
|
|
778
|
+
)
|
|
779
|
+
}
|
|
759
780
|
// Sub-project J — islands + components. If this template has an enriched
|
|
760
781
|
// islands manifest or a components manifest, merge per-island context vars
|
|
761
782
|
// (island_<id>_props, plus island_<id>_html for ssr entries) and per-component
|
|
@@ -842,7 +863,7 @@ export function makeRenderer(
|
|
|
842
863
|
// or render resolves the same per-request instance. Snapshot is collected
|
|
843
864
|
// after loaders (buildRenderElement resolved) — that's where Spec A stores
|
|
844
865
|
// are seeded — and threaded into the render for <script> injection.
|
|
845
|
-
return await
|
|
866
|
+
return await runInRequestContext(call.req?.cookies ?? {}, async () => {
|
|
846
867
|
let element: ReactNode
|
|
847
868
|
let errorBoundary: ComponentType<{ error: Error }>
|
|
848
869
|
try {
|
|
@@ -869,7 +890,7 @@ export function makeRenderer(
|
|
|
869
890
|
napi,
|
|
870
891
|
errorBoundary,
|
|
871
892
|
status: verdict.status,
|
|
872
|
-
headers: verdict.headers,
|
|
893
|
+
headers: flushSetCookie(verdict.headers),
|
|
873
894
|
routePath: flat.fullPath,
|
|
874
895
|
storeSnapshot,
|
|
875
896
|
})
|
|
@@ -1047,12 +1068,19 @@ async function navigationBranch(
|
|
|
1047
1068
|
// nav payload so the client can apply it to its live stores. Native nav
|
|
1048
1069
|
// collects no snapshot (Spec B owns native store delivery).
|
|
1049
1070
|
let store: Record<string, Record<string, unknown>> | null = null
|
|
1071
|
+
// Set-Cookie staged by a React nav loader, flushed onto the nav response
|
|
1072
|
+
// below. The request scope is opened per-path (inside runInRequestContext),
|
|
1073
|
+
// so capture the flushed headers inside that scope — the emit runs after the
|
|
1074
|
+
// scope has closed. Native nav (renderNativeRouteToHtml) opens its own scope
|
|
1075
|
+
// with no headers param, so staged cookies are dropped there (same as the
|
|
1076
|
+
// full-document native render path).
|
|
1077
|
+
let navHeaders: Record<string, string> | undefined
|
|
1050
1078
|
if (flat.nativeTemplate !== undefined) {
|
|
1051
1079
|
fullHtml = await renderNativeRouteToHtml(call, flat, view, encoder, workerId)
|
|
1052
1080
|
} else {
|
|
1053
1081
|
// Wrap loader run (inside buildRenderElement) + render in one store scope so
|
|
1054
1082
|
// store reads resolve the per-request instance; collect after render.
|
|
1055
|
-
fullHtml = await
|
|
1083
|
+
fullHtml = await runInRequestContext(call.req?.cookies ?? {}, async () => {
|
|
1056
1084
|
const element = await buildRenderElement(call as any, flat, getWorkerId)
|
|
1057
1085
|
if (!element) throw new Error('render setup failed')
|
|
1058
1086
|
// Use renderToPipeableStream + onAllReady so pages with <Suspense> emit
|
|
@@ -1061,6 +1089,7 @@ async function navigationBranch(
|
|
|
1061
1089
|
// would otherwise ship "loading…" and never recover.
|
|
1062
1090
|
const html = await renderToAwaitedString(element)
|
|
1063
1091
|
store = collectSnapshot()
|
|
1092
|
+
navHeaders = flushSetCookie(undefined)
|
|
1064
1093
|
return html
|
|
1065
1094
|
})
|
|
1066
1095
|
}
|
|
@@ -1087,6 +1116,7 @@ async function navigationBranch(
|
|
|
1087
1116
|
status: 200,
|
|
1088
1117
|
contentType: 'application/json; charset=utf-8',
|
|
1089
1118
|
body,
|
|
1119
|
+
headers: navHeaders,
|
|
1090
1120
|
})
|
|
1091
1121
|
} catch (err) {
|
|
1092
1122
|
console.error('[brust] navigation render failed:', err)
|
|
@@ -1122,7 +1152,7 @@ async function renderNativeRouteToHtml(
|
|
|
1122
1152
|
// Run the WHOLE route chain's loaders top-down and merge into ONE flat context
|
|
1123
1153
|
// (child keys win), mirroring the full-render branch. One per-request store
|
|
1124
1154
|
// scope wraps the entire loop (isolation only — no snapshot / no <script>).
|
|
1125
|
-
const chainResult = await
|
|
1155
|
+
const chainResult = await runInRequestContext(call.req?.cookies ?? {}, () =>
|
|
1126
1156
|
runNativeChainLoaders(flat.chain, {
|
|
1127
1157
|
params: call.params,
|
|
1128
1158
|
path: call.path,
|
|
@@ -1397,6 +1427,42 @@ function actionErrorResponse(err: ActionError): RouteResponse {
|
|
|
1397
1427
|
}
|
|
1398
1428
|
}
|
|
1399
1429
|
|
|
1430
|
+
/** Flush any cookies staged via `cookies.set`/`cookies.delete` in the active
|
|
1431
|
+
* request scope onto the response headers.
|
|
1432
|
+
*
|
|
1433
|
+
* The Rust response-header writer stores worker-response headers in a
|
|
1434
|
+
* CASE-SENSITIVE map (no lowercase dedup), so a mix of 'Set-Cookie' /
|
|
1435
|
+
* 'set-cookie' would emit two lines. We therefore use the SINGLE canonical key
|
|
1436
|
+
* 'set-cookie' (lowercase) for ALL cookie writes.
|
|
1437
|
+
*
|
|
1438
|
+
* RouteResponse.headers is Record<string,string>, so only ONE Set-Cookie per
|
|
1439
|
+
* response is representable. If multiple were staged, only the LAST is sent
|
|
1440
|
+
* (documented limitation; dev-warn). If the handler already set a 'set-cookie'
|
|
1441
|
+
* header explicitly (respond({ headers })), the explicit value WINS and staged
|
|
1442
|
+
* cookies are dropped (dev-warn on conflict). */
|
|
1443
|
+
function flushSetCookie(
|
|
1444
|
+
headers: Record<string, string> | undefined,
|
|
1445
|
+
): Record<string, string> | undefined {
|
|
1446
|
+
const staged = __scope()?.setCookies ?? []
|
|
1447
|
+
if (staged.length === 0) return headers
|
|
1448
|
+
if (headers && 'set-cookie' in headers) {
|
|
1449
|
+
if (process.env.BRUST_DEV === '1') {
|
|
1450
|
+
console.warn(
|
|
1451
|
+
'[brust] cookies.set conflicts with an explicit set-cookie header — explicit respond() wins',
|
|
1452
|
+
)
|
|
1453
|
+
}
|
|
1454
|
+
return headers
|
|
1455
|
+
}
|
|
1456
|
+
if (staged.length > 1 && process.env.BRUST_DEV === '1') {
|
|
1457
|
+
console.warn(
|
|
1458
|
+
`[brust] ${staged.length} cookies staged but only one Set-Cookie per response is supported — only the last is sent`,
|
|
1459
|
+
)
|
|
1460
|
+
}
|
|
1461
|
+
const out = { ...(headers ?? {}) }
|
|
1462
|
+
out['set-cookie'] = staged[staged.length - 1]
|
|
1463
|
+
return out
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1400
1466
|
export async function dispatchAction(
|
|
1401
1467
|
call: Extract<RouteCall, { kind: 'action' }>,
|
|
1402
1468
|
byId: Map<string, EndpointDef>,
|
|
@@ -1487,28 +1553,33 @@ export async function dispatchAction(
|
|
|
1487
1553
|
}
|
|
1488
1554
|
}
|
|
1489
1555
|
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1556
|
+
// Open a per-request scope (OUTER) so cookies.set during middleware/handler
|
|
1557
|
+
// stage onto this request, then flush the staged Set-Cookie onto the response
|
|
1558
|
+
// headers. The cache + store scopes wrap INNER — request-scope is outermost.
|
|
1559
|
+
return await runInRequestContext(call.req.cookies ?? {}, async () => {
|
|
1560
|
+
const chain = composeChain(call.req, def.middleware, terminal)
|
|
1561
|
+
let response: RouteResponse
|
|
1562
|
+
try {
|
|
1563
|
+
response = await chain()
|
|
1564
|
+
} catch (err) {
|
|
1565
|
+
if (isActionError(err)) {
|
|
1566
|
+
response = actionErrorResponse(err)
|
|
1567
|
+
} else {
|
|
1568
|
+
console.error('[brust] action middleware uncaught:', err)
|
|
1569
|
+
response = {
|
|
1570
|
+
status: 500,
|
|
1571
|
+
body: '{"error":{"message":"internal error"}}',
|
|
1572
|
+
contentType: 'application/json; charset=utf-8',
|
|
1573
|
+
}
|
|
1503
1574
|
}
|
|
1504
1575
|
}
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
}
|
|
1576
|
+
return {
|
|
1577
|
+
status: response.status,
|
|
1578
|
+
body: response.body,
|
|
1579
|
+
contentType: response.contentType ?? 'application/json; charset=utf-8',
|
|
1580
|
+
headers: flushSetCookie(response.headers),
|
|
1581
|
+
}
|
|
1582
|
+
})
|
|
1512
1583
|
}
|
|
1513
1584
|
|
|
1514
1585
|
async function mcpBranchToResponse(
|
package/runtime/treaty.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ActionsBuilder } from './define-actions.ts'
|
|
1
|
+
import type { ActionsBuilder, EndpointEntry } from './define-actions.ts'
|
|
2
2
|
|
|
3
3
|
const METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head'])
|
|
4
4
|
|
|
@@ -15,12 +15,6 @@ export interface ClientOptions {
|
|
|
15
15
|
fetch?: typeof fetch
|
|
16
16
|
}
|
|
17
17
|
|
|
18
|
-
type FirstSegment<S extends string> = S extends `/${infer Rest}`
|
|
19
|
-
? FirstSegment<Rest>
|
|
20
|
-
: S extends `${infer T}/${infer _U}`
|
|
21
|
-
? T
|
|
22
|
-
: S
|
|
23
|
-
|
|
24
18
|
export type PermissiveProxy = {
|
|
25
19
|
(arg?: any): PermissiveProxy
|
|
26
20
|
[key: string]: PermissiveProxy
|
|
@@ -33,10 +27,53 @@ export type PermissiveProxy = {
|
|
|
33
27
|
head: (options?: any) => Promise<TreatyResponse<any, any>>
|
|
34
28
|
}
|
|
35
29
|
|
|
30
|
+
// ─── Typed Treaty<App> (B2, descoped) ───────────────────────────────────────
|
|
31
|
+
// Static paths get fully-typed methods (output + discriminated error union);
|
|
32
|
+
// any param path (`{...}`) or unknown segment falls through to PermissiveProxy.
|
|
33
|
+
// Reference shape proven by spike5 (EXIT=0).
|
|
34
|
+
|
|
35
|
+
/** Per-method client signatures for one endpoint-entry map (the `{ GET, POST, … }`
|
|
36
|
+
* object for a single path). Bodyless methods (GET/HEAD) take only options. */
|
|
37
|
+
type Methods<E> = {
|
|
38
|
+
[M in keyof E & string as Lowercase<M>]: M extends 'GET' | 'HEAD'
|
|
39
|
+
? E[M] extends EndpointEntry
|
|
40
|
+
? (o?: {
|
|
41
|
+
query?: Record<string, string>
|
|
42
|
+
headers?: Record<string, string>
|
|
43
|
+
}) => Promise<TreatyResponse<E[M]['output'], E[M]['error']>>
|
|
44
|
+
: never
|
|
45
|
+
: E[M] extends EndpointEntry
|
|
46
|
+
? (
|
|
47
|
+
b?: E[M]['input'],
|
|
48
|
+
o?: { headers?: Record<string, string> },
|
|
49
|
+
) => Promise<TreatyResponse<E[M]['output'], E[M]['error']>>
|
|
50
|
+
: never
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A path is static iff it contains no `{param}` segment. */
|
|
54
|
+
type IsStatic<K extends string> = K extends `${string}{${string}}${string}` ? false : true
|
|
55
|
+
/** Keep only the static path keys of the accumulator. */
|
|
56
|
+
type StaticAcc<Acc> = {
|
|
57
|
+
[K in keyof Acc as K extends string ? (IsStatic<K> extends true ? K : never) : never]: Acc[K]
|
|
58
|
+
}
|
|
59
|
+
/** Given a path key `K` and the accumulated prefix `P`, the next segment after `P`. */
|
|
60
|
+
type Tail<K extends string, P extends string> = K extends `${P}/${infer Rest}`
|
|
61
|
+
? Rest extends `${infer H}/${string}`
|
|
62
|
+
? H
|
|
63
|
+
: Rest
|
|
64
|
+
: never
|
|
65
|
+
/** All immediate child segments under prefix `P`. */
|
|
66
|
+
type ChildSegs<SA, P extends string> = { [K in keyof SA]: Tail<K & string, P> }[keyof SA]
|
|
67
|
+
/** The entry map for the exact path `P`, if one exists. */
|
|
68
|
+
// biome-ignore lint/complexity/noBannedTypes: `{}` is the empty-methods identity when no exact endpoint matches the prefix
|
|
69
|
+
type ExactEntry<SA, P extends string> = P extends keyof SA ? SA[P] : {}
|
|
70
|
+
/** A treaty node: methods of the exact path + child segment nodes + permissive fallback. */
|
|
71
|
+
type TNode<SA, P extends string> = Methods<ExactEntry<SA, P>> & {
|
|
72
|
+
[Seg in ChildSegs<SA, P> & string]: TNode<SA, `${P}/${Seg}`>
|
|
73
|
+
} & PermissiveProxy
|
|
74
|
+
|
|
36
75
|
export type Treaty<App> =
|
|
37
|
-
App extends ActionsBuilder<infer Acc>
|
|
38
|
-
? { [K in FirstSegment<keyof Acc & string>]: PermissiveProxy } & PermissiveProxy
|
|
39
|
-
: PermissiveProxy
|
|
76
|
+
App extends ActionsBuilder<infer Acc> ? TNode<StaticAcc<Acc>, ''> : PermissiveProxy
|
|
40
77
|
|
|
41
78
|
function resolvePrefix(opts?: ClientOptions): string {
|
|
42
79
|
if (opts?.prefix) return opts.prefix
|