@barqjs/start 0.2.0-next.0 → 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/README.md +26 -0
- package/dist/{client-BHyIiYxt.js → client-BsyxVCyu.js} +49 -22
- package/dist/client-BsyxVCyu.js.map +1 -0
- package/dist/{client-DHCV7yvQ.d.ts → client-DidH0F2e.d.ts} +28 -18
- package/dist/client-DidH0F2e.d.ts.map +1 -0
- package/dist/client.d.ts +25 -3
- package/dist/client.js +3 -3
- package/dist/{env-qA8EyOr1.d.ts → env-Bhk_aIkx.d.ts} +1 -3
- package/dist/env-Bhk_aIkx.d.ts.map +1 -0
- package/dist/env.d.ts +1 -1
- package/dist/env.js +1 -2
- package/dist/{index-Bm_-MTj6.d.ts → index-B4o7eyCr.d.ts} +32 -22
- package/dist/index-B4o7eyCr.d.ts.map +1 -0
- package/dist/index.d.ts +18 -5
- package/dist/index.js +4 -4
- package/dist/{middleware-BdVlE8qm.d.ts → middleware-B-tI8QHQ.d.ts} +1 -3
- package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
- package/dist/middleware.d.ts +1 -1
- package/dist/middleware.js +1 -2
- package/dist/middleware.js.map +1 -1
- package/dist/prerender.d.ts +22 -2
- package/dist/prerender.d.ts.map +1 -1
- package/dist/prerender.js +4 -4
- package/dist/prerender.js.map +1 -1
- package/dist/protocol.d.ts +0 -2
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +1 -2
- package/dist/serve.d.ts +14 -5
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +3 -5
- package/dist/serve.js.map +1 -1
- package/dist/{server-BV3xKmLa.js → server-DG6jb_NA.js} +162 -57
- package/dist/server-DG6jb_NA.js.map +1 -0
- package/dist/server.d.ts +21 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +1 -1
- package/dist/{src-ChnB_xug.js → src-odXG7kLA.js} +31 -20
- package/dist/src-odXG7kLA.js.map +1 -0
- package/dist/{static-fn-DgjNArBe.js → static-fn-CXjJi-It.js} +10 -11
- package/dist/{static-fn-DgjNArBe.js.map → static-fn-CXjJi-It.js.map} +1 -1
- package/package.json +11 -11
- package/src/client.ts +27 -1
- package/src/context.ts +33 -0
- package/src/fn-error.ts +25 -1
- package/src/frames-client.ts +5 -1
- package/src/index.ts +32 -6
- package/src/live-server.ts +154 -44
- package/src/server.ts +43 -7
- package/src/wire-types.ts +2 -3
- package/dist/client-BHyIiYxt.js.map +0 -1
- package/dist/client-DHCV7yvQ.d.ts.map +0 -1
- package/dist/env-qA8EyOr1.d.ts.map +0 -1
- package/dist/index-Bm_-MTj6.d.ts.map +0 -1
- package/dist/middleware-BdVlE8qm.d.ts.map +0 -1
- package/dist/server-BV3xKmLa.js.map +0 -1
- package/dist/src-ChnB_xug.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-odXG7kLA.js","names":[],"sources":["../src/cookies.ts","../src/context.ts","../src/rate-limit.ts","../src/session.ts","../src/timing.ts","../src/index.ts"],"sourcesContent":["/**\n * Cookies, parsed and serialized here rather than taken from a package.\n *\n * It is a hundred lines and the traps are all known, so a dependency buys\n * nothing this file does not — but the traps are REAL, and every one of them is\n * a rule a browser enforces SILENTLY. A cookie a browser drops looks exactly\n * like a cookie the server never set, so each rule below is a THROW rather than\n * a correction: being told the attribute combination is impossible beats\n * debugging a login that works on the server and not in Chrome.\n *\n * The rules, and where they come from:\n *\n * - `SameSite=None` REQUIRES `Secure`. Chrome 80 made this a hard drop\n * (RFC 6265bis §5.4.7); without it the cookie is not stored at all.\n * - `Partitioned` REQUIRES `Secure` (CHIPS), and is rejected without it.\n * - `__Host-` requires `Secure`, `Path=/`, and NO `Domain` (RFC 6265bis\n * §4.1.3). `__Secure-` requires `Secure`.\n * - `Max-Age` must be an INTEGER. A fractional one is ignored, which silently\n * turns a dated cookie into a session one.\n * - `Expires` is an IMF-fixdate, which is what `Date.toUTCString()` produces\n * and what nothing else does.\n * - A cookie NAME may not hold a separator or a control character (RFC 6265\n * §4.1.1), and a VALUE is percent-encoded by default — a raw `;` in one\n * truncates the cookie where the browser splits it.\n */\n\n/** Attributes a `Set-Cookie` may carry. */\nexport interface CookieOptions {\n readonly domain?: string;\n readonly expires?: Date;\n readonly httpOnly?: boolean;\n /** Seconds. Must be an integer — a browser ignores anything else. */\n readonly maxAge?: number;\n /** CHIPS. Browsers that do not know it ignore it. */\n readonly partitioned?: boolean;\n readonly path?: string;\n readonly priority?: \"low\" | \"medium\" | \"high\";\n readonly sameSite?: \"strict\" | \"lax\" | \"none\";\n readonly secure?: boolean;\n /**\n * How the VALUE is encoded. `encodeURIComponent` by default, because a raw\n * `;` or `,` truncates the cookie where the browser splits it. Pass the\n * identity function for a value already in a cookie-safe alphabet — a\n * base64url session token, say — to keep it readable in devtools.\n */\n readonly encode?: (value: string) => string;\n}\n\n/** A control character, or DEL. The RFC defines every set below by code point. */\nconst isControl = (code: number): boolean => code <= 0x1f || code === 0x7f;\n\n/** Whether any character of `text` is one `refused` names. */\nfunction holdsAny(text: string, refused: (code: number) => boolean): boolean {\n for (let index = 0; index < text.length; index++) {\n if (refused(text.charCodeAt(index))) return true;\n }\n return false;\n}\n\nconst codes = (characters: string): ReadonlySet<number> =>\n new Set(Array.from(characters, (character) => character.charCodeAt(0)));\n\nconst NAME_SEPARATORS = codes(' ()<>@,;:\\\\\"/[]?={}');\nconst VALUE_SEPARATORS = codes(' \",;\\\\');\nconst SEMICOLON = 0x3b;\n\n/**\n * A separator or a control character, neither of which a cookie NAME may hold\n * (RFC 6265 §4.1.1: a name is a `token`).\n */\nconst illegalInName = (code: number): boolean => isControl(code) || NAME_SEPARATORS.has(code);\n\n/** What a cookie VALUE may not hold (RFC 6265 §4.1.1: `cookie-octet`). */\nconst illegalInValue = (code: number): boolean => isControl(code) || VALUE_SEPARATORS.has(code);\n\n/** What an attribute value may not hold, since `;` ends it. */\nconst illegalInAttribute = (code: number): boolean => isControl(code) || code === SEMICOLON;\n\n/**\n * Every cookie on a request, by name.\n *\n * FIRST WINS on a duplicate, which is what a browser sends when one cookie\n * exists at two paths and is what every parser in the survey does. A value that\n * is not valid percent-encoding comes back RAW rather than throwing: it arrived\n * off the wire, a client may put anything there, and one malformed cookie must\n * not take the request down.\n */\nexport function parseCookies(header: string | null | undefined): Record<string, string> {\n const out: Record<string, string> = Object.create(null) as Record<string, string>;\n if (header === null || header === undefined || header === \"\") return out;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n if (equals < 0) continue;\n const name = pair.slice(0, equals).trim();\n if (name === \"\" || name in out) continue;\n let value = pair.slice(equals + 1).trim();\n // A quoted-string value keeps its quotes on the wire and loses them here.\n if (value.length > 1 && value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1);\n }\n out[name] = decode(value);\n }\n return out;\n}\n\nfunction decode(value: string): string {\n if (!value.includes(\"%\")) return value;\n try {\n return decodeURIComponent(value);\n } catch {\n // Malformed percent-encoding from a client is not this server's error.\n return value;\n }\n}\n\n/**\n * One `Set-Cookie` line.\n *\n * Throws on any combination a browser would drop in silence — see the header\n * for which, and why a throw is the kinder answer.\n */\nexport function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n if (name === \"\" || holdsAny(name, illegalInName)) {\n throw new TypeError(\n `[barq] ${JSON.stringify(name)} is not a valid cookie name, and a browser would drop the cookie. A name made of letters, digits, \\`-\\` and \\`_\\`, such as \\`\"session_id\"\\`, is always valid.`,\n );\n }\n\n const secure = options.secure ?? false;\n const path = options.path;\n\n if (options.sameSite === \"none\" && !secure) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" sets \\`sameSite: \"none\"\\` without \\`secure: true\\`, and browsers drop a SameSite=None cookie that is not Secure (RFC 6265bis §5.4.7). ` +\n 'Add `secure: true`, or use `sameSite: \"lax\"`.',\n );\n }\n if (options.partitioned === true && !secure) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" sets \\`partitioned: true\\` without \\`secure: true\\`, and a browser rejects a Partitioned cookie that is not Secure. ` +\n \"Add `secure: true`.\",\n );\n }\n if (name.startsWith(\"__Host-\")) {\n if (!secure || path !== \"/\" || options.domain !== undefined) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" uses the \\`__Host-\\` prefix without the options the prefix requires, so a browser would reject it (RFC 6265bis §4.1.3). ` +\n 'Set `secure: true` and `path: \"/\"`, and leave `domain` unset.',\n );\n }\n } else if (name.startsWith(\"__Secure-\") && !secure) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" uses the \\`__Secure-\\` prefix without \\`secure: true\\`, so a browser would reject it (RFC 6265bis §4.1.3). ` +\n \"Add `secure: true`.\",\n );\n }\n\n const encoded = (options.encode ?? encodeURIComponent)(value);\n if (holdsAny(encoded, illegalInValue)) {\n throw new TypeError(\n `[barq] The value of the cookie \"${name}\" holds a character a cookie cannot carry after the custom \\`encode\\` ran, such as \\`;\\`, a space or a control character. ` +\n \"A browser would cut the value short. Leave `encode` at its default, which percent-encodes it.\",\n );\n }\n\n const parts = [`${name}=${encoded}`];\n\n if (options.maxAge !== undefined) {\n if (!Number.isInteger(options.maxAge)) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" has a non-integer maxAge (${options.maxAge}). A browser ignores a fractional \\`Max-Age\\` instead of rounding it, so the cookie would last only for the session. ` +\n \"Pass whole seconds, such as `maxAge: 3600`.\",\n );\n }\n parts.push(`Max-Age=${options.maxAge}`);\n }\n if (options.domain !== undefined) {\n assertAttribute(name, \"domain\", options.domain);\n parts.push(`Domain=${options.domain}`);\n }\n if (path !== undefined) {\n assertAttribute(name, \"path\", path);\n parts.push(`Path=${path}`);\n }\n if (options.expires !== undefined) {\n if (Number.isNaN(options.expires.getTime())) {\n throw new TypeError(\n `[barq] The cookie \"${name}\" has an \\`expires\\` that is an invalid \\`Date\\`, so no expiry could be written. Pass a valid date, such as \\`new Date(Date.now() + 86_400_000)\\`.`,\n );\n }\n // IMF-fixdate, the only format RFC 6265 §5.1.1 requires a browser to parse\n // and the only one `toUTCString` produces.\n parts.push(`Expires=${options.expires.toUTCString()}`);\n }\n if (options.httpOnly === true) parts.push(\"HttpOnly\");\n if (secure) parts.push(\"Secure\");\n if (options.partitioned === true) parts.push(\"Partitioned\");\n if (options.priority !== undefined) parts.push(`Priority=${capitalize(options.priority)}`);\n if (options.sameSite !== undefined) parts.push(`SameSite=${capitalize(options.sameSite)}`);\n\n return parts.join(\"; \");\n}\n\nfunction assertAttribute(cookie: string, attribute: string, value: string): void {\n if (holdsAny(value, illegalInAttribute)) {\n throw new TypeError(\n `[barq] The cookie \"${cookie}\" has a \\`${attribute}\\` holding a character such as \\`;\\` that would terminate the attribute and let the rest be read as further cookie attributes. ` +\n `Pass a plain ${attribute}, and never build it from user input without validating it.`,\n );\n }\n}\n\nfunction capitalize(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\n/**\n * The line that DELETES a cookie.\n *\n * A cookie is deleted by being set again, expired — and the `path` and `domain`\n * must MATCH the ones it was set with, or the browser deletes nothing and keeps\n * the original. That is why both ride through rather than being dropped: a\n * `deleteCookie(\"sid\")` against a cookie set at `path: \"/app\"` is a no-op, and\n * a silent one.\n */\nexport function deleteCookieLine(name: string, options: CookieOptions = {}): string {\n return serializeCookie(name, \"\", { ...options, expires: new Date(0), maxAge: 0 });\n}\n","/**\n * The request a server function, a loader or a route handler is running for —\n * and the response it is building.\n *\n * Ambient rather than threaded through every signature, because a handler five\n * calls deep needs the cookie header and passing a `Request` down to it turns\n * every intermediate function into plumbing. That argument applies to the\n * RESPONSE just as hard: a login sets a cookie from inside the function that\n * checked the password, and threading a `Response` back up through the value it\n * returns is the plumbing again, in the other direction.\n *\n * `AsyncLocalStorage` and not a module-level variable: two requests are in\n * flight at once on any real server, and a module-level variable would hand one\n * request's handler the other's session. SvelteKit shipped exactly that:\n * concurrent requests merged under one context, disclosing data across users.\n * TanStack reaches for the same primitive for the same reason.\n *\n * THE DRAFT IS THE FIX FOR A MEASURED HOLE. Before it, a server function could\n * not set a cookie at all on the JS path: `handleServerFn` answered the `.data`\n * channel with `Response.json(encodeWire(result))`, so a returned `Response`\n * went into the value codec and came back as `Seroval Error (step: 1)` — a 500\n * with nothing in it. The no-JS form path returned it correctly, so the same\n * function behaved differently depending on whether JS had run, which is the\n * one divergence progressive enhancement exists to prevent.\n */\n\nimport type { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { RequestEventLocals, ResponseStub } from \"@barqjs/web\";\nimport {\n commitResponseStub,\n createRequestEvent,\n createResponseStub,\n foldResponseStub,\n} from \"@barqjs/web/internal\";\nimport { diagnosticsEnabled, emitDiagnostic } from \"@barqjs/core/internal\";\nimport { provideRequestEvent } from \"@barqjs/server/storage\";\n\nimport { type CookieOptions, deleteCookieLine, parseCookies, serializeCookie } from \"./cookies.ts\";\nimport type { OpenContext } from \"./middleware.ts\";\nimport type { OpenSession } from \"./session.ts\";\nimport type { GlobalRequestContext } from \"./start-instance.ts\";\n\nconst REQUEST_EVENT = Symbol.for(\"barq.request-event\");\n\n/**\n * Headers and a status a handler asked for, merged into whatever is returned:\n * the request event's response head, Solid's `ResponseStub`, under the name\n * this package's helpers have always given it.\n */\nexport type ResponseDraft = ResponseStub;\n\nexport interface RequestContext {\n request: Request;\n /** What the handler has asked the response to carry. */\n response: ResponseDraft;\n /** Solid's `RequestEvent.locals`: what middleware hangs on the request. */\n locals: RequestEventLocals;\n /**\n * The request's cookies, parsed ONCE.\n *\n * `getCookie` went through `parseCookies` every call, so a middleware that\n * reads a session, a handler that reads a preference and a loader that reads a\n * locale re-split the same header three times. The header is immutable for the\n * life of the request, so the parse is too.\n */\n cookies?: Record<string, string>;\n /**\n * Rules `@barqjs/css` registered while rendering THIS request.\n *\n * A server imports the application once and serves forever, so a module-scope\n * rule belongs to every request and a rule a component body registers belongs\n * to one. Kept here rather than in the css package because this is what knows\n * which request is current — two in flight at once cannot take each other's.\n */\n css?: Map<string, string>;\n /**\n * Reads every rule registered after THIS request's head sheet was serialised.\n *\n * What the page is owed once it has a head, in place of {@link css}: a rule\n * ANOTHER request registered after this one's head is one this render can\n * still use, as a class a module already holds, and it registers nothing\n * when it does. So the line is the head and not who registered what.\n */\n lateCss?: () => string;\n /**\n * What a server function's chain asked to send back, held for the request\n * handler to put on the response.\n *\n * Here and not in a module-level variable for the reason this file opens\n * with: two requests whose handlers settle in the same tick would each read\n * whichever chain wrote last, and that is one caller's `sendContext` on\n * another caller's response.\n */\n sendContext?: Record<string, unknown>;\n /** The server functions whose frames this request's mutation changed. */\n invalidatedFrames?: Set<string>;\n /**\n * The sessions this request has opened, by cookie name.\n *\n * The request's cookie is what the browser HAD. A second `useSession` that\n * read it again would start from before the first one's `update`, and its own\n * `update` would then seal a session without that change over the top of it.\n */\n sessions?: Map<string, Promise<OpenSession>>;\n /**\n * What the request middleware chain contributed with `next({ context })`.\n *\n * A server function's own chain starts from it, and a route handler is\n * handed it, so a global middleware that resolved a session says so once.\n */\n middlewareContext?: Record<string, unknown>;\n /**\n * Why this request must not be read, when it must not be.\n *\n * A PRERENDER holds a `Request` a build minted, so `getRequest()` would\n * answer with a build machine's headers and a cookie jar that is empty for\n * everyone. SvelteKit guards `url.search` alone and lets `cookies.get` and\n * `request.headers` return null in silence; its own tracker records that as\n * multi-day debugging. Refusing is the honest answer, and the message names\n * what to do instead.\n */\n refuse?: string;\n}\n\n/**\n * The request event's storage, under the symbol `getRequestEvent` reads and\n * `provideRequestEvent` enters, so a component asking Solid's way finds the\n * request a handler entered.\n *\n * ONE storage per process, whichever copy of this module asks: a build\n * compiles this module into its server bundle, and a host serving that bundle\n * through its own `serveBarq` has imported a second copy. Each holding its own,\n * the host entered the request into one and the bundle's functions read the\n * other, so every server function that read a cookie answered 500.\n *\n * Read lazily, and nothing is constructed here: `@barqjs/start` is the\n * ISOMORPHIC entry, so a browser bundle evaluates this module, and a bundler\n * answers `node:async_hooks` there with an empty stub. No storage is no\n * request in flight, which is what the read path reports.\n */\nconst SHARED = {\n get storage(): AsyncLocalStorage<RequestContext> | undefined {\n return (globalThis as { [REQUEST_EVENT]?: AsyncLocalStorage<RequestContext> })[REQUEST_EVENT];\n },\n};\n\n/** A fresh, empty draft, one per request: Solid's `createResponseStub`. */\nexport const createResponseDraft: () => ResponseDraft = createResponseStub;\n\n/**\n * Send `@barqjs/css`'s render-time rules to whichever request is running.\n *\n * Installed once, by the generated server entry. Outside a request — module\n * scope, and the browser — there is nothing to attribute a rule to, so it falls\n * back to the package's own sheet, which is where a module-scope rule belongs.\n */\nexport function collectRequestCss(): string {\n const store = SHARED.storage?.getStore();\n if (store?.lateCss !== undefined) return store.lateCss();\n return store?.css === undefined ? \"\" : [...store.css.values()].join(\"\");\n}\n\nconst DEV_STYLESHEETS = Symbol.for(\"barq.dev.stylesheets\");\n\n/**\n * The compiled module stylesheets a page made of `routes` reaches, in the order\n * the page's modules run, when a dev server answered that, and `undefined`\n * where none did: a build links its stylesheets instead of inlining them.\n *\n * A dev server imports the application once and renders every page from the\n * one registry, so without this a page's head carried the rules of every module\n * any earlier request had reached. `@barqjs/vite` installs the answer, read off\n * its module graph in the order a build links the same modules' stylesheets.\n */\nexport function devStylesheets(\n routes: readonly string[],\n): Promise<DevStylesheets | undefined> | undefined {\n const answer = (\n globalThis as {\n [DEV_STYLESHEETS]?: (routes: readonly string[]) => Promise<DevStylesheets>;\n }\n )[DEV_STYLESHEETS];\n return answer?.(routes);\n}\n\n/** `@barqjs/css`'s `CssScope`, restated so this package does not import that one. */\nexport interface DevStylesheets {\n readonly keys: readonly string[];\n readonly modules: ReadonlySet<string>;\n}\n\n/** `@barqjs/css`'s `CssSink`, restated so this package does not import that one. */\ninterface CssSink {\n (key: string, rules: string): boolean;\n head?(late: () => string): void;\n owns?(key: string): boolean;\n}\n\nexport function installCssSink(setSink: (sink: CssSink) => void): void {\n const sink: CssSink = (key, rules) => {\n const store = SHARED.storage?.getStore();\n // Outside a request there is nothing to attribute the rule to — module\n // scope, which every request needs — so it goes to the package's own sheet.\n if (store === undefined) return false;\n store.css ??= new Map();\n store.css.set(key, rules);\n return true;\n };\n // The FIRST read of the whole sheet in a request is its `<head>`; a later\n // one is somebody else's and must not move the line.\n sink.head = (late) => {\n const store = SHARED.storage?.getStore();\n if (store !== undefined) store.lateCss ??= late;\n };\n // Outside a request every rule is every page's, so nothing is owned and the\n // registry shows what no request registered.\n sink.owns = (key) => SHARED.storage?.getStore()?.css?.has(key) === true;\n setSink(sink);\n}\n\n/**\n * Run `body` with `request` as the ambient one, under the event\n * `createRequestEvent` builds for it and `provideRequestEvent` enters.\n *\n * The DRAFT is the caller's to hold, because the caller is what builds the\n * response and it does so after `body` has returned.\n */\nexport function withRequest<T>(\n request: Request,\n body: () => T,\n options: { readonly refuse?: string; readonly response?: ResponseDraft } | string = {},\n): T {\n // The third argument was a bare `refuse` string before the draft existed.\n // Both spellings work, because the string form reads better at the one call\n // site that uses it — the prerenderer, which refuses and carries no draft.\n const resolved = typeof options === \"string\" ? { refuse: options } : options;\n return provideRequestEvent(\n createRequestEvent(request, {\n refuse: resolved.refuse,\n response: resolved.response ?? createResponseStub(),\n }),\n body,\n );\n}\n\n/**\n * The request this handler is running for.\n *\n * Throws outside one rather than returning undefined: a handler reading cookies\n * off `undefined` is a bug that should surface where it happens, not resolve to\n * \"no session\" and let the request through.\n */\nexport function getRequest(): Request {\n return context().request;\n}\n\n/**\n * The request, or undefined outside one. For code that legitimately runs both ways.\n *\n * A refused context reads as ABSENT here rather than throwing: `peekRequest` is\n * the \"I may not be in a request\" spelling, and a prerender is exactly that\n * case. Code that must have one calls `getRequest` and gets the refusal.\n */\nexport function peekRequest(): Request | undefined {\n const found = SHARED.storage?.getStore();\n return found === undefined || found.refuse !== undefined ? undefined : found.request;\n}\n\nfunction context(): RequestContext {\n const found = SHARED.storage?.getStore();\n if (found === undefined) {\n throw new Error(\n \"[barq] A request helper such as `getRequest()`, `getCookie()` or `setResponseHeader()` was called outside a request, so there is no request to read and no response to write to. \" +\n \"These helpers are only available inside a request: call them from a server function, a route handler, a loader or a `beforeLoad`.\",\n );\n }\n if (found.refuse !== undefined) throw new Error(found.refuse);\n return found;\n}\n\n/**\n * The draft, or `undefined` outside a request.\n *\n * Used by the two handlers to merge on the way out, and by nothing else. A\n * REFUSED context still answers here: a prerender may not read the request, but\n * a `head` or a loader that sets a cache header during one is describing the\n * page rather than the requester, and the prerenderer can write it to disk.\n */\nexport function peekResponseDraft(): ResponseDraft | undefined {\n return SHARED.storage?.getStore()?.response;\n}\n\n/**\n * Leave a chain's `sendContext` for whoever builds this request's response.\n *\n * Outside a request there is no response to carry it, so it is dropped: that is\n * a server function called in-process, whose caller is handed the result alone.\n */\nexport function offerSendContext(sendContext: Record<string, unknown>): void {\n const found = SHARED.storage?.getStore();\n if (found !== undefined) found.sendContext = sendContext;\n}\n\n/**\n * Say that this mutation changed what these server functions' frames show, so\n * its answer carries those regions, rendered again, beside its value: single\n * flight, one round trip. A frame the page has not mounted is not rendered.\n * Outside a request it does nothing, as there is no answer to carry them.\n */\nexport function invalidateFrames(\n ...fns: readonly { readonly meta: { readonly id: string } }[]\n): void {\n const found = SHARED.storage?.getStore();\n if (found === undefined) return;\n found.invalidatedFrames ??= new Set();\n for (const fn of fns) found.invalidatedFrames.add(fn.meta.id);\n}\n\n/** The server functions `invalidateFrames` named in this request, or none. */\nexport function invalidatedFrames(): ReadonlySet<string> {\n return SHARED.storage?.getStore()?.invalidatedFrames ?? EMPTY_SET;\n}\n\nconst EMPTY_SET: ReadonlySet<string> = new Set();\n\n/** Take the pending `sendContext`, leaving nothing behind for the next call. */\nexport function takeSendContext(): Record<string, unknown> {\n const found = SHARED.storage?.getStore();\n const taken = found?.sendContext ?? {};\n if (found !== undefined) found.sendContext = undefined;\n return taken;\n}\n\n/**\n * What this request's middleware chain has contributed, or an empty record\n * outside a request. TanStack's name.\n *\n * Typed by what the registered global request middleware passes to\n * `next({ context })`, each key optional: outside a request, or before the\n * chain has reached the step that adds it, it is not there.\n */\nexport function getGlobalStartContext(): OpenContext<Partial<GlobalRequestContext>> {\n const written: Record<string, unknown> = SHARED.storage?.getStore()?.middlewareContext ?? {};\n return written;\n}\n\n/** Record what the request middleware chain is contributing, for the rest of the request. */\nexport function setRequestMiddlewareContext(context: Record<string, unknown>): void {\n const found = SHARED.storage?.getStore();\n if (found !== undefined) found.middlewareContext = context;\n}\n\n/** The sessions this request has opened. See {@link RequestContext.sessions}. */\nexport function openSessions(): Map<string, Promise<OpenSession>> {\n const found = context();\n found.sessions ??= new Map();\n return found.sessions;\n}\n\n// ---------------------------------------------------------------------------\n// The request, read\n// ---------------------------------------------------------------------------\n\nexport function getRequestHeaders(): Headers {\n return getRequest().headers;\n}\n\nexport function getRequestHeader(name: string): string | undefined {\n return getRequest().headers.get(name) ?? undefined;\n}\n\n/** The request URL, parsed. */\nexport function getRequestUrl(): URL {\n return new URL(getRequest().url);\n}\n\n/**\n * How far `X-Forwarded-For` is believed.\n *\n * `true` takes the LEFTMOST entry, and is safe only when the edge proxy\n * OVERWRITES the header. A proxy that appends, which is what most do, leaves\n * whatever the client sent at the front: `X-Forwarded-For: 203.0.113.9` on the\n * request arrives as `203.0.113.9, <real address>`, and the leftmost entry is\n * the one the caller typed.\n *\n * `{ trustedProxies: n }` counts from the RIGHT instead: the entry the nth\n * proxy in front of this process wrote, which is the address that proxy saw.\n * Entries to its left were there before any trusted hop touched the header, so\n * a forged prefix is never read. A header with fewer than `n` entries did not\n * come through that chain and is ignored whole.\n */\nexport type ForwardedForTrust = boolean | { readonly trustedProxies: number };\n\n/** Refuse a hop count that names no entry, where the option is written. */\nexport function assertForwardedForTrust(trust: ForwardedForTrust | undefined): void {\n if (typeof trust !== \"object\") return;\n if (!Number.isInteger(trust.trustedProxies) || trust.trustedProxies < 1) {\n throw new RangeError(\n `[barq] \\`trustedProxies\\` must be a positive integer, and it is ${trust.trustedProxies}. ` +\n \"Set it to the number of proxies you run in front of this server: each one appends one entry to `X-Forwarded-For`, and the client address is counted back from the end.\",\n );\n }\n}\n\n/**\n * The client's address, or `undefined`.\n *\n * `xForwardedFor` IS OFF BY DEFAULT and that is the whole design of this\n * function. `X-Forwarded-For` is a header a client can send, so trusting it\n * unconditionally lets any caller claim any address — and an address is exactly\n * what rate limiting and audit logging key on. It is trustworthy only when a\n * proxy you control overwrites it, which is a fact about the deployment that\n * this process cannot discover. So it is opt-in, and the opt-in is per call.\n *\n * The LEFTMOST entry is taken when it is trusted, since that is the original\n * client; every entry to its right was appended by a hop. {@link\n * ForwardedForTrust} says when that is forgeable and what to pass instead.\n */\nexport function getRequestIP(\n options: { readonly xForwardedFor?: ForwardedForTrust } = {},\n): string | undefined {\n const request = getRequest();\n const trust = options.xForwardedFor;\n if (trust !== undefined && trust !== false) {\n assertForwardedForTrust(trust);\n const entries = request.headers.get(\"x-forwarded-for\")?.split(\",\") ?? [];\n const entry = trust === true ? entries[0] : entries[entries.length - trust.trustedProxies];\n const address = entry?.trim();\n if (address !== undefined && address !== \"\") return address;\n }\n // What a runtime attaches when it knows. `srvx` and Bun both use this name.\n const direct = (request as { ip?: string }).ip;\n return direct === \"\" ? undefined : direct;\n}\n\n/**\n * The host, from the URL — and from `X-Forwarded-Host` only when asked.\n *\n * Same rule as `getRequestIP`, and the consequence is sharper: a host taken\n * from an untrusted header and used to build an absolute URL is a host-header\n * injection, which turns a password-reset link into a link to the attacker.\n */\nexport function getRequestHost(options: { readonly xForwardedHost?: boolean } = {}): string {\n const request = getRequest();\n if (options.xForwardedHost === true) {\n const forwarded = request.headers.get(\"x-forwarded-host\");\n if (forwarded !== null && forwarded !== \"\") return forwarded;\n }\n return new URL(request.url).host;\n}\n\n/** `http` or `https`. `X-Forwarded-Proto` only when asked, for the reason above. */\nexport function getRequestProtocol(options: { readonly xForwardedProto?: boolean } = {}): string {\n const request = getRequest();\n if (options.xForwardedProto === true) {\n const forwarded = request.headers.get(\"x-forwarded-proto\")?.split(\",\")[0]?.trim();\n if (forwarded !== undefined && forwarded !== \"\") return forwarded;\n }\n return new URL(request.url).protocol.replace(\":\", \"\");\n}\n\n// ---------------------------------------------------------------------------\n// The response, written\n// ---------------------------------------------------------------------------\n\n/**\n * Mark the draft's response as handed to the server: Solid's\n * `commitResponseStub`. A streamed page goes on rendering after this, and so\n * does a streamed server function, and a header one of them writes now changes\n * nothing the browser receives.\n */\nexport const markResponseSent: typeof commitResponseStub = commitResponseStub;\n\n/**\n * The draft a write goes to, reporting the write when the response has already\n * gone. `api` is the public function the caller called, so the stack the\n * report carries starts at the caller rather than in here.\n */\nfunction draftFor(api: (...args: never[]) => unknown, argument?: unknown): ResponseDraft {\n const draft = context().response;\n if (draft.committed !== true) return draft;\n if (diagnosticsEnabled()) reportLateWrite(api, argument);\n // Somewhere the write can land and go nowhere, reported once, here.\n return createResponseStub();\n}\n\nfunction reportLateWrite(api: (...args: never[]) => unknown, argument: unknown): void {\n const call = `${api.name}(${argument === undefined ? \"\" : JSON.stringify(argument)})`;\n const error = new Error(`${call} ran after the response was sent`);\n Error.captureStackTrace(error, api);\n const caller = /^\\s*at\\s+(.*)$/m.exec(error.stack?.split(\"\\n\").slice(1).join(\"\\n\") ?? \"\")?.[1];\n emitDiagnostic(\n {\n code: \"LATE_HEADER_WRITE\",\n kind: \"head\",\n severity: \"warn\",\n message:\n `\\`${call}\\` ran ${caller === undefined ? \"\" : `at ${caller} `}after the response's status ` +\n \"and headers had been sent, so it changed nothing the browser receives. Code runs that late \" +\n \"inside a part of the page that renders after the shell (a `<Loading>` boundary or a \" +\n \"loader the shell does not wait for), or in a streamed server function after its first \" +\n \"value. Set the status, headers and cookies while the response is still open: in a \" +\n \"`beforeLoad`, a loader the route awaits, a route handler, a middleware, or a server \" +\n \"function before it returns.\",\n data: { call, error },\n },\n null,\n );\n}\n\nexport function getResponseHeaders(): Headers {\n return context().response.headers;\n}\n\nexport function getResponseHeader(name: string): string | undefined {\n return context().response.headers.get(name) ?? undefined;\n}\n\n/**\n * Set a response header. An array APPENDS each value, which is what a header\n * that may legitimately repeat needs.\n */\nexport function setResponseHeader(name: string, value: string | readonly string[]): void {\n const headers = draftFor(setResponseHeader, name).headers;\n if (typeof value === \"string\") {\n headers.set(name, value);\n return;\n }\n headers.delete(name);\n for (const one of value) headers.append(name, one);\n}\n\n/**\n * Add a value to a response header, keeping the ones already there.\n *\n * For a header that is a list: `Vary`, `Link`, `Cache-Control` built up by more\n * than one caller. `setResponseHeader` replaces.\n */\nexport function appendResponseHeader(name: string, value: string): void {\n draftFor(appendResponseHeader, name).headers.append(name, value);\n}\n\nexport function setResponseHeaders(headers: Record<string, string>): void {\n for (const [name, value] of Object.entries(headers)) setResponseHeader(name, value);\n}\n\nexport function removeResponseHeader(name: string): void {\n draftFor(removeResponseHeader, name).headers.delete(name);\n}\n\n/** Clear the named headers, or every header this request has drafted. */\nexport function clearResponseHeaders(names?: readonly string[]): void {\n const headers = draftFor(clearResponseHeaders).headers;\n if (names !== undefined) {\n for (const name of names) headers.delete(name);\n return;\n }\n // Collected first, because deleting while iterating a live `Headers` skips.\n const present: string[] = [];\n for (const name of headers.keys()) present.push(name);\n for (const name of present) headers.delete(name);\n}\n\nexport function getResponseStatus(): number {\n return context().response.status ?? 200;\n}\n\n/**\n * Set the status the framework's own response will carry.\n *\n * It does NOT override a `Response` a handler returns for itself — see\n * `applyResponseDraft`, which says why.\n */\nexport function setResponseStatus(status: number, statusText?: string): void {\n const draft = draftFor(setResponseStatus, status);\n if (!Number.isInteger(status) || status < 200 || status > 599) {\n throw new RangeError(\n `[barq] \\`setResponseStatus(${status})\\` was given a value that is not an HTTP response status. Pass an integer from 200 to 599, such as \\`setResponseStatus(404)\\`.`,\n );\n }\n draft.status = status;\n if (statusText !== undefined) draft.statusText = statusText;\n}\n\n// ---------------------------------------------------------------------------\n// Cookies\n// ---------------------------------------------------------------------------\n\n/**\n * Every cookie the REQUEST carried, by name.\n *\n * Parsed once and memoised on the context: the header cannot change for the life\n * of the request, and re-splitting it per lookup made three readers three\n * parses. The object is returned as it stands rather than copied, which is the\n * point — copying it per call would put the allocation back.\n */\nexport function getCookies(): Record<string, string> {\n const found = context();\n found.cookies ??= parseCookies(found.request.headers.get(\"cookie\"));\n return found.cookies;\n}\n\nexport function getCookie(name: string): string | undefined {\n return getCookies()[name];\n}\n\n/**\n * Set a cookie on the response.\n *\n * APPENDS, because several cookies are several `Set-Cookie` lines and a\n * browser keeps only the last of a set. Setting the same NAME twice in one\n * request is the caller's business — the last one wins in the browser, as ever.\n */\nexport function setCookie(name: string, value: string, options?: CookieOptions): void {\n draftFor(setCookie, name).headers.append(\n \"set-cookie\",\n serializeCookie(name, value, rooted(options)),\n );\n}\n\n/**\n * Set a cookie in place of any line this request already drafted for its name.\n *\n * For a cookie one request may write more than once and of which only the last\n * line means anything, which is a session: each of its lines runs to 4 KB, and\n * a proxy that buffers response headers in 4 or 8 KB answers 502 to two of\n * them. `setCookie` appends, which is right for everything else.\n */\nexport function replaceCookie(name: string, value: string, options?: CookieOptions): void {\n const headers = draftFor(replaceCookie, name).headers;\n // Serialized before anything is removed, so a cookie that is refused leaves\n // the draft as it was.\n const line = serializeCookie(name, value, rooted(options));\n const prefix = `${name}=`;\n const kept = headers.getSetCookie().filter((other) => !other.startsWith(prefix));\n headers.delete(\"set-cookie\");\n for (const other of kept) headers.append(\"set-cookie\", other);\n headers.append(\"set-cookie\", line);\n}\n\n/**\n * The options, with `path: \"/\"` where the caller chose none.\n *\n * A browser gives a cookie that names no `Path` the directory of the URL that\n * set it (RFC 6265 §5.1.4). For a server function that is `/_barq/fn`, so the\n * cookie would come back on other server functions and on no page at all.\n * `serializeCookie` stays literal; the default belongs where the URL is known\n * to be the wrong scope.\n */\nfunction rooted(options: CookieOptions | undefined): CookieOptions {\n return options?.path === undefined ? { ...options, path: \"/\" } : options;\n}\n\n/**\n * Delete a cookie.\n *\n * `path` and `domain` MUST match the ones it was set with, or the browser\n * deletes nothing and keeps the original — silently. They are options here for\n * exactly that reason rather than as decoration. With no `path` it names `/`,\n * which is what `setCookie` gave a cookie that was set with none.\n */\nexport function deleteCookie(name: string, options?: CookieOptions): void {\n draftFor(deleteCookie, name).headers.append(\n \"set-cookie\",\n deleteCookieLine(name, rooted(options)),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Merging\n// ---------------------------------------------------------------------------\n\n/**\n * Fold a draft into a response, Solid's fold for `commitEventResponse` without\n * the commit: `foldResponseStub` in `@barqjs/web` says what wins and why.\n *\n * It does NOT override the status of a `Response` a handler returned, because\n * a handler that built a whole response has said what it wants.\n */\nexport const applyResponseDraft: (\n response: Response,\n draft: ResponseDraft | undefined,\n) => Response = foldResponseStub;\n\n/**\n * The status and text a framework-built response should carry.\n *\n * Separate from `applyResponseDraft` because the two answer different\n * questions: this is \"what did the handler ask for\", used where the framework\n * is deciding the status itself, and that one is \"what does a returned response\n * already say\", where the handler has decided.\n */\nexport function draftedStatus(\n draft: ResponseDraft | undefined,\n fallback: number,\n): { status: number; statusText?: string } {\n return { status: draft?.status ?? fallback, statusText: draft?.statusText };\n}\n","/**\n * Rate limiting, as a middleware — so one closure guards a server function and\n * a route handler alike.\n *\n * THE STORE HAS NO DEFAULT, and that is the whole design of this file.\n *\n * An in-memory counter is correct for exactly one process. Behind a load\n * balancer with three instances it permits three times the limit, and behind an\n * autoscaler it permits an unbounded multiple — while passing every test, on\n * every machine, in every CI run. That is the silent failure this codebase\n * refuses: a limiter that reads as working and protects nothing. Requiring the\n * store makes the distributed question unavoidable at the call site, which is\n * the only place it can be answered.\n *\n * `memoryStore()` ships beside it and is named for what it is. Use it for a\n * single instance, and know that is what you have chosen.\n *\n * WHAT THIS IS NOT: a defence against a distributed flood. A limiter in the\n * application has already paid for the TLS handshake, the routing and the\n * middleware above it. It is here to stop credential stuffing, scraping and one\n * client hammering an expensive handler — the things a proxy in front cannot see\n * because they are shaped like ordinary traffic. Volumetric denial of service is\n * the edge's problem and always was.\n */\n\nimport { type ForwardedForTrust, assertForwardedForTrust, getRequestIP } from \"./context.ts\";\nimport type { Middleware } from \"./index.ts\";\n\n/** One key's usage, as the store hands it back. */\nexport interface RateLimitCount {\n /** How many requests this key has made in the current window. */\n readonly count: number;\n /** When the current window ends, as a millisecond timestamp. */\n readonly resetAt: number;\n}\n\n/**\n * Where the counts live.\n *\n * ONE METHOD, and it is atomic by contract: `hit` must increment and return the\n * new value in a single step. A `get` then `set` pair is a race — two requests\n * read the same count and both write it — and a limiter that loses increments\n * under load is one that stops working exactly when it is needed. Redis does\n * this with `INCR` plus `PEXPIRE`; the memory store below does it by being\n * single-threaded.\n */\nexport interface RateLimitStore {\n hit(key: string, windowMs: number): RateLimitCount | Promise<RateLimitCount>;\n}\n\nexport interface RateLimitOptions {\n /** How many requests a key may make per window. */\n readonly limit: number;\n /** The window, in milliseconds. */\n readonly windowMs: number;\n /**\n * What counts as one caller.\n *\n * There is no default, for the same reason the store has none: keying by IP is\n * right for a public endpoint and wrong for an authenticated one behind a\n * corporate NAT, where it limits a whole building as though it were one user.\n * Key by user id where there is one, and by IP only where there is not.\n *\n * Returning `null` EXEMPTS the request — an internal caller, a health check.\n */\n readonly key: () => string | null | Promise<string | null>;\n readonly store: RateLimitStore;\n /**\n * What to answer when the limit is reached. A 429 with `Retry-After` by\n * default, which is what a well-behaved client backs off on.\n */\n readonly onLimit?: (info: RateLimitCount & { readonly limit: number }) => Response;\n}\n\n/**\n * A store for ONE PROCESS. Named so the choice is visible at the call site.\n *\n * Correct for a single instance and wrong for every other deployment — see the\n * header. It is here because \"no store at all\" would push everyone to write this\n * same map badly, not because it is the one to reach for.\n *\n * Expired entries are swept by a `hit` rather than on a timer: a timer keeps\n * the process alive on Node and has to be unref'd. A key is one caller and most\n * callers are never seen again (a scan, a client rotating through an IPv6\n * prefix), so an entry dropped only when its own key came back would stay for\n * the life of the process and the map would grow with every address ever seen.\n *\n * The sweep runs at most once per the longest window in use, so an entry that\n * has expired is gone by the second sweep after it was made, and the map holds\n * what the last two such windows saw rather than everything since boot.\n */\nexport function memoryStore(): RateLimitStore {\n const windows = new Map<string, { count: number; resetAt: number }>();\n let longest = 0;\n let sweepAt = 0;\n return {\n hit(key, windowMs) {\n const now = Date.now();\n if (windowMs > longest) longest = windowMs;\n if (now >= sweepAt) {\n for (const [seen, window] of windows) {\n if (window.resetAt <= now) windows.delete(seen);\n }\n sweepAt = now + longest;\n }\n const found = windows.get(key);\n if (found === undefined || found.resetAt <= now) {\n const resetAt = now + windowMs;\n windows.set(key, { count: 1, resetAt });\n return { count: 1, resetAt };\n }\n found.count += 1;\n // A COPY, because the record goes on counting. A caller reads this after\n // an `await`, and by then the hits that arrived behind it have landed.\n return { count: found.count, resetAt: found.resetAt };\n },\n };\n}\n\n/**\n * Key a limit by client address.\n *\n * `xForwardedFor` IS OFF BY DEFAULT and turning it on is a claim about the\n * deployment: `X-Forwarded-For` is a header a CLIENT can send, so trusting it\n * where no proxy overwrites it lets any caller pick their own bucket and the\n * limit stops existing. See `getRequestIP`.\n *\n * `true` reads the LEFTMOST entry, which is the client only when the edge proxy\n * overwrites the header. Behind a proxy that appends, pass\n * `{ trustedProxies: n }` for the `n` proxies you run: it reads the entry the\n * outermost of them wrote and ignores anything a caller put in front of it.\n *\n * A request with no address at all keys as `\"unknown\"`, which pools every such\n * caller into one bucket — strict rather than exempt, because the alternative is\n * a bucket an attacker can opt into by arranging to have no address.\n */\nexport function byIP(options: { readonly xForwardedFor?: ForwardedForTrust } = {}): () => string {\n // Here and not on the first request: `rateLimit` fails OPEN when its key\n // throws, so a bad hop count found per call would switch the limit off.\n assertForwardedForTrust(options.xForwardedFor);\n return () => getRequestIP(options) ?? \"unknown\";\n}\n\nfunction tooMany(info: RateLimitCount & { limit: number }): Response {\n const seconds = Math.max(1, Math.ceil((info.resetAt - Date.now()) / 1000));\n return new Response(\"too many requests\", {\n status: 429,\n headers: {\n \"retry-after\": String(seconds),\n \"ratelimit-limit\": String(info.limit),\n \"ratelimit-remaining\": \"0\",\n \"ratelimit-reset\": String(seconds),\n },\n });\n}\n\n/**\n * The middleware.\n *\n * It runs BEFORE the handler and before validation, which is the whole point:\n * refusing after the body has been parsed is a refusal that already did the\n * work. That ordering is `serverRpc`'s and the route dispatch's, and it is why\n * this is a middleware rather than something a handler calls.\n *\n * A STORE THAT THROWS FAILS OPEN, deliberately and loudly. If Redis is down,\n * refusing every request turns a limiter into the outage — so the request\n * proceeds and the failure is reported. That is the right trade for a limiter\n * and the wrong one for an authorization check, which is why this is not one.\n */\nexport function rateLimit(options: RateLimitOptions): Middleware {\n const { limit, windowMs, key, store, onLimit = tooMany } = options;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n `[barq] \\`rateLimit({ limit })\\` must be a positive integer, and it is ${limit}. Pass how many requests one key may make per window, such as \\`limit: 10\\`.`,\n );\n }\n if (!Number.isFinite(windowMs) || windowMs <= 0) {\n throw new RangeError(\n `[barq] \\`rateLimit({ windowMs })\\` must be a positive number of milliseconds, and it is ${windowMs}. Pass the window length, such as \\`windowMs: 60_000\\`.`,\n );\n }\n\n return async (next) => {\n let info: RateLimitCount;\n try {\n const bucket = await key();\n // `null` exempts — an internal caller, a health check.\n if (bucket === null) return next();\n info = await store.hit(bucket, windowMs);\n } catch (error) {\n // FAIL OPEN. A limiter that refuses everything when its store is down has\n // become the outage it exists to prevent.\n console.error(\n \"[barq] The rate-limit `store` or `key` threw, so this request was let through without being counted. The error:\",\n error,\n );\n return next();\n }\n if (info.count > limit) throw onLimit({ ...info, limit });\n return next();\n };\n}\n","/**\n * Sealed-cookie sessions, on WebCrypto and nothing else.\n *\n * The session lives in the cookie, encrypted and authenticated, so there is no\n * store to run and no sticky routing to arrange. That is h3's design and\n * therefore TanStack's, and the interface\n * below is theirs — `{ id, data, update, clear }` from `useSession({ password\n * })` — so the shape a reader already knows is the shape here.\n *\n * THE SEALING IS NOT THEIRS, and the divergence is deliberate. h3 uses iron,\n * which is AES-256-CBC for confidentiality plus a separate HMAC-SHA256 for\n * integrity, composed by hand. barq uses AES-GCM, which is AEAD: one primitive,\n * authenticated by construction, with no encrypt-then-MAC composition to get\n * wrong and no separate integrity key to derive. It is in WebCrypto, which Node,\n * Bun, Deno and workerd all have, so it costs no dependency. The consequence is\n * stated rather than hidden: a cookie sealed by h3 does not open here and one\n * sealed here does not open there.\n *\n * WHAT A SEALED COOKIE IS AND IS NOT. It is tamper-proof and unreadable by the\n * client. It is NOT revocable — a cookie already issued stays valid until it\n * expires, because nothing on the server is consulted to open it. That is the\n * trade the whole design makes, and an application that needs revocation needs a\n * store; `maxAge` bounds the damage and is enforced on unseal, not merely on the\n * cookie, so a client that keeps replaying an expired token gets nothing.\n */\n\nimport { getCookie, getRequest, openSessions, replaceCookie } from \"./context.ts\";\nimport type { CookieOptions } from \"./cookies.ts\";\n\n/** What a session holds. An application narrows it with the type argument. */\nexport type SessionData = Record<string, unknown>;\n\nexport interface Session<T extends SessionData = SessionData> {\n /** Stable for the life of the session. Useful as a log correlation key. */\n readonly id: string;\n /** When it was first sealed, as a millisecond timestamp. */\n readonly createdAt: number;\n readonly data: Partial<T>;\n}\n\nexport interface SessionManager<T extends SessionData = SessionData> {\n readonly id: string;\n /** When the session was first sealed, as a millisecond timestamp. */\n readonly createdAt: number;\n readonly data: Partial<T>;\n /** Merge and re-seal. A function receives the current data. */\n update(\n patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined),\n ): Promise<SessionManager<T>>;\n /** Drop it and expire the cookie. */\n clear(): Promise<SessionManager<T>>;\n}\n\nexport interface SessionConfig {\n /**\n * The key the cookie is sealed with. At least 32 characters.\n *\n * It is a SECRET and belongs in the environment, never in source. Rotating it\n * invalidates every live session, which is the intended way to log everyone\n * out.\n */\n readonly password: string;\n /** Cookie name. Default `barq-session`. */\n readonly name?: string;\n /**\n * How long a sealed cookie stays valid, in seconds. Default 7 days.\n *\n * Enforced on UNSEAL as well as on the cookie, because the cookie's own expiry\n * is a request the client is free to ignore — the timestamp inside the sealed\n * payload is the one that cannot be edited.\n */\n readonly maxAge?: number;\n /**\n * Cookie attributes. The defaults are the strict ones — `httpOnly`, `secure`,\n * `sameSite: \"lax\"`, `path: \"/\"` — because a session cookie readable from\n * script is a session cookie an XSS takes.\n */\n readonly cookie?: CookieOptions;\n /**\n * Has this session been revoked? Asked on every unseal.\n *\n * THE ONE THING A SEALED COOKIE CANNOT DO BY ITSELF. Nothing on the server is\n * consulted to open one, so \"log out everywhere\" and \"ban this account now\"\n * are otherwise impossible — an issued cookie is valid until it expires, and\n * that is the trade the whole design makes.\n *\n * This is the smallest seam that closes it. The fast path stays stateless:\n * without the hook there is no lookup, and with it an application keeps only a\n * set of revoked IDS until they expire, which `maxAge` bounds. That is a much\n * smaller thing to store than a session per user, and it is only ever written\n * when somebody signs out or is banned.\n *\n * A REVOKED SESSION READS AS ABSENT, like every other reason a cookie will not\n * open — see `unsealSession`. Throwing here would tell a caller the difference\n * between \"forged\" and \"revoked\", which is an oracle.\n *\n * It is asked AFTER the cookie is authenticated, so an unauthenticated client\n * cannot make the application do a lookup by sending a garbage cookie.\n */\n readonly isRevoked?: (id: string) => boolean | Promise<boolean>;\n}\n\nconst DEFAULT_NAME = \"barq-session\";\nconst DEFAULT_MAX_AGE = 60 * 60 * 24 * 7;\n/** Below this a password is not a key, whatever the KDF does with it. */\nconst MINIMUM_PASSWORD = 32;\n/** Recognises our own envelope, and refuses another version rather than guessing. */\nconst VERSION = \"b2\";\n/**\n * The envelope that authenticates no cookie name. Opened, never written.\n *\n * Refusing it would sign every visitor out on the deploy that stopped sealing\n * it, and the price of not doing that is stated: a `b1` value opens under ANY\n * cookie name sharing the password until its sealed timestamp passes `maxAge`.\n */\nconst NAMELESS_VERSION = \"b1\";\n/** Leads the additional data, so another layout of it is never read as this one. */\nconst NAME_BINDING = 2;\nconst IV_BYTES = 12;\nconst SALT_BYTES = 16;\n/** Domain separation for the KDF — see `deriveKey`. */\nconst HKDF_INFO = new TextEncoder().encode(\"barq.session.v1\");\n/**\n * What a browser will actually store.\n *\n * RFC 6265 §6.1 requires at least 4096 bytes per cookie, and every browser\n * treats that as the limit — over it the cookie is DROPPED, silently, which\n * looks exactly like a user who is not signed in. A session that quietly stops\n * working once a field grows is the worst failure this file could have, so the\n * seal refuses instead and says what to do.\n */\nconst MAX_COOKIE_BYTES = 4096;\n\ninterface Sealed {\n readonly id: string;\n readonly createdAt: number;\n readonly data: SessionData;\n}\n\n/**\n * A session as one request holds it: what the cookie said, then every `update`\n * and `clear` since.\n */\nexport interface OpenSession {\n current: Sealed;\n /** Settles when the write in flight has, whichever way it went. */\n writing: Promise<unknown>;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\n// `Uint8Array<ArrayBuffer>`, not the default `ArrayBufferLike`: WebCrypto's\n// `BufferSource` requires the narrower one, and typing it here is what keeps a\n// cast off every call site — where the lint rightly objects to one that does not\n// change the type.\nfunction fromBase64url(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\");\n const binary = atob(padded.padEnd(Math.ceil(padded.length / 4) * 4, \"=\"));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\n/**\n * The key, derived per SALT rather than used raw.\n *\n * HKDF AND NOT PBKDF2, and the reason is correctness AND a denial of service.\n *\n * PBKDF2 exists to STRETCH a low-entropy secret — a human password — so that\n * guessing it costs an attacker real time. This input is not that: `password` is\n * refused below 32 characters and is documented as a key. Stretching something\n * already high-entropy buys nothing, and HKDF is the KDF for exactly this case.\n *\n * The cost of getting it wrong was MEASURED on this machine: PBKDF2 at 100,000\n * iterations is 7.93 ms and HKDF is 0.014 ms — 566x — per REQUEST, on every\n * request that touches a session. Worse, it is per request an ATTACKER makes:\n * the salt comes out of the cookie, so an unauthenticated client sending garbage\n * cookies chooses how much CPU each packet costs. Eight milliseconds a packet is\n * an amplifier, and HKDF removes it rather than bounding it.\n *\n * A fresh salt per seal still keeps two seals of the same data under the same\n * password from sharing a key, so the ciphertexts stay incomparable.\n */\nasync function deriveKey(password: string, salt: Uint8Array<ArrayBuffer>): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(password),\n \"HKDF\",\n false,\n [\"deriveKey\"],\n );\n return crypto.subtle.deriveKey(\n // `info` DOMAIN-SEPARATES the output, so a key derived here is not the key\n // the same secret would derive for anything else.\n { name: \"HKDF\", salt, info: HKDF_INFO, hash: \"SHA-256\" },\n material,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\n/**\n * Keys this process has derived AND seen authenticate, by password, then salt.\n *\n * A signed-in visitor sends one cookie on every request, so its salt and its\n * key repeat. WebCrypto answers on another thread, and measured on this machine\n * the derivation is 42 us of the 73 us an unseal costs; held, a repeat visit\n * pays for the decryption alone.\n *\n * Only a key that OPENED something is kept, or one this process sealed with. A\n * caller sending garbage cookies therefore adds nothing here and evicts no one,\n * which is what would otherwise make a cache of attacker-chosen salts a way to\n * push real visitors out of it.\n */\nconst DERIVED = new Map<string, Map<string, CryptoKey>>();\n/** Per password. The oldest goes first, and a key that is used is the newest. */\nconst DERIVED_KEYS = 1000;\n\nfunction keep(password: string, salt: string, key: CryptoKey): void {\n let keys = DERIVED.get(password);\n if (keys === undefined) {\n keys = new Map();\n DERIVED.set(password, keys);\n }\n keys.delete(salt);\n keys.set(salt, key);\n if (keys.size <= DERIVED_KEYS) return;\n const oldest = keys.keys().next().value;\n if (oldest !== undefined) keys.delete(oldest);\n}\n\n/**\n * What the tag covers beside the ciphertext: the cookie the session was sealed\n * FOR.\n *\n * One password commonly seals more than one cookie, and a tag that covers the\n * payload alone makes the value issued as `barq-session` a valid\n * `barq-session-admin` for anyone who renames it.\n */\nfunction nameBinding(config: SessionConfig): Uint8Array<ArrayBuffer> {\n const name = new TextEncoder().encode(config.name ?? DEFAULT_NAME);\n const binding = new Uint8Array(name.length + 1);\n binding[0] = NAME_BINDING;\n binding.set(name, 1);\n return binding;\n}\n\nfunction assertPassword(password: string): void {\n if (password.length < MINIMUM_PASSWORD) {\n throw new TypeError(\n `[barq] A session \\`password\\` must be at least ${MINIMUM_PASSWORD} characters, and this one is ${password.length}. ` +\n \"It is the key that encrypts the cookie, so a short one can be guessed. \" +\n \"Generate one with `crypto.randomUUID() + crypto.randomUUID()` and read it from an environment variable.\",\n );\n }\n}\n\n/** Encrypt and sign a session. Exported for code that seals outside a request. */\nexport async function sealSession(config: SessionConfig, session: Sealed): Promise<string> {\n assertPassword(config.password);\n const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const key = await deriveKey(config.password, salt);\n const plaintext = new TextEncoder().encode(JSON.stringify(session));\n const salted = base64url(salt);\n const sealed = new Uint8Array(\n await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: nameBinding(config) },\n key,\n plaintext,\n ),\n );\n const value = [VERSION, salted, base64url(iv), base64url(sealed)].join(\".\");\n // Name and value together, which is the sum a browser measures.\n const size = (config.name ?? DEFAULT_NAME).length + value.length;\n if (size > MAX_COOKIE_BYTES) {\n throw new RangeError(\n `[barq] This session is ${size} bytes once encrypted, counting the cookie name, and a browser drops any cookie over ${MAX_COOKIE_BYTES} bytes without an error. ` +\n \"The user would appear signed out. Keep only an id in the session and the rest in a store on the server.\",\n );\n }\n keep(config.password, salted, key);\n return value;\n}\n\n/**\n * Decrypt and verify, or `null`.\n *\n * `null` for EVERY failure — a wrong password, a tampered ciphertext, an expired\n * timestamp, a envelope from a future version — and never a throw. A session\n * that will not open is not an error the request should fail on; it is a visitor\n * who is not signed in, and the two must be indistinguishable to the caller so\n * that a forged cookie cannot be told apart from an absent one.\n */\nexport async function unsealSession(config: SessionConfig, sealed: string): Promise<Sealed | null> {\n assertPassword(config.password);\n const parts = sealed.split(\".\");\n if (parts.length !== 4) return null;\n const bound = parts[0] === VERSION;\n if (!bound && parts[0] !== NAMELESS_VERSION) return null;\n try {\n const key =\n DERIVED.get(config.password)?.get(parts[1]) ??\n (await deriveKey(config.password, fromBase64url(parts[1])));\n const plaintext = await crypto.subtle.decrypt(\n bound\n ? { name: \"AES-GCM\", iv: fromBase64url(parts[2]), additionalData: nameBinding(config) }\n : { name: \"AES-GCM\", iv: fromBase64url(parts[2]) },\n key,\n fromBase64url(parts[3]),\n );\n keep(config.password, parts[1], key);\n const session = JSON.parse(new TextDecoder().decode(plaintext)) as Sealed;\n if (typeof session.id !== \"string\" || typeof session.createdAt !== \"number\") return null;\n // The cookie's own expiry is a REQUEST the client is free to ignore. The\n // timestamp inside the sealed payload is the one that cannot be edited, so\n // it is the one that decides.\n const maxAge = config.maxAge ?? DEFAULT_MAX_AGE;\n if (Date.now() - session.createdAt > maxAge * 1000) return null;\n // AFTER the tag has verified, never before: asking first would let an\n // unauthenticated client drive a lookup with a garbage cookie, which is the\n // same amplifier the KDF used to be.\n if (config.isRevoked !== undefined && (await config.isRevoked(session.id))) return null;\n return session;\n } catch {\n // AES-GCM's tag failed, or the envelope was not ours. Same answer either way.\n return null;\n }\n}\n\nfunction cookieOptions(config: SessionConfig): CookieOptions {\n return {\n httpOnly: true,\n secure: true,\n sameSite: \"lax\",\n path: \"/\",\n maxAge: config.maxAge ?? DEFAULT_MAX_AGE,\n ...config.cookie,\n // The sealed value is base64url and a `.` separator, every character of\n // which a cookie carries as it stands — so it stays readable in devtools\n // rather than becoming a wall of `%3D`.\n encode: (value) => value,\n };\n}\n\n/**\n * The session for this request, opening the cookie if there is one.\n *\n * Always answers a manager, never `null`: a visitor with no session has an empty\n * one, which is the same thing from the application's side and removes the\n * branch that is easy to get backwards.\n *\n * NOTHING IS WRITTEN until `update` is called. Reading a session must not\n * re-issue its cookie, or every page render would refresh an expiry the user did\n * not earn — and on a page that also sets `Cache-Control: public` that\n * `Set-Cookie` is a cache poisoning waiting to happen.\n */\nexport async function useSession<T extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<SessionManager<T>> {\n assertPassword(config.password);\n const name = config.name ?? DEFAULT_NAME;\n // `getRequest` first, so the error outside a request names the real problem\n // rather than surfacing as an empty session.\n getRequest();\n\n // OPENED ONCE PER REQUEST AND NAME. The cookie on the request is what the\n // browser held before this request wrote anything, so a second reader that\n // unsealed it again would not see the first one's `update`, and would seal its\n // own change over it. Every manager for a name works on the one record.\n const sessions = openSessions();\n let opening = sessions.get(name);\n if (opening === undefined) {\n opening = open(config, getCookie(name));\n sessions.set(name, opening);\n }\n const session = await opening;\n\n // ONE WRITE AT A TIME. A write reads the record, seals across an `await` and\n // then stores what it sealed, so two that overlapped would both start from the\n // same record and the later cookie would drop the earlier change.\n const write = (change: (current: Sealed) => Promise<Sealed>): Promise<SessionManager<T>> => {\n const written = session.writing.then(async () => {\n session.current = await change(session.current);\n return manage();\n });\n session.writing = written.catch(() => undefined);\n return written;\n };\n\n const manage = (): SessionManager<T> => ({\n id: session.current.id,\n createdAt: session.current.createdAt,\n data: session.current.data as Partial<T>,\n update: (patch) =>\n write(async (current) => {\n const next = typeof patch === \"function\" ? patch(current.data as Partial<T>) : patch;\n const merged: Sealed = { ...current, data: { ...current.data, ...next } };\n replaceCookie(name, await sealSession(config, merged), cookieOptions(config));\n return merged;\n }),\n clear: () =>\n write(async () => {\n // EXPIRED, not re-sealed empty: an empty session cookie is still a cookie\n // the browser sends, and the user asked for it to be gone.\n replaceCookie(name, \"\", { ...cookieOptions(config), maxAge: 0, expires: new Date(0) });\n return { id: crypto.randomUUID(), createdAt: Date.now(), data: {} };\n }),\n });\n\n return manage();\n}\n\nasync function open(config: SessionConfig, cookie: string | undefined): Promise<OpenSession> {\n const opened = cookie === undefined ? null : await unsealSession(config, cookie);\n return {\n current: opened ?? { id: crypto.randomUUID(), createdAt: Date.now(), data: {} },\n writing: Promise.resolve(),\n };\n}\n\n/** The session's data, for code that only reads. */\nexport async function getSession<T extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<Session<T>> {\n const manager = await useSession<T>(config);\n // The SEALED timestamp, not now. `Date.now()` here reported every session as\n // brand new, which is exactly wrong for the one thing `createdAt` is for —\n // deciding how old a session is.\n return { id: manager.id, createdAt: manager.createdAt, data: manager.data };\n}\n\n/** Merge into the session and re-seal it. */\nexport async function updateSession<T extends SessionData = SessionData>(\n config: SessionConfig,\n patch: Partial<T> | ((current: Partial<T>) => Partial<T> | undefined),\n): Promise<SessionManager<T>> {\n return (await useSession<T>(config)).update(patch);\n}\n\n/** Drop the session and expire its cookie. */\nexport async function clearSession(config: SessionConfig): Promise<void> {\n await (await useSession(config)).clear();\n}\n","/**\n * `Server-Timing` entries for the development server: how long a page's\n * `beforeLoad`, its awaited loaders and its render took, and how long a server\n * function ran. The browser's network panel shows them under Timing.\n *\n * Callers gate on `isDev`, a literal `false` in a production build, so none of\n * this reaches a production response.\n */\n\n/** A clock that starts now and reads off one `Server-Timing` entry per phase. */\nexport interface ServerTiming {\n /** Close the phase that began at the last call (or at the start) under `name`. */\n phase(name: string, description: string): void;\n /** The header value, or `\"\"` when nothing was measured. */\n header(): string;\n}\n\nexport function serverTiming(): ServerTiming {\n const entries: string[] = [];\n let from = performance.now();\n return {\n phase(name, description) {\n const now = performance.now();\n entries.push(`${name};dur=${(now - from).toFixed(1)};desc=${JSON.stringify(description)}`);\n from = now;\n },\n header: () => entries.join(\", \"),\n };\n}\n","/**\n * Server functions — the builder, and the two stubs the compiler emits.\n *\n * A server function is written once and reachable from both sides. The compiler\n * decides which side a module is being compiled for and replaces the handler\n * with the matching stub: `serverRpc` on the server, where the body runs, and\n * `clientRpc` on the client, where it becomes a fetch. That decision is a\n * compile-time one and is never taken at runtime, so the body cannot reach a\n * client bundle by being unreachable-but-present.\n *\n * Nothing in this file is safe to call from a browser bundle except\n * `clientRpc`. `./server` is where the request handler lives.\n */\n\nexport {\n type ForwardedForTrust,\n type RequestContext,\n type ResponseDraft,\n appendResponseHeader,\n applyResponseDraft,\n clearResponseHeaders,\n collectRequestCss,\n createResponseDraft,\n devStylesheets,\n type DevStylesheets,\n deleteCookie,\n draftedStatus,\n getCookie,\n getCookies,\n getGlobalStartContext,\n getRequest,\n getRequestHeader,\n markResponseSent,\n getRequestHeaders,\n getRequestHost,\n getRequestIP,\n getRequestProtocol,\n getRequestUrl,\n getResponseHeader,\n getResponseHeaders,\n getResponseStatus,\n invalidateFrames,\n peekRequest,\n peekResponseDraft,\n removeResponseHeader,\n setCookie,\n setResponseHeader,\n setResponseHeaders,\n installCssSink,\n setRequestMiddlewareContext,\n setResponseStatus,\n takeSendContext,\n withRequest,\n} from \"./context.ts\";\n\nexport { type CookieOptions, deleteCookieLine, parseCookies, serializeCookie } from \"./cookies.ts\";\n\n/**\n * Sessions: a sealed cookie, with no store behind it.\n *\n * The interface is TanStack's; the SEALING is not: AES-GCM through WebCrypto rather than iron's AES-CBC plus a separate\n * HMAC, which costs no dependency and has no encrypt-then-MAC composition to get\n * wrong. A cookie sealed by one does not open in the other, and `session.ts`\n * says so where it can be read.\n */\n/**\n * Rate limiting, as a middleware — so one closure guards a server function and a\n * route handler alike. The STORE has no default on purpose; `rate-limit.ts` says\n * why at length.\n */\nexport {\n type RateLimitCount,\n type RateLimitOptions,\n type RateLimitStore,\n byIP,\n memoryStore,\n rateLimit,\n} from \"./rate-limit.ts\";\n\nexport {\n type Session,\n type SessionConfig,\n type SessionData,\n type SessionManager,\n clearSession,\n getSession,\n sealSession,\n unsealSession,\n updateSession,\n useSession,\n} from \"./session.ts\";\n\n/**\n * The client half lives in `./client.ts` and is re-exported here.\n *\n * SPLIT FOR ONE REASON: the compiler's client stub imports `clientRpc`, and\n * importing it from THIS module dragged `context.ts` — `node:async_hooks` — plus\n * the middleware runner and the validators into every client bundle that\n * reached one server function. Re-exporting keeps `import { createServerFn }\n * from \"@barqjs/start\"` the only thing an application writes.\n */\nexport {\n type AnyServerFn,\n type ChainStep,\n type RpcControl,\n type ServerFn,\n type ServerFnArgs,\n type ServerFnCallOptions,\n type ServerFnMeta,\n type ServerFnMethod,\n type Streamed,\n BUILD_HEADER,\n DATA_SUFFIX,\n LIVE_SUFFIX,\n NOT_FOUND,\n PAYLOAD_PARAM,\n REDIRECT,\n RPC_CALLER,\n RPC_CONTEXT,\n RPC_CONTROL,\n RPC_PREFIX,\n RPC_STREAM,\n RpcNotFound,\n RpcRedirect,\n SERVER_FN,\n STATIC_PREFIX,\n ServerFnError,\n UNKNOWN_HEADER,\n clientRpc,\n isServerFn,\n staticFunctionMiddleware,\n staticUrl,\n} from \"./client.ts\";\nexport type { ServerFnInputAnswer, ServerFnIssue, ServerFnThrown } from \"./client.ts\";\nexport { type ServerTiming, serverTiming } from \"./timing.ts\";\nexport { type BindingSlot, FRAME_APPLIED_EVENT, type Slot, isFrame } from \"./frames.ts\";\nexport { type LiveIterable, type LiveStatus, live } from \"./live-client.ts\";\n\nimport {\n type AnyServerFn,\n type ChainStep,\n SERVER_FN,\n SERVER_FN_CHAIN,\n type ServerFn,\n type ServerFnMeta,\n type ServerFnMethod,\n type Streamed,\n callOptionsOf,\n dataOf,\n inlineServerFns,\n urlOf,\n} from \"./client.ts\";\nimport { getGlobalStartContext, offerSendContext, peekRequest } from \"./context.ts\";\nimport { asFrame } from \"./frames.ts\";\nimport {\n type Carries,\n type ChainContribution,\n type Contribution,\n type Empty,\n type Merged,\n type Middleware,\n type NoContribution,\n type OpenContext,\n type StandardInput,\n type StandardOutput,\n type StandardSchemaLike,\n type Validator,\n type ValidatorInput,\n UncheckedInputError,\n applyValidator,\n flattenMiddleware,\n isBuiltMiddleware,\n runMiddleware,\n toValidator,\n} from \"./middleware.ts\";\nimport { type GlobalFunctionContext, startOptions } from \"./start-instance.ts\";\nimport type { Crossable, InputProblem, ResultProblem, StrictOn, Strictness } from \"./wire-types.ts\";\n\nexport type {\n Crossable,\n InputProblem,\n ResultProblem,\n StrictOn,\n Strictness,\n WireProblem,\n} from \"./wire-types.ts\";\n\nexport {\n type FunctionContextOf,\n type GlobalFunctionContext,\n type GlobalRequestContext,\n type Register,\n type RequestContextOf,\n type StartInstance,\n type StartOptions,\n clearStart,\n createStart,\n startOptions,\n} from \"./start-instance.ts\";\n\n/**\n * Middleware and the validator surface it composes, re-exported so an\n * application still writes one import. `middleware.ts` says why they live apart.\n */\nexport {\n type IsomorphicBuilder,\n type IsomorphicFn,\n createClientOnlyFn,\n createIsomorphicFn,\n createServerOnlyFn,\n} from \"./env.ts\";\n\nexport {\n type BuiltMiddleware,\n type Carries,\n type ChainContribution,\n type ClientReplaced,\n type DataAt,\n type FreshMiddleware,\n type FromNext,\n type OwnReplaced,\n type Plain,\n type ValidatorReplaced,\n type WithChain,\n type WithClient,\n type WithServer,\n type WithValidator,\n type ClientMiddlewareContext,\n type ContributedBy,\n type Contribution,\n type ContributionOf,\n type Empty,\n type Merged,\n type Middleware,\n type MiddlewareContext,\n type MiddlewareFn,\n type MiddlewareNext,\n type MiddlewareOptions,\n type MiddlewareState,\n type NextOptions,\n type NextResult,\n type NoContribution,\n type OpenContext,\n type RequestMiddleware,\n type RequestMiddlewareContext,\n type RequestMiddlewareFn,\n type RequestMiddlewareNext,\n type RequestMiddlewareStart,\n type StandardInput,\n type StandardOutput,\n type StandardSchema,\n type StandardSchemaLike,\n type Validator,\n type ValidatorInput,\n InputError,\n UncheckedInputError,\n ValidationError,\n applyValidator,\n createMiddleware,\n isInputError,\n flattenMiddleware,\n isBuiltMiddleware,\n runMiddleware,\n runRequestMiddleware,\n toValidator,\n} from \"./middleware.ts\";\n\nexport {\n type AnySerializationAdapter,\n type SerializationAdapter,\n createSerializationAdapter,\n} from \"@barqjs/server/codec\";\n\n/** TanStack's `json`: a JSON `Response`, which a handler returns as its answer. */\nexport function json(payload: unknown, init?: ResponseInit): Response {\n return Response.json(payload, init);\n}\n\nexport async function checkInput(\n built: { readonly validator: Validator<unknown> | null },\n raw: unknown,\n /**\n * Whether a MIDDLEWARE in the chain declared a validator.\n *\n * The refusal below asks \"does anything expect input?\", and before middleware\n * validators existed the function's own was the only thing that could answer.\n * A chain that validates has opened the channel just as surely, so refusing\n * here would make `.validator(schema)` on a middleware unusable by any\n * function that declares none of its own — which is the whole point of\n * putting one there.\n */\n chainValidates = false,\n): Promise<unknown> {\n if (built.validator === null) {\n // `undefined` is what a no-argument call sends, and it is the only input a\n // function with no validator accepts.\n if (raw !== undefined && !chainValidates) throw new UncheckedInputError();\n return raw;\n }\n return applyValidator(built.validator, raw);\n}\n\n/**\n * What a handler is handed, which is TanStack's shape:\n * `.handler(async ({ data }) => …)`.\n *\n * `context` is what the middleware chain contributed, merged outermost-first,\n * and typed by what each middleware passed to `next({ context })`.\n * `signal` aborts with the request, so a handler can hand it to `fetch` and a\n * client that navigates away stops paying for the work.\n */\nexport interface HandlerContext<In, Context extends object = Empty> {\n readonly data: In;\n readonly context: OpenContext<Context>;\n readonly signal: AbortSignal;\n /** The method this function answers. */\n readonly method: ServerFnMethod;\n /** Which function is running, by the id it is mounted at. Empty when it is not mounted. */\n readonly serverFnMeta: { readonly id: string };\n}\n\ninterface Built<Data, Out, Context extends object = Empty> {\n validator: Validator<unknown> | null;\n middleware: readonly Middleware[];\n handler: (context: HandlerContext<Data, Context>) => Out | Promise<Out>;\n}\n\ninterface Staged {\n readonly validator: Validator<unknown> | null;\n readonly middleware: readonly Middleware[];\n readonly method: ServerFnMethod;\n readonly broadcast: boolean;\n}\n\n/**\n * Where a server function's builder is: its chain, its own validator, its\n * method, and whether what crosses the wire is checked.\n */\nexport interface ServerFnState {\n readonly chain: Contribution;\n readonly own: Contribution;\n readonly method: ServerFnMethod;\n readonly strict: Strictness;\n}\n\nexport interface FreshServerFn<\n Method extends ServerFnMethod,\n Strict extends Strictness = true,\n> extends ServerFnState {\n readonly chain: NoContribution;\n readonly own: NoContribution;\n readonly method: Method;\n readonly strict: Strict;\n}\n\nexport interface FnWithChain<State extends ServerFnState, Chain> extends ServerFnState {\n readonly chain: Merged<State[\"chain\"], ChainContribution<Chain>>;\n readonly own: State[\"own\"];\n readonly method: State[\"method\"];\n readonly strict: State[\"strict\"];\n}\n\nexport interface Validates<In, Out> extends Contribution {\n readonly context: Empty;\n readonly sent: Empty;\n readonly clientContext: Empty;\n readonly input: In;\n readonly output: Out;\n readonly validates: true;\n}\n\nexport interface FnWithValidator<State extends ServerFnState, In, Out> extends ServerFnState {\n readonly chain: State[\"chain\"];\n readonly own: Validates<In, Out>;\n readonly method: State[\"method\"];\n readonly strict: State[\"strict\"];\n}\n\n/**\n * What a validator's input must also be: anything, unless it holds something\n * the codec cannot carry, when it must be a type naming that, which nothing is.\n */\nexport type InputCheck<State extends ServerFnState, In> =\n StrictOn<State[\"strict\"], \"input\"> extends true\n ? Crossable<InputProblem<In, State[\"method\"]>>\n : unknown;\n\n/** The same, for what a handler returns. */\nexport type ResultCheck<State extends ServerFnState, Result> =\n StrictOn<State[\"strict\"], \"output\"> extends true ? Crossable<ResultProblem<Result>> : unknown;\n\n/**\n * What the caller passes: the input of the first validator that runs, which is\n * a middleware's when the chain validates. `undefined` when nothing validates,\n * since a function that declares no validator accepts no argument.\n */\nexport type CallerInput<State extends ServerFnState> = State[\"chain\"][\"validates\"] extends true\n ? State[\"chain\"][\"input\"]\n : State[\"own\"][\"validates\"] extends true\n ? State[\"own\"][\"input\"]\n : undefined;\n\n/** What the handler is handed: the last validator's output. */\nexport type HandlerData<State extends ServerFnState> = State[\"own\"][\"validates\"] extends true\n ? State[\"own\"][\"output\"]\n : State[\"chain\"][\"validates\"] extends true\n ? State[\"chain\"][\"output\"]\n : undefined;\n\n/** What the handler's `context` holds: the global middleware's, then its own chain's. */\nexport type HandlerContextOf<State extends ServerFnState> = GlobalFunctionContext &\n State[\"chain\"][\"context\"];\n\n/**\n * The three-state discriminator, which is SvelteKit's idea and the best value\n * in the survey: no validator means any argument is a 400, and opening the\n * channel costs a schema or the literal `'unchecked'`.\n *\n * Every step is typed: the schema decides what a caller passes and what the\n * handler is handed, and each middleware's `next({ context })` decides what the\n * handler's `context` holds.\n */\nexport interface ServerFnBuilder<State extends ServerFnState = ServerFnState> {\n /**\n * Middleware that runs before the handler, after any listed before. A server\n * function in the list stands for the middleware it declared: its guards\n * run here, its handler does not.\n */\n middleware<const Chain extends readonly ChainStep[]>(\n chain: Chain,\n ): ServerFnBuilder<FnWithChain<State, Chain>>;\n /**\n * Open the input channel: a Standard Schema, a function that returns the\n * validated value or throws, an object with a `parse`, or `\"unchecked\"`.\n * What a caller passes is the schema's input, and what it produces is the\n * type of `data` in the handler. The schema form is tried first: an arktype\n * type is callable as well, and read as a function its input would be lost.\n */\n validator<Schema extends StandardSchemaLike>(\n schema: Schema & InputCheck<State, StandardInput<Schema>>,\n ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n validator<In, Out>(\n validate: ((input: In) => Out) & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n validator<In, Out>(\n schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n validator(unchecked: \"unchecked\"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;\n /** `validator` under the name TanStack's release candidates used. */\n inputValidator<Schema extends StandardSchemaLike>(\n schema: Schema & InputCheck<State, StandardInput<Schema>>,\n ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n inputValidator<In, Out>(\n validate: ((input: In) => Out) & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n inputValidator<In, Out>(\n schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n inputValidator(unchecked: \"unchecked\"): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;\n /**\n * The body. What it returns must cross the wire: a function, a symbol, or an\n * instance of a class the codec refuses is a type error here, naming where\n * it is. `createServerFn({ strict: false })` turns the check off.\n */\n handler<Result>(\n fn: ((\n context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,\n ) => Result | Promise<Result>) &\n ResultCheck<State, Result>,\n ): ServerFn<CallerInput<State>, Streamed<Awaited<Result>>, State[\"method\"]> &\n Carries<State[\"chain\"]>;\n}\n\n/**\n * What `createServerFn` accepts.\n *\n * `method` is TanStack's, with TanStack's default: `GET`. A function that\n * writes declares `POST`, which is also the only method a form can reach. A\n * link still cannot reach a `GET` one: every call carries the\n * {@link RPC_CALLER} header, which nothing but script can set, and the server\n * refuses a `GET` without it.\n */\nexport interface ServerFnOptions<\n Method extends ServerFnMethod = ServerFnMethod,\n Strict extends Strictness = Strictness,\n> {\n readonly method?: Method;\n /**\n * Whether the types refuse an input or a result the codec cannot carry. On\n * by default; `false` turns both off, `{ input: false }` or\n * `{ output: false }` one side. The codec still refuses at runtime what it\n * cannot carry: this only says the author knows, as for a class a\n * `createSerializationAdapter` carries.\n */\n readonly strict?: Strict;\n /**\n * The answer is the same for every caller with the same arguments, so a\n * `live` call shares one rendering with every other connection asking the\n * same thing: Solid 2.0's `broadcast`. The handler still runs per call, as the\n * gate it is (an auth check, a redirect), and a joiner's own answer is closed\n * unread. The shared rendering belongs to no request: it reads no cookie,\n * header or session, and it stops when its last connection goes.\n */\n readonly broadcast?: boolean;\n}\n\n/**\n * Author a server function. The value this returns is replaced by the compiler\n * on both sides, so what it does when compiled by nothing is only the\n * uncompiled-development path: it runs the handler in-process.\n */\nexport function createServerFn<\n Method extends ServerFnMethod = \"GET\",\n const Strict extends Strictness = true,\n>(options: ServerFnOptions<Method, Strict> = {}): ServerFnBuilder<FreshServerFn<Method, Strict>> {\n // A runtime refusal beside the type one, because a JavaScript application has\n // no type to fail.\n const method = options.method ?? \"GET\";\n if (method !== \"POST\" && method !== \"GET\") {\n throw new TypeError(\n `[barq] \\`createServerFn({ method: ${JSON.stringify(method)} })\\` is not supported: a server function answers GET or POST. ` +\n \"Use a route's `server.handlers` for any other method.\",\n );\n }\n return builderAt<FreshServerFn<Method, Strict>>({\n validator: null,\n middleware: [],\n method,\n broadcast: options.broadcast === true,\n });\n}\n\n/**\n * A NEW BUILDER PER STEP, as `createMiddleware` is: one that mutated a shared\n * record would let a base kept in a variable and finished twice hand the first\n * function the second one's handler, validator and chain.\n */\nfunction builderAt<State extends ServerFnState>(staged: Staged): ServerFnBuilder<State> {\n function validated<Schema extends StandardSchemaLike>(\n schema: Schema & InputCheck<State, StandardInput<Schema>>,\n ): ServerFnBuilder<FnWithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n function validated<In, Out>(\n validate: ((input: In) => Out) & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n function validated<In, Out>(\n schema: { readonly parse: (input: In) => Out } & InputCheck<State, In>,\n ): ServerFnBuilder<FnWithValidator<State, In, Awaited<Out>>>;\n function validated(\n unchecked: \"unchecked\",\n ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>>;\n function validated(\n schema: ValidatorInput<unknown>,\n ): ServerFnBuilder<FnWithValidator<State, unknown, unknown>> {\n return builderAt({ ...staged, validator: toValidator(schema) });\n }\n return {\n middleware: <const Chain extends readonly ChainStep[]>(chain: Chain) =>\n builderAt<FnWithChain<State, Chain>>({\n ...staged,\n middleware: [...staged.middleware, ...inlineServerFns(chain)],\n }),\n validator: validated,\n inputValidator: validated,\n handler: <Result>(\n fn: ((\n context: HandlerContext<HandlerData<State>, HandlerContextOf<State>>,\n ) => Result | Promise<Result>) &\n ResultCheck<State, Result>,\n ) =>\n serverRpc<\n CallerInput<State>,\n Result,\n HandlerData<State>,\n HandlerContextOf<State>,\n State[\"method\"]\n >(\n {\n id: \"\",\n ...(staged.method === \"GET\" ? { method: \"GET\" as const } : {}),\n ...(staged.broadcast ? { broadcast: true as const } : {}),\n },\n {\n validator: staged.validator,\n middleware: staged.middleware,\n handler: fn,\n },\n ),\n };\n}\n\n/**\n * The server half. The compiler emits this in a module compiled for the server,\n * with the real handler and the id it assigned.\n *\n * `In` is what a caller passes and `Data` what the handler is handed; the\n * validator is what turns one into the other, at runtime.\n */\nexport function serverRpc<\n In,\n Out,\n Data = In,\n Context extends object = Empty,\n Method extends ServerFnMethod = \"POST\",\n>(\n meta: ServerFnMeta,\n built: Built<Data, Out, Context>,\n): ServerFn<In, Streamed<Awaited<Out>>, Method> {\n // The application's global function middleware runs ahead of the function's\n // own, and is read when it is first needed: `src/start.ts` may be evaluated\n // after the module that declares this function. Flattening drops a step the\n // function lists again, so a guard named in both places runs once.\n let composed: {\n readonly from: readonly Middleware[] | undefined;\n readonly chain: readonly Middleware[];\n /** Whether a bare argument has somewhere to be validated before the handler. */\n readonly validates: boolean;\n } | null = null;\n const composition = (): NonNullable<typeof composed> => {\n const global = startOptions().functionMiddleware;\n if (composed !== null && composed.from === global) return composed;\n const chain = flattenMiddleware([...(global ?? []), ...built.middleware]);\n composed = {\n from: global,\n chain,\n validates: chain.some(\n (step) => isBuiltMiddleware(step) && step.options.validator !== undefined,\n ),\n };\n return composed;\n };\n\n const call = async (\n options?: unknown,\n /**\n * What the CLIENT's halves sent, and it is UNTRUSTED.\n *\n * A second positional rather than a property of `options`, so it is\n * invisible to the public `ServerFn` signature and cannot be reached by\n * writing `fn({ data, context })` in application code. The request handler\n * is the only caller that passes it.\n *\n * Handed to the chain BESIDE `context` and never merged into it. Merging it\n * under would let it survive wherever no server step set the same key on\n * this request, and a middleware that names the user only for a signed-in\n * caller would leave `context.user` to whoever is not signed in.\n */\n clientContext?: Record<string, unknown>,\n ): Promise<Streamed<Awaited<Out>>> => {\n const input = dataOf(options);\n const { chain, validates: chainValidates } = composition();\n // What the chain contributed, merged as it unwinds inward. One object the\n // chain mutates rather than one per step: `next({ context })` is additive\n // by definition, and a handler wants the union of everything above it. It\n // starts from what the request's own middleware already said.\n const context: Record<string, unknown> = { ...getGlobalStartContext() };\n const sendContext: Record<string, unknown> = {};\n // The call's own when it named one, which only an in-process caller can.\n // Otherwise the request's, so a caller that goes away stops the work it\n // asked for; with neither there is nothing to abort it.\n const signal =\n callOptionsOf(options)?.signal ?? peekRequest()?.signal ?? new AbortController().signal;\n\n // Middleware runs BEFORE the function's own validation. An unauthenticated\n // caller should be refused without the server parsing its payload first,\n // and a rejection that depended on the payload being well-formed would be\n // one an attacker could skip by sending a malformed one. A MIDDLEWARE's own\n // validator is the exception and has to be: its body is handed `data`.\n const method = meta.method ?? \"POST\";\n const result = await runMiddleware(chain, \"server\", {\n data: input,\n meta,\n method,\n signal,\n context,\n clientContext,\n sendContext,\n run: async (data) =>\n built.handler({\n // What the validators produced and what the chain wrote: the two\n // facts the builder's types describe, which exist only at runtime.\n data: (await checkInput(built, data, chainValidates)) as Data,\n context: context as OpenContext<Context>,\n signal,\n method,\n serverFnMeta: { id: meta.id },\n }),\n });\n\n offerSendContext(sendContext);\n // A `ReadableStream` is handed on as the async iterable every caller is\n // told to expect, so one in process reads what one in a browser does, and\n // a component is a frame, which a route renders and a browser asks for.\n if (result instanceof ReadableStream) return valuesOf(result) as Streamed<Awaited<Out>>;\n return asFrame(meta.id, input, result) as Streamed<Awaited<Out>>;\n };\n\n const fn = Object.assign(call, {\n [SERVER_FN]: true as const,\n [SERVER_FN_CHAIN]: built.middleware,\n meta,\n serverFnMeta: meta,\n method: meta.method ?? \"POST\",\n built,\n url: \"\",\n });\n // Read when asked: the id is stamped when the function is mounted.\n Object.defineProperty(fn, \"url\", { enumerable: true, get: () => urlOf(meta.id) });\n return fn;\n}\n\n/**\n * The middleware chain a server function carries, by REFERENCE.\n *\n * `serverRpc` attaches `built` to the function object, so the chain is the real\n * array of closures rather than something re-derived. That matters: a build\n * cannot read a chain out of source. `.middleware([m])`, `.middleware([...c])`\n * and `.middleware(c.filter(Boolean))` are all runtime expressions, and\n * `Middleware` is an anonymous closure with no build-visible identity — so the\n * only sound comparison is `===` against the same closure the route declared.\n *\n * Empty for a client stub, which carries no chain because it carries no handler.\n */\nexport function middlewareOf(fn: AnyServerFn): readonly Middleware[] {\n const built = (fn as unknown as { built?: Built<unknown, unknown> }).built;\n return built?.middleware ?? [];\n}\n\n/** A stream's values, releasing it when the reader leaves early. */\nasync function* valuesOf(stream: ReadableStream<unknown>): AsyncIterableIterator<unknown> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n void reader.cancel().catch(() => {});\n }\n}\n"],"mappings":";;;;;;;;AAiDA,MAAM,aAAa,SAA0B,QAAQ,MAAQ,SAAS;;AAGtE,SAAS,SAAS,MAAc,SAA6C;CAC3E,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SACvC,IAAI,QAAQ,KAAK,WAAW,KAAK,CAAC,GAAG,OAAO;CAE9C,OAAO;AACT;AAEA,MAAM,SAAS,eACb,IAAI,IAAI,MAAM,KAAK,aAAa,cAAc,UAAU,WAAW,CAAC,CAAC,CAAC;AAExE,MAAM,kBAAkB,MAAM,sBAAqB;AACnD,MAAM,mBAAmB,MAAM,SAAQ;AACvC,MAAM,YAAY;;;;;AAMlB,MAAM,iBAAiB,SAA0B,UAAU,IAAI,KAAK,gBAAgB,IAAI,IAAI;;AAG5F,MAAM,kBAAkB,SAA0B,UAAU,IAAI,KAAK,iBAAiB,IAAI,IAAI;;AAG9F,MAAM,sBAAsB,SAA0B,UAAU,IAAI,KAAK,SAAS;;;;;;;;;;AAWlF,SAAgB,aAAa,QAA2D;CACtF,MAAM,MAA8B,OAAO,OAAO,IAAI;CACtD,IAAI,WAAW,QAAQ,WAAW,KAAA,KAAa,WAAW,IAAI,OAAO;CAErE,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,GAAG;EACpC,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,SAAS,GAAG;EAChB,MAAM,OAAO,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,KAAK;EACxC,IAAI,SAAS,MAAM,QAAQ,KAAK;EAChC,IAAI,QAAQ,KAAK,MAAM,SAAS,CAAC,CAAC,CAAC,KAAK;EAExC,IAAI,MAAM,SAAS,KAAK,MA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AgB,aAAa,IAAwC;CAEnE,OADe,GAAsD,OACvD,cAAc,CAAC;AAC/B;;AAGA,gBAAgB,SAAS,QAAiE;CACxF,MAAM,SAAS,OAAO,UAAU;CAChC,IAAI;EACF,SAAS;GACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MAAM;GACV,MAAM;EACR;CACF,UAAU;EACH,OAAO,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACrC;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { createMiddleware } from "./middleware.js";
|
|
2
1
|
import { decodeWire, encodeWire } from "@barqjs/server/codec";
|
|
3
|
-
|
|
2
|
+
import { createMiddleware } from "./middleware.js";
|
|
3
|
+
// src/static-fn.ts
|
|
4
4
|
/**
|
|
5
5
|
* Static server functions: answered once, at prerender time, and read back as
|
|
6
6
|
* files.
|
|
@@ -56,18 +56,18 @@ function sorted(value) {
|
|
|
56
56
|
*/
|
|
57
57
|
function staticKey(id, input) {
|
|
58
58
|
const text = `${id}\n${input}`;
|
|
59
|
-
return hash53(text,
|
|
59
|
+
return hash53(text, 0x9e3779b9).toString(16).padStart(14, "0") + hash53(text, 0x85ebca6b).toString(16).padStart(14, "0");
|
|
60
60
|
}
|
|
61
61
|
function hash53(text, seed) {
|
|
62
|
-
let h1 =
|
|
63
|
-
let h2 =
|
|
62
|
+
let h1 = 0xdeadbeef ^ seed;
|
|
63
|
+
let h2 = 0x41c6ce57 ^ seed;
|
|
64
64
|
for (let index = 0; index < text.length; index++) {
|
|
65
65
|
const code = text.charCodeAt(index);
|
|
66
|
-
h1 = Math.imul(h1 ^ code,
|
|
67
|
-
h2 = Math.imul(h2 ^ code,
|
|
66
|
+
h1 = Math.imul(h1 ^ code, 0x9e3779b1);
|
|
67
|
+
h2 = Math.imul(h2 ^ code, 0x5f356495);
|
|
68
68
|
}
|
|
69
|
-
h1 = Math.imul(h1 ^ h1 >>> 16,
|
|
70
|
-
h2 = Math.imul(h2 ^ h2 >>> 16,
|
|
69
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 0x85ebca6b) ^ Math.imul(h2 ^ h2 >>> 13, 0xc2b2ae35);
|
|
70
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 0x85ebca6b) ^ Math.imul(h1 ^ h1 >>> 13, 0xc2b2ae35);
|
|
71
71
|
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
|
72
72
|
}
|
|
73
73
|
/** Where the answer for one call is, as a URL. */
|
|
@@ -117,7 +117,6 @@ const staticFunctionMiddleware = /* @__PURE__ */ createMiddleware({ type: "funct
|
|
|
117
117
|
}
|
|
118
118
|
return answer;
|
|
119
119
|
});
|
|
120
|
-
//#endregion
|
|
121
120
|
export { staticUrl as i, installStaticWriter as n, staticFunctionMiddleware as r, STATIC_PREFIX as t };
|
|
122
121
|
|
|
123
|
-
//# sourceMappingURL=static-fn-
|
|
122
|
+
//# sourceMappingURL=static-fn-CXjJi-It.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static-fn-
|
|
1
|
+
{"version":3,"file":"static-fn-CXjJi-It.js","names":[],"sources":["../src/static-fn.ts"],"sourcesContent":["/**\n * Static server functions: answered once, at prerender time, and read back as\n * files.\n *\n * `staticFunctionMiddleware` is TanStack's. While the build prerenders, its\n * server half writes each call's answer to `/_barq/static/<key>.json` in the\n * client output; in the browser its client half asks for that file first and\n * calls the server only when there is none. A site prerendered whole can then\n * answer these calls from a static host with no server at all.\n *\n * Nothing here imports anything that is not safe in a browser: the client stub\n * names this middleware, so the whole module reaches the client bundle. The\n * writer that touches the disk belongs to the prerenderer and is handed over\n * through {@link installStaticWriter}.\n */\n\nimport { decodeWire, encodeWire } from \"@barqjs/server/codec\";\n\nimport {\n type BuiltMiddleware,\n type FreshMiddleware,\n type WithClient,\n type WithServer,\n createMiddleware,\n} from \"./middleware.ts\";\n\n/** Where a static answer is served from, under the client output. */\nexport const STATIC_PREFIX = \"/_barq/static/\";\n\n/** What a static answer file holds. */\nexport interface StaticAnswer {\n readonly result: unknown;\n}\n\n/**\n * What the prerenderer hands over to receive each answer: the file's key, the\n * function and input it was derived from, and the file's contents.\n */\nexport type StaticWriter = (key: string, identity: string, answer: string) => Promise<void>;\n\n/**\n * One writer per process, whichever copy of this module asks: the prerenderer\n * imports the server bundle, which carries a copy of its own, and installs the\n * writer from outside it.\n */\nconst SHARED = ((globalThis as Record<symbol, unknown>)[Symbol.for(\"barq.start.static-writer\")] ??=\n { writer: null }) as { writer: StaticWriter | null };\n\n/** Install the prerenderer's writer, or remove it with `null`. Not for application use. */\nexport function installStaticWriter(writer: StaticWriter | null): void {\n SHARED.writer = writer;\n}\n\n/**\n * The input as one string that does not depend on how the caller ordered its\n * keys: `{ a, b }` and `{ b, a }` are the same call and must find the same\n * file.\n */\nexport function canonicalInput(input: unknown): string {\n return JSON.stringify(encodeWire(sorted(input)));\n}\n\nfunction sorted(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sorted);\n if (typeof value !== \"object\" || value === null) return value;\n const prototype: unknown = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value).toSorted()) {\n out[key] = sorted((value as Record<string, unknown>)[key]);\n }\n return out;\n}\n\n/**\n * The file name for one function and one input.\n *\n * Two independent 53-bit hashes, so a name is 106 bits wide: a collision would\n * hand one input's answer to another, and the prerenderer refuses one outright\n * if it ever sees it. Not a cryptographic hash, because nothing here is secret\n * and `crypto.subtle` exists only in a secure context, which a page served over\n * plain HTTP is not.\n */\nexport function staticKey(id: string, input: string): string {\n const text = `${id}\\n${input}`;\n return (\n hash53(text, 0x9e3779b9).toString(16).padStart(14, \"0\") +\n hash53(text, 0x85ebca6b).toString(16).padStart(14, \"0\")\n );\n}\n\nfunction hash53(text: string, seed: number): number {\n let h1 = 0xdeadbeef ^ seed;\n let h2 = 0x41c6ce57 ^ seed;\n for (let index = 0; index < text.length; index++) {\n const code = text.charCodeAt(index);\n h1 = Math.imul(h1 ^ code, 2654435761);\n h2 = Math.imul(h2 ^ code, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return 4294967296 * (2097151 & h2) + (h1 >>> 0);\n}\n\n/** Where the answer for one call is, as a URL. */\nexport function staticUrl(id: string, input: unknown): string {\n return `${STATIC_PREFIX}${staticKey(id, canonicalInput(input))}.json`;\n}\n\n/** Whether an answer can be written to a file and read back as the same value. */\nfunction cacheable(answer: unknown): boolean {\n // A client half answering `undefined` without calling `next()` is refused as\n // a middleware that forgot to, so a result of nothing goes to the server.\n if (answer === undefined) return false;\n if (answer instanceof Response || answer instanceof ReadableStream) return false;\n return !(\n typeof answer === \"object\" &&\n answer !== null &&\n typeof (answer as Partial<AsyncIterable<unknown>>)[Symbol.asyncIterator] === \"function\"\n );\n}\n\nconst MISSING = Symbol(\"missing\");\n\n/** The file's answer, or {@link MISSING} when there is no file to read. */\nasync function readStatic(id: string, input: unknown): Promise<unknown> {\n let response: Response;\n try {\n response = await fetch(staticUrl(id, input), { headers: { accept: \"application/json\" } });\n } catch {\n return MISSING;\n }\n // A dev server or a host with an SPA fallback answers a missing file with a\n // page, so the type is what says the file exists.\n if (!response.ok || !(response.headers.get(\"content-type\") ?? \"\").includes(\"json\")) {\n return MISSING;\n }\n return decodeWire<StaticAnswer>(await response.json()).result;\n}\n\n/**\n * Make a server function static: answered at prerender time, read from a file\n * afterwards.\n *\n * List it LAST: the key is the input as this middleware sees it, which is the\n * input the caller passed only when nothing before it has validated or\n * reshaped it. An input no prerendered page called with has no file, and the\n * call goes to the server as any other would.\n *\n * Only the RESULT is stored. What a server middleware sends back with\n * `sendContext` is not, and a `Response` or a stream is never written.\n */\nexport const staticFunctionMiddleware: BuiltMiddleware<\n WithServer<WithClient<FreshMiddleware, Promise<{} | null>>, Promise<unknown>>\n> = /* @__PURE__ */ createMiddleware({ type: \"function\" })\n .client(async ({ next, data, serverFnMeta }) => {\n if (serverFnMeta === undefined || serverFnMeta.id === \"\" || data instanceof FormData) {\n return next();\n }\n const found = await readStatic(serverFnMeta.id, data);\n return found === MISSING || found === undefined ? next() : found;\n })\n .server(async ({ next, data, serverFnMeta }) => {\n const answer: unknown = await next();\n const writer = SHARED.writer;\n if (\n writer !== null &&\n serverFnMeta !== undefined &&\n serverFnMeta.id !== \"\" &&\n !(data instanceof FormData) &&\n cacheable(answer)\n ) {\n const input = canonicalInput(data);\n await writer(\n staticKey(serverFnMeta.id, input),\n `${serverFnMeta.id}\\n${input}`,\n JSON.stringify(encodeWire({ result: answer } satisfies StaticAnswer)),\n );\n }\n return answer;\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,MAAa,gBAAgB;;;;;;AAkB7B,MAAM,SAAW,WAAuC,OAAO,IAAI,0BAA0B,OAC3F,EAAE,QAAQ,KAAK;;AAGjB,SAAgB,oBAAoB,QAAmC;CACrE,OAAO,SAAS;AAClB;;;;;;AAOA,SAAgB,eAAe,OAAwB;CACrD,OAAO,KAAK,UAAU,WAAW,OAAO,KAAK,CAAC,CAAC;AACjD;AAEA,SAAS,OAAO,OAAyB;CACvC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,MAAM;CACjD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,KAAK;CACtD,IAAI,cAAc,OAAO,aAAa,cAAc,MAAM,OAAO;CACjE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,GAC5C,IAAI,OAAO,OAAQ,MAAkC,IAAI;CAE3D,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,UAAU,IAAY,OAAuB;CAC3D,MAAM,OAAO,GAAG,GAAG,I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AAK,GAAA,CAAI,SAAS,MAAM,GAC/E,OAAO;CAET,OAAO,WAAyB,MAAM,SAAS,KAAK,CAAC,CAAC,CAAC;AACzD;;;;;;;;;;;;;AAcA,MAAa,2BAEO,iCAAiB,EAAE,MAAM,WAAW,CAAC,CAAC,CACvD,OAAO,OAAO,EAAE,MAAM,MAAM,mBAAmB;CAC9C,IAAI,iBAAiB,KAAA,KAAa,aAAa,OAAO,MAAM,gBAAgB,UAC1E,OAAO,KAAK;CAEd,MAAM,QAAQ,MAAM,WAAW,aAAa,IAAI,IAAI;CACpD,OAAO,UAAU,WAAW,UAAU,KAAA,IAAY,KAAK,IAAI;AAC7D,CAAC,CAAC,CACD,OAAO,OAAO,EAAE,MAAM,MAAM,mBAAmB;CAC9C,MAAM,SAAkB,MAAM,KAAK;CACnC,MAAM,SAAS,OAAO;CACtB,IACE,WAAW,QACX,iBAAiB,KAAA,KACjB,aAAa,OAAO,MACpB,EAAE,gBAAgB,aAClB,UAAU,MAAM,GAChB;EACA,MAAM,QAAQ,eAAe,IAAI;EACjC,MAAM,OACJ,UAAU,aAAa,IAAI,KAAK,GAChC,GAAG,aAAa,GAAG,IAAI,SACvB,KAAK,UAAU,WAAW,EAAE,QAAQ,OAAO,CAAwB,CAAC,CACtE;CACF;CACA,OAAO;AACT,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@barqjs/start",
|
|
3
|
-
"version": "0.2.0-next.
|
|
3
|
+
"version": "0.2.0-next.1",
|
|
4
4
|
"description": "Server functions, middleware, sessions, cookies and the built server for barq",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"barq",
|
|
@@ -86,21 +86,21 @@
|
|
|
86
86
|
"test": "bun test --timeout 10000 && bun test --timeout 10000 --conditions=development"
|
|
87
87
|
},
|
|
88
88
|
"dependencies": {
|
|
89
|
-
"@barqjs/css": "0.2.0-next.
|
|
90
|
-
"srvx": "^1.0.
|
|
89
|
+
"@barqjs/css": "0.2.0-next.1",
|
|
90
|
+
"srvx": "^1.0.8"
|
|
91
91
|
},
|
|
92
92
|
"devDependencies": {
|
|
93
|
-
"@barqjs/compiler": "0.2.0-next.
|
|
94
|
-
"@barqjs/core": "0.2.0-next.
|
|
95
|
-
"@barqjs/server": "0.2.0-next.
|
|
96
|
-
"@barqjs/web": "0.2.0-next.
|
|
97
|
-
"@types/bun": "^1.4.
|
|
93
|
+
"@barqjs/compiler": "0.2.0-next.1",
|
|
94
|
+
"@barqjs/core": "0.2.0-next.1",
|
|
95
|
+
"@barqjs/server": "0.2.0-next.1",
|
|
96
|
+
"@barqjs/web": "0.2.0-next.1",
|
|
97
|
+
"@types/bun": "^1.4.4",
|
|
98
98
|
"typescript": "^7.0.2"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
|
-
"@barqjs/core": ">=0.2.0-next.
|
|
102
|
-
"@barqjs/server": ">=0.2.0-next.
|
|
103
|
-
"@barqjs/web": ">=0.2.0-next.
|
|
101
|
+
"@barqjs/core": ">=0.2.0-next.1",
|
|
102
|
+
"@barqjs/server": ">=0.2.0-next.1",
|
|
103
|
+
"@barqjs/web": ">=0.2.0-next.1"
|
|
104
104
|
},
|
|
105
105
|
"engines": {
|
|
106
106
|
"node": ">=20.16.0"
|
package/src/client.ts
CHANGED
|
@@ -42,7 +42,12 @@ import { startOptions } from "./start-instance.ts";
|
|
|
42
42
|
|
|
43
43
|
export { STATIC_PREFIX, staticFunctionMiddleware, staticUrl } from "./static-fn.ts";
|
|
44
44
|
export { NOT_FOUND, REDIRECT } from "./middleware.ts";
|
|
45
|
-
export {
|
|
45
|
+
export {
|
|
46
|
+
ServerFnError,
|
|
47
|
+
UNKNOWN_HEADER,
|
|
48
|
+
type ServerFnIssue,
|
|
49
|
+
type ServerFnThrown,
|
|
50
|
+
} from "./fn-error.ts";
|
|
46
51
|
export { LIVE_CALL, type LiveRequest, clientStub } from "./stubs.ts";
|
|
47
52
|
export { type FrameComponent, applyFrameResponse, frameAdapter } from "./frames-client.ts";
|
|
48
53
|
export { type LiveIterable, type LiveStatus, live } from "./live-client.ts";
|
|
@@ -242,6 +247,8 @@ export interface ServerFnMeta {
|
|
|
242
247
|
id: string;
|
|
243
248
|
/** Absent for `POST`, which is every function that did not ask for `GET`. */
|
|
244
249
|
readonly method?: ServerFnMethod;
|
|
250
|
+
/** Declared `createServerFn({ broadcast: true })`; the server half alone knows it. */
|
|
251
|
+
readonly broadcast?: true;
|
|
245
252
|
}
|
|
246
253
|
|
|
247
254
|
/**
|
|
@@ -257,6 +264,20 @@ export interface ServerFnMeta {
|
|
|
257
264
|
*/
|
|
258
265
|
export const RPC_CALLER = "x-barq-fn";
|
|
259
266
|
|
|
267
|
+
/**
|
|
268
|
+
* The build a call was bundled with. A server stamped with another build
|
|
269
|
+
* answers it with a 409 rather than running a function whose arguments or
|
|
270
|
+
* result may have changed shape under the same id. A GET read does not send
|
|
271
|
+
* it: its url is its identity to every cache in between.
|
|
272
|
+
*/
|
|
273
|
+
export const BUILD_HEADER = "x-barq-build";
|
|
274
|
+
|
|
275
|
+
declare const __BARQ_BUILD__: string | undefined;
|
|
276
|
+
|
|
277
|
+
/** The build `@barqjs/vite` stamped this bundle with, or none outside a build. */
|
|
278
|
+
export const BUNDLED_BUILD: string | undefined =
|
|
279
|
+
typeof __BARQ_BUILD__ === "string" ? __BARQ_BUILD__ : undefined;
|
|
280
|
+
|
|
260
281
|
/** Where a GET call's payload rides, since a GET has no body. */
|
|
261
282
|
export const PAYLOAD_PARAM = "payload";
|
|
262
283
|
|
|
@@ -468,6 +489,11 @@ export function clientRpc<In, Out, Method extends ServerFnMethod = "POST">(
|
|
|
468
489
|
if (live.lastEventId !== null) withPosition.set("last-event-id", live.lastEventId);
|
|
469
490
|
headers = withPosition;
|
|
470
491
|
}
|
|
492
|
+
if (BUNDLED_BUILD !== undefined && method !== "GET") {
|
|
493
|
+
const withBuild = new Headers(headers);
|
|
494
|
+
withBuild.set(BUILD_HEADER, BUNDLED_BUILD);
|
|
495
|
+
headers = withBuild;
|
|
496
|
+
}
|
|
471
497
|
const endpoint =
|
|
472
498
|
RPC_PREFIX + encodeURIComponent(id) + (live === undefined ? DATA_SUFFIX : LIVE_SUFFIX);
|
|
473
499
|
const response = await (asked?.fetch ?? chainFetch ?? startOptions().serverFns?.fetch ?? fetch)(
|
package/src/context.ts
CHANGED
|
@@ -161,10 +161,40 @@ export function collectRequestCss(): string {
|
|
|
161
161
|
return store?.css === undefined ? "" : [...store.css.values()].join("");
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
const DEV_STYLESHEETS = Symbol.for("barq.dev.stylesheets");
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The compiled module stylesheets a page made of `routes` reaches, in the order
|
|
168
|
+
* the page's modules run, when a dev server answered that, and `undefined`
|
|
169
|
+
* where none did: a build links its stylesheets instead of inlining them.
|
|
170
|
+
*
|
|
171
|
+
* A dev server imports the application once and renders every page from the
|
|
172
|
+
* one registry, so without this a page's head carried the rules of every module
|
|
173
|
+
* any earlier request had reached. `@barqjs/vite` installs the answer, read off
|
|
174
|
+
* its module graph in the order a build links the same modules' stylesheets.
|
|
175
|
+
*/
|
|
176
|
+
export function devStylesheets(
|
|
177
|
+
routes: readonly string[],
|
|
178
|
+
): Promise<DevStylesheets | undefined> | undefined {
|
|
179
|
+
const answer = (
|
|
180
|
+
globalThis as {
|
|
181
|
+
[DEV_STYLESHEETS]?: (routes: readonly string[]) => Promise<DevStylesheets>;
|
|
182
|
+
}
|
|
183
|
+
)[DEV_STYLESHEETS];
|
|
184
|
+
return answer?.(routes);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** `@barqjs/css`'s `CssScope`, restated so this package does not import that one. */
|
|
188
|
+
export interface DevStylesheets {
|
|
189
|
+
readonly keys: readonly string[];
|
|
190
|
+
readonly modules: ReadonlySet<string>;
|
|
191
|
+
}
|
|
192
|
+
|
|
164
193
|
/** `@barqjs/css`'s `CssSink`, restated so this package does not import that one. */
|
|
165
194
|
interface CssSink {
|
|
166
195
|
(key: string, rules: string): boolean;
|
|
167
196
|
head?(late: () => string): void;
|
|
197
|
+
owns?(key: string): boolean;
|
|
168
198
|
}
|
|
169
199
|
|
|
170
200
|
export function installCssSink(setSink: (sink: CssSink) => void): void {
|
|
@@ -183,6 +213,9 @@ export function installCssSink(setSink: (sink: CssSink) => void): void {
|
|
|
183
213
|
const store = SHARED.storage?.getStore();
|
|
184
214
|
if (store !== undefined) store.lateCss ??= late;
|
|
185
215
|
};
|
|
216
|
+
// Outside a request every rule is every page's, so nothing is owned and the
|
|
217
|
+
// registry shows what no request registered.
|
|
218
|
+
sink.owns = (key) => SHARED.storage?.getStore()?.css?.has(key) === true;
|
|
186
219
|
setSink(sink);
|
|
187
220
|
}
|
|
188
221
|
|
package/src/fn-error.ts
CHANGED
|
@@ -18,6 +18,14 @@ export interface ServerFnIssue {
|
|
|
18
18
|
readonly path?: readonly (string | number)[];
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* The label on an answer from a deployment that does not know the call: an
|
|
23
|
+
* unknown id (a tab holding the previous build's ids across a deploy, or a
|
|
24
|
+
* removed function), or a call from another build. A CDN 404 and a skew 404
|
|
25
|
+
* look alike without it.
|
|
26
|
+
*/
|
|
27
|
+
export const UNKNOWN_HEADER = "x-barq-fn-unknown";
|
|
28
|
+
|
|
21
29
|
/** What a failed call's JSON body may carry. */
|
|
22
30
|
export interface FailedAnswer {
|
|
23
31
|
readonly message?: string;
|
|
@@ -59,16 +67,32 @@ export class ServerFnError extends Error {
|
|
|
59
67
|
* for the reason above.
|
|
60
68
|
*/
|
|
61
69
|
readonly response?: Response;
|
|
70
|
+
/**
|
|
71
|
+
* The deployment that answered does not know this call: the page came from
|
|
72
|
+
* another build, or the function was removed. Retrying cannot help; reloading
|
|
73
|
+
* the document onto the current build can.
|
|
74
|
+
*/
|
|
75
|
+
readonly unknownFunction?: true;
|
|
62
76
|
constructor(id: string, status: number, response?: Response, answer?: FailedAnswer) {
|
|
63
|
-
|
|
77
|
+
const unknown = (response?.headers.get(UNKNOWN_HEADER) ?? null) !== null;
|
|
78
|
+
super(unknown ? skewMessage(id, status) : failureMessage(id, status, answer));
|
|
64
79
|
this.name = "ServerFnError";
|
|
65
80
|
this.status = status;
|
|
66
81
|
this.response = response;
|
|
82
|
+
if (unknown) this.unknownFunction = true;
|
|
67
83
|
if (answer?.issues !== undefined) this.issues = answer.issues;
|
|
68
84
|
if (answer?.thrown !== undefined) this.thrown = answer.thrown;
|
|
69
85
|
}
|
|
70
86
|
}
|
|
71
87
|
|
|
88
|
+
function skewMessage(id: string, status: number): string {
|
|
89
|
+
return (
|
|
90
|
+
`The server function \`${id}\` is not part of the deployment that answered (${status}): this ` +
|
|
91
|
+
"page came from another build, or the function was removed. Reload the page to run the " +
|
|
92
|
+
"current build; `error.unknownFunction` is set for exactly this case."
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
72
96
|
function failureMessage(id: string, status: number, answer: FailedAnswer | undefined): string {
|
|
73
97
|
const issues = answer?.issues;
|
|
74
98
|
if (issues !== undefined && issues.length > 0) {
|
package/src/frames-client.ts
CHANGED
|
@@ -948,7 +948,11 @@ async function loadStylesheets(head: readonly HeadTag[]): Promise<void> {
|
|
|
948
948
|
link.addEventListener("error", () => resolve(), { once: true });
|
|
949
949
|
}),
|
|
950
950
|
);
|
|
951
|
-
|
|
951
|
+
// In front of the build's atoms, which win a property against a `css`
|
|
952
|
+
// block of the same specificity by being linked after it.
|
|
953
|
+
const atoms = document.head.querySelector('link[rel="stylesheet"][data-barq-atoms]');
|
|
954
|
+
if (atoms === null) document.head.appendChild(link);
|
|
955
|
+
else atoms.before(link);
|
|
952
956
|
}
|
|
953
957
|
await Promise.all(loading);
|
|
954
958
|
}
|