@barqjs/start 0.0.0-stage → 0.2.0-next.1
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/LICENSE +21 -0
- package/README.md +817 -2
- package/dist/client-BsyxVCyu.js +1554 -0
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/client-DidH0F2e.d.ts +450 -0
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.js +4 -0
- package/dist/env-Bhk_aIkx.d.ts +47 -0
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +2 -0
- package/dist/env.js +43 -0
- package/dist/env.js.map +1 -0
- package/dist/index-B4o7eyCr.d.ts +925 -0
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +6 -0
- package/dist/middleware-B-tI8QHQ.d.ts +574 -0
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.js +281 -0
- package/dist/middleware.js.map +1 -0
- package/dist/prerender.d.ts +118 -0
- package/dist/prerender.d.ts.map +1 -0
- package/dist/prerender.js +289 -0
- package/dist/prerender.js.map +1 -0
- package/dist/protocol.d.ts +56 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +25 -0
- package/dist/protocol.js.map +1 -0
- package/dist/serve.d.ts +144 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +221 -0
- package/dist/serve.js.map +1 -0
- package/dist/server-DG6jb_NA.js +1253 -0
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +159 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +1 -0
- package/dist/src-odXG7kLA.js +1151 -0
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/static-fn-CXjJi-It.js +122 -0
- package/dist/static-fn-CXjJi-It.js.map +1 -0
- package/package.json +106 -4
- package/src/client.ts +698 -0
- package/src/context.ts +699 -0
- package/src/cookies.ts +229 -0
- package/src/env.ts +86 -0
- package/src/fn-error.ts +121 -0
- package/src/frames-client.ts +1220 -0
- package/src/frames-server.ts +464 -0
- package/src/frames.ts +285 -0
- package/src/index.ts +740 -0
- package/src/live-client.ts +50 -0
- package/src/live-server.ts +292 -0
- package/src/middleware.ts +994 -0
- package/src/prerender.ts +477 -0
- package/src/protocol.ts +61 -0
- package/src/rate-limit.ts +202 -0
- package/src/serve.ts +153 -0
- package/src/server.ts +1026 -0
- package/src/session.ts +449 -0
- package/src/start-instance.ts +147 -0
- package/src/static-fn.ts +181 -0
- package/src/static.ts +302 -0
- package/src/stubs.ts +32 -0
- package/src/timing.ts +29 -0
- package/src/wire-types.ts +138 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-DG6jb_NA.js","names":["isIterable"],"sources":["../src/frames-server.ts","../src/live-server.ts","../src/server.ts"],"sourcesContent":["/**\n * The server half of frames: what a server function's component result becomes,\n * rendered two ways.\n *\n * In the document, where a route renders it with the page's own props, the\n * frame is written inline and each slot holds the browser's content rendered\n * here for the first paint. Over the wire, answering a call from the browser,\n * the region is rendered on its own and its slots are left empty for the\n * browser to fill. Both write the markup `frames.ts` describes.\n */\n\nimport type { HeadTag } from \"@barqjs/web\";\nimport { block, childScope, getOwner, runWithOwner, untrack } from \"@barqjs/core\";\nimport { SSR_HTML_BRAND, setHeadSink } from \"@barqjs/web/internal\";\nimport { setHydratable } from \"@barqjs/core/internal\";\nimport { SlotValue, esc, html, renderFrame, setServerComponent } from \"@barqjs/server\";\nimport {\n encodeWire,\n registerSerializationAdapters,\n serializationAdapters,\n} from \"@barqjs/server/codec\";\n\nimport { collectRequestCss } from \"./context.ts\";\nimport {\n FRAME,\n FRAME_CLOSE,\n FLIGHT_TYPE,\n FRAMES_BUDGET,\n FRAME_VERSION,\n type FramePayload,\n RPC_FLIGHT,\n type FrameRef,\n RPC_FRAME,\n type SlotRecord,\n bindEntries,\n frameAddress,\n frameOpen,\n isFrame,\n regionMarkup,\n slotClose,\n slotOpen,\n} from \"./frames.ts\";\n\n/** A server component: what a frame-answering handler returns. */\ntype ServerComponent = (props: Record<string, unknown>) => unknown;\n\n/** What a server function returns in place of its handler's component. */\nexport interface ServerFrame {\n (props: Record<string, unknown>): unknown;\n readonly [FRAME]: FrameRef & {\n readonly args: unknown;\n readonly component: ServerComponent;\n readonly markup: (options: { readonly session?: symbol }) => Promise<string>;\n /** Called through `live`: the page keeps it current over a connection. */\n live?: boolean;\n };\n}\n\n/**\n * How a frame crosses inside the page's own seed: by address, as a reference\n * the browser resolves to the region already on the page. Registered when a\n * frame is made and the registry does not hold it, so an application that has\n * none sends the bytes it always did.\n */\nconst FRAME_ADAPTER = {\n key: \"barq.frame\",\n test: isFrame,\n toSerializable: (frame: ServerFrame): FrameRef => ({\n id: frame[FRAME].id,\n address: frame[FRAME].address,\n }),\n fromSerializable: (ref: FrameRef): FrameRef => ref,\n};\n\nfunction registerFrameAdapter(): void {\n if (serializationAdapters().some((adapter) => adapter.key === FRAME_ADAPTER.key)) return;\n registerSerializationAdapters([FRAME_ADAPTER]);\n}\n\n/** The server function's component result, as a frame. */\nexport function serverFrame(id: string, data: unknown, component: ServerComponent): ServerFrame {\n registerFrameAdapter();\n // What the call was given, absent when it was given nothing: a function with\n // no validator refuses a `data` it did not declare, `null` included.\n const args = data === undefined ? undefined : encodeWire(data);\n const address = frameAddress(id, encodeWire(data ?? null));\n const state: ServerFrame[typeof FRAME] = {\n id,\n address,\n args,\n component,\n markup: (options) => renderMarkup(state, options),\n };\n const render = (props: Record<string, unknown>): unknown =>\n documentFrame(address, args, component, props, state.live === true);\n return Object.assign(render, { [FRAME]: state });\n}\n\n/** A value read from a slot argument: a Cell is called, anything else is the value. */\nfunction valueOf(argument: unknown): unknown {\n return typeof argument === \"function\" ? untrack(argument as () => unknown) : argument;\n}\n\n/** What a slot call returns that is never one of its properties: the markup's own names. */\nconst NOT_A_PROPERTY = new Set([\"t\", \"then\", \"toString\", \"toJSON\", \"valueOf\", \"constructor\"]);\n\ntype Record_ = { -readonly [K in keyof SlotRecord]: SlotRecord[K] };\n\n/** The page's fill for one occurrence, run once, and the scope it ran under. */\ninterface Filled {\n readonly result: unknown;\n readonly scope: ReturnType<typeof childScope>;\n}\n\n/**\n * The props a server component is rendered with: every name is a slot.\n *\n * A slot call is placed as markup, `<props.comment … />`, or read as data,\n * `props.row(args).done`, which makes it a binding slot. Which one is known\n * only once the component uses what the call returned, so the call answers\n * both: its markup when it is placed, a stand-in for each property read.\n *\n * `fills` are the page's own props, when the frame is written into the page:\n * each slot then holds what the browser would put there, for the first paint,\n * and a binding slot's stand-ins hold the fill's first values.\n */\nclass Slots {\n private readonly records: (Record_ | null)[] = [];\n readonly props: Record<string, unknown>;\n\n constructor(private readonly fills: Record<string, unknown> | null) {\n this.props = new Proxy(\n {},\n { get: (_, name) => (typeof name === \"string\" ? this.slot(name) : undefined) },\n );\n }\n\n private slot(name: string): unknown {\n if (name === \"children\") {\n const at = this.reserve();\n this.records[at] = { at, name, key: \"\" };\n return html(this.markup(at, this.fill(name, at, {}, undefined)));\n }\n return (args?: Record<string, unknown>): unknown => this.call(name, args);\n }\n\n /**\n * Taken before the region renders, so an occurrence inside it numbers after\n * this one, in document order.\n */\n private reserve(): number {\n this.records.push(null);\n return this.records.length - 1;\n }\n\n private call(name: string, args: Record<string, unknown> | undefined): unknown {\n const at = this.reserve();\n const values: Record<string, unknown> = {};\n let explicit = \"\";\n for (const [key, argument] of Object.entries(args ?? {})) {\n if (key === \"children\") continue;\n if (key === \"$key\") explicit = String(valueOf(argument));\n else values[key] = valueOf(argument);\n }\n const children = args?.children;\n const region = children === undefined ? undefined : esc(children);\n const record: Record_ = {\n at,\n name,\n key: explicit,\n ...(args === undefined ? {} : { args: encodeWire(values) }),\n ...(region === undefined ? {} : { region, hasRegion: true }),\n };\n this.records[at] = record;\n const filled = this.fill(name, at, values, region);\n let markup: string | null = null;\n const placed = (): string => {\n if (record.bind === true) throw readTwice(name);\n markup ??= this.markup(at, filled);\n return markup;\n };\n const standIns = new Map<string, SlotValue>();\n const read = (key: string): SlotValue => {\n if (markup !== null) throw readTwice(name);\n record.bind = true;\n let standIn = standIns.get(key);\n if (standIn === undefined) {\n const result = filled?.result;\n const known = typeof result === \"object\" && result !== null;\n const value = known\n ? runWithOwner(filled!.scope, () =>\n untrack(() => (result as Record<string, unknown>)[key]),\n )\n : undefined;\n standIn = new SlotValue(at, key, this.fills !== null && known, value);\n standIns.set(key, standIn);\n }\n return standIn;\n };\n return new Proxy(\n {},\n {\n get: (_, key) => {\n if (key === SSR_HTML_BRAND) return record.bind !== true;\n if (key === \"t\") return placed();\n if (key === \"toString\") return placed;\n if (typeof key === \"symbol\" || NOT_A_PROPERTY.has(key)) return undefined;\n return read(key);\n },\n ownKeys: () => {\n throw new Error(\n `[barq] A server component spread what \\`props.${name}()\\` returned. A binding slot's properties are placed one position at a time, ` +\n \"so the markup shows what the browser fills: name each one, as in `<li hidden={row.hidden}>`.\",\n );\n },\n },\n );\n }\n\n private markup(at: number, filled: Filled | null): string {\n const content = filled === null ? \"\" : runWithOwner(filled.scope, () => esc(filled.result));\n return `<!--${slotOpen(at)}-->${content}<!--${slotClose(at)}-->`;\n }\n\n /**\n * The page's fill for a slot, run once for the first paint: its content for\n * a slot that is placed, its values for one read as data. Nothing over the\n * wire, where the browser fills every slot itself.\n */\n private fill(\n name: string,\n at: number,\n values: Record<string, unknown>,\n region: string | undefined,\n ): Filled | null {\n if (this.fills === null) return null;\n const given = this.fills[name];\n // The page's own content, which the browser claims, under a scope that\n // hydrates again inside the server component's.\n const scope = childScope(getOwner(), \"branch\");\n setHydratable(scope, true);\n setServerComponent(scope, false);\n if (name === \"children\") return { result: given, scope };\n const props: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) props[key] = (): unknown => value;\n if (region !== undefined) props.children = block(() => html(regionMarkup(String(at), region)));\n // A fill that takes nothing reaches the props as the Cell it is, so reading\n // the prop is calling it.\n const result = runWithOwner(scope, () => {\n const fill = valueOf(given);\n return typeof fill === \"function\" ? (fill as ServerComponent)(props) : fill;\n });\n return result === undefined ? null : { result, scope };\n }\n\n /**\n * The records the markup still carries, keyed: a boundary resumed during the\n * render built its slots again, so only the occurrences in the final markup\n * count, and a positional key is taken in that markup's order. `inline`\n * drops each region, which the page already carries inside the slot.\n */\n final(markup: string, inline: boolean): SlotRecord[] {\n const present = new Set<number>();\n for (const found of markup.matchAll(/<!--s:(\\d+)-->/g)) present.add(Number(found[1]));\n for (const found of markup.matchAll(/ _b-[^\\s=>]+=\"([^\"]*)\"/g)) {\n for (const entry of bindEntries(found[1])) present.add(entry.at);\n }\n for (const found of markup.matchAll(/<!--_b:(\\d+):/g)) present.add(Number(found[1]));\n const ordinal = new Map<string, number>();\n const out: SlotRecord[] = [];\n for (const record of this.records) {\n if (record === null || !present.has(record.at)) continue;\n const count = ordinal.get(record.name) ?? 0;\n ordinal.set(record.name, count + 1);\n out.push({\n at: record.at,\n name: record.name,\n key: record.key === \"\" ? `${record.name}:${count}` : `$${record.key}`,\n ...(record.args === undefined ? {} : { args: record.args }),\n ...(record.bind === true\n ? { bind: true }\n : {\n ...(record.hasRegion === true ? { hasRegion: true } : {}),\n ...(inline || record.region === undefined ? {} : { region: record.region }),\n }),\n });\n }\n return out;\n }\n}\n\nfunction readTwice(name: string): Error {\n return new Error(\n `[barq] A server component both placed \\`props.${name}()\\` as markup and read it as data. ` +\n \"A slot call is one or the other: place it, `<props.\" +\n name +\n \" />`, for the browser's content, or read its properties, for a binding slot.\",\n );\n}\n\n/** Render a server component: what renders under it may read binding slots. */\nfunction asServerComponent<T>(render: () => T): T {\n const scope = childScope(getOwner(), \"branch\");\n setServerComponent(scope, true);\n return runWithOwner(scope, render);\n}\n\n/**\n * The frame written into the page, where a route renders it.\n *\n * What the component declares for the head goes to the page's head as any\n * component's does, and is recorded too, so the browser takes those tags over\n * with the frame and drops them with it.\n */\nfunction documentFrame(\n address: string,\n args: unknown,\n component: ServerComponent,\n fills: Record<string, unknown>,\n live: boolean,\n): unknown {\n const slots = new Slots(fills);\n const head: HeadTag[] = [];\n let outer: ReturnType<typeof setHeadSink> = null;\n outer = setHeadSink({\n add: (tags) => {\n head.push(...tags);\n outer?.add(tags);\n },\n module: (url) => outer?.module?.(url),\n });\n // Nothing the server component itself reads reaches the page's seed: the\n // browser never runs it, so a value seeded for it is one nothing claims.\n const scope = childScope(getOwner(), \"branch\");\n setHydratable(scope, false);\n setServerComponent(scope, true);\n let region: string;\n try {\n region = runWithOwner(scope, () => esc(component(slots.props)));\n } finally {\n setHeadSink(outer);\n }\n const payload: FramePayload = {\n v: FRAME_VERSION,\n args,\n ...(live ? { live: true } : {}),\n slots: slots.final(region, true),\n head,\n };\n return html(frameOpen(address, payload) + region + FRAME_CLOSE);\n}\n\n/**\n * The answer to a call from the browser: the region rendered on its own, its\n * slots empty. Its head carries what the region declared, the stylesheets and\n * chunks its `lazy()` modules need, and the rules `@barqjs/css` registered\n * while it rendered.\n */\nexport async function frameResponse(frame: ServerFrame): Promise<Response> {\n const answer = new Response(await frameMarkup(frame));\n answer.headers.set(\"content-type\", \"text/html; charset=utf-8\");\n answer.headers.set(\"cache-control\", \"no-store\");\n answer.headers.set(\"x-barq-rpc\", RPC_FRAME);\n return answer;\n}\n\n/**\n * A frame's markup over the wire: the region rendered on its own, its slots\n * empty. Rendered by the frame itself, so by the copy of this module that made\n * it: a host serving a built server through its own `serveBarq` answers the\n * call from another copy, whose renderer is not the one the component was\n * compiled against.\n */\nexport function frameMarkup(\n frame: ServerFrame,\n options: { readonly session?: symbol } = {},\n): Promise<string> {\n return frame[FRAME].markup(options);\n}\n\nasync function renderMarkup(\n frame: ServerFrame[typeof FRAME],\n options: { readonly session?: symbol },\n): Promise<string> {\n const { address, args, component } = frame;\n const slots = new Slots(null);\n const rendered = await renderFrame(\n () => asServerComponent(() => component(slots.props)) as never,\n {\n renderId: `f${address.slice(address.lastIndexOf(\"#\") + 1)}-`,\n session: options.session,\n },\n );\n const head = [...rendered.head];\n const css = collectRequestCss();\n if (css !== \"\") head.push({ tag: \"style\", props: { \"data-frame-css\": address }, children: css });\n const payload: FramePayload = {\n v: FRAME_VERSION,\n args,\n ...(frame.live === true ? { live: true } : {}),\n slots: slots.final(rendered.html, false),\n head,\n };\n return frameOpen(address, payload) + rendered.html + FRAME_CLOSE;\n}\n\n/** A frame the page says it has mounted, from the request's `x-barq-frames`. */\nexport interface MountedFrame {\n readonly id: string;\n readonly args: unknown;\n}\n\n/**\n * The frames a request says its page has mounted. Untrusted input like any\n * other: each one is asked for through its own function, validator and\n * middleware included, and a malformed list is no list.\n */\nexport function mountedFrames(header: string | null): MountedFrame[] {\n if (header === null || header === \"\") return [];\n let parsed: unknown;\n try {\n parsed = JSON.parse(header);\n } catch {\n return [];\n }\n if (!Array.isArray(parsed)) return [];\n const out: MountedFrame[] = [];\n for (const entry of parsed.slice(0, FRAMES_BUDGET)) {\n if (typeof entry !== \"object\" || entry === null) continue;\n const { id, args } = entry as { id?: unknown; args?: unknown };\n if (typeof id === \"string\") out.push({ id, args });\n }\n return out;\n}\n\n/**\n * A mutation's answer with the regions it changed: its value in a script, then\n * each changed frame's markup, as the page applies them. `ask` calls a mounted\n * frame's server function again with the arguments the page sent.\n */\nexport async function flightResponse(\n value: unknown,\n mounted: readonly MountedFrame[],\n invalidated: ReadonlySet<string>,\n ask: (frame: MountedFrame) => Promise<unknown>,\n): Promise<Response> {\n const seen = new Set<string>();\n let regions = \"\";\n for (const frame of mounted) {\n if (!invalidated.has(frame.id)) continue;\n const answered = await ask(frame);\n if (!isFrame(answered)) continue;\n const { address } = (answered as ServerFrame)[FRAME];\n if (seen.has(address)) continue;\n seen.add(address);\n regions += await frameMarkup(answered as ServerFrame);\n }\n const script = `<script type=\"${FLIGHT_TYPE}\">${JSON.stringify(encodeWire(value)).replaceAll(\"<\", \"\\\\u003c\")}</script>`;\n const answer = new Response(script + regions);\n answer.headers.set(\"content-type\", \"text/html; charset=utf-8\");\n answer.headers.set(\"cache-control\", \"no-store\");\n answer.headers.set(\"x-barq-rpc\", RPC_FLIGHT);\n return answer;\n}\n","/**\n * The server half of `live`: a call at the live address answered as server-sent\n * events, for as long as the answer stands.\n *\n * A frame is rendered again each time an async source it reads moves, and each\n * new rendering that differs from the last goes out as one event carrying the\n * frame's markup. Any other answer goes out a value per event. An answer whose\n * every source has ended says so with a `complete` event; a body that ends\n * without one is a connection that died, which the page's loop reconnects.\n *\n * Each event's id is the digest of what it carried. A reconnect names the last\n * one it applied in `Last-Event-ID`, and an answer that still matches it is not\n * sent again.\n */\n\nimport { SharedSources, shareSources, unshareSources } from \"@barqjs/core/internal\";\nimport { encodeWire } from \"@barqjs/server/codec\";\nimport { withoutRequestEvent } from \"@barqjs/server/storage\";\n\nimport { type ServerFrame, frameMarkup } from \"./frames-server.ts\";\nimport { isFrame } from \"./frames.ts\";\n\n/** The `x-barq-rpc` value a live answer carries. */\nexport const RPC_LIVE = \"live\";\n\n/** How often an idle connection says it is still there, against proxies that time one out. */\nconst HEARTBEAT_MS = 20_000;\n\nfunction digest(text: string): string {\n let hash = 0x811c9dc5;\n for (let at = 0; at < text.length; at++) {\n hash ^= text.charCodeAt(at);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction isIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\"\n );\n}\n\n/**\n * One event: its kind, an id, and data that is JSON and so carries no line\n * break of its own. A frame's markup is `frame`, a value the default kind.\n */\nfunction event(kind: \"frame\" | \"message\", id: string, data: string): string {\n return `${kind === \"frame\" ? \"event: frame\\n\" : \"\"}id: ${id}\\ndata: ${data}\\n\\n`;\n}\n\ntype Emit = (data: string, kind: \"frame\" | \"message\") => void;\n\n/**\n * Drive a live answer: each rendering of a frame, or each value of an\n * iterable, through `emit` until it ends, then `finish(complete)`. Returns\n * what stops it early.\n */\nfunction produce(result: unknown, emit: Emit, finish: (complete: boolean) => void): () => void {\n let ended = false;\n const stops: (() => void)[] = [];\n const end = (complete: boolean): void => {\n if (ended) return;\n ended = true;\n for (const stop of stops) stop();\n finish(complete);\n };\n\n const frames = async (frame: ServerFrame): Promise<void> => {\n const shared = new SharedSources();\n stops.push(() => shared.close());\n let rendering = false;\n let again = false;\n const render = async (): Promise<void> => {\n if (rendering) {\n again = true;\n return;\n }\n rendering = true;\n try {\n for (;;) {\n again = false;\n const session = Symbol(\"live-frame\");\n shared.begin();\n shareSources(session, shared);\n let markup: string;\n try {\n markup = await frameMarkup(frame, { session });\n } finally {\n unshareSources(session);\n }\n shared.sweep();\n if (ended) return;\n emit(JSON.stringify(markup), \"frame\");\n if (!again) break;\n }\n } catch (error) {\n console.error(\n \"[barq] A live frame failed to render, so its connection ends and the page reconnects. The error:\",\n error,\n );\n end(false);\n return;\n } finally {\n rendering = false;\n }\n if (shared.settled) end(true);\n };\n shared.onChange(() => void render());\n await render();\n };\n\n const values = async (source: AsyncIterable<unknown>): Promise<void> => {\n const iterator = source[Symbol.asyncIterator]();\n stops.push(() => void iterator.return?.());\n try {\n for (;;) {\n const step = await iterator.next();\n if (ended) return;\n if (step.done === true) break;\n emit(JSON.stringify(encodeWire(step.value)), \"message\");\n }\n end(true);\n } catch (error) {\n console.error(\n \"[barq] A live answer failed while streaming, so its connection ends and the page reconnects. The error:\",\n error,\n );\n end(false);\n }\n };\n\n if (isFrame(result)) void frames(result as ServerFrame);\n else if (isIterable(result)) void values(result);\n else {\n emit(JSON.stringify(encodeWire(result)), \"message\");\n end(true);\n }\n return () => {\n if (ended) return;\n ended = true;\n for (const stop of stops) stop();\n };\n}\n\ninterface Connection {\n readonly emit: Emit;\n readonly end: (complete: boolean) => void;\n}\n\n/**\n * One server-sent event stream. `attach` is handed the connection when the\n * stream starts and answers with what to run when it ends, either way.\n */\nfunction connection(request: Request, attach: (connection: Connection) => () => void): Response {\n const encoder = new TextEncoder();\n let controller: ReadableStreamDefaultController<Uint8Array> | null = null;\n let ended = false;\n const stops: (() => void)[] = [];\n const end = (complete: boolean): void => {\n if (ended) return;\n ended = true;\n for (const stop of stops) stop();\n if (controller === null) return;\n try {\n if (complete) controller.enqueue(encoder.encode(\"event: complete\\ndata: \\n\\n\"));\n controller.close();\n } catch {\n // The reader has gone.\n }\n };\n const send = (text: string): void => {\n if (ended || controller === null) return;\n try {\n controller.enqueue(encoder.encode(text));\n } catch {\n end(false);\n }\n };\n let sentId = request.headers.get(\"last-event-id\");\n const emit: Emit = (data, kind) => {\n const id = digest(data);\n if (id === sentId) return;\n sentId = id;\n send(event(kind, id, data));\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(given) {\n controller = given;\n const heartbeat = setInterval(() => send(\": still here\\n\\n\"), HEARTBEAT_MS);\n (heartbeat as { unref?: () => void }).unref?.();\n stops.push(() => clearInterval(heartbeat));\n const abort = (): void => end(false);\n request.signal.addEventListener(\"abort\", abort, { once: true });\n stops.push(() => request.signal.removeEventListener(\"abort\", abort));\n stops.push(attach({ emit, end }));\n },\n cancel() {\n end(false);\n },\n });\n const answer = new Response(body);\n answer.headers.set(\"content-type\", \"text/event-stream; charset=utf-8\");\n answer.headers.set(\"cache-control\", \"no-store\");\n answer.headers.set(\"x-accel-buffering\", \"no\");\n answer.headers.set(\"x-barq-rpc\", RPC_LIVE);\n return answer;\n}\n\n/** The answer to a call at the live address. */\nexport function liveResponse(result: unknown, request: Request): Response {\n return connection(request, (to) => produce(result, to.emit, to.end));\n}\n\ninterface Broadcast {\n readonly connections: Set<Connection>;\n latest: { readonly data: string; readonly kind: \"frame\" | \"message\" } | null;\n ended: boolean;\n stop: () => void;\n}\n\n/** The running shared answers, by function and arguments. */\nconst BROADCASTS = new Map<string, Broadcast>();\n\n/**\n * A joiner's own answer, closed without reading it. Only an answer that is\n * already an iterator, a generator object, holds anything: an iterable nobody\n * has asked for an iterator has started nothing, and asking would start it.\n */\nfunction closeUnread(result: unknown): void {\n const iterator = result as { return?: () => unknown } | null;\n if (typeof iterator?.return !== \"function\") return;\n try {\n const closing = iterator.return();\n if (closing instanceof Promise) void closing.catch(() => {});\n } catch {\n // Nothing read it, and nothing will.\n }\n}\n\n/**\n * The answer to a live call to a `broadcast` function: one rendering per\n * `key`, every connection asking the same thing a reader of it. The first call\n * starts it, outside its own request, and each later one joins it with the\n * latest event and closes its own answer unread. It stops when its last\n * connection goes.\n */\nexport function broadcastResponse(key: string, result: unknown, request: Request): Response {\n let shared = BROADCASTS.get(key);\n if (shared !== undefined && !shared.ended) {\n closeUnread(result);\n } else {\n const started: Broadcast = {\n connections: new Set(),\n latest: null,\n ended: false,\n stop: () => {},\n };\n BROADCASTS.set(key, started);\n started.stop = withoutRequestEvent(() =>\n produce(\n result,\n (data, kind) => {\n started.latest = { data, kind };\n for (const each of started.connections) each.emit(data, kind);\n },\n (complete) => {\n started.ended = true;\n if (BROADCASTS.get(key) === started) BROADCASTS.delete(key);\n for (const each of started.connections) each.end(complete);\n },\n ),\n );\n shared = started;\n }\n const joined = shared;\n return connection(request, (to) => {\n joined.connections.add(to);\n if (joined.latest !== null) to.emit(joined.latest.data, joined.latest.kind);\n if (joined.ended) to.end(true);\n return () => {\n joined.connections.delete(to);\n if (joined.connections.size > 0 || joined.ended) return;\n joined.ended = true;\n if (BROADCASTS.get(key) === joined) BROADCASTS.delete(key);\n joined.stop();\n };\n });\n}\n","/**\n * The request handler: one URL shape, one lookup, and the checks that run\n * before a handler body does.\n *\n * Every default here is the strict one, because the survey found the same four\n * failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,\n * publicly-mounted endpoint reached by an id enumerable from the client bundle.\n * Each is cheap to close and expensive to retrofit.\n */\n\nimport { isDev, isSafeError } from \"@barqjs/core\";\nimport {\n commitEventResponse,\n commitResponseStub,\n createRequestEvent,\n isNavigable,\n} from \"@barqjs/web/internal\";\nimport { diagnosticsEnabled, emitDiagnostic } from \"@barqjs/core/internal\";\nimport { decodeWire, encodeWire } from \"@barqjs/server/codec\";\nimport { provideRequestEvent } from \"@barqjs/server/storage\";\nimport { createBodyTooLargeError, limitBodyStream } from \"srvx/body-limit\";\n\nimport {\n type ResponseDraft,\n applyResponseDraft,\n createResponseDraft,\n draftedStatus,\n invalidatedFrames,\n setRequestMiddlewareContext,\n} from \"./context.ts\";\nimport {\n BUILD_HEADER,\n BUNDLED_BUILD,\n NOT_FOUND,\n PAYLOAD_PARAM,\n REDIRECT,\n RPC_CALLER,\n RPC_CONTEXT,\n RPC_CONTROL,\n RPC_RESPONSE,\n RPC_THROWN,\n RPC_STREAM,\n type RpcControl,\n type RpcStreamLine,\n type ServerFnInputAnswer,\n type ServerFnIssue,\n type ServerFnThrown,\n UNKNOWN_HEADER,\n} from \"./client.ts\";\nimport {\n type AnyServerFn,\n DATA_SUFFIX,\n LIVE_SUFFIX,\n type InputError,\n isInputError,\n RPC_PREFIX,\n type ServerFn,\n isServerFn,\n runRequestMiddleware,\n startOptions,\n takeSendContext,\n} from \"./index.ts\";\nimport { serverTiming } from \"./timing.ts\";\nimport {\n type ServerFrame,\n flightResponse,\n frameResponse,\n mountedFrames,\n serverFrame,\n} from \"./frames-server.ts\";\nimport { FRAMES_HEADER, installFrames, isFrame } from \"./frames.ts\";\nimport { broadcastResponse, liveResponse } from \"./live-server.ts\";\n\ninstallFrames(serverFrame as never);\n\n/**\n * id → function, and the ONLY way an id becomes callable.\n *\n * A `Map` rather than an object, because the id comes off the wire and an\n * object's prototype is reachable through one. A client-supplied name used as a\n * raw property access has shipped as a critical RCE elsewhere: asking for\n * `constructor` yields `Function`, and then arbitrary code. `Map.get`\n * has no prototype chain to walk into, so the guard is structural rather than a\n * `hasOwnProperty` call someone can later forget.\n */\ninterface Mounted {\n readonly registry: Map<string, ServerFn<unknown, unknown>>;\n /** How to mount the build's manifest, once something has said. */\n manifest: (() => Promise<unknown>) | null;\n}\n\n/**\n * ONE registry per process, whichever copy of this module asks.\n *\n * A build compiles this module INTO its server bundle, and a host that serves\n * that bundle through its own `serveBarq` has imported a second copy. Kept in\n * a module variable, each copy had a registry of its own: the bundle mounted\n * every function into one and the host answered 404 out of the other.\n */\nconst MOUNTED = ((globalThis as Record<symbol, unknown>)[Symbol.for(\"barq.start.server-fns\")] ??= {\n registry: new Map<string, ServerFn<unknown, unknown>>(),\n manifest: null,\n}) as Mounted;\n\nconst REGISTRY = MOUNTED.registry;\n\n/**\n * Say how the build's manifest is mounted, so a call can ask for it.\n *\n * The server entry imports the manifest when it first renders a page, which is\n * late for a function called before any page has been asked for: a server that\n * has just started and a browser tab that was already open. The id it names\n * was in no registry yet, and the answer was a 404 for a function that exists.\n */\nexport function mountOnDemand(manifest: () => Promise<unknown>): void {\n MOUNTED.manifest = manifest;\n}\n\n/**\n * Mount a server function. The compiler emits one call per EXPORTED server\n * function in a module compiled for the server.\n *\n * Export-ness is what decides reachability, which is SvelteKit's rule and the\n * only genuine notion of an internal server function in the survey: a\n * non-exported one is never registered, so it has no id and no endpoint, and is\n * still callable from its siblings.\n */\nexport function mount(id: string, fn: AnyServerFn): void {\n if (!isServerFn(fn))\n throw new TypeError(\n `[barq] \\`mount(${JSON.stringify(id)}, fn)\\` was given something that is not a server function, so there is nothing to answer calls with. Pass a function built with \\`createServerFn().handler(...)\\`.`,\n );\n if (id === \"\")\n throw new TypeError(\n \"[barq] `mount(id, fn)` was given an empty `id`, so no request could reach the function. Pass a non-empty string that is unique in the application.\",\n );\n // RE-MOUNTING AN ID REPLACES, and refusing it was a dev-server bug rather\n // than a safeguard. The generated manifest is invalidated whenever a\n // server-function module is transformed and re-imported on the next request,\n // while this registry lives in a module nothing invalidates — so the second\n // evaluation was refusing ids the first had legitimately claimed, and every\n // page answered 500 after the first edit.\n //\n // Nothing is lost by replacing: an id is `<root-relative file>#<export>`, so\n // two DISTINCT functions can only collide if two paths normalise to one, and\n // the manifest generator refuses that where it can see the whole set at once.\n // Here there is no second set to compare against — only the same module,\n // again, newer.\n // Stamped rather than read. The compiler leaves the SERVER half of a module\n // alone — it is the module, compiled — so the builder has no id of its own;\n // the id lives in the manifest the build generates, and mounting is where the\n // two meet. `formAttr` reads it back off the function to write a form's\n // action, so a function that is mounted has a URL and one that is not has\n // neither an id nor an endpoint.\n fn.meta.id = id;\n REGISTRY.set(id, fn);\n}\n\n/** The mounted surface, for the build to record and a reviewer to read. */\nexport function mounted(): string[] {\n return [...REGISTRY.keys()].toSorted();\n}\n\n/**\n * The function mounted at an id, or `undefined`.\n *\n * Exported for the BUILD's chain check, which has to ask each reachable id what\n * middleware it actually carries. It reads the registry inside whichever bundle\n * it is called from, which is why the check runs through the server entry\n * rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`\n * INTO the ssr bundle, so a plugin importing this module would be asking a\n * second, empty registry.\n */\nexport function mountedFn(id: string): ServerFn<unknown, unknown> | undefined {\n return REGISTRY.get(id);\n}\n\n/** Test seam. Not for application use. */\nexport function unmountAll(): void {\n REGISTRY.clear();\n MOUNTED.manifest = null;\n}\n\nexport interface HandlerOptions {\n /**\n * Origins allowed to call, beyond the request's own. Same-origin is always\n * allowed; this widens it.\n */\n allowedOrigins?: readonly string[];\n /**\n * The largest body a call may send, in bytes. 1 MiB when omitted.\n *\n * Enforced on the bytes as they are read, and answered with a 413. The body\n * is parsed BEFORE the chain runs, so this is the only thing standing between\n * a caller no middleware has seen yet and the server's memory.\n *\n * srvx's `maxRequestBodySize` is the same idea for the whole server and has\n * no default; this one is for the server-function channel alone, so it holds\n * under a handler that srvx is not in front of.\n */\n maxBodySize?: number;\n /**\n * The largest FORM body, multipart or urlencoded. `maxBodySize` when omitted.\n *\n * Apart from it because a file upload is the one body that legitimately\n * outgrows the default, and raising `maxBodySize` to admit one would widen\n * the value channel by the same amount for no caller that needs it. A form is\n * parsed whole into memory, so this is what one request can make the server\n * hold.\n */\n maxFormSize?: number;\n /**\n * What a failed call may tell its caller about the error, beyond its status.\n *\n * Only the development server passes it, so a production server answers a\n * handler's failure with the status and a fixed line and nothing of the\n * error: its message can name a table, a column or a path. In development the\n * caller is the developer, and the error's name, message and stack (mapped\n * to source by the dev server) are what make the failure debuggable from the\n * browser.\n */\n revealError?: (error: unknown) => ServerFnThrown;\n /**\n * The build this server is, such as a commit hash. A call whose\n * `x-barq-build` header names another build is answered `409` and its\n * function does not run, which catches the skew an unknown id cannot: a\n * function whose id survived a deploy while its arguments or result changed\n * shape. The build `@barqjs/vite` stamped the bundle with when omitted, so\n * a built application needs nothing here; a call with no header is not\n * checked.\n */\n buildId?: string;\n /**\n * Whether some route in this application can reach this id.\n *\n * The narrow half of the route-action manifest. Export-ness already decides\n * what is MOUNTED, and that is deliberately generous — a server function\n * exported for a sibling to import is mounted whether or not any page calls\n * it. Next.js concedes the consequence in its own release notes: \"Even if a\n * Server Action or utility function is not imported elsewhere in your code,\n * it's still a publicly accessible HTTP endpoint.\"\n *\n * This closes that: an id no route reaches answers the 404 an unknown id\n * already answers, so the two are indistinguishable from outside.\n *\n * It takes NO route from the caller, deliberately. A client-supplied route\n * selecting a policy lets the caller pick the weakest one that reaches the\n * action, and this file's own rule says why that is not allowed — values\n * derived from the request are fine to navigate to and never fine to\n * authorize with. Which CHAIN runs is decided at build time by\n * `@barqjs/router`, not here and not per request.\n */\n reachable?: (id: string) => boolean;\n}\n\n/**\n * Is this request allowed to invoke a server function?\n *\n * `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback\n * is Waku's post-CVE shape and it is the strictest default found: `Origin` is\n * legitimately absent on some same-origin requests and on non-browser clients,\n * while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged\n * from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.\n */\nexport function originAllowed(request: Request, options?: HandlerOptions): boolean {\n const origin = request.headers.get(\"origin\");\n if (origin !== null) {\n // A sandboxed iframe sends the literal string, so it is refused rather than\n // read as absent and fallen through.\n if (origin === \"null\") return false;\n if (origin === new URL(request.url).origin) return true;\n return options?.allowedOrigins?.includes(origin) ?? false;\n }\n const site = request.headers.get(\"sec-fetch-site\");\n if (site === null) return false;\n return site === \"same-origin\" || site === \"none\";\n}\n\n/** Methods that cannot change state, so CSRF does not apply to them. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/**\n * Is this a request a BROWSER made from another origin?\n *\n * A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole\n * design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be\n * called by this application's own pages — so a request with no origin signal at\n * all is refused there, because there is no legitimate caller that omits one.\n *\n * A route handler is the opposite: an API route exists so that something OTHER\n * than a browser can call it. A Stripe webhook, a GitHub delivery, a cron\n * hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and\n * refusing on their absence would refuse the main reason API routes exist.\n *\n * So this answers the narrower question, and the narrower question is the one\n * CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER\n * with the victim's cookies attached, and a browser making a cross-origin\n * state-changing request always says so — `Origin` on any cross-origin POST\n * since forever, `Sec-Fetch-Site` on everything in every current browser. So:\n * refuse when a signal is present and says cross-origin; allow when there is no\n * signal, because then it is not a browser and cannot be a forgery.\n *\n * `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than\n * read as absent, which is a bypass that has shipped.\n */\nexport function crossOriginRefused(request: Request, allowedOrigins?: readonly string[]): boolean {\n if (SAFE_METHODS.has(request.method.toUpperCase())) return false;\n\n const origin = request.headers.get(\"origin\");\n if (origin !== null) {\n if (origin === \"null\") return true;\n if (origin === new URL(request.url).origin) return false;\n return !(allowedOrigins?.includes(origin) ?? false);\n }\n\n const site = request.headers.get(\"sec-fetch-site\");\n // No signal at all: not a browser, so not a forgery.\n if (site === null) return false;\n return site !== \"same-origin\" && site !== \"none\";\n}\n\n/** The labelled 404: the client reports it as skew rather than as a failed call. */\nfunction unknownFunction(): Response {\n return new Response(\"not found\", { status: 404, headers: { [UNKNOWN_HEADER]: \"true\" } });\n}\n\n/**\n * Handle one server-function request, or return null if the URL is not one.\n *\n * Returning null rather than a 404 is what lets this compose as middleware in\n * front of a page handler.\n */\nexport async function handleServerFn(\n request: Request,\n options?: HandlerOptions,\n): Promise<Response | null> {\n const url = new URL(request.url);\n if (!url.pathname.startsWith(RPC_PREFIX)) return null;\n\n // A mutation must not be reachable by navigation. RedwoodSDK shipped server\n // functions invocable over GET, which made a plain link a one-click mutation\n // carrying SameSite=Lax cookies. A GET reaches only a function that asked for\n // it, and only with the header no link can send; both are checked below.\n const method = request.method;\n if (method !== \"POST\" && method !== \"GET\") {\n return new Response(\"method not allowed\", { status: 405, headers: { allow: \"GET, POST\" } });\n }\n if (!originAllowed(request, options)) return new Response(\"forbidden\", { status: 403 });\n\n // The URL decides the shape, so a form and an RPC call cannot be confused for\n // one another by a header either of them can set.\n const path = url.pathname.slice(RPC_PREFIX.length);\n // The live address answers what the data address does, framed as events for\n // as long as the answer stands. Only `live`'s loop calls it.\n const isLive = path.endsWith(LIVE_SUFFIX);\n const isData = isLive || path.endsWith(DATA_SUFFIX);\n let id: string;\n try {\n id = decodeURIComponent(\n isLive\n ? path.slice(0, -LIVE_SUFFIX.length)\n : isData\n ? path.slice(0, -DATA_SUFFIX.length)\n : path,\n );\n } catch {\n // Not percent-encoding at all, so it names nothing.\n return new Response(\"bad request\", { status: 400 });\n }\n\n let fn = REGISTRY.get(id);\n if (fn === undefined && MOUNTED.manifest !== null) {\n await MOUNTED.manifest();\n fn = REGISTRY.get(id);\n }\n if (fn === undefined) return unknownFunction();\n // Same answer as an unknown id, so a caller cannot tell a function that\n // exists but is unrouted from one that does not exist.\n if (options?.reachable?.(id) === false) return unknownFunction();\n const build = options?.buildId ?? BUNDLED_BUILD;\n const callerBuild = request.headers.get(BUILD_HEADER);\n if (build !== undefined && callerBuild !== null && callerBuild !== build) {\n return new Response(`call from build ${JSON.stringify(callerBuild)} refused`, {\n status: 409,\n headers: { [UNKNOWN_HEADER]: \"true\", [BUILD_HEADER]: build, \"cache-control\": \"no-store\" },\n });\n }\n // The function's own method, and only on the channel that can carry it: a\n // form is a POST, so a GET function has the data channel alone.\n const expected = fn.meta.method ?? \"POST\";\n if (method !== expected) {\n return new Response(\"method not allowed\", { status: 405, headers: { allow: expected } });\n }\n if (method === \"GET\") {\n if (!isData) return new Response(\"not found\", { status: 404 });\n if (request.headers.get(RPC_CALLER) === null) return new Response(\"forbidden\", { status: 403 });\n }\n\n const bodyLimit = options?.maxBodySize ?? DEFAULT_BODY_LIMIT;\n const target = fn;\n // The draft the handler writes to through `setCookie` / `setResponseHeader`,\n // held HERE because the response is built after the handler has returned.\n const draft = createResponseDraft();\n\n /**\n * The call itself: read the body, run the function, build the answer. The\n * innermost step of the request middleware chain, so a global middleware\n * that refuses does so before a byte of the payload has been parsed.\n */\n const respond = async (): Promise<Response> => {\n let input: unknown;\n let clientContext: Record<string, unknown> | undefined;\n // The arguments as they arrived: a broadcast's share key. Encoded rather\n // than decoded, because two values the codec tells apart can decode to the\n // same JSON; encodings that differ for equal values only cost sharing.\n let encoded: string | undefined;\n if (isData && (method === \"GET\" || !isFormBody(request))) {\n try {\n if (method === \"POST\") encoded = await capped(request, bodyLimit).text();\n else encoded = url.searchParams.get(PAYLOAD_PARAM) ?? \"\";\n const body = (method === \"GET\" ? queryPayload(url, bodyLimit) : JSON.parse(encoded)) as {\n input?: unknown;\n context?: unknown;\n };\n input = body?.input === undefined ? undefined : decodeWire(body.input);\n // WHAT THE CLIENT HALVES SENT, and it is UNTRUSTED — a caller writes this\n // body by hand as readily as the stub does. It reaches a server half as\n // `clientContext` and is never merged into `context`; `serverRpc` says\n // what merging it would let through. Spread, so a body that put a string\n // or a list here still hands the chain an object.\n clientContext =\n body?.context === undefined ? undefined : { ...decodeWire<object>(body.context) };\n } catch (error) {\n return unreadable(error);\n }\n } else {\n try {\n input = await capped(request, options?.maxFormSize ?? bodyLimit).formData();\n } catch (error) {\n return unreadable(error);\n }\n }\n\n try {\n // `{ data }` on the value channel; a bare `FormData` on the form one, which\n // is the shape `<form action={fn}>` hands the function on the enhanced path\n // — so a handler sees the same input type whether or not JS ran.\n // `sendContext` is taken INSIDE the request context, because that is where\n // the function's chain left it: each request has its own, so two calls that\n // settle together cannot read one another's.\n const result = await (input instanceof FormData\n ? target(input)\n : (target as (o: unknown, c?: Record<string, unknown>) => Promise<unknown>)(\n { data: input },\n clientContext,\n ));\n const sendContext = takeSendContext();\n if (isLive) {\n if (result instanceof Response) return applyResponseDraft(result, draft);\n if (target.meta.broadcast === true && encoded !== undefined) {\n return applyResponseDraft(\n broadcastResponse(`${id}\\0${method}\\0${encoded}`, result, request),\n draft,\n );\n }\n return applyResponseDraft(liveResponse(result, request), draft);\n }\n // A RETURNED RESPONSE IS HONOURED ON BOTH CHANNELS, and it did not used to\n // be: the value channel handed it to `encodeWire`, which answered\n // `Seroval Error (step: 1)` and a 500 with nothing in it. So a function that\n // set a cookie by returning a response worked with JS disabled and crashed\n // with JS enabled — the one divergence the form path exists to prevent.\n if (result instanceof Response) {\n // The data channel's client reads every other answer as a wire value, so\n // this one says it is not. A browser following a form needs no telling.\n if (isData) draft.headers.set(RPC_CONTROL, RPC_RESPONSE);\n return applyResponseDraft(result, draft);\n }\n // A component is a frame: the region it renders, for the page to apply.\n // A browser following a form has no page to apply it to.\n if (isFrame(result)) {\n if (isData) return applyResponseDraft(await frameResponse(result as ServerFrame), draft);\n return applyResponseDraft(seeOther(request), draft);\n }\n if (isIterable(result)) {\n if (isData) {\n return applyResponseDraft(streamed(result, sendContext, id, revealerOf(options)), draft);\n }\n // A browser following a form has nothing to read a stream with, so the\n // function is told nobody is listening and the form goes back.\n void result[Symbol.asyncIterator]().return?.();\n return applyResponseDraft(seeOther(request), draft);\n }\n if (isData) {\n // `draftedStatus` here and NOT inside `applyResponseDraft`, because the\n // two answer different questions: this response is the framework's to\n // build, so `setResponseStatus(201)` decides it — where a response the\n // handler RETURNED has already decided for itself.\n const answer = draftedStatus(draft, 200);\n // SINGLE FLIGHT: a mutation that said which frames it changed answers\n // with them, rendered again for the arguments the page has them\n // mounted with, beside its value. Each is asked for through its own\n // function, so its validator and its middleware decide as for a call.\n const mountedHere = mountedFrames(request.headers.get(FRAMES_HEADER));\n const changed = invalidatedFrames();\n if (mountedHere.length > 0 && changed.size > 0) {\n const flight = await flightResponse(\n Object.keys(sendContext).length === 0 ? result : { result, context: sendContext },\n mountedHere,\n changed,\n async (frame) => {\n const asked = REGISTRY.get(frame.id);\n if (asked === undefined || options?.reachable?.(frame.id) === false) return undefined;\n try {\n return await (asked as (o: unknown) => Promise<unknown>)({\n data: frame.args === undefined ? undefined : decodeWire(frame.args),\n });\n } catch (error) {\n console.error(\n `[barq] The frame of ${JSON.stringify(frame.id)} could not be rendered again for the mutation ${JSON.stringify(id)}, so its answer leaves it out. The error:`,\n error,\n );\n return undefined;\n }\n },\n );\n if (Object.keys(sendContext).length > 0) flight.headers.set(RPC_CONTEXT, \"1\");\n return applyResponseDraft(\n new Response(flight.body, { ...answer, headers: flight.headers }),\n draft,\n );\n }\n // The ordinary shape is the RESULT and nothing around it. A chain that\n // sent something back gets the envelope instead, flagged by a header, so\n // a call that sends nothing pays neither the wrapper nor a second parse.\n if (Object.keys(sendContext).length === 0) {\n return applyResponseDraft(Response.json(encodeWire(result), answer), draft);\n }\n return applyResponseDraft(\n Response.json(encodeWire({ result, context: sendContext }), {\n ...answer,\n headers: { [RPC_CONTEXT]: \"1\" },\n }),\n draft,\n );\n }\n // Otherwise the browser goes back where it came from, which is what makes\n // the no-JS path a round trip rather than a dead end.\n return applyResponseDraft(seeOther(request), draft);\n } catch (error) {\n // A middleware rejects by throwing a Response — `throw new Response(\"\", {\n // status: 401 })` — and it is returned as it stands.\n // The draft rides an error out as well. A middleware that rotated a session\n // cookie and THEN refused must not lose the rotation — the browser would\n // keep replaying a token the server has already retired.\n if (error instanceof Response) return thrownAnswer(error, isData, draft);\n // `throw redirect(...)` and `throw notFound()` are ANSWERS, and a server\n // function is entitled to both — a handler that finds the session expired\n // redirects to the login page, and one asked for a row that is gone says\n // so. Left to the catch-all below they would be a 500 with nothing in it,\n // and the two most ordinary control-flow throws in the framework would be\n // the two it could not carry.\n const control = controlOf(error);\n if (control !== null) {\n return applyResponseDraft(\n controlResponse(control, isData, (error as { headers?: unknown }).headers),\n draft,\n );\n }\n // A validation failure is the caller's fault and says so, with what was\n // wrong with each field: the issues describe the caller's own input, so a\n // form can show them. Anything else is reported without a body: a\n // handler's message can name a table, a column or a path, and none of that\n // is the caller's business.\n if (isInputError(error)) {\n return applyResponseDraft(\n isData\n ? Response.json(inputAnswer(error), { status: 400 })\n : new Response(\"invalid input\", { status: 400 }),\n draft,\n );\n }\n return applyResponseDraft(failed(id, error, isData, options, \"threw\"), draft);\n }\n };\n\n // AFTER the method, the origin and the id have been checked, never before: a\n // forged or mistyped call is refused above without a middleware having run\n // for it, so it costs nothing and reaches nothing.\n const context: Record<string, unknown> = {};\n const timing = isDev ? serverTiming() : undefined;\n const event = createRequestEvent(request, { response: draft });\n try {\n const response = await provideRequestEvent(event, () => {\n setRequestMiddlewareContext(context);\n return runRequestMiddleware(\n startOptions().requestMiddleware ?? [],\n { request, pathname: url.pathname, handlerType: \"serverFn\", context },\n respond,\n );\n });\n if (timing !== undefined) {\n timing.phase(\"barq-fn\", id);\n draft.headers.append(\"server-timing\", timing.header());\n }\n return commitEventResponse(response, event);\n } catch (error) {\n // A request middleware refuses the way a function's own does.\n if (error instanceof Response)\n return commitEventResponse(thrownAnswer(error, isData, draft), event);\n return commitEventResponse(failed(id, error, isData, options, \"middleware\"), event);\n } finally {\n commitResponseStub(draft, { event });\n }\n}\n\n/**\n * The 400 a refused input answers with: the refusal and each issue with the\n * path to the field it is about.\n */\nfunction inputAnswer(error: InputError): ServerFnInputAnswer {\n const issues = (error as { issues?: ReadonlyArray<unknown> }).issues ?? [];\n return {\n error: \"invalid input\",\n message: error.message,\n issues: issues.map((issue): ServerFnIssue => {\n const { message, path } = (issue ?? {}) as { message?: unknown; path?: unknown };\n const keys = Array.isArray(path)\n ? path.map((segment: unknown) => {\n const key =\n typeof segment === \"object\" && segment !== null && \"key\" in segment\n ? segment.key\n : segment;\n return typeof key === \"number\" ? key : String(key);\n })\n : [];\n return keys.length === 0\n ? { message: String(message) }\n : { message: String(message), path: keys };\n }),\n };\n}\n\n/**\n * What a failed call may tell its caller: everything the development server\n * asks for, and in production only an error the application branded with\n * `markSafeError`, by its name and message.\n */\nfunction revealerOf(\n options: HandlerOptions | undefined,\n): (error: unknown) => ServerFnThrown | undefined {\n const reveal = options?.revealError;\n return (error) => {\n if (reveal !== undefined) return reveal(error);\n if (!(error instanceof Error) || !isSafeError(error)) return undefined;\n return { name: error.name, message: error.message };\n };\n}\n\n/**\n * A call that failed on the server: logged there, reported on the diagnostics\n * channel, and answered 500. The caller learns what was thrown only when the\n * development server asked for it.\n */\nfunction failed(\n id: string,\n error: unknown,\n isData: boolean,\n options: HandlerOptions | undefined,\n where: \"threw\" | \"middleware\",\n): Response {\n const thrown = revealerOf(options)(error);\n const happened =\n where === \"threw\"\n ? `The server function ${JSON.stringify(id)} threw`\n : `A request middleware threw before the server function ${JSON.stringify(id)} ran`;\n if (diagnosticsEnabled()) reportFailure(id, error, happened);\n console.error(\n `[barq] ${happened}, so the call answered 500${thrown === undefined ? \" without the error's text\" : \"\"}. The error:`,\n error,\n );\n if (thrown === undefined) return new Response(\"internal server error\", { status: 500 });\n return isData\n ? Response.json({ error: \"internal server error\", thrown }, { status: 500 })\n : new Response(\n `internal server error\\n\\n${thrown.stack ?? `${thrown.name}: ${thrown.message}`}`,\n {\n status: 500,\n },\n );\n}\n\nfunction reportFailure(id: string, error: unknown, happened: string): void {\n const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);\n emitDiagnostic(\n {\n code: \"SERVER_FUNCTION_FAILED\",\n kind: \"ssr\",\n severity: \"error\",\n message:\n `${happened}: \\`${text}\\`. The caller received a 500. Fix the throw at the top of the ` +\n \"stack, or throw a `Response`, `redirect()` or `notFound()` to answer the caller on purpose.\",\n data: { id, error },\n },\n null,\n );\n}\n\n/**\n * A `Response` the chain or the handler threw, as the answer. The data\n * channel's client rejects the call with it, so the header says it was thrown\n * rather than returned; a browser following a form needs no telling.\n */\nfunction thrownAnswer(error: Response, isData: boolean, draft: ResponseDraft): Response {\n if (isData) draft.headers.set(RPC_CONTROL, RPC_THROWN);\n return applyResponseDraft(error, draft);\n}\n\n/**\n * Read a thrown value as a control answer, by BRAND rather than by class.\n *\n * The classes are `@barqjs/router`'s and this package cannot import them; see\n * {@link REDIRECT}. A brand check is also what lets the same code recognise a\n * redirect the router threw and one `@barqjs/start/client` rebuilt off the\n * wire, which matters when a server function calls another one.\n */\nfunction controlOf(error: unknown): RpcControl | null {\n if (typeof error !== \"object\" || error === null) return null;\n const branded = error as Record<symbol, unknown> & {\n to?: unknown;\n status?: unknown;\n options?: unknown;\n data?: unknown;\n routeId?: unknown;\n };\n if (branded[REDIRECT] === true) {\n // The shape is checked rather than trusted: the brand says what this claims\n // to be, and a `to` that is not a string would put `undefined` in a\n // `Location` header.\n if (typeof branded.to !== \"string\") return null;\n const status = typeof branded.status === \"number\" ? branded.status : 302;\n const options = describedNavigation(branded.options);\n return {\n kind: \"redirect\",\n to: branded.to,\n status,\n ...(options === undefined ? {} : { options: encodeWire(options) }),\n };\n }\n if (branded[NOT_FOUND] === true) {\n const message = (error as { message?: unknown }).message;\n return {\n kind: \"not-found\",\n message: typeof message === \"string\" ? message : \"not found\",\n ...(branded.data === undefined ? {} : { data: encodeWire(branded.data) }),\n ...(typeof branded.routeId === \"string\" ? { routeId: branded.routeId } : {}),\n };\n }\n return null;\n}\n\n/** The parts of a navigation that are values, and so can be sent. */\nconst NAVIGATION = [\"to\", \"from\", \"params\", \"search\", \"hash\", \"replace\", \"reloadDocument\", \"href\"];\n\n/**\n * The navigation an options-form redirect described, as far as it can cross.\n *\n * A function among them cannot: `search: (current) => ...` is asked about a\n * location only the browser has. A redirect holding one is sent as its resolved\n * target alone, which is what every redirect was sent as before this existed.\n * `statusCode` and `headers` are the answer rather than the navigation, and\n * travel as the status and on the response.\n */\nfunction describedNavigation(described: unknown): Record<string, unknown> | undefined {\n if (typeof described !== \"object\" || described === null) return undefined;\n const given = described as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const name of NAVIGATION) {\n const value = given[name];\n if (value === undefined) continue;\n if (typeof value === \"function\") return undefined;\n out[name] = value;\n }\n if (typeof given.statusCode === \"number\") out.statusCode = given.statusCode;\n return out;\n}\n\n/**\n * A control answer, on whichever channel asked.\n *\n * THE TWO CHANNELS DIVERGE HERE ON PURPOSE, because their clients are different\n * programs. The form channel's client is a BROWSER following the response\n * itself, so a redirect has to be a real 3xx with a `Location`. The data\n * channel's client is `clientRpc`, and a real 3xx there would be FOLLOWED by\n * `fetch` — the caller would receive the target page's HTML instead of a\n * navigation. So the data channel answers 200 and describes the redirect in the\n * body, and the client re-throws it for the router to act on. That is a soft\n * navigation rather than a document load, which is both correct and faster;\n * TanStack returns the raw 3xx and the fetch follows it.\n *\n * `not-found` is a 404 on both, because 404 is the honest status and no client\n * follows one.\n *\n * `extra` is the thrown value's own `headers`, which are the response's on\n * either channel: a redirect that signs a visitor out carries the cookie that\n * does it.\n */\nfunction controlResponse(control: RpcControl, isData: boolean, extra?: unknown): Response {\n const headers = answerHeaders(extra);\n if (control.kind === \"not-found\") {\n if (!isData) return new Response(control.message, { status: 404, headers });\n headers.set(RPC_CONTROL, control.kind);\n return Response.json(control, { status: 404, headers });\n }\n if (!isNavigable(control.to)) {\n reportRefusedRedirect(control.to);\n return new Response(\"bad redirect\", { status: 500 });\n }\n if (isData) {\n headers.set(RPC_CONTROL, control.kind);\n return Response.json(control, { status: 200, headers });\n }\n // 303 unless the handler asked for something else, so the browser re-issues\n // as GET and a reload does not repost — the same reason `seeOther` below is\n // 303. A handler that set an explicit status gets the one it set.\n const status = control.status === 302 ? 303 : control.status;\n headers.set(\"location\", control.to);\n return new Response(null, { status, headers });\n}\n\n/** A thrown answer's `headers`, or none when it carried nothing a response can take. */\nfunction answerHeaders(extra: unknown): Headers {\n if (extra === undefined || extra === null) return new Headers();\n try {\n return new Headers(extra as HeadersInit);\n } catch {\n return new Headers();\n }\n}\n\nfunction reportRefusedRedirect(to: string): void {\n console.error(\n `[barq] A server function threw \\`redirect(${JSON.stringify(to)})\\`, which is not a path or an \\`http(s)\\` URL, so the redirect was refused and the call answered 500. ` +\n \"Validate the value passed to `redirect()` before using it, especially when it comes from the request.\",\n );\n}\n\nfunction isIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Partial<AsyncIterable<unknown>>)[Symbol.asyncIterator] === \"function\"\n );\n}\n\n/**\n * An answer that arrives over time: one JSON line for each value yielded.\n *\n * Produced from `start`, so the function keeps running inside the request it\n * was called for: a `pull` is made from wherever the body is read, where there\n * is no request. It waits to be asked all the same, so a reader that falls\n * behind holds the function at its next `yield` rather than filling memory.\n *\n * A failure after the first value cannot become a status, so it is one last\n * line that says so and nothing else: a handler's message can name a table, a\n * column or a path.\n */\nfunction streamed(\n values: AsyncIterable<unknown>,\n sendContext: Record<string, unknown>,\n id: string,\n reveal: (error: unknown) => ServerFnThrown | undefined,\n): Response {\n const encoder = new TextEncoder();\n const line = (payload: RpcStreamLine): Uint8Array =>\n encoder.encode(`${JSON.stringify(payload)}\\n`);\n const source = values[Symbol.asyncIterator]();\n let wanted: (() => void) | null = null;\n let cancelled = false;\n\n const produce = async (\n controller: ReadableStreamDefaultController<Uint8Array>,\n ): Promise<void> => {\n try {\n if (Object.keys(sendContext).length > 0) {\n controller.enqueue(line({ c: encodeWire(sendContext) }));\n }\n for (;;) {\n if ((controller.desiredSize ?? 1) <= 0) {\n await new Promise<void>((resolve) => {\n wanted = resolve;\n });\n }\n if (cancelled) return;\n const next = await source.next();\n if (cancelled || next.done === true) break;\n controller.enqueue(line({ v: encodeWire(next.value) }));\n }\n if (!cancelled) controller.close();\n } catch (error) {\n if (cancelled) return;\n const thrown = reveal(error);\n const happened = `The server function ${JSON.stringify(id)} threw while streaming its result`;\n if (diagnosticsEnabled()) reportFailure(id, error, happened);\n console.error(\n `[barq] ${happened}, so the stream ended early and the caller receives a \\`ServerFnError\\`. The error:`,\n error,\n );\n controller.enqueue(line(thrown === undefined ? { e: 1 } : { e: 1, t: thrown }));\n controller.close();\n }\n };\n\n const body = new ReadableStream<Uint8Array>({\n start(controller) {\n void produce(controller);\n },\n pull() {\n const waiting = wanted;\n wanted = null;\n waiting?.();\n },\n cancel() {\n cancelled = true;\n const waiting = wanted;\n wanted = null;\n waiting?.();\n void source.return?.();\n },\n });\n return new Response(body, {\n headers: {\n \"content-type\": \"application/x-ndjson; charset=utf-8\",\n \"cache-control\": \"no-store\",\n [RPC_CONTROL]: RPC_STREAM,\n },\n });\n}\n\nconst DEFAULT_BODY_LIMIT = 1024 * 1024;\n\n/**\n * The request's body behind a cap, as something that can still be parsed.\n *\n * The declared length is only the early exit. A chunked request declares none\n * and a header can understate, so the stream is counted as it is read and\n * errors the moment it passes the limit, with the rest left unread.\n *\n * A `Response` carrying the content type, because that is what parses a\n * multipart body: the boundary is in the header, and srvx's own\n * `limitRequestBody` drops it and so cannot read a form.\n */\nfunction capped(request: Request, limit: number): Response {\n if (Number(request.headers.get(\"content-length\")) > limit) throw createBodyTooLargeError(limit);\n const type = request.headers.get(\"content-type\");\n return new Response(\n request.body === null ? null : limitBodyStream(request.body, limit),\n type === null ? undefined : { headers: { \"content-type\": type } },\n );\n}\n\n/**\n * A GET call's payload: the body a POST would have sent, in `?payload=`.\n *\n * Held to the body limit, since a URL is a body a caller chose the size of,\n * and refused as a 413 the way an oversized body is.\n */\nfunction queryPayload(url: URL, limit: number): unknown {\n const payload = url.searchParams.get(PAYLOAD_PARAM);\n if (payload === null) return {};\n if (payload.length > limit) throw createBodyTooLargeError(limit);\n return JSON.parse(payload);\n}\n\n/**\n * What a body that could not be read is answered with.\n *\n * By the error's code and not by who threw it: a server in front that enforces\n * `maxRequestBodySize` fails the read with the same error, and that caller is\n * owed the same 413.\n */\nfunction unreadable(error: unknown): Response {\n return (error as { code?: unknown } | null)?.code === \"ERR_BODY_TOO_LARGE\"\n ? new Response(\"payload too large\", { status: 413 })\n : new Response(\"bad request\", { status: 400 });\n}\n\n/**\n * Whether the body is a form rather than a value. The enhanced path posts\n * `FormData` to the data channel so that a handler sees the SAME input type\n * whether or not JS ran.\n */\nfunction isFormBody(request: Request): boolean {\n const type = request.headers.get(\"content-type\") ?? \"\";\n return type.includes(\"multipart/form-data\") || type.includes(\"application/x-www-form-urlencoded\");\n}\n\n/**\n * Back where the form was. 303 and not 302, so the browser re-issues as GET and\n * a reload does not repost — the POST/redirect/GET the no-JS path exists for.\n *\n * `Referer` is used only as a destination and never as a decision. SvelteKit's\n * docs make the distinction for the same reason: values derived from the\n * request are fine to navigate to and never fine to authorize with.\n */\nfunction seeOther(request: Request): Response {\n const referer = request.headers.get(\"referer\");\n const origin = new URL(request.url).origin;\n let location = \"/\";\n if (referer !== null) {\n try {\n const target = new URL(referer);\n // An off-site Referer would make this an open redirect.\n if (target.origin === origin) {\n const path = target.pathname + target.search;\n // A path that opens `//` is another HOST to a browser handed it alone,\n // and `/\\` parses to the same thing. Written with its origin it can only\n // be what it was: a path on this one.\n location = path.startsWith(\"//\") ? origin + path : path;\n }\n } catch {\n // A malformed Referer is not a destination.\n }\n }\n return new Response(null, { status: 303, headers: { location } });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgEA,MAAM,gBAAgB;CACpB,KAAK;CACL,MAAM;CACN,iBAAiB,WAAkC;EACjD,IAAI,MAAM,MAAM,CAAC;EACjB,SAAS,MAAM,MAAM,CAAC;CACxB;CACA,mBAAmB,QAA4B;AACjD;AAEA,SAAS,uBAA6B;CACpC,IAAI,sBAAsB,CAAC,CAAC,MAAM,YAAY,QAAQ,QAAQ,cAAc,GAAG,GAAG;CAClF,8BAA8B,CAAC,aAAa,CAAC;AAC/C;;AAGA,SAAgB,YAAY,IAAY,MAAe,WAAyC;CAC9F,qBAAqB;CAGrB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AAK,SAAS,mCAAmC;AAClG;;;;;;;;;AAUA,SAAS,SAAS,SAA4B;CAC5C,MAAM,UAAU,QAAQ,QAAQ,IAAI,SAAS;CAC7C,MAAM,SAAS,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;CACpC,IAAI,WAAW;CACf,IAAI,YAAY,MACd,IAAI;EACF,MAAM,SAAS,IAAI,IAAI,OAAO;EAE9B,IAAI,OAAO,WAAW,QAAQ;GAC5B,MAAM,OAAO,OAAO,WAAW,OAAO;GAItC,WAAW,KAAK,WAAW,IAAI,IAAI,SAAS,OAAO;EACrD;CACF,QAAQ,CAER;CAEF,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ;EAAK,SAAS,EAAE,SAAS;CAAE,CAAC;AAClE"}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request handler: one URL shape, one lookup, and the checks that run
|
|
3
|
+
* before a handler body does.
|
|
4
|
+
*
|
|
5
|
+
* Every default here is the strict one, because the survey found the same four
|
|
6
|
+
* failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,
|
|
7
|
+
* publicly-mounted endpoint reached by an id enumerable from the client bundle.
|
|
8
|
+
* Each is cheap to close and expensive to retrofit.
|
|
9
|
+
*/
|
|
10
|
+
import { $ as ServerFnThrown, S as ServerFn, t as AnyServerFn } from "./client-DidH0F2e.js";
|
|
11
|
+
import "./index-B4o7eyCr.js";
|
|
12
|
+
/**
|
|
13
|
+
* Say how the build's manifest is mounted, so a call can ask for it.
|
|
14
|
+
*
|
|
15
|
+
* The server entry imports the manifest when it first renders a page, which is
|
|
16
|
+
* late for a function called before any page has been asked for: a server that
|
|
17
|
+
* has just started and a browser tab that was already open. The id it names
|
|
18
|
+
* was in no registry yet, and the answer was a 404 for a function that exists.
|
|
19
|
+
*/
|
|
20
|
+
export declare function mountOnDemand(manifest: () => Promise<unknown>): void;
|
|
21
|
+
/**
|
|
22
|
+
* Mount a server function. The compiler emits one call per EXPORTED server
|
|
23
|
+
* function in a module compiled for the server.
|
|
24
|
+
*
|
|
25
|
+
* Export-ness is what decides reachability, which is SvelteKit's rule and the
|
|
26
|
+
* only genuine notion of an internal server function in the survey: a
|
|
27
|
+
* non-exported one is never registered, so it has no id and no endpoint, and is
|
|
28
|
+
* still callable from its siblings.
|
|
29
|
+
*/
|
|
30
|
+
export declare function mount(id: string, fn: AnyServerFn): void;
|
|
31
|
+
/** The mounted surface, for the build to record and a reviewer to read. */
|
|
32
|
+
export declare function mounted(): string[];
|
|
33
|
+
/**
|
|
34
|
+
* The function mounted at an id, or `undefined`.
|
|
35
|
+
*
|
|
36
|
+
* Exported for the BUILD's chain check, which has to ask each reachable id what
|
|
37
|
+
* middleware it actually carries. It reads the registry inside whichever bundle
|
|
38
|
+
* it is called from, which is why the check runs through the server entry
|
|
39
|
+
* rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`
|
|
40
|
+
* INTO the ssr bundle, so a plugin importing this module would be asking a
|
|
41
|
+
* second, empty registry.
|
|
42
|
+
*/
|
|
43
|
+
export declare function mountedFn(id: string): ServerFn<unknown, unknown> | undefined;
|
|
44
|
+
/** Test seam. Not for application use. */
|
|
45
|
+
export declare function unmountAll(): void;
|
|
46
|
+
export interface HandlerOptions {
|
|
47
|
+
/**
|
|
48
|
+
* Origins allowed to call, beyond the request's own. Same-origin is always
|
|
49
|
+
* allowed; this widens it.
|
|
50
|
+
*/
|
|
51
|
+
allowedOrigins?: readonly string[];
|
|
52
|
+
/**
|
|
53
|
+
* The largest body a call may send, in bytes. 1 MiB when omitted.
|
|
54
|
+
*
|
|
55
|
+
* Enforced on the bytes as they are read, and answered with a 413. The body
|
|
56
|
+
* is parsed BEFORE the chain runs, so this is the only thing standing between
|
|
57
|
+
* a caller no middleware has seen yet and the server's memory.
|
|
58
|
+
*
|
|
59
|
+
* srvx's `maxRequestBodySize` is the same idea for the whole server and has
|
|
60
|
+
* no default; this one is for the server-function channel alone, so it holds
|
|
61
|
+
* under a handler that srvx is not in front of.
|
|
62
|
+
*/
|
|
63
|
+
maxBodySize?: number;
|
|
64
|
+
/**
|
|
65
|
+
* The largest FORM body, multipart or urlencoded. `maxBodySize` when omitted.
|
|
66
|
+
*
|
|
67
|
+
* Apart from it because a file upload is the one body that legitimately
|
|
68
|
+
* outgrows the default, and raising `maxBodySize` to admit one would widen
|
|
69
|
+
* the value channel by the same amount for no caller that needs it. A form is
|
|
70
|
+
* parsed whole into memory, so this is what one request can make the server
|
|
71
|
+
* hold.
|
|
72
|
+
*/
|
|
73
|
+
maxFormSize?: number;
|
|
74
|
+
/**
|
|
75
|
+
* What a failed call may tell its caller about the error, beyond its status.
|
|
76
|
+
*
|
|
77
|
+
* Only the development server passes it, so a production server answers a
|
|
78
|
+
* handler's failure with the status and a fixed line and nothing of the
|
|
79
|
+
* error: its message can name a table, a column or a path. In development the
|
|
80
|
+
* caller is the developer, and the error's name, message and stack (mapped
|
|
81
|
+
* to source by the dev server) are what make the failure debuggable from the
|
|
82
|
+
* browser.
|
|
83
|
+
*/
|
|
84
|
+
revealError?: (error: unknown) => ServerFnThrown;
|
|
85
|
+
/**
|
|
86
|
+
* The build this server is, such as a commit hash. A call whose
|
|
87
|
+
* `x-barq-build` header names another build is answered `409` and its
|
|
88
|
+
* function does not run, which catches the skew an unknown id cannot: a
|
|
89
|
+
* function whose id survived a deploy while its arguments or result changed
|
|
90
|
+
* shape. The build `@barqjs/vite` stamped the bundle with when omitted, so
|
|
91
|
+
* a built application needs nothing here; a call with no header is not
|
|
92
|
+
* checked.
|
|
93
|
+
*/
|
|
94
|
+
buildId?: string;
|
|
95
|
+
/**
|
|
96
|
+
* Whether some route in this application can reach this id.
|
|
97
|
+
*
|
|
98
|
+
* The narrow half of the route-action manifest. Export-ness already decides
|
|
99
|
+
* what is MOUNTED, and that is deliberately generous — a server function
|
|
100
|
+
* exported for a sibling to import is mounted whether or not any page calls
|
|
101
|
+
* it. Next.js concedes the consequence in its own release notes: "Even if a
|
|
102
|
+
* Server Action or utility function is not imported elsewhere in your code,
|
|
103
|
+
* it's still a publicly accessible HTTP endpoint."
|
|
104
|
+
*
|
|
105
|
+
* This closes that: an id no route reaches answers the 404 an unknown id
|
|
106
|
+
* already answers, so the two are indistinguishable from outside.
|
|
107
|
+
*
|
|
108
|
+
* It takes NO route from the caller, deliberately. A client-supplied route
|
|
109
|
+
* selecting a policy lets the caller pick the weakest one that reaches the
|
|
110
|
+
* action, and this file's own rule says why that is not allowed — values
|
|
111
|
+
* derived from the request are fine to navigate to and never fine to
|
|
112
|
+
* authorize with. Which CHAIN runs is decided at build time by
|
|
113
|
+
* `@barqjs/router`, not here and not per request.
|
|
114
|
+
*/
|
|
115
|
+
reachable?: (id: string) => boolean;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Is this request allowed to invoke a server function?
|
|
119
|
+
*
|
|
120
|
+
* `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback
|
|
121
|
+
* is Waku's post-CVE shape and it is the strictest default found: `Origin` is
|
|
122
|
+
* legitimately absent on some same-origin requests and on non-browser clients,
|
|
123
|
+
* while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged
|
|
124
|
+
* from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.
|
|
125
|
+
*/
|
|
126
|
+
export declare function originAllowed(request: Request, options?: HandlerOptions): boolean;
|
|
127
|
+
/**
|
|
128
|
+
* Is this a request a BROWSER made from another origin?
|
|
129
|
+
*
|
|
130
|
+
* A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole
|
|
131
|
+
* design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be
|
|
132
|
+
* called by this application's own pages — so a request with no origin signal at
|
|
133
|
+
* all is refused there, because there is no legitimate caller that omits one.
|
|
134
|
+
*
|
|
135
|
+
* A route handler is the opposite: an API route exists so that something OTHER
|
|
136
|
+
* than a browser can call it. A Stripe webhook, a GitHub delivery, a cron
|
|
137
|
+
* hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and
|
|
138
|
+
* refusing on their absence would refuse the main reason API routes exist.
|
|
139
|
+
*
|
|
140
|
+
* So this answers the narrower question, and the narrower question is the one
|
|
141
|
+
* CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER
|
|
142
|
+
* with the victim's cookies attached, and a browser making a cross-origin
|
|
143
|
+
* state-changing request always says so — `Origin` on any cross-origin POST
|
|
144
|
+
* since forever, `Sec-Fetch-Site` on everything in every current browser. So:
|
|
145
|
+
* refuse when a signal is present and says cross-origin; allow when there is no
|
|
146
|
+
* signal, because then it is not a browser and cannot be a forgery.
|
|
147
|
+
*
|
|
148
|
+
* `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than
|
|
149
|
+
* read as absent, which is a bypass that has shipped.
|
|
150
|
+
*/
|
|
151
|
+
export declare function crossOriginRefused(request: Request, allowedOrigins?: readonly string[]): boolean;
|
|
152
|
+
/**
|
|
153
|
+
* Handle one server-function request, or return null if the URL is not one.
|
|
154
|
+
*
|
|
155
|
+
* Returning null rather than a 404 is what lets this compose as middleware in
|
|
156
|
+
* front of a page handler.
|
|
157
|
+
*/
|
|
158
|
+
export declare function handleServerFn(request: Request, options?: HandlerOptions): Promise<Response | null>;
|
|
159
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.d.ts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;;;;;;;;;;;;;;;wBAkHgB,cAAc,gBAAgB;;;;;;;;;;wBAa9B,MAAM,YAAY,IAAI;;wBAgCtB;;;;;;;;;;;wBAcA,UAAU,aAAa;;wBAKvB;iBAKC;;;;;EAKf;;;;;;;;;;;;EAYA;;;;;;;;;;EAUA;;;;;;;;;;;EAWA,eAAe,mBAAmB;;;;;;;;;;EAUlC;;;;;;;;;;;;;;;;;;;;;EAqBA,aAAa;;;;;;;;;;;wBAYC,cAAc,SAAS,SAAS,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;wBAyC1C,mBAAmB,SAAS,SAAS;;;;;;;wBA2B/B,eACpB,SAAS,SACT,UAAU,iBACT,QAAQ"}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as crossOriginRefused, n as handleServerFn, r as mount, i as mountOnDemand, a as mounted, o as mountedFn, s as originAllowed, c as unmountAll } from "./server-DG6jb_NA.js";
|