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.
- package/example/pokedex/actions.ts +14 -8
- package/example/pokedex/app.css +30 -30
- package/example/pokedex/components/AddToTeamButton.tsx +8 -4
- package/example/pokedex/components/{PageLayout.tsx → AppLayout.tsx} +22 -12
- package/example/pokedex/components/ThemeToggle.tsx +51 -0
- package/example/pokedex/lib/loaders.ts +31 -8
- package/example/pokedex/lib/pokeapi.ts +7 -5
- package/example/pokedex/lib/types.ts +19 -7
- package/example/pokedex/pages/DetailPage.tsx +9 -9
- package/example/pokedex/pages/ListPage.tsx +7 -14
- package/example/pokedex/pages/TypeChart.tsx +9 -14
- package/example/pokedex/routes.tsx +21 -6
- package/package.json +9 -8
- package/runtime/action-error.ts +31 -0
- package/runtime/cli/build.ts +4 -1
- package/runtime/cli/dev.ts +4 -1
- package/runtime/cli/native-routes-emit.ts +180 -8
- package/runtime/cookies.ts +61 -0
- package/runtime/define-actions.ts +34 -7
- package/runtime/index.js +52 -52
- package/runtime/index.ts +12 -0
- package/runtime/loader-cache.ts +42 -0
- package/runtime/request-context.ts +35 -0
- package/runtime/routes.ts +239 -61
- package/runtime/treaty.ts +47 -10
- package/runtime/treaty.type-test.ts +69 -0
- package/runtime/tsconfig.typecheck.json +15 -0
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,
|
|
@@ -18,10 +20,21 @@ import {
|
|
|
18
20
|
resolveComponentContext,
|
|
19
21
|
} from './islands/native-render.ts'
|
|
20
22
|
import type { IslandCache } from './islands/native-render.ts'
|
|
23
|
+
import { isActionError, type ActionError, type ActionErrorBody } from './action-error.ts'
|
|
21
24
|
import type { EndpointDef } from './define-actions.ts'
|
|
22
25
|
import { isRespondSentinel, makeRespond } from './define-actions.ts'
|
|
23
26
|
import { validate } from './standard-schema.ts'
|
|
24
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
|
+
|
|
25
38
|
// Sub-project J — island ISR cache, backed by the Rust-side store (shared across
|
|
26
39
|
// the worker pool) via NAPI. napi-rs maps snake→camel: island_cache_get →
|
|
27
40
|
// islandCacheGet, island_cache_set → islandCacheSet. `as any` avoids depending on
|
|
@@ -180,6 +193,54 @@ export function isNativeVerdict(x: unknown): x is NativeVerdict {
|
|
|
180
193
|
)
|
|
181
194
|
}
|
|
182
195
|
|
|
196
|
+
/** Loader context passed to native chain loaders. */
|
|
197
|
+
export interface NativeLoaderCtx {
|
|
198
|
+
params: Record<string, string>
|
|
199
|
+
path: string
|
|
200
|
+
req: BrustRequest
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Result of running a native route's chain loaders top-down: either a merged
|
|
204
|
+
* flat context object (all loader results shallow-merged, child keys win), or
|
|
205
|
+
* the first verdict encountered (top-down) which short-circuits the chain. */
|
|
206
|
+
export type NativeChainResult = { data: Record<string, unknown> } | { verdict: NativeVerdict }
|
|
207
|
+
|
|
208
|
+
/** Run a native route's `flat.chain` loaders top-down (parent → leaf) and merge
|
|
209
|
+
* their results into ONE flat context object.
|
|
210
|
+
*
|
|
211
|
+
* Semantics (T3 — native <Outlet> loader chain):
|
|
212
|
+
* - Each chain node may lack a loader → skip it.
|
|
213
|
+
* - Results merge shallow: `merged = { ...merged, ...result }` — later (child)
|
|
214
|
+
* keys win over earlier (parent) keys.
|
|
215
|
+
* - First verdict wins: if any loader returns a `notFound()`/`redirect()`
|
|
216
|
+
* verdict (top-down), STOP — remaining loaders are NOT run — and return it.
|
|
217
|
+
* - `chain.length === 1` (or only the leaf has a loader) → behaves exactly as
|
|
218
|
+
* the old leaf-only read (no regression).
|
|
219
|
+
*
|
|
220
|
+
* The caller is responsible for wrapping this in a SINGLE `runInStoreContext`
|
|
221
|
+
* (one Map per request) so parent loader store writes are visible to child
|
|
222
|
+
* loaders — mirroring the React path. This helper itself does NOT open a store
|
|
223
|
+
* scope. */
|
|
224
|
+
export async function runNativeChainLoaders(
|
|
225
|
+
chain: Route[],
|
|
226
|
+
ctx: NativeLoaderCtx,
|
|
227
|
+
): Promise<NativeChainResult> {
|
|
228
|
+
let merged: Record<string, unknown> = {}
|
|
229
|
+
for (const node of chain) {
|
|
230
|
+
if (!node.loader) continue
|
|
231
|
+
// `as never` bypasses per-route Params narrowing — NativeLoaderCtx is the
|
|
232
|
+
// default-instantiated loader ctx shape ({ params, path, req }).
|
|
233
|
+
const result = await node.loader(ctx as never)
|
|
234
|
+
if (isNativeVerdict(result)) {
|
|
235
|
+
return { verdict: result }
|
|
236
|
+
}
|
|
237
|
+
if (result && typeof result === 'object') {
|
|
238
|
+
merged = { ...merged, ...(result as Record<string, unknown>) }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return { data: merged }
|
|
242
|
+
}
|
|
243
|
+
|
|
183
244
|
/** Middleware contract — Express/Koa-style chain. Receives a structured
|
|
184
245
|
* request and a `next()` that runs the rest of the chain (eventually the
|
|
185
246
|
* loader + render). Return a `RouteResponse` to short-circuit, or call
|
|
@@ -332,8 +393,12 @@ function validateRoute(r: Route, basePath: string): void {
|
|
|
332
393
|
if (r.websocket !== undefined) {
|
|
333
394
|
throw new Error(`Route ${where}: 'native: true' cannot coexist with 'websocket'`)
|
|
334
395
|
}
|
|
396
|
+
// T2 — `native: true` MAY have children, but only if the ENTIRE subtree is
|
|
397
|
+
// also native. The build synthesizes a per-leaf wrapper that composes the
|
|
398
|
+
// whole route chain into one native template; a non-native node anywhere in
|
|
399
|
+
// that chain can't be inlined (it would render via React, breaking native).
|
|
335
400
|
if (r.children !== undefined) {
|
|
336
|
-
|
|
401
|
+
assertNativeSubtree(r.children, where)
|
|
337
402
|
}
|
|
338
403
|
if (r.cache !== undefined) {
|
|
339
404
|
throw new Error(`Route ${where}: 'native: true' cannot coexist with 'cache' (deferred)`)
|
|
@@ -369,6 +434,24 @@ function validateRoute(r: Route, basePath: string): void {
|
|
|
369
434
|
}
|
|
370
435
|
}
|
|
371
436
|
|
|
437
|
+
/** T2 — recursively assert every node in a native subtree is also `native: true`.
|
|
438
|
+
* A native chain is composed into one native template at build time, so a
|
|
439
|
+
* non-native node anywhere in the subtree would have to render via React,
|
|
440
|
+
* breaking the native fast path. */
|
|
441
|
+
function assertNativeSubtree(children: Route[], where: string): void {
|
|
442
|
+
for (const child of children) {
|
|
443
|
+
if (child.native !== true) {
|
|
444
|
+
// Name the offending CHILD, not the native parent — `where` is the parent.
|
|
445
|
+
throw new Error(
|
|
446
|
+
`native route cannot mix native and non-native components in one chain (offending child: ${child.path ?? child.Component?.name ?? '(no path)'}, under: ${where})`,
|
|
447
|
+
)
|
|
448
|
+
}
|
|
449
|
+
if (child.children !== undefined) {
|
|
450
|
+
assertNativeSubtree(child.children, child.path ?? where)
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
372
455
|
/** Walk the nested route tree, emitting one FlatRoute per leaf or index node.
|
|
373
456
|
* Composes paths, middleware, errorBoundary, and cache per the rules in
|
|
374
457
|
* the design spec (S3). */
|
|
@@ -416,6 +499,17 @@ function makeFlat(chain: Route[], fullPath: string): FlatRoute {
|
|
|
416
499
|
}
|
|
417
500
|
const leaf = chain[chain.length - 1]
|
|
418
501
|
const cache = leaf.cache
|
|
502
|
+
// T2 — a native leaf demands an all-native chain (the build composes the
|
|
503
|
+
// whole chain into one native template). Reject a native leaf reached through
|
|
504
|
+
// a non-native ancestor. NOTE: this is the PRIMARY (not redundant) guard for the
|
|
505
|
+
// non-native-parent → native-child direction — `assertNativeSubtree` only runs
|
|
506
|
+
// from a native PARENT (validateRoute's `if (r.native)` block), so a non-native
|
|
507
|
+
// parent never triggers it; this check is what catches that case.
|
|
508
|
+
if (leaf.native === true && chain.some((node) => node.native !== true)) {
|
|
509
|
+
throw new Error(
|
|
510
|
+
`native route cannot mix native and non-native components in one chain (route: ${leaf.path ?? fullPath})`,
|
|
511
|
+
)
|
|
512
|
+
}
|
|
419
513
|
const nativeTemplate = leaf.native === true && leaf.Component ? leaf.Component.name : undefined
|
|
420
514
|
return { fullPath, chain, middleware, errorBoundary, cache, nativeTemplate }
|
|
421
515
|
}
|
|
@@ -632,43 +726,57 @@ export function makeRenderer(
|
|
|
632
726
|
// deferred to v2.x. If your middleware needs to mutate, use a React
|
|
633
727
|
// route for now.
|
|
634
728
|
if (flat.nativeTemplate !== undefined) {
|
|
635
|
-
let data: unknown
|
|
636
|
-
const
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
729
|
+
let data: Record<string, unknown>
|
|
730
|
+
const ctx = { params: call.params, path: call.path, req: call.req }
|
|
731
|
+
let chainResult: NativeChainResult
|
|
732
|
+
try {
|
|
733
|
+
// Run the WHOLE route chain's loaders top-down (parent → leaf) and
|
|
734
|
+
// merge into ONE flat context (child keys win), mirroring the React
|
|
735
|
+
// chain-loader path. Wrap the entire loop in a SINGLE per-request
|
|
736
|
+
// store scope so a parent loader's defineStore writes are visible to
|
|
737
|
+
// child loaders (one Map per request — NOT one per loader). No
|
|
738
|
+
// snapshot is collected and no <script> is injected on native paths —
|
|
739
|
+
// Spec B owns native store delivery (hard non-goal here).
|
|
740
|
+
chainResult = await runInRequestContext(call.req?.cookies ?? {}, () =>
|
|
741
|
+
runNativeChainLoaders(flat.chain, ctx),
|
|
742
|
+
)
|
|
743
|
+
} catch (err) {
|
|
744
|
+
console.error(`[brust] loader failed for native route ${flat.fullPath}:`, err)
|
|
745
|
+
// FAST LANE: native routes take dispatch_single_chunk (no chunk
|
|
746
|
+
// channel), so every native fallback MUST pack + return a length.
|
|
747
|
+
return packSingleChunkResponse(view, encoder, {
|
|
748
|
+
status: 500,
|
|
749
|
+
contentType: 'text/html; charset=utf-8',
|
|
750
|
+
body: 'internal error',
|
|
751
|
+
})
|
|
655
752
|
}
|
|
656
753
|
let renderStatus: number | undefined
|
|
657
|
-
if (
|
|
658
|
-
|
|
754
|
+
if ('verdict' in chainResult) {
|
|
755
|
+
// First verdict wins (top-down). Remaining loaders already skipped.
|
|
756
|
+
const verdict = chainResult.verdict
|
|
757
|
+
if (!verdict.render) {
|
|
659
758
|
// redirect — no template render; fast-lane packed response with Location.
|
|
660
759
|
return packSingleChunkResponse(view, encoder, {
|
|
661
|
-
status:
|
|
760
|
+
status: verdict.status,
|
|
662
761
|
contentType: 'text/html; charset=utf-8',
|
|
663
762
|
body: '',
|
|
664
|
-
headers:
|
|
763
|
+
headers: verdict.headers,
|
|
665
764
|
})
|
|
666
765
|
}
|
|
667
766
|
// notFound — render the route's own template, but with the verdict's status.
|
|
668
|
-
renderStatus =
|
|
669
|
-
data =
|
|
767
|
+
renderStatus = verdict.status
|
|
768
|
+
data = (verdict.data ?? {}) as Record<string, unknown>
|
|
769
|
+
} else {
|
|
770
|
+
data = chainResult.data
|
|
771
|
+
}
|
|
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
|
+
)
|
|
670
779
|
}
|
|
671
|
-
const json = JSON.stringify(data ?? {})
|
|
672
780
|
// Sub-project J — islands + components. If this template has an enriched
|
|
673
781
|
// islands manifest or a components manifest, merge per-island context vars
|
|
674
782
|
// (island_<id>_props, plus island_<id>_html for ssr entries) and per-component
|
|
@@ -755,7 +863,7 @@ export function makeRenderer(
|
|
|
755
863
|
// or render resolves the same per-request instance. Snapshot is collected
|
|
756
864
|
// after loaders (buildRenderElement resolved) — that's where Spec A stores
|
|
757
865
|
// are seeded — and threaded into the render for <script> injection.
|
|
758
|
-
return await
|
|
866
|
+
return await runInRequestContext(call.req?.cookies ?? {}, async () => {
|
|
759
867
|
let element: ReactNode
|
|
760
868
|
let errorBoundary: ComponentType<{ error: Error }>
|
|
761
869
|
try {
|
|
@@ -782,7 +890,7 @@ export function makeRenderer(
|
|
|
782
890
|
napi,
|
|
783
891
|
errorBoundary,
|
|
784
892
|
status: verdict.status,
|
|
785
|
-
headers: verdict.headers,
|
|
893
|
+
headers: flushSetCookie(verdict.headers),
|
|
786
894
|
routePath: flat.fullPath,
|
|
787
895
|
storeSnapshot,
|
|
788
896
|
})
|
|
@@ -960,12 +1068,19 @@ async function navigationBranch(
|
|
|
960
1068
|
// nav payload so the client can apply it to its live stores. Native nav
|
|
961
1069
|
// collects no snapshot (Spec B owns native store delivery).
|
|
962
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
|
|
963
1078
|
if (flat.nativeTemplate !== undefined) {
|
|
964
1079
|
fullHtml = await renderNativeRouteToHtml(call, flat, view, encoder, workerId)
|
|
965
1080
|
} else {
|
|
966
1081
|
// Wrap loader run (inside buildRenderElement) + render in one store scope so
|
|
967
1082
|
// store reads resolve the per-request instance; collect after render.
|
|
968
|
-
fullHtml = await
|
|
1083
|
+
fullHtml = await runInRequestContext(call.req?.cookies ?? {}, async () => {
|
|
969
1084
|
const element = await buildRenderElement(call as any, flat, getWorkerId)
|
|
970
1085
|
if (!element) throw new Error('render setup failed')
|
|
971
1086
|
// Use renderToPipeableStream + onAllReady so pages with <Suspense> emit
|
|
@@ -974,6 +1089,7 @@ async function navigationBranch(
|
|
|
974
1089
|
// would otherwise ship "loading…" and never recover.
|
|
975
1090
|
const html = await renderToAwaitedString(element)
|
|
976
1091
|
store = collectSnapshot()
|
|
1092
|
+
navHeaders = flushSetCookie(undefined)
|
|
977
1093
|
return html
|
|
978
1094
|
})
|
|
979
1095
|
}
|
|
@@ -1000,6 +1116,7 @@ async function navigationBranch(
|
|
|
1000
1116
|
status: 200,
|
|
1001
1117
|
contentType: 'application/json; charset=utf-8',
|
|
1002
1118
|
body,
|
|
1119
|
+
headers: navHeaders,
|
|
1003
1120
|
})
|
|
1004
1121
|
} catch (err) {
|
|
1005
1122
|
console.error('[brust] navigation render failed:', err)
|
|
@@ -1013,7 +1130,8 @@ async function navigationBranch(
|
|
|
1013
1130
|
|
|
1014
1131
|
/** Render a native (jinja) route to its full HTML document for a SPA navigation.
|
|
1015
1132
|
*
|
|
1016
|
-
* Mirrors the render-branch native path: run the
|
|
1133
|
+
* Mirrors the render-branch native path: run the whole route chain's loaders
|
|
1134
|
+
* (top-down, merged), merge island /
|
|
1017
1135
|
* component manifest context, then call the SYNC `napiRenderJinja`, which writes
|
|
1018
1136
|
* a framed `[meta_len u16 BE][meta JSON][body]` response into the SAB and returns
|
|
1019
1137
|
* its length. Here — unlike the render branch, which returns that length so Rust
|
|
@@ -1030,24 +1148,25 @@ async function renderNativeRouteToHtml(
|
|
|
1030
1148
|
workerId: bigint,
|
|
1031
1149
|
): Promise<string> {
|
|
1032
1150
|
const templateName = flat.nativeTemplate as string
|
|
1033
|
-
const leaf = flat.chain[flat.chain.length - 1]
|
|
1034
|
-
|
|
1035
|
-
let data: unknown = {}
|
|
1036
|
-
if (leaf.loader) {
|
|
1037
|
-
// Per-request store scope for native loader writes (isolation only). No
|
|
1038
|
-
// snapshot collected / no <script> injected — Spec B owns native delivery.
|
|
1039
|
-
data = await runInStoreContext(() =>
|
|
1040
|
-
leaf.loader!({ params: call.params, path: call.path, req: call.req } as any),
|
|
1041
|
-
)
|
|
1042
|
-
}
|
|
1043
1151
|
|
|
1044
|
-
|
|
1152
|
+
// Run the WHOLE route chain's loaders top-down and merge into ONE flat context
|
|
1153
|
+
// (child keys win), mirroring the full-render branch. One per-request store
|
|
1154
|
+
// scope wraps the entire loop (isolation only — no snapshot / no <script>).
|
|
1155
|
+
const chainResult = await runInRequestContext(call.req?.cookies ?? {}, () =>
|
|
1156
|
+
runNativeChainLoaders(flat.chain, {
|
|
1157
|
+
params: call.params,
|
|
1158
|
+
path: call.path,
|
|
1159
|
+
req: call.req,
|
|
1160
|
+
}),
|
|
1161
|
+
)
|
|
1162
|
+
|
|
1163
|
+
if ('verdict' in chainResult) {
|
|
1045
1164
|
// SPA nav can't emit a redirect/404 in-place; force the client's full-reload
|
|
1046
1165
|
// fallback so the document path produces the authoritative status.
|
|
1047
1166
|
throw new Error('native verdict on SPA navigation — falling back to full reload')
|
|
1048
1167
|
}
|
|
1049
1168
|
|
|
1050
|
-
let ctx =
|
|
1169
|
+
let ctx = chainResult.data
|
|
1051
1170
|
const manifest = loadIslandManifest(templateName)
|
|
1052
1171
|
const compManifest = loadComponentManifest(templateName)
|
|
1053
1172
|
if ((manifest && manifest.length > 0) || (compManifest && compManifest.length > 0)) {
|
|
@@ -1295,6 +1414,55 @@ async function decodeActionBody(
|
|
|
1295
1414
|
}
|
|
1296
1415
|
}
|
|
1297
1416
|
|
|
1417
|
+
function actionErrorResponse(err: ActionError): RouteResponse {
|
|
1418
|
+
// Flat domain-error body `{ code, message, data? }` — `code` is the client-side
|
|
1419
|
+
// discriminator (vs the framework's enveloped `{ error: { … } }`). `data` is
|
|
1420
|
+
// included only when present so the wire shape omits the key entirely otherwise.
|
|
1421
|
+
const body: ActionErrorBody = { code: err.code, message: err.message }
|
|
1422
|
+
if (err.data !== undefined) body.data = err.data
|
|
1423
|
+
return {
|
|
1424
|
+
status: err.status,
|
|
1425
|
+
body: JSON.stringify(body),
|
|
1426
|
+
contentType: 'application/json; charset=utf-8',
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
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
|
+
|
|
1298
1466
|
export async function dispatchAction(
|
|
1299
1467
|
call: Extract<RouteCall, { kind: 'action' }>,
|
|
1300
1468
|
byId: Map<string, EndpointDef>,
|
|
@@ -1374,6 +1542,7 @@ export async function dispatchAction(
|
|
|
1374
1542
|
contentType: 'application/json; charset=utf-8',
|
|
1375
1543
|
}
|
|
1376
1544
|
} catch (err) {
|
|
1545
|
+
if (isActionError(err)) return actionErrorResponse(err)
|
|
1377
1546
|
const e = err instanceof Error ? err : new Error(String(err))
|
|
1378
1547
|
console.error(`[brust] action ${def.method} ${def.path} threw:`, err)
|
|
1379
1548
|
return {
|
|
@@ -1384,24 +1553,33 @@ export async function dispatchAction(
|
|
|
1384
1553
|
}
|
|
1385
1554
|
}
|
|
1386
1555
|
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
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
|
+
}
|
|
1574
|
+
}
|
|
1397
1575
|
}
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
}
|
|
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
|
+
})
|
|
1405
1583
|
}
|
|
1406
1584
|
|
|
1407
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
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Isolated TYPE TEST for the B2 typed treaty client. Not executed — every
|
|
2
|
+
// assertion is a pure type check inside an un-called async function. Run via:
|
|
3
|
+
// bun run typecheck:treaty → tsc -p tsconfig.typecheck.json --noEmit
|
|
4
|
+
//
|
|
5
|
+
// It exercises: (1) static-path methods are fully typed (output + error union),
|
|
6
|
+
// (2) the discriminated error union narrows on `code`, (3) accessing a
|
|
7
|
+
// non-existent output field is a type error, (4) a wrong error code / field is a
|
|
8
|
+
// type error, (5) param paths stay permissive (no type error, the fallback).
|
|
9
|
+
import { z } from 'zod'
|
|
10
|
+
import { defineActions } from './define-actions.ts'
|
|
11
|
+
import { client } from './treaty.ts'
|
|
12
|
+
|
|
13
|
+
const actions = defineActions()
|
|
14
|
+
.get('/team', () => ({ team: [{ id: 1 }], max: 6 }))
|
|
15
|
+
.post('/team', ({ body }: { body: { id: number } }) => ({ team: [{ id: body.id }], max: 6 }), {
|
|
16
|
+
body: z.object({ id: z.number() }),
|
|
17
|
+
errors: {
|
|
18
|
+
TEAM_FULL: z.object({ max: z.number() }),
|
|
19
|
+
DUPLICATE: z.object({ existingId: z.number() }),
|
|
20
|
+
},
|
|
21
|
+
})
|
|
22
|
+
.delete('/team/{id}', () => ({ ok: true }))
|
|
23
|
+
|
|
24
|
+
const api = client<typeof actions>()
|
|
25
|
+
|
|
26
|
+
// Never called — purely for type checking.
|
|
27
|
+
export async function _typeTest() {
|
|
28
|
+
// (1) static POST → output typed.
|
|
29
|
+
const r = await api.team.post({ id: 5 })
|
|
30
|
+
if (r.data) {
|
|
31
|
+
const max: number = r.data.max
|
|
32
|
+
void max
|
|
33
|
+
// (3) non-existent output field → must be a type error.
|
|
34
|
+
// @ts-expect-error `nope` is not a field of the typed output
|
|
35
|
+
void r.data.nope
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// (2) error union narrows on the discriminant `code` to the SPECIFIC branch,
|
|
39
|
+
// and that branch's `data` is typed (multi-member union: TEAM_FULL | DUPLICATE).
|
|
40
|
+
if (r.error && r.error.value.code === 'TEAM_FULL') {
|
|
41
|
+
const m: number = r.error.value.data.max
|
|
42
|
+
void m
|
|
43
|
+
// (4a) non-existent error-data field → must be a type error.
|
|
44
|
+
// @ts-expect-error `min` is not a field of the TEAM_FULL error data
|
|
45
|
+
void r.error.value.data.min
|
|
46
|
+
// (4c) narrowing is per-branch: DUPLICATE's `existingId` is NOT on TEAM_FULL.
|
|
47
|
+
// @ts-expect-error `existingId` belongs to the DUPLICATE branch, not TEAM_FULL
|
|
48
|
+
void r.error.value.data.existingId
|
|
49
|
+
}
|
|
50
|
+
if (r.error && r.error.value.code === 'DUPLICATE') {
|
|
51
|
+
const e: number = r.error.value.data.existingId
|
|
52
|
+
void e
|
|
53
|
+
}
|
|
54
|
+
// (4b) comparing against an undeclared error code → must be a type error.
|
|
55
|
+
if (r.error) {
|
|
56
|
+
// @ts-expect-error 'NOPE' is not a declared error code
|
|
57
|
+
void (r.error.value.code === 'NOPE')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// GET → output typed.
|
|
61
|
+
const g = await api.team.get()
|
|
62
|
+
if (g.data) {
|
|
63
|
+
const max2: number = g.data.max
|
|
64
|
+
void max2
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// (5) param path stays permissive — MUST NOT error (locks the fallback).
|
|
68
|
+
await api.team({ id: '5' }).delete()
|
|
69
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"strict": true,
|
|
4
|
+
"skipLibCheck": true,
|
|
5
|
+
"target": "ES2022",
|
|
6
|
+
"lib": ["ES2022", "DOM"],
|
|
7
|
+
"module": "ESNext",
|
|
8
|
+
"moduleResolution": "bundler",
|
|
9
|
+
"allowImportingTsExtensions": true,
|
|
10
|
+
"noEmit": true,
|
|
11
|
+
"jsx": "react-jsx",
|
|
12
|
+
"types": []
|
|
13
|
+
},
|
|
14
|
+
"files": ["treaty.ts", "define-actions.ts", "standard-schema.ts", "treaty.type-test.ts"]
|
|
15
|
+
}
|