@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.
Files changed (56) hide show
  1. package/README.md +26 -0
  2. package/dist/{client-BHyIiYxt.js → client-BsyxVCyu.js} +49 -22
  3. package/dist/client-BsyxVCyu.js.map +1 -0
  4. package/dist/{client-DHCV7yvQ.d.ts → client-DidH0F2e.d.ts} +28 -18
  5. package/dist/client-DidH0F2e.d.ts.map +1 -0
  6. package/dist/client.d.ts +25 -3
  7. package/dist/client.js +3 -3
  8. package/dist/{env-qA8EyOr1.d.ts → env-Bhk_aIkx.d.ts} +1 -3
  9. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  10. package/dist/env.d.ts +1 -1
  11. package/dist/env.js +1 -2
  12. package/dist/{index-Bm_-MTj6.d.ts → index-B4o7eyCr.d.ts} +32 -22
  13. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  14. package/dist/index.d.ts +18 -5
  15. package/dist/index.js +4 -4
  16. package/dist/{middleware-BdVlE8qm.d.ts → middleware-B-tI8QHQ.d.ts} +1 -3
  17. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  18. package/dist/middleware.d.ts +1 -1
  19. package/dist/middleware.js +1 -2
  20. package/dist/middleware.js.map +1 -1
  21. package/dist/prerender.d.ts +22 -2
  22. package/dist/prerender.d.ts.map +1 -1
  23. package/dist/prerender.js +4 -4
  24. package/dist/prerender.js.map +1 -1
  25. package/dist/protocol.d.ts +0 -2
  26. package/dist/protocol.d.ts.map +1 -1
  27. package/dist/protocol.js +1 -2
  28. package/dist/serve.d.ts +14 -5
  29. package/dist/serve.d.ts.map +1 -1
  30. package/dist/serve.js +3 -5
  31. package/dist/serve.js.map +1 -1
  32. package/dist/{server-BV3xKmLa.js → server-DG6jb_NA.js} +162 -57
  33. package/dist/server-DG6jb_NA.js.map +1 -0
  34. package/dist/server.d.ts +21 -4
  35. package/dist/server.d.ts.map +1 -1
  36. package/dist/server.js +1 -1
  37. package/dist/{src-ChnB_xug.js → src-odXG7kLA.js} +31 -20
  38. package/dist/src-odXG7kLA.js.map +1 -0
  39. package/dist/{static-fn-DgjNArBe.js → static-fn-CXjJi-It.js} +10 -11
  40. package/dist/{static-fn-DgjNArBe.js.map → static-fn-CXjJi-It.js.map} +1 -1
  41. package/package.json +11 -11
  42. package/src/client.ts +27 -1
  43. package/src/context.ts +33 -0
  44. package/src/fn-error.ts +25 -1
  45. package/src/frames-client.ts +5 -1
  46. package/src/index.ts +32 -6
  47. package/src/live-server.ts +154 -44
  48. package/src/server.ts +43 -7
  49. package/src/wire-types.ts +2 -3
  50. package/dist/client-BHyIiYxt.js.map +0 -1
  51. package/dist/client-DHCV7yvQ.d.ts.map +0 -1
  52. package/dist/env-qA8EyOr1.d.ts.map +0 -1
  53. package/dist/index-Bm_-MTj6.d.ts.map +0 -1
  54. package/dist/middleware-BdVlE8qm.d.ts.map +0 -1
  55. package/dist/server-BV3xKmLa.js.map +0 -1
  56. package/dist/src-ChnB_xug.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.js","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware, and the input validation it composes.\n *\n * ITS OWN MODULE FOR ONE REASON: `client.ts` needs it. A middleware's client\n * half runs in the browser, so the runner has to be reachable from the client\n * stub — and `index.ts` re-exports `context.ts`, which reaches\n * `node:async_hooks`. Importing the index from `client.ts` is the leak\n * `DEFAULT_CLIENT_SOURCE` exists to avoid, and it is not theoretical: the same\n * import through a route's `middleware` once left a fully server-rendered page\n * on which nothing was interactive.\n *\n * Nothing here imports anything of barq's, for that reason.\n */\n\n/**\n * A validator in the Standard Schema shape, which zod, valibot and arktype all\n * implement. Taking the interface rather than a library keeps the dependency\n * out and lets an application bring its own.\n */\nexport interface StandardSchema<In = unknown, Out = In> {\n \"~standard\": {\n version: 1;\n vendor: string;\n validate: (\n value: unknown,\n ) =>\n | { value: Out }\n | { issues: ReadonlyArray<unknown> }\n | Promise<{ value: Out } | { issues: ReadonlyArray<unknown> }>;\n /** The spec's type carrier: what the schema takes and what it produces. */\n readonly types?: { readonly input: In; readonly output: Out };\n };\n}\n\n/** Anything with a Standard Schema validator on it, which is all a schema is read for. */\nexport interface StandardSchemaLike {\n readonly \"~standard\": { readonly validate: (value: unknown) => unknown };\n}\n\n/** What a caller hands a schema: its declared input, or anything when it declares none. */\nexport type StandardInput<Schema> = [SchemaTypes<Schema>] extends [{ readonly input: infer In }]\n ? In\n : unknown;\n\n/** What a schema produces: its declared output, or what its `validate` succeeds with. */\nexport type StandardOutput<Schema> = [SchemaTypes<Schema>] extends [{ readonly output: infer Out }]\n ? Out\n : Schema extends { readonly \"~standard\": { readonly validate: (value: unknown) => infer Result } }\n ? Succeeded<Awaited<Result>>\n : unknown;\n\n/** The spec's optional `types`, read by key: a schema without it shares no member to match on. */\ntype SchemaTypes<Schema> = Schema extends { readonly \"~standard\": infer Spec }\n ? \"types\" extends keyof Spec\n ? NonNullable<Spec[\"types\" & keyof Spec]>\n : undefined\n : undefined;\n\ntype Succeeded<Result> = Result extends { readonly value: infer Out } ? Out : never;\n\n/**\n * `'unchecked'` is the only way to open the input channel without a schema, and\n * it has to be typed out.\n *\n * The default is the opposite: a server function declared with no validator\n * rejects ANY argument off the wire with a 400. Every system surveyed except\n * SvelteKit passes raw deserialized input straight into the handler, and the\n * cost of not doing so is one word.\n */\nexport type Validator<T> = StandardSchema<unknown, T> | \"unchecked\";\n\n/**\n * What `.validator()` and `.inputValidator()` accept: a Standard Schema, a\n * function that returns the validated value or throws, or an object with a\n * `parse` that does. TanStack's three, probed in that order, since a zod schema\n * is both the first and the third and the first reports issues without\n * throwing.\n */\nexport type ValidatorInput<T> =\n | Validator<T>\n | ((input: unknown) => T | Promise<T>)\n | { readonly parse: (input: unknown) => T | Promise<T> };\n\n/** Any accepted validator, as the one shape the runner applies. */\nexport function toValidator<T>(input: ValidatorInput<T>): Validator<T> {\n if (input === \"unchecked\") return input;\n // The schema before the function: an arktype type is BOTH, and called as a\n // function it returns its errors rather than throwing them.\n if (\"~standard\" in input) return input;\n if (typeof input === \"function\") return checkedBy(input);\n return checkedBy((raw) => input.parse(raw));\n}\n\nfunction checkedBy<T>(check: (input: unknown) => T | Promise<T>): StandardSchema<unknown, T> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"barq\",\n validate: async (value) => {\n try {\n return { value: await check(value) };\n } catch (error) {\n // A refusal that is an answer of its own stays one.\n if (error instanceof Response) throw error;\n return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };\n }\n },\n },\n };\n}\n\nconst INPUT_ERROR = Symbol.for(\"barq.input-error\");\n\n/**\n * The caller's input was not acceptable — a 400 rather than a 500, whichever way\n * it failed. One base so the handler cannot answer one of them correctly and\n * turn the other into a server error, which is exactly what shipped first here.\n */\nexport class InputError extends Error {\n /**\n * A brand, read by {@link isInputError}, because `instanceof` answers for one\n * copy of this module: a host's request handler would read a refusal the\n * bundle's validator threw as a server error and answer 500.\n */\n readonly [INPUT_ERROR] = true as const;\n}\n\n/** Whether a thrown value is the caller's fault, whichever copy of this module threw it. */\nexport function isInputError(error: unknown): error is InputError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[INPUT_ERROR] === true\n );\n}\n\nexport class ValidationError extends InputError {\n readonly issues: ReadonlyArray<unknown>;\n constructor(issues: ReadonlyArray<unknown>) {\n super(\n \"The `data` passed to this server function failed validation against its `.validator(schema)`, so the handler did not run. \" +\n \"Read `error.issues` for what failed.\",\n );\n this.name = \"ValidationError\";\n this.issues = issues;\n }\n}\n\n/** Thrown when a call arrives for a function that declared no validator. */\nexport class UncheckedInputError extends InputError {\n constructor() {\n super(\n \"This server function was called with `data`, but it declares no validator, so the call was refused. \" +\n 'Add `.validator(schema)` to validate the input, or `.validator(\"unchecked\")` to accept it as it arrives.',\n );\n this.name = \"UncheckedInputError\";\n }\n}\n\n/** The empty contribution: what a step that adds nothing adds. */\nexport type Empty = object;\n\n/**\n * A context the types know some of. A key no typed step declared still reads,\n * as `unknown`: an untyped closure may have put it there.\n */\nexport type OpenContext<Known extends object> = Known & Record<string, unknown>;\n\ndeclare const NEXT: unique symbol;\n\n/**\n * What `next()` resolves to, as far as the types can see.\n *\n * At runtime it is whatever the rest of the chain answered. The type carries\n * what this call contributed, so a middleware's context is read off the\n * `return next({ context })` it ends with rather than declared a second time.\n */\nexport interface NextResult<Context extends object = Empty, Sent extends object = Empty> {\n readonly [NEXT]: { readonly context: Context; readonly sent: Sent };\n}\n\n/** What a middleware may hand `next`. */\nexport interface NextOptions<Context extends object = Empty, Sent extends object = Empty> {\n /**\n * MERGED into what every step below is handed, the handler included. This is\n * how a middleware that authenticates hands the session down without a\n * module-level store.\n */\n readonly context?: Context;\n /**\n * Context the OTHER side is given.\n *\n * From a server half it travels back on the response, so a middleware that\n * resolved a session can tell the browser who it decided the user is without\n * a second round trip. From a client half it travels to the server, where it\n * arrives as `clientContext`: untrusted input, never `context`.\n *\n * It is SERIALIZED, so it carries what the value codec carries and nothing\n * else. A `context` holding a database handle is fine; a `sendContext`\n * holding one is a value the other side cannot be given.\n */\n readonly sendContext?: Sent;\n /**\n * Request headers for the fetch, from a CLIENT half: an `Authorization` a\n * middleware holds the token for, a trace id.\n *\n * A later step's value for a name replaces an earlier one's, and the call's\n * own `headers` replace both. A server half has no request to add to, so\n * there it does nothing; its response headers are `setResponseHeader`'s.\n */\n readonly headers?: HeadersInit;\n /**\n * The `fetch` the call goes out through, from a CLIENT half: a retry, a\n * tracer, a test double. A later step's replaces an earlier one's, and the\n * call's own `fetch` option replaces both.\n */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * What a middleware calls to run the rest of the chain. `next()` with no\n * argument runs it unchanged.\n */\nexport type MiddlewareNext = <Context extends object = Empty, Sent extends object = Empty>(\n options?: NextOptions<Context, Sent>,\n // Read off the argument alone: inferred from where the result is returned to,\n // `next()` would satisfy any context a declared `Middleware<…>` promises.\n) => Promise<NextResult<NoInfer<Context>, NoInfer<Sent>>>;\n\n/**\n * A middleware runs before the handler and decides whether there is going to be\n * one. Rejecting is `throw new Response(...)`, which the request handler returns\n * as it stands.\n *\n * Per FUNCTION, not per route. Every framework in the survey documents the same\n * hole instead of closing it — Next.js: \"A page-level authentication check does\n * not extend to the Server Actions defined within it… the Server Action is a\n * separate entry point.\" A middleware attached here cannot be escaped by\n * reaching the function from somewhere else, because there is nowhere else.\n *\n * `Context` is what a bare closure promises to add, and it is checked against\n * what it passes to `next`: `Middleware<{ user: string }>` that ends in\n * `next()` is a type error. A built middleware needs no annotation, since its\n * context is read off its body.\n */\nexport type Middleware<Context extends object = Empty> = Empty extends Context\n ? (next: MiddlewareNext) => Promise<unknown>\n : (next: MiddlewareNext) => Promise<NextResult<Context>>;\n\n/**\n * What a middleware contributes to everything after it, at the type level.\n * Nothing here exists at runtime.\n */\nexport interface Contribution {\n /** Added to the server `context` of every later step and of the handler. */\n readonly context: object;\n /** What its server halves send back to the caller. */\n readonly sent: object;\n /** What its client halves add to the client `context`. */\n readonly clientContext: object;\n /** What the first validator in the chain is handed: the caller's `data`. */\n readonly input: unknown;\n /** What the last validator in the chain produced: every later step's `data`. */\n readonly output: unknown;\n readonly validates: boolean;\n}\n\nexport interface NoContribution extends Contribution {\n readonly context: Empty;\n readonly sent: Empty;\n readonly clientContext: Empty;\n readonly input: undefined;\n readonly output: undefined;\n readonly validates: false;\n}\n\n/** `first`, then `second`: in the order the chain runs them. */\nexport interface Merged<\n First extends Contribution,\n Second extends Contribution,\n> extends Contribution {\n readonly context: First[\"context\"] & Second[\"context\"];\n readonly sent: First[\"sent\"] & Second[\"sent\"];\n readonly clientContext: First[\"clientContext\"] & Second[\"clientContext\"];\n readonly input: First[\"validates\"] extends true ? First[\"input\"] : Second[\"input\"];\n readonly output: Second[\"validates\"] extends true ? Second[\"output\"] : First[\"output\"];\n readonly validates: First[\"validates\"] extends true ? true : Second[\"validates\"];\n}\n\n/** What one `next(...)` call contributed, from the result it resolved to. */\nexport type FromNext<Result> =\n Result extends NextResult<infer Context, infer Sent>\n ? { readonly context: Plain<Context>; readonly sent: Plain<Sent> }\n : never;\n\n/** The same keys as one object, so a hover shows the context rather than how it was built. */\nexport type Plain<Value> = { [Key in keyof Value]: Value[Key] };\n\n/**\n * What a body contributed, from everything it can return. A branch that\n * answers without calling `next` contributes nothing, and the handler never\n * runs on it, so it is left out rather than widening the rest to nothing.\n */\nexport type ContributedBy<Result> = [FromNext<Result>] extends [never]\n ? { readonly context: Empty; readonly sent: Empty }\n : FromNext<Result>;\n\ndeclare const CONTRIBUTES: unique symbol;\n\n/**\n * The type-level record a built middleware carries.\n *\n * A METHOD and optional, so it exists in no value and compares bivariantly:\n * one builder implementation serves every state, and what is read back is\n * exact because it is read with `infer`.\n */\nexport interface Carries<Types extends Contribution> {\n [CONTRIBUTES]?(types: Types): void;\n}\n\n/** What a middleware contributes, whichever way it was written. */\nexport type ContributionOf<Step> =\n Step extends Carries<infer Types>\n ? Types\n : Step extends (next: never) => Promise<infer Result>\n ? Merged<\n NoContribution,\n NoContribution & Omit<ContributedBy<Result>, never>\n > extends infer Out\n ? Out extends Contribution\n ? Out\n : NoContribution\n : NoContribution\n : NoContribution;\n\n/** What a whole chain contributes, steps in the order they run. */\nexport type ChainContribution<Chain> = Chain extends readonly [infer Head, ...infer Rest]\n ? Merged<ContributionOf<Head>, ChainContribution<Rest>>\n : Chain extends readonly []\n ? NoContribution\n : Chain extends readonly (infer Step)[]\n ? ContributionOf<Step>\n : NoContribution;\n\n/** Where a built middleware is: the chain it declared, and what it adds itself. */\nexport interface MiddlewareState {\n readonly chain: Contribution;\n readonly own: Contribution;\n}\n\nexport interface FreshMiddleware extends MiddlewareState {\n readonly chain: NoContribution;\n readonly own: NoContribution;\n}\n\nexport interface WithChain<State extends MiddlewareState, Chain> extends MiddlewareState {\n readonly chain: ChainContribution<Chain>;\n readonly own: State[\"own\"];\n}\n\nexport interface OwnReplaced<\n Own extends Contribution,\n Context extends object,\n Sent extends object,\n> extends Contribution {\n readonly context: Context;\n readonly sent: Sent;\n readonly clientContext: Own[\"clientContext\"];\n readonly input: Own[\"input\"];\n readonly output: Own[\"output\"];\n readonly validates: Own[\"validates\"];\n}\n\nexport interface WithServer<State extends MiddlewareState, Result> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: OwnReplaced<\n State[\"own\"],\n ContributedBy<Awaited<Result>>[\"context\"],\n ContributedBy<Awaited<Result>>[\"sent\"]\n >;\n}\n\nexport interface ClientReplaced<\n Own extends Contribution,\n ClientContext extends object,\n> extends Contribution {\n readonly context: Own[\"context\"];\n readonly sent: Own[\"sent\"];\n readonly clientContext: ClientContext;\n readonly input: Own[\"input\"];\n readonly output: Own[\"output\"];\n readonly validates: Own[\"validates\"];\n}\n\nexport interface WithClient<State extends MiddlewareState, Result> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: ClientReplaced<State[\"own\"], ContributedBy<Awaited<Result>>[\"context\"]>;\n}\n\nexport interface ValidatorReplaced<Own extends Contribution, In, Out> extends Contribution {\n readonly context: Own[\"context\"];\n readonly sent: Own[\"sent\"];\n readonly clientContext: Own[\"clientContext\"];\n readonly input: In;\n readonly output: Out;\n readonly validates: true;\n}\n\nexport interface WithValidator<State extends MiddlewareState, In, Out> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: ValidatorReplaced<State[\"own\"], In, Out>;\n}\n\n/** What a built middleware contributes: its chain, then itself. */\nexport type ContributionOfState<State extends MiddlewareState> = Merged<\n State[\"chain\"],\n State[\"own\"]\n>;\n\n/** The `data` a step is handed: what the nearest validator above it produced. */\nexport type DataAt<State extends MiddlewareState> = State[\"own\"][\"validates\"] extends true\n ? State[\"own\"][\"output\"]\n : State[\"chain\"][\"validates\"] extends true\n ? State[\"chain\"][\"output\"]\n : unknown;\n\n/**\n * What a built middleware's server half is handed.\n *\n * The OBJECT shape, where a bare `Middleware` closure takes `next` positionally.\n * Both are supported and neither is deprecated: the closure is what a\n * one-line guard writes, and this is what a middleware with a validator, a\n * client half or a `sendContext` needs.\n */\nexport interface MiddlewareContext<Data = unknown, Context extends object = Empty> {\n readonly next: MiddlewareNext;\n /**\n * The input, as THIS middleware's validator left it.\n *\n * Validators compose along the chain: each one is handed what the one before\n * it returned, and the function's own runs last. That is TanStack's pipeline\n * (`createServerFn.ts:271-274`) and it is what lets a middleware normalise an\n * argument every function under it then receives already normalised.\n */\n readonly data: Data;\n /** What the middlewares outside this one contributed. */\n readonly context: OpenContext<Context>;\n /**\n * What the client halves sent with `next({ sendContext })`, as it came off\n * the wire.\n *\n * UNTRUSTED, and kept apart from `context` for that reason: a caller writes\n * the request body by hand as readily as the stub does, so this is input to\n * check and never a fact to act on. Everything read from `context` was put\n * there by a server step; a value from here joins it only when a server half\n * passes it on with `next({ context })`. Untyped for the same reason: a type\n * here would be a claim about what a stranger sent.\n *\n * Empty in a client half, and for a call made in-process.\n */\n readonly clientContext: Readonly<Record<string, unknown>>;\n readonly signal: AbortSignal;\n /**\n * The request, when this middleware is running for one: as a request\n * middleware, global or on a route. Absent around a server function's own\n * chain, where `getRequest()` is the way to it.\n */\n readonly request?: Request;\n /** The request's path, with any base stripped. Present with `request`. */\n readonly pathname?: string;\n /** What the request is for. Present with `request`. */\n readonly handlerType?: \"router\" | \"serverFn\";\n /**\n * The server function this chain is running around, by its id. Absent for a\n * request middleware, and the id is empty for a function that is not mounted.\n */\n readonly serverFnMeta?: { readonly id: string };\n /** The method the server function answers. Absent for a request middleware. */\n readonly method?: \"GET\" | \"POST\";\n}\n\n/**\n * What a client half is handed: the caller's raw `data`, since validators run\n * on the server, and a `context` holding what the client halves before it\n * added and, once `next()` has resolved, what the server sent back.\n */\nexport interface ClientMiddlewareContext<\n Context extends object = Empty,\n Sent extends object = Empty,\n> extends MiddlewareContext<unknown, Context & Partial<Sent>> {}\n\n/** Any server or client half, as the runner calls it. */\nexport type MiddlewareFn = (context: MiddlewareContext) => unknown;\n\n/** What a request middleware calls to run the rest of the request. */\nexport type RequestMiddlewareNext = <Context extends object = Empty>(options?: {\n readonly context?: Context;\n}) => Promise<(Response & NextResult<NoInfer<Context>>) | undefined>;\n\n/**\n * What a request middleware is handed: the request is always there.\n *\n * `next()` resolves to the response, or `undefined` from a route handler that\n * declined, so the page render answers instead.\n */\nexport interface RequestMiddlewareContext<Context extends object = Empty> {\n readonly next: RequestMiddlewareNext;\n readonly data: undefined;\n readonly context: OpenContext<Context>;\n readonly clientContext: Readonly<Record<string, unknown>>;\n readonly signal: AbortSignal;\n readonly request: Request;\n readonly pathname: string;\n readonly handlerType: \"router\" | \"serverFn\";\n}\n\nexport type RequestMiddlewareFn = (context: RequestMiddlewareContext) => unknown;\n\n/** What a built middleware carries, and what the runner reads off it. */\nexport interface MiddlewareOptions {\n /**\n * TanStack's two kinds. `\"request\"` runs for a server request and is handed\n * it; `\"function\"` runs around a server function and may have a client half.\n * One builder makes both and the runner asks only where a middleware was\n * listed, so the kind decides the TYPES of what `.server` is handed.\n */\n readonly type?: \"request\" | \"function\";\n readonly middleware?: readonly Middleware[];\n readonly validator?: Validator<unknown>;\n readonly server?: MiddlewareFn;\n readonly client?: MiddlewareFn;\n}\n\n/**\n * A middleware with more than a body: a chain of its own, an input validator,\n * and separate halves for the two sides.\n *\n * IT IS STILL A FUNCTION. `Middleware` is a callable and the route-action\n * verifier compares chains with `===`, so making this an object — which is what\n * TanStack's is — would have broken both at once: a route's `middleware: [m]`\n * would no longer typecheck, and every existing bare closure would need\n * wrapping. A callable object is neither: it runs where a closure ran, it\n * compares by identity as a closure did, and `options` is there for the runner\n * that wants more.\n *\n * What each step adds is TYPED: a `.server` that ends in\n * `next({ context: { user } })` hands `user` to every function that lists this\n * middleware, typed as the body wrote it.\n */\nexport type BuiltMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &\n Carries<ContributionOfState<State>> & {\n readonly options: MiddlewareOptions;\n /** Middlewares that run BEFORE this one, flattened into the chain that uses it. */\n middleware<const Chain extends readonly Middleware[]>(\n chain: Chain,\n ): BuiltMiddleware<WithChain<State, Chain>>;\n /**\n * Validates and narrows the input every step after this one is handed. The\n * schema form is tried first: an arktype type is callable as well, and read\n * as a function its declared input would be lost.\n */\n validator<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n validator<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n validator<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n validator(unchecked: \"unchecked\"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n /** `validator` under the name TanStack's release candidates used. */\n inputValidator<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n inputValidator<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n inputValidator<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n inputValidator(unchecked: \"unchecked\"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n /** The half that runs on the server, where the handler is. */\n server<Result>(\n fn: (context: MiddlewareContext<DataAt<State>, State[\"chain\"][\"context\"]>) => Result,\n ): BuiltMiddleware<WithServer<State, Result>>;\n /**\n * The half that runs in the BROWSER, around the fetch.\n *\n * `next({ sendContext })` from here is what travels to the server half as\n * `clientContext`. The compiler carries this into the client stub and leaves\n * the server half behind, so a middleware may hold both without either\n * reaching the wrong bundle.\n */\n client<Result>(\n fn: (\n context: ClientMiddlewareContext<State[\"chain\"][\"clientContext\"], State[\"chain\"][\"sent\"]>,\n ) => Result,\n ): BuiltMiddleware<WithClient<State, Result>>;\n };\n\n/**\n * The two brands a thrown redirect and a thrown `notFound()` carry.\n *\n * DECLARED TWICE ON PURPOSE. The classes live in `@barqjs/router`, which this\n * package must not import: the dependency runs router -> start and start is an\n * OPTIONAL peer of it, so an import here would be a cycle and would break the\n * router for anyone using it without server functions. `Symbol.for` is the\n * global registry, so both declarations name the same symbol with no edge\n * between the packages — `SERVER_FN` in `client.ts` already works this way. The other\n * declaration is `REDIRECT` / `NOT_FOUND` in `packages/router/src/errors.ts`,\n * and `server.test.ts` checks the two agree.\n */\nexport const REDIRECT: unique symbol = Symbol.for(\"barq.redirect\");\nexport const NOT_FOUND: unique symbol = Symbol.for(\"barq.not-found\");\n\n/**\n * What a middleware handed back, held to TanStack's rule: it ends in\n * `return next(...)`, answers with a result of its own, or throws.\n *\n * `undefined` is the one answer that cannot be a decision. Returned without\n * `next()` having been called, the step neither ran the rest of the chain nor\n * said what to answer with; returned after a `next()` that resolved to\n * something, it is the `return` the body forgot, and the result the handler\n * produced would be lost without a word. Either way the call would resolve to\n * nothing, so it fails here, naming the step. A thrown or returned redirect\n * or `notFound()` is an answer, so a returned one is thrown as one.\n */\nfunction answerOf(returned: unknown, answers: readonly unknown[], step: () => string): unknown {\n if (isControl(returned)) throw returned;\n if (returned !== undefined || answers.includes(undefined)) return returned;\n throw new Error(\n answers.length === 0\n ? `[barq] ${step()} returned without calling \\`next()\\`, so the call has no answer. ` +\n \"A middleware ends in `return next(...)`, returns a result of its own, or throws (a `Response` to refuse).\"\n : `[barq] ${step()} called \\`next()\\` and returned \\`undefined\\` in place of its result, so the result was lost. ` +\n \"Return what `next()` resolved to: `return next(...)`.\",\n );\n}\n\nfunction isControl(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const branded = value as Record<symbol, unknown>;\n return branded[REDIRECT] === true || branded[NOT_FOUND] === true;\n}\n\n/**\n * Which step a refusal is about, for a person reading the error: its name when\n * the closure or the half has one, its place in the chain, and the function.\n */\nfunction describeStep(\n kind: string,\n named: readonly ((...args: never[]) => unknown)[],\n position: number,\n length: number,\n around: string,\n): string {\n const name = named\n .map((fn) => fn.name)\n .find((candidate) => candidate !== \"\" && candidate !== \"run\");\n const place = `${position + 1} of ${length}`;\n return name === undefined\n ? `The ${kind} middleware ${place} ${around}`\n : `The ${kind} middleware \\`${name}\\` (${place}) ${around}`;\n}\n\n/** Frozen, because every call that was sent nothing is handed this one object. */\nconst NOTHING_SENT: Record<string, unknown> = Object.freeze({});\n\n/** Whether a middleware was built by {@link createMiddleware}. */\nexport function isBuiltMiddleware(value: Middleware): value is BuiltMiddleware {\n return (value as Partial<BuiltMiddleware>).options !== undefined;\n}\n\n/**\n * Author a middleware that is more than one closure.\n *\n * `createMiddleware().server(async ({ next, context }) => next({ context: … }))`\n * is the ordinary shape, and it is what a bare closure already did. What the\n * builder adds is the three things a closure has nowhere to put: a chain of its\n * own, an input validator, and a client half.\n *\n * EACH CALL RETURNS A NEW MIDDLEWARE, and the exported one is the last. That\n * matters because the verifier compares by identity: a builder that mutated and\n * returned itself would make every intermediate the same object as the final\n * one, which is harmless, and one that shared its options object across\n * branches — which TanStack's does — would make two middlewares built from one\n * base overwrite each other. Neither is a risk worth carrying for an allocation.\n */\nexport function createMiddleware(\n options: MiddlewareOptions & { readonly type: \"request\" },\n): RequestMiddleware<FreshMiddleware>;\nexport function createMiddleware(options?: MiddlewareOptions): BuiltMiddleware<FreshMiddleware>;\nexport function createMiddleware(\n options: MiddlewareOptions = {},\n): BuiltMiddleware<FreshMiddleware> | RequestMiddleware<FreshMiddleware> {\n return built<FreshMiddleware>(options);\n}\n\n/**\n * A typed body, stored where the runner reads it.\n *\n * The runner hands each body the `data` its validators produced and the\n * `context` the steps outside it wrote, which is what the body's own types say;\n * the types cannot follow a value through `options`, so they are restated here,\n * once, rather than at every call.\n */\nfunction asBody<Data, Context extends object>(\n fn: (context: MiddlewareContext<Data, Context>) => unknown,\n): MiddlewareFn {\n return fn as MiddlewareFn;\n}\n\n/**\n * A runner's `next`.\n *\n * It resolves to whatever the rest of the chain answered. `NextResult` is the\n * types' record of what the caller passed, and no value carries it, so the one\n * place a runner makes a `next` is the one place that says so.\n */\nfunction nextOf(step: (options?: NextOptions) => Promise<unknown>): MiddlewareNext {\n return step as MiddlewareNext;\n}\n\nfunction built<State extends MiddlewareState>(options: MiddlewareOptions): BuiltMiddleware<State> {\n // The callable body is the SERVER half, because that is where a middleware in\n // a chain is invoked from. A middleware with no server half still has to be\n // callable — it may exist only to validate, or only to run on the client — and\n // passing straight through is what \"no half here\" means.\n const run: Middleware = async (next) =>\n options.server === undefined\n ? next()\n : options.server({\n next,\n data: undefined,\n context: {},\n clientContext: NOTHING_SENT,\n signal: new AbortController().signal,\n });\n\n function validated<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n function validated<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n function validated<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n function validated(\n unchecked: \"unchecked\",\n ): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n function validated(schema: ValidatorInput<unknown>): BuiltMiddleware {\n return built({ ...options, validator: toValidator(schema) });\n }\n\n return Object.assign(run, {\n options,\n middleware: <const Chain extends readonly Middleware[]>(chain: Chain) =>\n built<WithChain<State, Chain>>({ ...options, middleware: chain }),\n validator: validated,\n inputValidator: validated,\n server: <Result>(\n fn: (context: MiddlewareContext<DataAt<State>, State[\"chain\"][\"context\"]>) => Result,\n ) => built<WithServer<State, Result>>({ ...options, server: asBody(fn) }),\n client: <Result>(\n fn: (\n context: ClientMiddlewareContext<State[\"chain\"][\"clientContext\"], State[\"chain\"][\"sent\"]>,\n ) => Result,\n ) => built<WithClient<State, Result>>({ ...options, client: asBody(fn) }),\n });\n}\n\n/**\n * A middleware built with `type: \"request\"`: a chain of its own and a server\n * body that is always handed the request. It is a {@link BuiltMiddleware}\n * underneath, so it goes wherever a `Middleware` does, and what its body passes\n * to `next({ context })` is typed into everything after it.\n */\nexport type RequestMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &\n Carries<ContributionOfState<State>> & {\n readonly options: MiddlewareOptions;\n middleware<const Chain extends readonly Middleware[]>(\n chain: Chain,\n ): RequestMiddleware<WithChain<State, Chain>>;\n server<Result>(\n fn: (context: RequestMiddlewareContext<State[\"chain\"][\"context\"]>) => Result,\n ): RequestMiddleware<WithServer<State, NonNullable<Awaited<Result>>>>;\n };\n\n/** Where a request middleware chain is running. */\nexport interface RequestMiddlewareStart {\n readonly request: Request;\n readonly pathname: string;\n readonly handlerType: \"router\" | \"serverFn\";\n /** What the chain has produced so far; mutated as it unwinds inward. */\n readonly context: Record<string, unknown>;\n}\n\n/**\n * Run a chain of request middleware around `run`.\n *\n * `next()` resolves to whatever is inside: the response, or `undefined` from a\n * route handler that declined. A middleware answers with what it returns, so\n * one that returns `next()` passes the answer through and one that returns a\n * `Response` of its own replaces it.\n */\nexport async function runRequestMiddleware<T>(\n chain: readonly Middleware[],\n start: RequestMiddlewareStart,\n run: () => Promise<T>,\n): Promise<T> {\n if (chain.length === 0) return run();\n const flattened = flattenMiddleware(chain);\n // By position, for the reason `runMiddleware` gives: a second `next()`\n // re-enters the steps below it instead of skipping them.\n const dispatch = async (position: number): Promise<unknown> => {\n const middleware = flattened[position];\n if (middleware === undefined) return run();\n const answers: unknown[] = [];\n const next = nextOf(async (step) => {\n if (step?.context !== undefined) Object.assign(start.context, step.context);\n const answer = await dispatch(position + 1);\n answers.push(answer);\n return answer;\n });\n const body = isBuiltMiddleware(middleware) ? middleware.options.server : undefined;\n if (isBuiltMiddleware(middleware) && body === undefined) return next();\n const returned = await (body === undefined\n ? middleware(next)\n : body({\n next,\n data: undefined,\n context: start.context,\n clientContext: NOTHING_SENT,\n signal: start.request.signal,\n request: start.request,\n pathname: start.pathname,\n handlerType: start.handlerType,\n }));\n return answerOf(returned, answers, () =>\n describeStep(\n \"request\",\n body === undefined ? [middleware] : [body],\n position,\n flattened.length,\n `on ${start.request.method} ${start.pathname}`,\n ),\n );\n };\n return (await dispatch(0)) as T;\n}\n\n/**\n * The chain a middleware list really is: every nested chain spliced in ahead of\n * the middleware that declared it, each step once.\n *\n * Depth-first and parents-first, which is TanStack's `flattenMiddlewares` and\n * the only order that means anything — a middleware declares a chain because it\n * DEPENDS on it, so those steps have to have run by the time it does.\n *\n * Deduplicated by IDENTITY, so two middlewares that both depend on\n * `requireSession` do not authenticate twice. That is also what keeps the\n * route-action verifier honest: it asks whether a function's flattened chain\n * contains the route's steps, and a step reached through a nest counts.\n */\nexport function flattenMiddleware(chain: readonly Middleware[], depth = 0): readonly Middleware[] {\n // A chain that reaches itself would otherwise recurse until the stack goes.\n // The cap is TanStack's and the number is theirs.\n if (depth > 100) {\n throw new RangeError(\n \"[barq] A middleware chain nests more than 100 levels deep, which almost always means a middleware's own `middleware` list reaches the middleware itself. \" +\n \"Remove the cycle.\",\n );\n }\n const out: Middleware[] = [];\n const push = (step: Middleware): void => {\n if (!out.includes(step)) out.push(step);\n };\n for (const step of chain) {\n if (isBuiltMiddleware(step) && step.options.middleware !== undefined) {\n for (const nested of flattenMiddleware(step.options.middleware, depth + 1)) push(nested);\n }\n push(step);\n }\n return out;\n}\n\n/** One validator, applied. `\"unchecked\"` and absence both pass the value through. */\nexport async function applyValidator(\n validator: Validator<unknown> | undefined,\n raw: unknown,\n): Promise<unknown> {\n if (validator === undefined || validator === \"unchecked\") return raw;\n const result = await validator[\"~standard\"].validate(raw);\n if (\"issues\" in result) throw new ValidationError(result.issues);\n return result.value;\n}\n\n/**\n * Run a flattened chain, then the innermost work.\n *\n * ONE RUNNER FOR BOTH SIDES, and `half` is which of a built middleware's two\n * bodies to call. A bare closure has neither and is invoked positionally, which\n * is what it has always been — so a chain may mix the two spellings and the\n * order is the order it was written in.\n *\n * A middleware that declares no half for THIS side is skipped rather than\n * refused: a `.server(...)`-only middleware is transparent in the browser, and\n * a `.client(...)`-only one is transparent on the server. That is what makes\n * one exported middleware usable from a route and a server function alike.\n */\nexport async function runMiddleware(\n chain: readonly Middleware[],\n half: \"server\" | \"client\",\n start: {\n readonly data: unknown;\n readonly signal: AbortSignal;\n /** What the chain has produced so far; mutated as the chain unwinds inward. */\n readonly context: Record<string, unknown>;\n /** What the client halves sent, on the server. Never merged into `context`. */\n readonly clientContext?: Record<string, unknown>;\n /** What travels back to the caller. */\n readonly sendContext: Record<string, unknown>;\n /** Where a client half's `next({ headers })` collects. Absent on the server. */\n readonly headers?: Headers;\n /** Where a client half's `next({ fetch })` lands. Absent on the server. */\n readonly fetch?: { current: typeof fetch | undefined };\n /** The function the chain is running around. */\n readonly meta?: { readonly id: string };\n /** The method that function answers. */\n readonly method?: \"GET\" | \"POST\";\n /** The innermost work: the handler on the server, the fetch on the client. */\n readonly run: (data: unknown) => Promise<unknown>;\n },\n): Promise<unknown> {\n // BY POSITION, never by a counter the whole chain shares. A middleware may\n // call `next` twice (a retry, a fallback), and a shared counter has already\n // moved past every step below it by then, so the second call would land on\n // the handler with the guards in between skipped. Each step's `next` names the\n // step after it, so a repeat re-enters the same guards.\n const dispatch = async (position: number, received: unknown): Promise<unknown> => {\n const middleware = chain[position];\n if (middleware === undefined) return start.run(received);\n let data = received;\n const answers: unknown[] = [];\n const next = nextOf(async (step) => {\n if (step?.context !== undefined) Object.assign(start.context, step.context);\n if (step?.sendContext !== undefined) Object.assign(start.sendContext, step.sendContext);\n if (step?.headers !== undefined && start.headers !== undefined) {\n for (const [name, value] of new Headers(step.headers)) start.headers.set(name, value);\n }\n if (step?.fetch !== undefined && start.fetch !== undefined) start.fetch.current = step.fetch;\n const answer = await dispatch(position + 1, data);\n answers.push(answer);\n return answer;\n });\n const step = (named: (...args: never[]) => unknown): string =>\n describeStep(\n half,\n [named],\n position,\n chain.length,\n `around the server function ${JSON.stringify(start.meta?.id ?? \"\")}`,\n );\n if (!isBuiltMiddleware(middleware)) {\n // A BARE CLOSURE IS A SERVER MIDDLEWARE, always. It takes `next` and runs\n // where the handler is; there is no half to choose and nothing about it\n // says it is safe in a browser — `requireSession` in the reference\n // application opens a sealed cookie. Calling one on the client would run\n // a session check in the page, so the client half skips it and only a\n // middleware that declared `.client(…)` runs there.\n if (half !== \"server\") return next();\n return answerOf(await middleware(next), answers, () => step(middleware));\n }\n // VALIDATION FIRST, so the body of this middleware sees what its own\n // validator produced and so does everything under it. TanStack applies them\n // in the same place and the same order.\n if (half === \"server\") data = await applyValidator(middleware.options.validator, data);\n const body = middleware.options[half];\n if (body === undefined) return next();\n const returned = await body({\n next,\n data,\n context: start.context,\n clientContext: start.clientContext ?? NOTHING_SENT,\n signal: start.signal,\n serverFnMeta: start.meta,\n method: start.method,\n });\n return answerOf(returned, answers, () => step(body));\n };\n return dispatch(0, start.data);\n}\n"],"mappings":";;AAoFA,SAAgB,YAAe,OAAwC;CACrE,IAAI,UAAU,aAAa,OAAO;CAGlC,IAAI,eAAe,OAAO,OAAO;CACjC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK;CACvD,OAAO,WAAW,QAAQ,MAAM,MAAM,GAAG,CAAC;AAC5C;AAEA,SAAS,UAAa,OAAuE;CAC3F,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,UAAU,OAAO,UAAU;GACzB,IAAI;IACF,OAAO,EAAE,OAAO,MAAM,MAAM,KAAK,EAAE;GACrC,SAAS,OAAO;IAEd,IAAI,iBAAiB,UAAU,MAAM;IACrC,OAAO,EAAE,QAAQ,CAAC,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC,EAAE;GACzF;EACF;CACF,EACF;AACF;AAEA,MAAM,cAAc,OAAO,IAAI,kBAAkB;;;;;;AAOjD,IAAa,aAAb,cAAgC,MAAM;;;;;;CAMpC,CAAU,eAAe;AAC3B;;AAGA,SAAgB,aAAa,OAAqC;CAChE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,iBAAiB;AAExD;AAEA,IAAa,kBAAb,cAAqC,WAAW;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MAAM,OAAO,OAAO,OAAO,SAAS;GAClC,IAAI,MAAM,YAAY,KAAA,GAAW,OAAO,OAAO,MAAM,SAAS,KAAK,OAAO;GAC1E,IAAI,MAAM,gBAAgB,KAAA,GAAW,OAAO,OAAO,MAAM,aAAa,KAAK,WAAW;GACtF,IAAI,MAAM,YAAY,KAAA,KAAa,MAAM,YAAY,KAAA,GACnD,KAAK,MAAM,CAAC,MAAM,UAAU,IAAI,QAAQ,KAAK,OAAO,GAAG,MAAM,QAAQ,IAAI,MAAM,KAAK;GAEtF,IAAI,MAAM,UAAU,KAAA,KAAa,MAAM,UAAU,KAAA,GAAW,MAAM,MAAM,UAAU,KAAK;GACvF,MAAM,SAAS,MAAM,SAAS,WAAW,GAAG,IAAI;GAChD,QAAQ,KAAK,MAAM;GACnB,OAAO;EACT,CAAC;EACD,MAAM,QAAQ,UACZ,aACE,MACA,CAAC,KAAK,GACN,UACA,MAAM,QACN,8BAA8B,KAAK,UAAU,MAAM,MAAM,MAAM,EAAE,GACnE;EACF,IAAI,CAAC,kBAAkB,UAAU,GAAG;GAOlC,IAAI,SAAS,UAAU,OAAO,KAAK;GACnC,OAAO,SAAS,MAAM,WAAW,IAAI,GAAG,eAAe,KAAK,UAAU,CAAC;EACzE;EAIA,IAAI,SAAS,UAAU,OAAO,MAAM,eAAe,WAAW,QAAQ,WAAW,IAAI;EACrF,MAAM,OAAO,WAAW,QAAQ;EAChC,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK;EAUpC,OAAO,SAAS,MATO,KAAK;GAC1B;GACA;GACA,SAAS,MAAM;GACf,eAAe,MAAM,iBAAiB;GACtC,QAAQ,MAAM;GACd,cAAc,MAAM;GACpB,QAAQ,MAAM;EAChB,CAAC,GACyB,eAAe,KAAK,IAAI,CAAC;CACrD;CACA,OAAO,SAAS,GAAG,MAAM,IAAI;AAC/B"}
1
+ {"version":3,"file":"middleware.js","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * Middleware, and the input validation it composes.\n *\n * ITS OWN MODULE FOR ONE REASON: `client.ts` needs it. A middleware's client\n * half runs in the browser, so the runner has to be reachable from the client\n * stub — and `index.ts` re-exports `context.ts`, which reaches\n * `node:async_hooks`. Importing the index from `client.ts` is the leak\n * `DEFAULT_CLIENT_SOURCE` exists to avoid, and it is not theoretical: the same\n * import through a route's `middleware` once left a fully server-rendered page\n * on which nothing was interactive.\n *\n * Nothing here imports anything of barq's, for that reason.\n */\n\n/**\n * A validator in the Standard Schema shape, which zod, valibot and arktype all\n * implement. Taking the interface rather than a library keeps the dependency\n * out and lets an application bring its own.\n */\nexport interface StandardSchema<In = unknown, Out = In> {\n \"~standard\": {\n version: 1;\n vendor: string;\n validate: (\n value: unknown,\n ) =>\n | { value: Out }\n | { issues: ReadonlyArray<unknown> }\n | Promise<{ value: Out } | { issues: ReadonlyArray<unknown> }>;\n /** The spec's type carrier: what the schema takes and what it produces. */\n readonly types?: { readonly input: In; readonly output: Out };\n };\n}\n\n/** Anything with a Standard Schema validator on it, which is all a schema is read for. */\nexport interface StandardSchemaLike {\n readonly \"~standard\": { readonly validate: (value: unknown) => unknown };\n}\n\n/** What a caller hands a schema: its declared input, or anything when it declares none. */\nexport type StandardInput<Schema> = [SchemaTypes<Schema>] extends [{ readonly input: infer In }]\n ? In\n : unknown;\n\n/** What a schema produces: its declared output, or what its `validate` succeeds with. */\nexport type StandardOutput<Schema> = [SchemaTypes<Schema>] extends [{ readonly output: infer Out }]\n ? Out\n : Schema extends { readonly \"~standard\": { readonly validate: (value: unknown) => infer Result } }\n ? Succeeded<Awaited<Result>>\n : unknown;\n\n/** The spec's optional `types`, read by key: a schema without it shares no member to match on. */\ntype SchemaTypes<Schema> = Schema extends { readonly \"~standard\": infer Spec }\n ? \"types\" extends keyof Spec\n ? NonNullable<Spec[\"types\" & keyof Spec]>\n : undefined\n : undefined;\n\ntype Succeeded<Result> = Result extends { readonly value: infer Out } ? Out : never;\n\n/**\n * `'unchecked'` is the only way to open the input channel without a schema, and\n * it has to be typed out.\n *\n * The default is the opposite: a server function declared with no validator\n * rejects ANY argument off the wire with a 400. Every system surveyed except\n * SvelteKit passes raw deserialized input straight into the handler, and the\n * cost of not doing so is one word.\n */\nexport type Validator<T> = StandardSchema<unknown, T> | \"unchecked\";\n\n/**\n * What `.validator()` and `.inputValidator()` accept: a Standard Schema, a\n * function that returns the validated value or throws, or an object with a\n * `parse` that does. TanStack's three, probed in that order, since a zod schema\n * is both the first and the third and the first reports issues without\n * throwing.\n */\nexport type ValidatorInput<T> =\n | Validator<T>\n | ((input: unknown) => T | Promise<T>)\n | { readonly parse: (input: unknown) => T | Promise<T> };\n\n/** Any accepted validator, as the one shape the runner applies. */\nexport function toValidator<T>(input: ValidatorInput<T>): Validator<T> {\n if (input === \"unchecked\") return input;\n // The schema before the function: an arktype type is BOTH, and called as a\n // function it returns its errors rather than throwing them.\n if (\"~standard\" in input) return input;\n if (typeof input === \"function\") return checkedBy(input);\n return checkedBy((raw) => input.parse(raw));\n}\n\nfunction checkedBy<T>(check: (input: unknown) => T | Promise<T>): StandardSchema<unknown, T> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"barq\",\n validate: async (value) => {\n try {\n return { value: await check(value) };\n } catch (error) {\n // A refusal that is an answer of its own stays one.\n if (error instanceof Response) throw error;\n return { issues: [{ message: error instanceof Error ? error.message : String(error) }] };\n }\n },\n },\n };\n}\n\nconst INPUT_ERROR = Symbol.for(\"barq.input-error\");\n\n/**\n * The caller's input was not acceptable — a 400 rather than a 500, whichever way\n * it failed. One base so the handler cannot answer one of them correctly and\n * turn the other into a server error, which is exactly what shipped first here.\n */\nexport class InputError extends Error {\n /**\n * A brand, read by {@link isInputError}, because `instanceof` answers for one\n * copy of this module: a host's request handler would read a refusal the\n * bundle's validator threw as a server error and answer 500.\n */\n readonly [INPUT_ERROR] = true as const;\n}\n\n/** Whether a thrown value is the caller's fault, whichever copy of this module threw it. */\nexport function isInputError(error: unknown): error is InputError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as Record<symbol, unknown>)[INPUT_ERROR] === true\n );\n}\n\nexport class ValidationError extends InputError {\n readonly issues: ReadonlyArray<unknown>;\n constructor(issues: ReadonlyArray<unknown>) {\n super(\n \"The `data` passed to this server function failed validation against its `.validator(schema)`, so the handler did not run. \" +\n \"Read `error.issues` for what failed.\",\n );\n this.name = \"ValidationError\";\n this.issues = issues;\n }\n}\n\n/** Thrown when a call arrives for a function that declared no validator. */\nexport class UncheckedInputError extends InputError {\n constructor() {\n super(\n \"This server function was called with `data`, but it declares no validator, so the call was refused. \" +\n 'Add `.validator(schema)` to validate the input, or `.validator(\"unchecked\")` to accept it as it arrives.',\n );\n this.name = \"UncheckedInputError\";\n }\n}\n\n/** The empty contribution: what a step that adds nothing adds. */\nexport type Empty = object;\n\n/**\n * A context the types know some of. A key no typed step declared still reads,\n * as `unknown`: an untyped closure may have put it there.\n */\nexport type OpenContext<Known extends object> = Known & Record<string, unknown>;\n\ndeclare const NEXT: unique symbol;\n\n/**\n * What `next()` resolves to, as far as the types can see.\n *\n * At runtime it is whatever the rest of the chain answered. The type carries\n * what this call contributed, so a middleware's context is read off the\n * `return next({ context })` it ends with rather than declared a second time.\n */\nexport interface NextResult<Context extends object = Empty, Sent extends object = Empty> {\n readonly [NEXT]: { readonly context: Context; readonly sent: Sent };\n}\n\n/** What a middleware may hand `next`. */\nexport interface NextOptions<Context extends object = Empty, Sent extends object = Empty> {\n /**\n * MERGED into what every step below is handed, the handler included. This is\n * how a middleware that authenticates hands the session down without a\n * module-level store.\n */\n readonly context?: Context;\n /**\n * Context the OTHER side is given.\n *\n * From a server half it travels back on the response, so a middleware that\n * resolved a session can tell the browser who it decided the user is without\n * a second round trip. From a client half it travels to the server, where it\n * arrives as `clientContext`: untrusted input, never `context`.\n *\n * It is SERIALIZED, so it carries what the value codec carries and nothing\n * else. A `context` holding a database handle is fine; a `sendContext`\n * holding one is a value the other side cannot be given.\n */\n readonly sendContext?: Sent;\n /**\n * Request headers for the fetch, from a CLIENT half: an `Authorization` a\n * middleware holds the token for, a trace id.\n *\n * A later step's value for a name replaces an earlier one's, and the call's\n * own `headers` replace both. A server half has no request to add to, so\n * there it does nothing; its response headers are `setResponseHeader`'s.\n */\n readonly headers?: HeadersInit;\n /**\n * The `fetch` the call goes out through, from a CLIENT half: a retry, a\n * tracer, a test double. A later step's replaces an earlier one's, and the\n * call's own `fetch` option replaces both.\n */\n readonly fetch?: typeof fetch;\n}\n\n/**\n * What a middleware calls to run the rest of the chain. `next()` with no\n * argument runs it unchanged.\n */\nexport type MiddlewareNext = <Context extends object = Empty, Sent extends object = Empty>(\n options?: NextOptions<Context, Sent>,\n // Read off the argument alone: inferred from where the result is returned to,\n // `next()` would satisfy any context a declared `Middleware<…>` promises.\n) => Promise<NextResult<NoInfer<Context>, NoInfer<Sent>>>;\n\n/**\n * A middleware runs before the handler and decides whether there is going to be\n * one. Rejecting is `throw new Response(...)`, which the request handler returns\n * as it stands.\n *\n * Per FUNCTION, not per route. Every framework in the survey documents the same\n * hole instead of closing it — Next.js: \"A page-level authentication check does\n * not extend to the Server Actions defined within it… the Server Action is a\n * separate entry point.\" A middleware attached here cannot be escaped by\n * reaching the function from somewhere else, because there is nowhere else.\n *\n * `Context` is what a bare closure promises to add, and it is checked against\n * what it passes to `next`: `Middleware<{ user: string }>` that ends in\n * `next()` is a type error. A built middleware needs no annotation, since its\n * context is read off its body.\n */\nexport type Middleware<Context extends object = Empty> = Empty extends Context\n ? (next: MiddlewareNext) => Promise<unknown>\n : (next: MiddlewareNext) => Promise<NextResult<Context>>;\n\n/**\n * What a middleware contributes to everything after it, at the type level.\n * Nothing here exists at runtime.\n */\nexport interface Contribution {\n /** Added to the server `context` of every later step and of the handler. */\n readonly context: object;\n /** What its server halves send back to the caller. */\n readonly sent: object;\n /** What its client halves add to the client `context`. */\n readonly clientContext: object;\n /** What the first validator in the chain is handed: the caller's `data`. */\n readonly input: unknown;\n /** What the last validator in the chain produced: every later step's `data`. */\n readonly output: unknown;\n readonly validates: boolean;\n}\n\nexport interface NoContribution extends Contribution {\n readonly context: Empty;\n readonly sent: Empty;\n readonly clientContext: Empty;\n readonly input: undefined;\n readonly output: undefined;\n readonly validates: false;\n}\n\n/** `first`, then `second`: in the order the chain runs them. */\nexport interface Merged<\n First extends Contribution,\n Second extends Contribution,\n> extends Contribution {\n readonly context: First[\"context\"] & Second[\"context\"];\n readonly sent: First[\"sent\"] & Second[\"sent\"];\n readonly clientContext: First[\"clientContext\"] & Second[\"clientContext\"];\n readonly input: First[\"validates\"] extends true ? First[\"input\"] : Second[\"input\"];\n readonly output: Second[\"validates\"] extends true ? Second[\"output\"] : First[\"output\"];\n readonly validates: First[\"validates\"] extends true ? true : Second[\"validates\"];\n}\n\n/** What one `next(...)` call contributed, from the result it resolved to. */\nexport type FromNext<Result> =\n Result extends NextResult<infer Context, infer Sent>\n ? { readonly context: Plain<Context>; readonly sent: Plain<Sent> }\n : never;\n\n/** The same keys as one object, so a hover shows the context rather than how it was built. */\nexport type Plain<Value> = { [Key in keyof Value]: Value[Key] };\n\n/**\n * What a body contributed, from everything it can return. A branch that\n * answers without calling `next` contributes nothing, and the handler never\n * runs on it, so it is left out rather than widening the rest to nothing.\n */\nexport type ContributedBy<Result> = [FromNext<Result>] extends [never]\n ? { readonly context: Empty; readonly sent: Empty }\n : FromNext<Result>;\n\ndeclare const CONTRIBUTES: unique symbol;\n\n/**\n * The type-level record a built middleware carries.\n *\n * A METHOD and optional, so it exists in no value and compares bivariantly:\n * one builder implementation serves every state, and what is read back is\n * exact because it is read with `infer`.\n */\nexport interface Carries<Types extends Contribution> {\n [CONTRIBUTES]?(types: Types): void;\n}\n\n/** What a middleware contributes, whichever way it was written. */\nexport type ContributionOf<Step> =\n Step extends Carries<infer Types>\n ? Types\n : Step extends (next: never) => Promise<infer Result>\n ? Merged<\n NoContribution,\n NoContribution & Omit<ContributedBy<Result>, never>\n > extends infer Out\n ? Out extends Contribution\n ? Out\n : NoContribution\n : NoContribution\n : NoContribution;\n\n/** What a whole chain contributes, steps in the order they run. */\nexport type ChainContribution<Chain> = Chain extends readonly [infer Head, ...infer Rest]\n ? Merged<ContributionOf<Head>, ChainContribution<Rest>>\n : Chain extends readonly []\n ? NoContribution\n : Chain extends readonly (infer Step)[]\n ? ContributionOf<Step>\n : NoContribution;\n\n/** Where a built middleware is: the chain it declared, and what it adds itself. */\nexport interface MiddlewareState {\n readonly chain: Contribution;\n readonly own: Contribution;\n}\n\nexport interface FreshMiddleware extends MiddlewareState {\n readonly chain: NoContribution;\n readonly own: NoContribution;\n}\n\nexport interface WithChain<State extends MiddlewareState, Chain> extends MiddlewareState {\n readonly chain: ChainContribution<Chain>;\n readonly own: State[\"own\"];\n}\n\nexport interface OwnReplaced<\n Own extends Contribution,\n Context extends object,\n Sent extends object,\n> extends Contribution {\n readonly context: Context;\n readonly sent: Sent;\n readonly clientContext: Own[\"clientContext\"];\n readonly input: Own[\"input\"];\n readonly output: Own[\"output\"];\n readonly validates: Own[\"validates\"];\n}\n\nexport interface WithServer<State extends MiddlewareState, Result> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: OwnReplaced<\n State[\"own\"],\n ContributedBy<Awaited<Result>>[\"context\"],\n ContributedBy<Awaited<Result>>[\"sent\"]\n >;\n}\n\nexport interface ClientReplaced<\n Own extends Contribution,\n ClientContext extends object,\n> extends Contribution {\n readonly context: Own[\"context\"];\n readonly sent: Own[\"sent\"];\n readonly clientContext: ClientContext;\n readonly input: Own[\"input\"];\n readonly output: Own[\"output\"];\n readonly validates: Own[\"validates\"];\n}\n\nexport interface WithClient<State extends MiddlewareState, Result> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: ClientReplaced<State[\"own\"], ContributedBy<Awaited<Result>>[\"context\"]>;\n}\n\nexport interface ValidatorReplaced<Own extends Contribution, In, Out> extends Contribution {\n readonly context: Own[\"context\"];\n readonly sent: Own[\"sent\"];\n readonly clientContext: Own[\"clientContext\"];\n readonly input: In;\n readonly output: Out;\n readonly validates: true;\n}\n\nexport interface WithValidator<State extends MiddlewareState, In, Out> extends MiddlewareState {\n readonly chain: State[\"chain\"];\n readonly own: ValidatorReplaced<State[\"own\"], In, Out>;\n}\n\n/** What a built middleware contributes: its chain, then itself. */\nexport type ContributionOfState<State extends MiddlewareState> = Merged<\n State[\"chain\"],\n State[\"own\"]\n>;\n\n/** The `data` a step is handed: what the nearest validator above it produced. */\nexport type DataAt<State extends MiddlewareState> = State[\"own\"][\"validates\"] extends true\n ? State[\"own\"][\"output\"]\n : State[\"chain\"][\"validates\"] extends true\n ? State[\"chain\"][\"output\"]\n : unknown;\n\n/**\n * What a built middleware's server half is handed.\n *\n * The OBJECT shape, where a bare `Middleware` closure takes `next` positionally.\n * Both are supported and neither is deprecated: the closure is what a\n * one-line guard writes, and this is what a middleware with a validator, a\n * client half or a `sendContext` needs.\n */\nexport interface MiddlewareContext<Data = unknown, Context extends object = Empty> {\n readonly next: MiddlewareNext;\n /**\n * The input, as THIS middleware's validator left it.\n *\n * Validators compose along the chain: each one is handed what the one before\n * it returned, and the function's own runs last. That is TanStack's pipeline\n * (`createServerFn.ts:271-274`) and it is what lets a middleware normalise an\n * argument every function under it then receives already normalised.\n */\n readonly data: Data;\n /** What the middlewares outside this one contributed. */\n readonly context: OpenContext<Context>;\n /**\n * What the client halves sent with `next({ sendContext })`, as it came off\n * the wire.\n *\n * UNTRUSTED, and kept apart from `context` for that reason: a caller writes\n * the request body by hand as readily as the stub does, so this is input to\n * check and never a fact to act on. Everything read from `context` was put\n * there by a server step; a value from here joins it only when a server half\n * passes it on with `next({ context })`. Untyped for the same reason: a type\n * here would be a claim about what a stranger sent.\n *\n * Empty in a client half, and for a call made in-process.\n */\n readonly clientContext: Readonly<Record<string, unknown>>;\n readonly signal: AbortSignal;\n /**\n * The request, when this middleware is running for one: as a request\n * middleware, global or on a route. Absent around a server function's own\n * chain, where `getRequest()` is the way to it.\n */\n readonly request?: Request;\n /** The request's path, with any base stripped. Present with `request`. */\n readonly pathname?: string;\n /** What the request is for. Present with `request`. */\n readonly handlerType?: \"router\" | \"serverFn\";\n /**\n * The server function this chain is running around, by its id. Absent for a\n * request middleware, and the id is empty for a function that is not mounted.\n */\n readonly serverFnMeta?: { readonly id: string };\n /** The method the server function answers. Absent for a request middleware. */\n readonly method?: \"GET\" | \"POST\";\n}\n\n/**\n * What a client half is handed: the caller's raw `data`, since validators run\n * on the server, and a `context` holding what the client halves before it\n * added and, once `next()` has resolved, what the server sent back.\n */\nexport interface ClientMiddlewareContext<\n Context extends object = Empty,\n Sent extends object = Empty,\n> extends MiddlewareContext<unknown, Context & Partial<Sent>> {}\n\n/** Any server or client half, as the runner calls it. */\nexport type MiddlewareFn = (context: MiddlewareContext) => unknown;\n\n/** What a request middleware calls to run the rest of the request. */\nexport type RequestMiddlewareNext = <Context extends object = Empty>(options?: {\n readonly context?: Context;\n}) => Promise<(Response & NextResult<NoInfer<Context>>) | undefined>;\n\n/**\n * What a request middleware is handed: the request is always there.\n *\n * `next()` resolves to the response, or `undefined` from a route handler that\n * declined, so the page render answers instead.\n */\nexport interface RequestMiddlewareContext<Context extends object = Empty> {\n readonly next: RequestMiddlewareNext;\n readonly data: undefined;\n readonly context: OpenContext<Context>;\n readonly clientContext: Readonly<Record<string, unknown>>;\n readonly signal: AbortSignal;\n readonly request: Request;\n readonly pathname: string;\n readonly handlerType: \"router\" | \"serverFn\";\n}\n\nexport type RequestMiddlewareFn = (context: RequestMiddlewareContext) => unknown;\n\n/** What a built middleware carries, and what the runner reads off it. */\nexport interface MiddlewareOptions {\n /**\n * TanStack's two kinds. `\"request\"` runs for a server request and is handed\n * it; `\"function\"` runs around a server function and may have a client half.\n * One builder makes both and the runner asks only where a middleware was\n * listed, so the kind decides the TYPES of what `.server` is handed.\n */\n readonly type?: \"request\" | \"function\";\n readonly middleware?: readonly Middleware[];\n readonly validator?: Validator<unknown>;\n readonly server?: MiddlewareFn;\n readonly client?: MiddlewareFn;\n}\n\n/**\n * A middleware with more than a body: a chain of its own, an input validator,\n * and separate halves for the two sides.\n *\n * IT IS STILL A FUNCTION. `Middleware` is a callable and the route-action\n * verifier compares chains with `===`, so making this an object — which is what\n * TanStack's is — would have broken both at once: a route's `middleware: [m]`\n * would no longer typecheck, and every existing bare closure would need\n * wrapping. A callable object is neither: it runs where a closure ran, it\n * compares by identity as a closure did, and `options` is there for the runner\n * that wants more.\n *\n * What each step adds is TYPED: a `.server` that ends in\n * `next({ context: { user } })` hands `user` to every function that lists this\n * middleware, typed as the body wrote it.\n */\nexport type BuiltMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &\n Carries<ContributionOfState<State>> & {\n readonly options: MiddlewareOptions;\n /** Middlewares that run BEFORE this one, flattened into the chain that uses it. */\n middleware<const Chain extends readonly Middleware[]>(\n chain: Chain,\n ): BuiltMiddleware<WithChain<State, Chain>>;\n /**\n * Validates and narrows the input every step after this one is handed. The\n * schema form is tried first: an arktype type is callable as well, and read\n * as a function its declared input would be lost.\n */\n validator<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n validator<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n validator<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n validator(unchecked: \"unchecked\"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n /** `validator` under the name TanStack's release candidates used. */\n inputValidator<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n inputValidator<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n inputValidator<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n inputValidator(unchecked: \"unchecked\"): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n /** The half that runs on the server, where the handler is. */\n server<Result>(\n fn: (context: MiddlewareContext<DataAt<State>, State[\"chain\"][\"context\"]>) => Result,\n ): BuiltMiddleware<WithServer<State, Result>>;\n /**\n * The half that runs in the BROWSER, around the fetch.\n *\n * `next({ sendContext })` from here is what travels to the server half as\n * `clientContext`. The compiler carries this into the client stub and leaves\n * the server half behind, so a middleware may hold both without either\n * reaching the wrong bundle.\n */\n client<Result>(\n fn: (\n context: ClientMiddlewareContext<State[\"chain\"][\"clientContext\"], State[\"chain\"][\"sent\"]>,\n ) => Result,\n ): BuiltMiddleware<WithClient<State, Result>>;\n };\n\n/**\n * The two brands a thrown redirect and a thrown `notFound()` carry.\n *\n * DECLARED TWICE ON PURPOSE. The classes live in `@barqjs/router`, which this\n * package must not import: the dependency runs router -> start and start is an\n * OPTIONAL peer of it, so an import here would be a cycle and would break the\n * router for anyone using it without server functions. `Symbol.for` is the\n * global registry, so both declarations name the same symbol with no edge\n * between the packages — `SERVER_FN` in `client.ts` already works this way. The other\n * declaration is `REDIRECT` / `NOT_FOUND` in `packages/router/src/errors.ts`,\n * and `server.test.ts` checks the two agree.\n */\nexport const REDIRECT: unique symbol = Symbol.for(\"barq.redirect\");\nexport const NOT_FOUND: unique symbol = Symbol.for(\"barq.not-found\");\n\n/**\n * What a middleware handed back, held to TanStack's rule: it ends in\n * `return next(...)`, answers with a result of its own, or throws.\n *\n * `undefined` is the one answer that cannot be a decision. Returned without\n * `next()` having been called, the step neither ran the rest of the chain nor\n * said what to answer with; returned after a `next()` that resolved to\n * something, it is the `return` the body forgot, and the result the handler\n * produced would be lost without a word. Either way the call would resolve to\n * nothing, so it fails here, naming the step. A thrown or returned redirect\n * or `notFound()` is an answer, so a returned one is thrown as one.\n */\nfunction answerOf(returned: unknown, answers: readonly unknown[], step: () => string): unknown {\n if (isControl(returned)) throw returned;\n if (returned !== undefined || answers.includes(undefined)) return returned;\n throw new Error(\n answers.length === 0\n ? `[barq] ${step()} returned without calling \\`next()\\`, so the call has no answer. ` +\n \"A middleware ends in `return next(...)`, returns a result of its own, or throws (a `Response` to refuse).\"\n : `[barq] ${step()} called \\`next()\\` and returned \\`undefined\\` in place of its result, so the result was lost. ` +\n \"Return what `next()` resolved to: `return next(...)`.\",\n );\n}\n\nfunction isControl(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const branded = value as Record<symbol, unknown>;\n return branded[REDIRECT] === true || branded[NOT_FOUND] === true;\n}\n\n/**\n * Which step a refusal is about, for a person reading the error: its name when\n * the closure or the half has one, its place in the chain, and the function.\n */\nfunction describeStep(\n kind: string,\n named: readonly ((...args: never[]) => unknown)[],\n position: number,\n length: number,\n around: string,\n): string {\n const name = named\n .map((fn) => fn.name)\n .find((candidate) => candidate !== \"\" && candidate !== \"run\");\n const place = `${position + 1} of ${length}`;\n return name === undefined\n ? `The ${kind} middleware ${place} ${around}`\n : `The ${kind} middleware \\`${name}\\` (${place}) ${around}`;\n}\n\n/** Frozen, because every call that was sent nothing is handed this one object. */\nconst NOTHING_SENT: Record<string, unknown> = Object.freeze({});\n\n/** Whether a middleware was built by {@link createMiddleware}. */\nexport function isBuiltMiddleware(value: Middleware): value is BuiltMiddleware {\n return (value as Partial<BuiltMiddleware>).options !== undefined;\n}\n\n/**\n * Author a middleware that is more than one closure.\n *\n * `createMiddleware().server(async ({ next, context }) => next({ context: … }))`\n * is the ordinary shape, and it is what a bare closure already did. What the\n * builder adds is the three things a closure has nowhere to put: a chain of its\n * own, an input validator, and a client half.\n *\n * EACH CALL RETURNS A NEW MIDDLEWARE, and the exported one is the last. That\n * matters because the verifier compares by identity: a builder that mutated and\n * returned itself would make every intermediate the same object as the final\n * one, which is harmless, and one that shared its options object across\n * branches — which TanStack's does — would make two middlewares built from one\n * base overwrite each other. Neither is a risk worth carrying for an allocation.\n */\nexport function createMiddleware(\n options: MiddlewareOptions & { readonly type: \"request\" },\n): RequestMiddleware<FreshMiddleware>;\nexport function createMiddleware(options?: MiddlewareOptions): BuiltMiddleware<FreshMiddleware>;\nexport function createMiddleware(\n options: MiddlewareOptions = {},\n): BuiltMiddleware<FreshMiddleware> | RequestMiddleware<FreshMiddleware> {\n return built<FreshMiddleware>(options);\n}\n\n/**\n * A typed body, stored where the runner reads it.\n *\n * The runner hands each body the `data` its validators produced and the\n * `context` the steps outside it wrote, which is what the body's own types say;\n * the types cannot follow a value through `options`, so they are restated here,\n * once, rather than at every call.\n */\nfunction asBody<Data, Context extends object>(\n fn: (context: MiddlewareContext<Data, Context>) => unknown,\n): MiddlewareFn {\n return fn as MiddlewareFn;\n}\n\n/**\n * A runner's `next`.\n *\n * It resolves to whatever the rest of the chain answered. `NextResult` is the\n * types' record of what the caller passed, and no value carries it, so the one\n * place a runner makes a `next` is the one place that says so.\n */\nfunction nextOf(step: (options?: NextOptions) => Promise<unknown>): MiddlewareNext {\n return step as MiddlewareNext;\n}\n\nfunction built<State extends MiddlewareState>(options: MiddlewareOptions): BuiltMiddleware<State> {\n // The callable body is the SERVER half, because that is where a middleware in\n // a chain is invoked from. A middleware with no server half still has to be\n // callable — it may exist only to validate, or only to run on the client — and\n // passing straight through is what \"no half here\" means.\n const run: Middleware = async (next) =>\n options.server === undefined\n ? next()\n : options.server({\n next,\n data: undefined,\n context: {},\n clientContext: NOTHING_SENT,\n signal: new AbortController().signal,\n });\n\n function validated<Schema extends StandardSchemaLike>(\n schema: Schema,\n ): BuiltMiddleware<WithValidator<State, StandardInput<Schema>, StandardOutput<Schema>>>;\n function validated<In, Out>(\n validate: (input: In) => Out,\n ): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n function validated<In, Out>(schema: {\n readonly parse: (input: In) => Out;\n }): BuiltMiddleware<WithValidator<State, In, Awaited<Out>>>;\n function validated(\n unchecked: \"unchecked\",\n ): BuiltMiddleware<WithValidator<State, unknown, unknown>>;\n function validated(schema: ValidatorInput<unknown>): BuiltMiddleware {\n return built({ ...options, validator: toValidator(schema) });\n }\n\n return Object.assign(run, {\n options,\n middleware: <const Chain extends readonly Middleware[]>(chain: Chain) =>\n built<WithChain<State, Chain>>({ ...options, middleware: chain }),\n validator: validated,\n inputValidator: validated,\n server: <Result>(\n fn: (context: MiddlewareContext<DataAt<State>, State[\"chain\"][\"context\"]>) => Result,\n ) => built<WithServer<State, Result>>({ ...options, server: asBody(fn) }),\n client: <Result>(\n fn: (\n context: ClientMiddlewareContext<State[\"chain\"][\"clientContext\"], State[\"chain\"][\"sent\"]>,\n ) => Result,\n ) => built<WithClient<State, Result>>({ ...options, client: asBody(fn) }),\n });\n}\n\n/**\n * A middleware built with `type: \"request\"`: a chain of its own and a server\n * body that is always handed the request. It is a {@link BuiltMiddleware}\n * underneath, so it goes wherever a `Middleware` does, and what its body passes\n * to `next({ context })` is typed into everything after it.\n */\nexport type RequestMiddleware<State extends MiddlewareState = MiddlewareState> = Middleware &\n Carries<ContributionOfState<State>> & {\n readonly options: MiddlewareOptions;\n middleware<const Chain extends readonly Middleware[]>(\n chain: Chain,\n ): RequestMiddleware<WithChain<State, Chain>>;\n server<Result>(\n fn: (context: RequestMiddlewareContext<State[\"chain\"][\"context\"]>) => Result,\n ): RequestMiddleware<WithServer<State, NonNullable<Awaited<Result>>>>;\n };\n\n/** Where a request middleware chain is running. */\nexport interface RequestMiddlewareStart {\n readonly request: Request;\n readonly pathname: string;\n readonly handlerType: \"router\" | \"serverFn\";\n /** What the chain has produced so far; mutated as it unwinds inward. */\n readonly context: Record<string, unknown>;\n}\n\n/**\n * Run a chain of request middleware around `run`.\n *\n * `next()` resolves to whatever is inside: the response, or `undefined` from a\n * route handler that declined. A middleware answers with what it returns, so\n * one that returns `next()` passes the answer through and one that returns a\n * `Response` of its own replaces it.\n */\nexport async function runRequestMiddleware<T>(\n chain: readonly Middleware[],\n start: RequestMiddlewareStart,\n run: () => Promise<T>,\n): Promise<T> {\n if (chain.length === 0) return run();\n const flattened = flattenMiddleware(chain);\n // By position, for the reason `runMiddleware` gives: a second `next()`\n // re-enters the steps below it instead of skipping them.\n const dispatch = async (position: number): Promise<unknown> => {\n const middleware = flattened[position];\n if (middleware === undefined) return run();\n const answers: unknown[] = [];\n const next = nextOf(async (step) => {\n if (step?.context !== undefined) Object.assign(start.context, step.context);\n const answer = await dispatch(position + 1);\n answers.push(answer);\n return answer;\n });\n const body = isBuiltMiddleware(middleware) ? middleware.options.server : undefined;\n if (isBuiltMiddleware(middleware) && body === undefined) return next();\n const returned = await (body === undefined\n ? middleware(next)\n : body({\n next,\n data: undefined,\n context: start.context,\n clientContext: NOTHING_SENT,\n signal: start.request.signal,\n request: start.request,\n pathname: start.pathname,\n handlerType: start.handlerType,\n }));\n return answerOf(returned, answers, () =>\n describeStep(\n \"request\",\n body === undefined ? [middleware] : [body],\n position,\n flattened.length,\n `on ${start.request.method} ${start.pathname}`,\n ),\n );\n };\n return (await dispatch(0)) as T;\n}\n\n/**\n * The chain a middleware list really is: every nested chain spliced in ahead of\n * the middleware that declared it, each step once.\n *\n * Depth-first and parents-first, which is TanStack's `flattenMiddlewares` and\n * the only order that means anything — a middleware declares a chain because it\n * DEPENDS on it, so those steps have to have run by the time it does.\n *\n * Deduplicated by IDENTITY, so two middlewares that both depend on\n * `requireSession` do not authenticate twice. That is also what keeps the\n * route-action verifier honest: it asks whether a function's flattened chain\n * contains the route's steps, and a step reached through a nest counts.\n */\nexport function flattenMiddleware(chain: readonly Middleware[], depth = 0): readonly Middleware[] {\n // A chain that reaches itself would otherwise recurse until the stack goes.\n // The cap is TanStack's and the number is theirs.\n if (depth > 100) {\n throw new RangeError(\n \"[barq] A middleware chain nests more than 100 levels deep, which almost always means a middleware's own `middleware` list reaches the middleware itself. \" +\n \"Remove the cycle.\",\n );\n }\n const out: Middleware[] = [];\n const push = (step: Middleware): void => {\n if (!out.includes(step)) out.push(step);\n };\n for (const step of chain) {\n if (isBuiltMiddleware(step) && step.options.middleware !== undefined) {\n for (const nested of flattenMiddleware(step.options.middleware, depth + 1)) push(nested);\n }\n push(step);\n }\n return out;\n}\n\n/** One validator, applied. `\"unchecked\"` and absence both pass the value through. */\nexport async function applyValidator(\n validator: Validator<unknown> | undefined,\n raw: unknown,\n): Promise<unknown> {\n if (validator === undefined || validator === \"unchecked\") return raw;\n const result = await validator[\"~standard\"].validate(raw);\n if (\"issues\" in result) throw new ValidationError(result.issues);\n return result.value;\n}\n\n/**\n * Run a flattened chain, then the innermost work.\n *\n * ONE RUNNER FOR BOTH SIDES, and `half` is which of a built middleware's two\n * bodies to call. A bare closure has neither and is invoked positionally, which\n * is what it has always been — so a chain may mix the two spellings and the\n * order is the order it was written in.\n *\n * A middleware that declares no half for THIS side is skipped rather than\n * refused: a `.server(...)`-only middleware is transparent in the browser, and\n * a `.client(...)`-only one is transparent on the server. That is what makes\n * one exported middleware usable from a route and a server function alike.\n */\nexport async function runMiddleware(\n chain: readonly Middleware[],\n half: \"server\" | \"client\",\n start: {\n readonly data: unknown;\n readonly signal: AbortSignal;\n /** What the chain has produced so far; mutated as the chain unwinds inward. */\n readonly context: Record<string, unknown>;\n /** What the client halves sent, on the server. Never merged into `context`. */\n readonly clientContext?: Record<string, unknown>;\n /** What travels back to the caller. */\n readonly sendContext: Record<string, unknown>;\n /** Where a client half's `next({ headers })` collects. Absent on the server. */\n readonly headers?: Headers;\n /** Where a client half's `next({ fetch })` lands. Absent on the server. */\n readonly fetch?: { current: typeof fetch | undefined };\n /** The function the chain is running around. */\n readonly meta?: { readonly id: string };\n /** The method that function answers. */\n readonly method?: \"GET\" | \"POST\";\n /** The innermost work: the handler on the server, the fetch on the client. */\n readonly run: (data: unknown) => Promise<unknown>;\n },\n): Promise<unknown> {\n // BY POSITION, never by a counter the whole chain shares. A middleware may\n // call `next` twice (a retry, a fallback), and a shared counter has already\n // moved past every step below it by then, so the second call would land on\n // the handler with the guards in between skipped. Each step's `next` names the\n // step after it, so a repeat re-enters the same guards.\n const dispatch = async (position: number, received: unknown): Promise<unknown> => {\n const middleware = chain[position];\n if (middleware === undefined) return start.run(received);\n let data = received;\n const answers: unknown[] = [];\n const next = nextOf(async (step) => {\n if (step?.context !== undefined) Object.assign(start.context, step.context);\n if (step?.sendContext !== undefined) Object.assign(start.sendContext, step.sendContext);\n if (step?.headers !== undefined && start.headers !== undefined) {\n for (const [name, value] of new Headers(step.headers)) start.headers.set(name, value);\n }\n if (step?.fetch !== undefined && start.fetch !== undefined) start.fetch.current = step.fetch;\n const answer = await dispatch(position + 1, data);\n answers.push(answer);\n return answer;\n });\n const step = (named: (...args: never[]) => unknown): string =>\n describeStep(\n half,\n [named],\n position,\n chain.length,\n `around the server function ${JSON.stringify(start.meta?.id ?? \"\")}`,\n );\n if (!isBuiltMiddleware(middleware)) {\n // A BARE CLOSURE IS A SERVER MIDDLEWARE, always. It takes `next` and runs\n // where the handler is; there is no half to choose and nothing about it\n // says it is safe in a browser — `requireSession` in the reference\n // application opens a sealed cookie. Calling one on the client would run\n // a session check in the page, so the client half skips it and only a\n // middleware that declared `.client(…)` runs there.\n if (half !== \"server\") return next();\n return answerOf(await middleware(next), answers, () => step(middleware));\n }\n // VALIDATION FIRST, so the body of this middleware sees what its own\n // validator produced and so does everything under it. TanStack applies them\n // in the same place and the same order.\n if (half === \"server\") data = await applyValidator(middleware.options.validator, data);\n const body = middleware.options[half];\n if (body === undefined) return next();\n const returned = await body({\n next,\n data,\n context: start.context,\n clientContext: start.clientContext ?? NOTHING_SENT,\n signal: start.signal,\n serverFnMeta: start.meta,\n method: start.method,\n });\n return answerOf(returned, answers, () => step(body));\n };\n return dispatch(0, start.data);\n}\n"],"mappings":";;AAoFA,SAAgB,YAAe,OAAwC;CACrE,IAAI,UAAU,aAAa,OAAO;CAGlC,IAAI,eAAe,OAAO,OAAO;CACjC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK;CACvD,OAAO,WAAW,QAAQ,MAAM,MAAM,GAAG,CAAC;AAC5C;AAEA,SAAS,UAAa,OAAuE;CAC3F,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,UAAU,OAAO,UAAU;G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C;EACzE;EAIA,IAAI,SAAS,UAAU,OAAO,MAAM,eAAe,WAAW,QAAQ,WAAW,IAAI;EACrF,MAAM,OAAO,WAAW,QAAQ;EAChC,IAAI,SAAS,KAAA,GAAW,OAAO,KAAK;EAUpC,OAAO,SAAS,MATO,KAAK;GAC1B;GACA;GACA,SAAS,MAAM;GACf,eAAe,MAAM,iBAAiB;GACtC,QAAQ,MAAM;GACd,cAAc,MAAM;GACpB,QAAQ,MAAM;EAChB,CAAC,GACyB,eAAe,KAAK,IAAI,CAAC;CACrD;CACA,OAAO,SAAS,GAAG,MAAM,IAAI;AAC/B"}
@@ -1,5 +1,26 @@
1
+ /**
2
+ * Static HTML, written by the SAME handler that serves a live request.
3
+ *
4
+ * The decision this file rests on, and the field is nearly unanimous on the
5
+ * other side of it: a prerendered page is `createPageHandler` with
6
+ * `stream: false`, NOT a streamed response buffered to a string.
7
+ *
8
+ * SvelteKit and Nitro — and so Solid Start, Nuxt and TanStack Start — prerender
9
+ * by calling the real handler and doing `Buffer.from(await res.arrayBuffer())`
10
+ * with streaming still on. Buffering does not undo streaming: the protocol is
11
+ * emitted at FLUSH time, so by the time you hold the bytes the placeholders and
12
+ * the swap scripts are already in them. A SvelteKit prerendered file, reproduced
13
+ * on 2.70.3, ships `<p>loading...</p>` as its static markup with
14
+ * `<script>…resolve(1, () => ["LATE_STREAMED_VALUE"])</script>` after `</html>`,
15
+ * for data that was fully known at build time.
16
+ *
17
+ * Astro is the exception and its fix is ten lines: a build-time subclass whose
18
+ * `resolveStreaming()` returns undefined. barq gets that for free, because
19
+ * `stream: false` is a different RENDERER — `renderPage` awaits `settle`, walks
20
+ * the seed with `settleNested`, and emits one `__BARQ_DATA__` script with no
21
+ * channel, no swap helper and no `<template>` anywhere.
22
+ */
1
23
  import { ServerEntryModule } from "./protocol.js";
2
- //#region src/prerender.d.ts
3
24
  export interface PrerenderRun {
4
25
  readonly entry: ServerEntryModule;
5
26
  readonly outDir: string;
@@ -93,6 +114,5 @@ export interface ShellRun {
93
114
  * second document to keep in step with it.
94
115
  */
95
116
  export declare function prerenderShell(run: ShellRun): Promise<string>;
96
- //#endregion
97
117
  export type { ServerEntryModule };
98
118
  //# sourceMappingURL=prerender.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.d.ts","names":[],"sources":["../src/prerender.ts"],"mappings":";;iBA+BiB;WACN,OAAO;WACP;WACA;WACA;WACA;WACA;WACA;;WAEA,UAAU;;;;;;;WAOV;;WAEA;;;;;;;WAOA,UAAU;WACV,OAAO;;iBAGD;WACN;WACA;;iBAGM;WACN,OAAO;;WAEP;;;;;;;;WAQA;;WAEA;;;iBAIM;WACN;WACA;WACA;;;;;;;;;;;;WAYA,SAAS;;;;;;;;;;;wBA4HE,UAAU,KAAK,eAAe,QAAQ;;iBA8M3C;WACN,OAAO;WACP;;WAEA;;WAEA;;;;;;;;;;wBAWW,eAAe,KAAK,WAAW"}
1
+ {"version":3,"file":"prerender.d.ts","names":[],"sources":["../src/prerender.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;iBA+BiB;WACN,OAAO;WACP;WACA;WACA;WACA;WACA;WACA;;WAEA,UAAU;;;;;;;WAOV;;WAEA;;;;;;;WAOA,UAAU;WACV,OAAO;;iBAGD;WACN;WACA;;iBAGM;WACN,OAAO;;WAEP;;;;;;;;WAQA;;WAEA;;;iBAIM;WACN;WACA;WACA;;;;;;;;;;;;WAYA,SAAS;;;;;;;;;;;wBA4HE,UAAU,KAAK,eAAe,QAAQ;;iBA8M3C;WACN,OAAO;WACP;;WAEA;;WAEA;;;;;;;;;;wBAWW,eAAe,KAAK,WAAW"}
package/dist/prerender.js CHANGED
@@ -1,8 +1,8 @@
1
- import { n as installStaticWriter, t as STATIC_PREFIX } from "./static-fn-DgjNArBe.js";
2
- import { PRERENDER_HEADER } from "./protocol.js";
3
1
  import { mkdir, writeFile } from "node:fs/promises";
4
2
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
- //#region src/prerender.ts
3
+ import { PRERENDER_HEADER } from "./protocol.js";
4
+ import { n as installStaticWriter, t as STATIC_PREFIX } from "./static-fn-CXjJi-It.js";
5
+ // src/prerender.ts
6
6
  /**
7
7
  * Static HTML, written by the SAME handler that serves a live request.
8
8
  *
@@ -57,6 +57,7 @@ function normalize(path) {
57
57
  const url = new URL(clean, ORIGIN);
58
58
  if (url.origin !== ORIGIN) return null;
59
59
  resolved = url.pathname;
60
+ decodeURI(resolved);
60
61
  } catch {
61
62
  return null;
62
63
  }
@@ -283,7 +284,6 @@ async function prerenderShell(run) {
283
284
  await writeFile(file, await response.text(), "utf8");
284
285
  return file;
285
286
  }
286
- //#endregion
287
287
  export { prerender, prerenderShell };
288
288
 
289
289
  //# sourceMappingURL=prerender.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prerender.js","names":[],"sources":["../src/prerender.ts"],"sourcesContent":["/**\n * Static HTML, written by the SAME handler that serves a live request.\n *\n * The decision this file rests on, and the field is nearly unanimous on the\n * other side of it: a prerendered page is `createPageHandler` with\n * `stream: false`, NOT a streamed response buffered to a string.\n *\n * SvelteKit and Nitro — and so Solid Start, Nuxt and TanStack Start — prerender\n * by calling the real handler and doing `Buffer.from(await res.arrayBuffer())`\n * with streaming still on. Buffering does not undo streaming: the protocol is\n * emitted at FLUSH time, so by the time you hold the bytes the placeholders and\n * the swap scripts are already in them. A SvelteKit prerendered file, reproduced\n * on 2.70.3, ships `<p>loading...</p>` as its static markup with\n * `<script>…resolve(1, () => [\"LATE_STREAMED_VALUE\"])</script>` after `</html>`,\n * for data that was fully known at build time.\n *\n * Astro is the exception and its fix is ten lines: a build-time subclass whose\n * `resolveStreaming()` returns undefined. barq gets that for free, because\n * `stream: false` is a different RENDERER — `renderPage` awaits `settle`, walks\n * the seed with `settleNested`, and emits one `__BARQ_DATA__` script with no\n * channel, no swap helper and no `<template>` anywhere.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, sep } from \"node:path\";\n\nimport { PRERENDER_HEADER, type ServerEntryModule } from \"./protocol.ts\";\nimport { STATIC_PREFIX, installStaticWriter } from \"./static-fn.ts\";\n\nexport type { ServerEntryModule };\n\nexport interface PrerenderRun {\n readonly entry: ServerEntryModule;\n readonly outDir: string;\n readonly routes: readonly string[];\n readonly crawl: boolean;\n readonly concurrency: number;\n readonly subfolderIndex: boolean;\n readonly base: string;\n /** Whether a path is prerendered at all. Asked with the normalised path. */\n readonly filter?: (path: string) => boolean;\n /**\n * How many more times a page is asked for after its request throws or answers\n * 5xx. Default 0.\n *\n * A 4xx is an answer, not a failure to answer: asking again gets it again.\n */\n readonly retryCount?: number;\n /** Milliseconds to wait before each retry. Default 0. */\n readonly retryDelay?: number;\n /**\n * Write a sitemap of what was prerendered.\n *\n * `host` is the origin the site is deployed at, which the build cannot know.\n * `outputPath` is relative to `outDir` and defaults to `sitemap.xml`.\n */\n readonly sitemap?: PrerenderSitemap;\n readonly log?: (message: string) => void;\n}\n\nexport interface PrerenderSitemap {\n readonly host: string;\n readonly outputPath?: string;\n}\n\nexport interface PrerenderResult {\n readonly pages: PrerenderedPage[];\n /** The sitemap's file, when one was asked for and a page belongs in it. */\n readonly sitemap?: string;\n /**\n * The copy of the `/404` page at `<outDir>/404.html`, the name a static host\n * serves for a path it has no file for.\n *\n * Absent when the page's own file is that one already. It has no entry in\n * `pages`: it is a second name for a page that is listed there.\n */\n readonly notFoundFile?: string;\n /** The files `staticFunctionMiddleware` answers were written to. */\n readonly staticAnswers: readonly string[];\n}\n\n/** One prerendered page, as the build records it. */\nexport interface PrerenderedPage {\n readonly path: string;\n readonly file: string;\n readonly status: number;\n /**\n * The response's own headers.\n *\n * Kept because a static host cannot recover them from a file, and every\n * framework that drops them has an open issue about it — SvelteKit rescues\n * `cache-control` alone into a `<meta http-equiv>` and leaves the rest\n * unhandled, Nitro loses `content-type` on a generated feed.\n *\n * `writeAssetManifest` in `vite.ts` is what finally persists them, and\n * `static.ts` is what serves a page with the status it was rendered as.\n */\n readonly headers: Record<string, string>;\n}\n\nfunction isHtml(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").includes(\"text/html\");\n}\n\n/** The origin every prerender request is made against. It never leaves the build. */\nconst ORIGIN = \"http://prerender.localhost\";\n\n/**\n * A path, as the dedup key sees it.\n *\n * Trailing slashes are normalised and the query is DROPPED, both because of\n * open bugs in the nearest prior art. TanStack's crawler appends a trailing\n * slash without `respectQueryAndFragment`, so `/posts?page=2` becomes\n * `/posts?page=2/`, re-serialises as `page=2%2F`, and every crawl step produces\n * a URL nothing has seen, and the crawl never terminates. `/x` against `/x/` as\n * two keys is a second open bug there. A query string has no effect on a statically\n * exported page anyway, which is the note SvelteKit's crawler carries.\n *\n * THROUGH `new URL`, because the key is also what gets requested and what names\n * the file. An `href` is whatever an author typed, and `/../../about` typed into\n * a page is `/about` to every browser that follows it: resolved here, it is one\n * key and one file, where the raw text is a second key and a path that climbs\n * out of the output directory.\n */\nfunction normalize(path: string): string | null {\n if (path.startsWith(\"//\") || /^[a-z][a-z0-9+.-]*:/i.test(path)) return null;\n const [withoutHash = \"\"] = path.split(\"#\");\n const [clean = \"\"] = withoutHash.split(\"?\");\n if (clean === \"\") return null;\n let resolved: string;\n try {\n const url = new URL(clean, ORIGIN);\n if (url.origin !== ORIGIN) return null;\n resolved = url.pathname;\n // Asked now so that a path which names no file is never queued.\n decodeURI(resolved);\n } catch {\n return null;\n }\n const trimmed = resolved.length > 1 ? resolved.replace(/\\/+$/, \"\") : resolved;\n return trimmed === \"\" ? \"/\" : trimmed;\n}\n\n/** Same-origin `href`s and `src`s, which is what a crawl follows. */\nfunction linksIn(html: string): string[] {\n const out: string[] = [];\n for (const match of html.matchAll(/<a\\b[^>]*?\\shref=[\"']([^\"']+)[\"']/gi)) {\n const href = match[1];\n if (href !== undefined) out.push(href);\n }\n return out;\n}\n\n/**\n * `/about` -> `dist/client/about/index.html`, or `about.html`.\n *\n * CONTAINMENT IS ASSERTED rather than assumed. {@link normalize} resolves dot\n * segments, but the name on disk is the DECODED path, and decoding can produce\n * a separator the URL never had: `..%5C` is one ordinary segment to a URL and a\n * step upward to a Windows path.\n */\nfunction fileFor(path: string, outDir: string, subfolderIndex: boolean): string {\n const clean = path.replace(/^\\/+/, \"\");\n let file: string;\n if (clean === \"\") file = join(outDir, \"index.html\");\n else if (clean.endsWith(\".html\")) file = join(outDir, clean);\n else file = subfolderIndex ? join(outDir, clean, \"index.html\") : join(outDir, `${clean}.html`);\n return contained(path, file, outDir);\n}\n\nfunction contained(what: string, file: string, outDir: string): string {\n const inside = relative(outDir, file);\n if (inside === \"..\" || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {\n throw new Error(\n `The file for ${what} would be written outside the output directory, to \\`${file}\\`, so it was refused. ` +\n \"Use a path or an `outputPath` that stays inside the output directory, without `..` segments.\",\n );\n }\n return file;\n}\n\n/** The path every static host looks a missing page up under. */\nconst NOT_FOUND_PATH = \"/404\";\n\n/** A count or a delay as given, or 0 for anything that is not a positive number. */\nfunction whole(value: number | undefined): number {\n return value !== undefined && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\nfunction escapeXml(text: string): string {\n return text\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n}\n\n/**\n * `<loc>` alone. A `<lastmod>` stamped with the build date, which is what the\n * nearest prior art writes, tells a crawler every page changed on every deploy.\n */\nfunction sitemapXml(locations: readonly string[]): string {\n const urls = locations.map((loc) => ` <url>\\n <loc>${escapeXml(loc)}</loc>\\n </url>\\n`);\n return (\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n' +\n urls.join(\"\") +\n \"</urlset>\\n\"\n );\n}\n\n/**\n * Render every reachable path and write it.\n *\n * Failures are COLLECTED and rethrown after the queue drains, never swallowed.\n * TanStack's equivalent adds to its queue without awaiting and resolves on\n * `onSettled` regardless of outcome, so their `failOnError` cannot fail a build\n * and their `retryCount` is dead code. A build that emits a broken page\n * and exits 0 is the failure a prerenderer exists to prevent.\n */\nexport async function prerender(run: PrerenderRun): Promise<PrerenderResult> {\n const build = run.entry.default?.createFetch;\n if (typeof build !== \"function\") {\n throw new Error(\n \"[barq-start] The `prerender` option is set, but the server entry's default export has no `createFetch`, so no page can be rendered to a static file. \" +\n \"Use `export default createStartHandler()` from `@barqjs/router/server` in the server entry.\",\n );\n }\n\n const fetchPage = build({\n stream: false,\n // A prerendered page has no request. Refusing beats SvelteKit's shape, where\n // `cookies.get` and `request.headers` silently answer null and the page is\n // built from a build machine's idea of who is asking.\n refuseRequest:\n \"getRequest() is not available while prerendering: this page is built once, for everyone. \" +\n \"Move what needs a request behind a route that is not prerendered.\",\n // A nonce baked into a static file is a constant an attacker reads, which is\n // the opposite of what a nonce is. SvelteKit bans `csp.mode: \"nonce\"` under\n // prerender outright and React ships the same note on its static entry.\n nonce: undefined,\n });\n\n // Asked before anything is rendered: a path that cannot be written is known\n // from the configuration alone, and the whole site is a long wait to find out.\n const sitemap =\n run.sitemap === undefined\n ? undefined\n : {\n host: run.sitemap.host.replace(/\\/+$/, \"\"),\n file: contained(\n \"the sitemap\",\n join(run.outDir, run.sitemap.outputPath ?? \"sitemap.xml\"),\n run.outDir,\n ),\n };\n const retries = whole(run.retryCount);\n const retryDelay = whole(run.retryDelay);\n\n const seen = new Set<string>();\n const queue: string[] = [];\n const pages: PrerenderedPage[] = [];\n const failures: string[] = [];\n // The URL paths, where `pages` holds the decoded names: a `<loc>` is a URL.\n const listed: string[] = [];\n let notFoundFile: string | undefined;\n\n const enqueue = (path: string): void => {\n const key = normalize(path);\n if (key === null || seen.has(key)) return;\n seen.add(key);\n // After `seen`, so a path linked from every page is asked about once.\n if (run.filter?.(key) === false) return;\n queue.push(key);\n };\n\n const named = new Set<string>();\n for (const route of run.routes.length > 0 ? run.routes : [\"/\"]) {\n const key = normalize(route);\n if (key !== null) named.add(key);\n enqueue(route);\n }\n\n const ask = async (path: string): Promise<{ response: Response; html: string }> => {\n for (let attempt = 0; ; attempt += 1) {\n const last = attempt >= retries;\n try {\n const response = await fetchPage(new Request(`${ORIGIN}${path}`));\n const html = await response.text();\n if (response.status < 500 || last) return { response, html };\n run.log?.(`${path} answered ${response.status}, asking again`);\n } catch (reason) {\n if (last) throw reason;\n run.log?.(`${path} threw, asking again`);\n }\n if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));\n }\n };\n\n const one = async (path: string): Promise<void> => {\n const { response, html } = await ask(path);\n const crawledOnly = !named.has(path);\n // A page the build NAMED and the application answers 404 for is the\n // application's not-found page, asked for on purpose: it is written, with\n // the status it was rendered as, for `static.ts` to serve. Anything else at\n // 400 or above is a link to nowhere or a server that failed.\n const notFoundPage = response.status === 404 && !crawledOnly && isHtml(response);\n if (response.status >= 400 && !notFoundPage) {\n failures.push(`${path} answered ${response.status}`);\n return;\n }\n const declined = response.headers.get(PRERENDER_HEADER) === \"0\";\n if (crawledOnly && declined) {\n // Rendered to find its links, not to be written. A route that has not said\n // `prerender` is a route the build has no business freezing.\n if (run.crawl) followLinks(html);\n return;\n }\n // The NAME, where `path` is the URL: `/caf%C3%A9` is `café/index.html` on\n // disk and `/café` in the manifest, which is how `static.ts` looks it up.\n const name = decodeURI(path);\n const file = fileFor(name, run.outDir, run.subfolderIndex);\n await mkdir(dirname(file), { recursive: true });\n // Written as each page finishes rather than accumulated: holding ~300\n // data-heavy pages to the end is a 2 GB heap, which SvelteKit shipped.\n await writeFile(file, html, \"utf8\");\n pages.push({\n path: name,\n file,\n status: response.status,\n headers: Object.fromEntries(response.headers),\n });\n run.log?.(`${path} -> ${file}`);\n if (path === NOT_FOUND_PATH) {\n const root = join(run.outDir, \"404.html\");\n if (root !== file) {\n await writeFile(root, html, \"utf8\");\n notFoundFile = root;\n }\n } else if (response.ok) {\n listed.push(path);\n }\n if (run.crawl && !notFoundPage) followLinks(html);\n };\n\n const followLinks = (html: string): void => {\n for (const href of linksIn(html)) {\n if (!href.startsWith(\"/\")) continue;\n const inside = run.base === \"/\" || href.startsWith(run.base);\n if (inside) enqueue(run.base === \"/\" ? href : href.slice(run.base.length - 1));\n }\n };\n\n // A POOL, not batches: a slot is refilled the moment its page finishes, so\n // one slow page costs its own time rather than its whole batch's. The queue\n // grows while it drains, since a crawled page adds what it links to.\n const slots = Math.max(1, run.concurrency);\n let next = 0;\n let active = 0;\n // A static server function's answer is written beside the pages that asked\n // for it, under the name its client half will look for. One name holding two\n // different calls would hand the second caller the first one's answer, so\n // that stops the build rather than being written.\n const answered = new Map<string, string>();\n const staticAnswers: string[] = [];\n installStaticWriter(async (key, identity, answer) => {\n const before = answered.get(key);\n if (before !== undefined && before !== identity) {\n throw new Error(\n `[barq-start] Two static server function calls share the cache name ${key}, so one would be answered with the other's result. ` +\n \"Pass a different input to one of them, or drop `staticFunctionMiddleware` from it.\",\n );\n }\n const file = contained(\n \"a static server function's answer\",\n join(run.outDir, STATIC_PREFIX.slice(1), `${key}.json`),\n run.outDir,\n );\n if (before === undefined) {\n answered.set(key, identity);\n staticAnswers.push(file);\n }\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, answer, \"utf8\");\n });\n await new Promise<void>((drained) => {\n const fill = (): void => {\n while (active < slots) {\n const path = queue[next];\n if (path === undefined) break;\n next += 1;\n active += 1;\n one(path)\n .catch((reason: unknown) => {\n const message = (reason as { message?: string } | null)?.message ?? String(reason);\n failures.push(`${path}: ${message}`);\n })\n .finally(() => {\n active -= 1;\n fill();\n });\n }\n if (active === 0) drained();\n };\n fill();\n }).finally(() => installStaticWriter(null));\n\n if (failures.length > 0) {\n throw new Error(\n `[barq-start] ${failures.length} page(s) failed to prerender, so the build stopped before shipping a broken page:\\n ` +\n failures.join(\"\\n \"),\n );\n }\n\n if (sitemap === undefined || listed.length === 0) return { pages, notFoundFile, staticAnswers };\n const base = run.base.replace(/\\/+$/, \"\");\n await mkdir(dirname(sitemap.file), { recursive: true });\n await writeFile(\n sitemap.file,\n sitemapXml(listed.toSorted().map((path) => `${sitemap.host}${base}${path}`)),\n \"utf8\",\n );\n return { pages, sitemap: sitemap.file, notFoundFile, staticAnswers };\n}\n\n/** What {@link prerenderShell} is asked for. */\nexport interface ShellRun {\n readonly entry: ServerEntryModule;\n readonly outDir: string;\n /** The path the shell is rendered at. `/` when omitted. */\n readonly maskPath?: string;\n /** Where it is written, relative to `outDir`. `_shell.html` when omitted. */\n readonly outputPath?: string;\n}\n\n/**\n * Write the SPA shell: the root route's document, with nothing under it\n * rendered, for a server or a static host to answer every page path with.\n *\n * TanStack's SPA mode. The file is one request to the same handler, built with\n * `shell: true`, so the shell is the application's own root route rather than a\n * second document to keep in step with it.\n */\nexport async function prerenderShell(run: ShellRun): Promise<string> {\n const build = run.entry.default?.createFetch;\n if (typeof build !== \"function\") {\n throw new Error(\n \"[barq-start] SPA mode is on, but the server entry's default export has no `createFetch`, so the shell document cannot be rendered. \" +\n \"Use `export default createStartHandler()` from `@barqjs/router/server` in the server entry.\",\n );\n }\n const file = contained(\n \"the SPA shell\",\n join(run.outDir, (run.outputPath ?? \"_shell.html\").replace(/^\\/+/, \"\")),\n run.outDir,\n );\n const fetchShell = build({\n stream: false,\n pages: true,\n shell: true,\n refuseRequest:\n \"[barq] `getRequest()` and the other request helpers are not available while the SPA shell is rendered: the shell is built once and served for every path, so there is no request to read. \" +\n \"Read the request in a loader or a server function instead.\",\n nonce: undefined,\n });\n const response = await fetchShell(new Request(`${ORIGIN}${run.maskPath ?? \"/\"}`));\n if (response.status >= 400 || !isHtml(response)) {\n throw new Error(\n `[barq-start] Rendering the SPA shell at \\`${run.maskPath ?? \"/\"}\\` answered ${response.status}${isHtml(response) ? \"\" : \" without an HTML body\"}, so no shell was written. ` +\n \"The root route's `shellComponent` has to render for that path: check the server output above for the error it threw.\",\n );\n }\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, await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,OAAO,MAAM,CAAC,GAC3E,MACF;CACA,OAAO;EAAE;EAAO,SAAS,QAAQ;EAAM;EAAc;CAAc;AACrE;;;;;;;;;AAoBA,eAAsB,eAAe,KAAgC;CACnE,MAAM,QAAQ,IAAI,MAAM,SAAS;CACjC,IAAI,OAAO,UAAU,YACnB,MAAM,IAAI,MACR,gOAEF;CAEF,MAAM,OAAO,UACX,iBACA,KAAK,IAAI,SAAS,IAAI,cAAc,cAAA,CAAe,QAAQ,QAAQ,EAAE,CAAC,GACtE,IAAI,MACN;CAUA,MAAM,WAAW,MATE,MAAM;EACvB,QAAQ;EACR,OAAO;EACP,OAAO;EACP,eACE;EAEF,OAAO,KAAA;CACT,CACgC,CAAC,CAAC,IAAI,QAAQ,GAAG,SAAS,IAAI,YAAY,KAAK,CAAC;CAChF,IAAI,SAAS,UAAU,OAAO,CAAC,OAAO,QAAQ,GAC5C,MAAM,IAAI,MACR,6CAA6C,IAAI,YAAY,IAAI,cAAc,SAAS,SAAS,OAAO,QAAQ,IAAI,KAAK,wBAAwB,kJAEnJ;CAEF,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,UAAU,MAAM,MAAM,SAAS,KAAK,GAAG,MAAM;CACnD,OAAO;AACT"}
1
+ {"version":3,"file":"prerender.js","names":[],"sources":["../src/prerender.ts"],"sourcesContent":["/**\n * Static HTML, written by the SAME handler that serves a live request.\n *\n * The decision this file rests on, and the field is nearly unanimous on the\n * other side of it: a prerendered page is `createPageHandler` with\n * `stream: false`, NOT a streamed response buffered to a string.\n *\n * SvelteKit and Nitro — and so Solid Start, Nuxt and TanStack Start — prerender\n * by calling the real handler and doing `Buffer.from(await res.arrayBuffer())`\n * with streaming still on. Buffering does not undo streaming: the protocol is\n * emitted at FLUSH time, so by the time you hold the bytes the placeholders and\n * the swap scripts are already in them. A SvelteKit prerendered file, reproduced\n * on 2.70.3, ships `<p>loading...</p>` as its static markup with\n * `<script>…resolve(1, () => [\"LATE_STREAMED_VALUE\"])</script>` after `</html>`,\n * for data that was fully known at build time.\n *\n * Astro is the exception and its fix is ten lines: a build-time subclass whose\n * `resolveStreaming()` returns undefined. barq gets that for free, because\n * `stream: false` is a different RENDERER — `renderPage` awaits `settle`, walks\n * the seed with `settleNested`, and emits one `__BARQ_DATA__` script with no\n * channel, no swap helper and no `<template>` anywhere.\n */\n\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, relative, sep } from \"node:path\";\n\nimport { PRERENDER_HEADER, type ServerEntryModule } from \"./protocol.ts\";\nimport { STATIC_PREFIX, installStaticWriter } from \"./static-fn.ts\";\n\nexport type { ServerEntryModule };\n\nexport interface PrerenderRun {\n readonly entry: ServerEntryModule;\n readonly outDir: string;\n readonly routes: readonly string[];\n readonly crawl: boolean;\n readonly concurrency: number;\n readonly subfolderIndex: boolean;\n readonly base: string;\n /** Whether a path is prerendered at all. Asked with the normalised path. */\n readonly filter?: (path: string) => boolean;\n /**\n * How many more times a page is asked for after its request throws or answers\n * 5xx. Default 0.\n *\n * A 4xx is an answer, not a failure to answer: asking again gets it again.\n */\n readonly retryCount?: number;\n /** Milliseconds to wait before each retry. Default 0. */\n readonly retryDelay?: number;\n /**\n * Write a sitemap of what was prerendered.\n *\n * `host` is the origin the site is deployed at, which the build cannot know.\n * `outputPath` is relative to `outDir` and defaults to `sitemap.xml`.\n */\n readonly sitemap?: PrerenderSitemap;\n readonly log?: (message: string) => void;\n}\n\nexport interface PrerenderSitemap {\n readonly host: string;\n readonly outputPath?: string;\n}\n\nexport interface PrerenderResult {\n readonly pages: PrerenderedPage[];\n /** The sitemap's file, when one was asked for and a page belongs in it. */\n readonly sitemap?: string;\n /**\n * The copy of the `/404` page at `<outDir>/404.html`, the name a static host\n * serves for a path it has no file for.\n *\n * Absent when the page's own file is that one already. It has no entry in\n * `pages`: it is a second name for a page that is listed there.\n */\n readonly notFoundFile?: string;\n /** The files `staticFunctionMiddleware` answers were written to. */\n readonly staticAnswers: readonly string[];\n}\n\n/** One prerendered page, as the build records it. */\nexport interface PrerenderedPage {\n readonly path: string;\n readonly file: string;\n readonly status: number;\n /**\n * The response's own headers.\n *\n * Kept because a static host cannot recover them from a file, and every\n * framework that drops them has an open issue about it — SvelteKit rescues\n * `cache-control` alone into a `<meta http-equiv>` and leaves the rest\n * unhandled, Nitro loses `content-type` on a generated feed.\n *\n * `writeAssetManifest` in `vite.ts` is what finally persists them, and\n * `static.ts` is what serves a page with the status it was rendered as.\n */\n readonly headers: Record<string, string>;\n}\n\nfunction isHtml(response: Response): boolean {\n return (response.headers.get(\"content-type\") ?? \"\").includes(\"text/html\");\n}\n\n/** The origin every prerender request is made against. It never leaves the build. */\nconst ORIGIN = \"http://prerender.localhost\";\n\n/**\n * A path, as the dedup key sees it.\n *\n * Trailing slashes are normalised and the query is DROPPED, both because of\n * open bugs in the nearest prior art. TanStack's crawler appends a trailing\n * slash without `respectQueryAndFragment`, so `/posts?page=2` becomes\n * `/posts?page=2/`, re-serialises as `page=2%2F`, and every crawl step produces\n * a URL nothing has seen, and the crawl never terminates. `/x` against `/x/` as\n * two keys is a second open bug there. A query string has no effect on a statically\n * exported page anyway, which is the note SvelteKit's crawler carries.\n *\n * THROUGH `new URL`, because the key is also what gets requested and what names\n * the file. An `href` is whatever an author typed, and `/../../about` typed into\n * a page is `/about` to every browser that follows it: resolved here, it is one\n * key and one file, where the raw text is a second key and a path that climbs\n * out of the output directory.\n */\nfunction normalize(path: string): string | null {\n if (path.startsWith(\"//\") || /^[a-z][a-z0-9+.-]*:/i.test(path)) return null;\n const [withoutHash = \"\"] = path.split(\"#\");\n const [clean = \"\"] = withoutHash.split(\"?\");\n if (clean === \"\") return null;\n let resolved: string;\n try {\n const url = new URL(clean, ORIGIN);\n if (url.origin !== ORIGIN) return null;\n resolved = url.pathname;\n // Asked now so that a path which names no file is never queued.\n decodeURI(resolved);\n } catch {\n return null;\n }\n const trimmed = resolved.length > 1 ? resolved.replace(/\\/+$/, \"\") : resolved;\n return trimmed === \"\" ? \"/\" : trimmed;\n}\n\n/** Same-origin `href`s and `src`s, which is what a crawl follows. */\nfunction linksIn(html: string): string[] {\n const out: string[] = [];\n for (const match of html.matchAll(/<a\\b[^>]*?\\shref=[\"']([^\"']+)[\"']/gi)) {\n const href = match[1];\n if (href !== undefined) out.push(href);\n }\n return out;\n}\n\n/**\n * `/about` -> `dist/client/about/index.html`, or `about.html`.\n *\n * CONTAINMENT IS ASSERTED rather than assumed. {@link normalize} resolves dot\n * segments, but the name on disk is the DECODED path, and decoding can produce\n * a separator the URL never had: `..%5C` is one ordinary segment to a URL and a\n * step upward to a Windows path.\n */\nfunction fileFor(path: string, outDir: string, subfolderIndex: boolean): string {\n const clean = path.replace(/^\\/+/, \"\");\n let file: string;\n if (clean === \"\") file = join(outDir, \"index.html\");\n else if (clean.endsWith(\".html\")) file = join(outDir, clean);\n else file = subfolderIndex ? join(outDir, clean, \"index.html\") : join(outDir, `${clean}.html`);\n return contained(path, file, outDir);\n}\n\nfunction contained(what: string, file: string, outDir: string): string {\n const inside = relative(outDir, file);\n if (inside === \"..\" || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {\n throw new Error(\n `The file for ${what} would be written outside the output directory, to \\`${file}\\`, so it was refused. ` +\n \"Use a path or an `outputPath` that stays inside the output directory, without `..` segments.\",\n );\n }\n return file;\n}\n\n/** The path every static host looks a missing page up under. */\nconst NOT_FOUND_PATH = \"/404\";\n\n/** A count or a delay as given, or 0 for anything that is not a positive number. */\nfunction whole(value: number | undefined): number {\n return value !== undefined && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\nfunction escapeXml(text: string): string {\n return text\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n}\n\n/**\n * `<loc>` alone. A `<lastmod>` stamped with the build date, which is what the\n * nearest prior art writes, tells a crawler every page changed on every deploy.\n */\nfunction sitemapXml(locations: readonly string[]): string {\n const urls = locations.map((loc) => ` <url>\\n <loc>${escapeXml(loc)}</loc>\\n </url>\\n`);\n return (\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\\n' +\n urls.join(\"\") +\n \"</urlset>\\n\"\n );\n}\n\n/**\n * Render every reachable path and write it.\n *\n * Failures are COLLECTED and rethrown after the queue drains, never swallowed.\n * TanStack's equivalent adds to its queue without awaiting and resolves on\n * `onSettled` regardless of outcome, so their `failOnError` cannot fail a build\n * and their `retryCount` is dead code. A build that emits a broken page\n * and exits 0 is the failure a prerenderer exists to prevent.\n */\nexport async function prerender(run: PrerenderRun): Promise<PrerenderResult> {\n const build = run.entry.default?.createFetch;\n if (typeof build !== \"function\") {\n throw new Error(\n \"[barq-start] The `prerender` option is set, but the server entry's default export has no `createFetch`, so no page can be rendered to a static file. \" +\n \"Use `export default createStartHandler()` from `@barqjs/router/server` in the server entry.\",\n );\n }\n\n const fetchPage = build({\n stream: false,\n // A prerendered page has no request. Refusing beats SvelteKit's shape, where\n // `cookies.get` and `request.headers` silently answer null and the page is\n // built from a build machine's idea of who is asking.\n refuseRequest:\n \"getRequest() is not available while prerendering: this page is built once, for everyone. \" +\n \"Move what needs a request behind a route that is not prerendered.\",\n // A nonce baked into a static file is a constant an attacker reads, which is\n // the opposite of what a nonce is. SvelteKit bans `csp.mode: \"nonce\"` under\n // prerender outright and React ships the same note on its static entry.\n nonce: undefined,\n });\n\n // Asked before anything is rendered: a path that cannot be written is known\n // from the configuration alone, and the whole site is a long wait to find out.\n const sitemap =\n run.sitemap === undefined\n ? undefined\n : {\n host: run.sitemap.host.replace(/\\/+$/, \"\"),\n file: contained(\n \"the sitemap\",\n join(run.outDir, run.sitemap.outputPath ?? \"sitemap.xml\"),\n run.outDir,\n ),\n };\n const retries = whole(run.retryCount);\n const retryDelay = whole(run.retryDelay);\n\n const seen = new Set<string>();\n const queue: string[] = [];\n const pages: PrerenderedPage[] = [];\n const failures: string[] = [];\n // The URL paths, where `pages` holds the decoded names: a `<loc>` is a URL.\n const listed: string[] = [];\n let notFoundFile: string | undefined;\n\n const enqueue = (path: string): void => {\n const key = normalize(path);\n if (key === null || seen.has(key)) return;\n seen.add(key);\n // After `seen`, so a path linked from every page is asked about once.\n if (run.filter?.(key) === false) return;\n queue.push(key);\n };\n\n const named = new Set<string>();\n for (const route of run.routes.length > 0 ? run.routes : [\"/\"]) {\n const key = normalize(route);\n if (key !== null) named.add(key);\n enqueue(route);\n }\n\n const ask = async (path: string): Promise<{ response: Response; html: string }> => {\n for (let attempt = 0; ; attempt += 1) {\n const last = attempt >= retries;\n try {\n const response = await fetchPage(new Request(`${ORIGIN}${path}`));\n const html = await response.text();\n if (response.status < 500 || last) return { response, html };\n run.log?.(`${path} answered ${response.status}, asking again`);\n } catch (reason) {\n if (last) throw reason;\n run.log?.(`${path} threw, asking again`);\n }\n if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));\n }\n };\n\n const one = async (path: string): Promise<void> => {\n const { response, html } = await ask(path);\n const crawledOnly = !named.has(path);\n // A page the build NAMED and the application answers 404 for is the\n // application's not-found page, asked for on purpose: it is written, with\n // the status it was rendered as, for `static.ts` to serve. Anything else at\n // 400 or above is a link to nowhere or a server that failed.\n const notFoundPage = response.status === 404 && !crawledOnly && isHtml(response);\n if (response.status >= 400 && !notFoundPage) {\n failures.push(`${path} answered ${response.status}`);\n return;\n }\n const declined = response.headers.get(PRERENDER_HEADER) === \"0\";\n if (crawledOnly && declined) {\n // Rendered to find its links, not to be written. A route that has not said\n // `prerender` is a route the build has no business freezing.\n if (run.crawl) followLinks(html);\n return;\n }\n // The NAME, where `path` is the URL: `/caf%C3%A9` is `café/index.html` on\n // disk and `/café` in the manifest, which is how `static.ts` looks it up.\n const name = decodeURI(path);\n const file = fileFor(name, run.outDir, run.subfolderIndex);\n await mkdir(dirname(file), { recursive: true });\n // Written as each page finishes rather than accumulated: holding ~300\n // data-heavy pages to the end is a 2 GB heap, which SvelteKit shipped.\n await writeFile(file, html, \"utf8\");\n pages.push({\n path: name,\n file,\n status: response.status,\n headers: Object.fromEntries(response.headers),\n });\n run.log?.(`${path} -> ${file}`);\n if (path === NOT_FOUND_PATH) {\n const root = join(run.outDir, \"404.html\");\n if (root !== file) {\n await writeFile(root, html, \"utf8\");\n notFoundFile = root;\n }\n } else if (response.ok) {\n listed.push(path);\n }\n if (run.crawl && !notFoundPage) followLinks(html);\n };\n\n const followLinks = (html: string): void => {\n for (const href of linksIn(html)) {\n if (!href.startsWith(\"/\")) continue;\n const inside = run.base === \"/\" || href.startsWith(run.base);\n if (inside) enqueue(run.base === \"/\" ? href : href.slice(run.base.length - 1));\n }\n };\n\n // A POOL, not batches: a slot is refilled the moment its page finishes, so\n // one slow page costs its own time rather than its whole batch's. The queue\n // grows while it drains, since a crawled page adds what it links to.\n const slots = Math.max(1, run.concurrency);\n let next = 0;\n let active = 0;\n // A static server function's answer is written beside the pages that asked\n // for it, under the name its client half will look for. One name holding two\n // different calls would hand the second caller the first one's answer, so\n // that stops the build rather than being written.\n const answered = new Map<string, string>();\n const staticAnswers: string[] = [];\n installStaticWriter(async (key, identity, answer) => {\n const before = answered.get(key);\n if (before !== undefined && before !== identity) {\n throw new Error(\n `[barq-start] Two static server function calls share the cache name ${key}, so one would be answered with the other's result. ` +\n \"Pass a different input to one of them, or drop `staticFunctionMiddleware` from it.\",\n );\n }\n const file = contained(\n \"a static server function's answer\",\n join(run.outDir, STATIC_PREFIX.slice(1), `${key}.json`),\n run.outDir,\n );\n if (before === undefined) {\n answered.set(key, identity);\n staticAnswers.push(file);\n }\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, answer, \"utf8\");\n });\n await new Promise<void>((drained) => {\n const fill = (): void => {\n while (active < slots) {\n const path = queue[next];\n if (path === undefined) break;\n next += 1;\n active += 1;\n one(path)\n .catch((reason: unknown) => {\n const message = (reason as { message?: string } | null)?.message ?? String(reason);\n failures.push(`${path}: ${message}`);\n })\n .finally(() => {\n active -= 1;\n fill();\n });\n }\n if (active === 0) drained();\n };\n fill();\n }).finally(() => installStaticWriter(null));\n\n if (failures.length > 0) {\n throw new Error(\n `[barq-start] ${failures.length} page(s) failed to prerender, so the build stopped before shipping a broken page:\\n ` +\n failures.join(\"\\n \"),\n );\n }\n\n if (sitemap === undefined || listed.length === 0) return { pages, notFoundFile, staticAnswers };\n const base = run.base.replace(/\\/+$/, \"\");\n await mkdir(dirname(sitemap.file), { recursive: true });\n await writeFile(\n sitemap.file,\n sitemapXml(listed.toSorted().map((path) => `${sitemap.host}${base}${path}`)),\n \"utf8\",\n );\n return { pages, sitemap: sitemap.file, notFoundFile, staticAnswers };\n}\n\n/** What {@link prerenderShell} is asked for. */\nexport interface ShellRun {\n readonly entry: ServerEntryModule;\n readonly outDir: string;\n /** The path the shell is rendered at. `/` when omitted. */\n readonly maskPath?: string;\n /** Where it is written, relative to `outDir`. `_shell.html` when omitted. */\n readonly outputPath?: string;\n}\n\n/**\n * Write the SPA shell: the root route's document, with nothing under it\n * rendered, for a server or a static host to answer every page path with.\n *\n * TanStack's SPA mode. The file is one request to the same handler, built with\n * `shell: true`, so the shell is the application's own root route rather than a\n * second document to keep in step with it.\n */\nexport async function prerenderShell(run: ShellRun): Promise<string> {\n const build = run.entry.default?.createFetch;\n if (typeof build !== \"function\") {\n throw new Error(\n \"[barq-start] SPA mode is on, but the server entry's default export has no `createFetch`, so the shell document cannot be rendered. \" +\n \"Use `export default createStartHandler()` from `@barqjs/router/server` in the server entry.\",\n );\n }\n const file = contained(\n \"the SPA shell\",\n join(run.outDir, (run.outputPath ?? \"_shell.html\").replace(/^\\/+/, \"\")),\n run.outDir,\n );\n const fetchShell = build({\n stream: false,\n pages: true,\n shell: true,\n refuseRequest:\n \"[barq] `getRequest()` and the other request helpers are not available while the SPA shell is rendered: the shell is built once and served for every path, so there is no request to read. \" +\n \"Read the request in a loader or a server function instead.\",\n nonce: undefined,\n });\n const response = await fetchShell(new Request(`${ORIGIN}${run.maskPath ?? \"/\"}`));\n if (response.status >= 400 || !isHtml(response)) {\n throw new Error(\n `[barq-start] Rendering the SPA shell at \\`${run.maskPath ?? \"/\"}\\` answered ${response.status}${isHtml(response) ? \"\" : \" without an HTML body\"}, so no shell was written. ` +\n \"The root route's `shellComponent` has to render for that path: check the server output above for the error it threw.\",\n );\n }\n await mkdir(dirname(file), { recursive: true });\n await writeFile(file, await response.text(), \"utf8\");\n return file;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAS,OAAO,UAA6B;CAC3C,QAAQ,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CAAI,SAAS,WAAW;AAC1E;;AAGA,MAAM,SAAS;;;;;;;;;;;;;;;;;;AAmBf,SAAS,UAAU,MAA6B;CAC9C,IAAI,KAAK,WAAW,IAAI,KAAK,uBAAuB,KAAK,IAAI,GAAG,OAAO;CACvE,MAAM,CAAC,cAAc,MAAM,KAAK,MAAM,GAAG;CACzC,MAAM,CAAC,QAAQ,MAAM,YAAY,MAAM,GAAG;CAC1C,IAAI,UAAU,IAAI,OAAO;CACzB,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,IAAI,IAAI,OAAO,MAAM;EACjC,IAAI,IAAI,WAAW,QAAQ,OAAO;EAClC,WAAW,IAAI;EAEf,UAAU,QAAQ;CACpB,QAAQ;EACN,OAAO;CACT;CACA,MAAM,UAAU,SAAS,SAAS,IAAI,SAAS,QAAQ,QAAQ,EAAE,IAAI;CACrE,OAAO,YAAY,KAAK,MAAM;AAChC;;AAGA,SAAS,QAAQ,MAAwB;CACvC,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,SAAS,KAAK,SAAS,qCAAqC,GAAG;EACxE,MAAM,OAAO,MAAM;EACnB,IAAI,SAAS,KAAA,GAAW,IAAI,KAAK,IAAI;CACvC;CACA,OAAO;AACT;;;;;;;;;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B,SAAS,OAAO,yFAC9B,SAAS,KAAK,MAAM,CACxB;CAGF,IAAI,YAAY,KAAA,KAAa,OAAO,WAAW,GAAG,OAAO;EAAE;EAAO;EAAc;CAAc;CAC9F,MAAM,OAAO,IAAI,KAAK,QAAQ,QAAQ,EAAE;CACxC,MAAM,MAAM,QAAQ,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CACtD,MAAM,UACJ,QAAQ,MACR,WAAW,OAAO,SAAS,CAAC,CAAC,KAAK,SAAS,GAAG,QAAQ,OAAO,OAAO,MAAM,CAAC,GAC3E,MACF;CACA,OAAO;EAAE;EAAO,SAAS,QAAQ;EAAM;EAAc;CAAc;AACrE;;;;;;;;;AAoBA,eAAsB,eAAe,KAAgC;CACnE,MAAM,QAAQ,IAAI,MAAM,SAAS;CACjC,IAAI,OAAO,UAAU,YACnB,MAAM,IAAI,MACR,gOAEF;CAEF,MAAM,OAAO,UACX,iBACA,KAAK,IAAI,SAAS,IAAI,cAAc,cAAA,CAAe,QAAQ,QAAQ,EAAE,CAAC,GACtE,IAAI,MACN;CAUA,MAAM,WAAW,MATE,MAAM;EACvB,QAAQ;EACR,OAAO;EACP,OAAO;EACP,eACE;EAEF,OAAO,KAAA;CACT,CACgC,CAAC,CAAC,IAAI,QAAQ,GAAG,SAAS,IAAI,YAAY,KAAK,CAAC;CAChF,IAAI,SAAS,UAAU,OAAO,CAAC,OAAO,QAAQ,GAC5C,MAAM,IAAI,MACR,6CAA6C,IAAI,YAAY,IAAI,cAAc,SAAS,SAAS,OAAO,QAAQ,IAAI,KAAK,wBAAwB,kJAEnJ;CAEF,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC9C,MAAM,UAAU,MAAM,MAAM,SAAS,KAAK,GAAG,MAAM;CACnD,OAAO;AACT"}
@@ -1,4 +1,3 @@
1
- //#region src/protocol.d.ts
2
1
  /**
3
2
  * The server-entry contract: what a built `dist/server` module exports, and the
4
3
  * one header the prerenderer and the page handler agree on.
@@ -54,5 +53,4 @@ export interface ServerEntryModule {
54
53
  readonly verifyChains?: (reachability: ReadonlyMap<string, ReadonlySet<string>>) => string | Promise<string>;
55
54
  };
56
55
  }
57
- //#endregion
58
56
  //# sourceMappingURL=protocol.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"protocol.d.ts","names":[],"sources":["../src/protocol.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAqBa;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BI;WACN;aACE,SAAS,SAAS,YAAY,QAAQ;aACtC,eACP,OAAO,6BACH,SAAS,YAAY,QAAQ;aAC1B,gBACP,cAAc,oBAAoB,kCACtB"}
1
+ {"version":3,"file":"protocol.d.ts","names":[],"sources":["../src/protocol.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;qBAqBa;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6BI;WACN;aACE,SAAS,SAAS,YAAY,QAAQ;aACtC,eACP,OAAO,6BACH,SAAS,YAAY,QAAQ;aAC1B,gBACP,cAAc,oBAAoB,kCACtB"}
package/dist/protocol.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/protocol.ts
1
+ // src/protocol.ts
2
2
  /**
3
3
  * The server-entry contract: what a built `dist/server` module exports, and the
4
4
  * one header the prerenderer and the page handler agree on.
@@ -20,7 +20,6 @@
20
20
  * named is always written — naming it is the declaration.
21
21
  */
22
22
  const PRERENDER_HEADER = "x-barq-prerender";
23
- //#endregion
24
23
  export { PRERENDER_HEADER };
25
24
 
26
25
  //# sourceMappingURL=protocol.js.map
package/dist/serve.d.ts CHANGED
@@ -1,6 +1,18 @@
1
- import { HandlerOptions } from "./server.js";
1
+ /**
2
+ * The production entry — runtime-agnostic.
3
+ *
4
+ * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,
5
+ * `node`, and a generic default), so one entry serves Node, Deno, Bun and
6
+ * Cloudflare without a per-runtime adapter here. The handler below is an
7
+ * ordinary `Request -> Response` function, which is the only shape all of them
8
+ * agree on.
9
+ *
10
+ * The dev half is deliberately NOT this: Vite's middleware pipeline is
11
+ * Connect-shaped and hands over a Node request/response pair, so `vite.ts`
12
+ * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.
13
+ */
2
14
  import { Server, ServerMiddleware, ServerOptions } from "srvx";
3
- //#region src/static.d.ts
15
+ import { HandlerOptions } from "./server.js";
4
16
  /** Where the build writes it, inside the client output directory. */
5
17
  export declare const ASSET_MANIFEST_FILE = "barq-assets.json";
6
18
  /** A page the prerenderer wrote, and the response it was rendered as. */
@@ -76,8 +88,6 @@ interface StaticOptions {
76
88
  * fast path is synchronous — the `await` is not paid per request.
77
89
  */
78
90
  export declare function assetMiddleware(options?: StaticOptions): ServerMiddleware;
79
- //#endregion
80
- //#region src/serve.d.ts
81
91
  export interface BarqServeOptions extends Omit<ServerOptions, "fetch">, HandlerOptions {
82
92
  /**
83
93
  * What answers everything that is not a server function — a page render, a
@@ -130,6 +140,5 @@ export declare function createFetchHandler(options?: BarqServeOptions): (request
130
140
  * it every call is a 404.
131
141
  */
132
142
  export declare function serveBarq(options?: BarqServeOptions): Server;
133
- //#endregion
134
143
  export type { AssetManifest, PrerenderedAsset, StaticOptions };
135
144
  //# sourceMappingURL=serve.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.ts","names":[],"sources":["../src/static.ts","../src/serve.ts"],"mappings":";;;;qBA4Ba;;UAGI;;WAEN;WACA;WACA,UAAU,SAAS;;UAGb;;WAEN,OAAO,SAAS,eAAe;;WAE/B;;;;;;;;;WASA;;;;;WAKA;;UAGM;;;;;;;;WAQN,eAAe;;;;;;;WAOf,WAAW;;;;;;;;;;;;WAYX;;;;;WAKA;;;;;;;;;;;;;wBA4CK,gBAAgB,UAAS,gBAAqB;;;iBCjH7C,yBAAyB,KAAK,yBAAyB;;;;;;;;;EAStE,SAAS,SAAS,YAAY,WAAW,QAAQ;;;;;;;;;;;;EAYjD,mBAAmB;;;;;;;;;;;;EAYnB,eAAe;;;;;;;;;;wBAWD,mBACd,UAAS,oBACP,SAAS,YAAY,QAAQ;;;;;;;;wBAsDjB,UAAU,UAAS,mBAAwB"}
1
+ {"version":3,"file":"serve.d.ts","names":[],"sources":["../src/static.ts","../src/serve.ts"],"mappings":";;;;;;;;;;;;;;;;qBA4Ba;;UAGI;;WAEN;WACA;WACA,UAAU,SAAS;;UAGb;;WAEN,OAAO,SAAS,eAAe;;WAE/B;;;;;;;;;WASA;;;;;WAKA;;UAGM;;;;;;;;WAQN,eAAe;;;;;;;WAOf,WAAW;;;;;;;;;;;;WAYX;;;;;WAKA;;;;;;;;;;;;;wBA4CK,gBAAgB,UAAS,gBAAqB;iBCjH7C,yBAAyB,KAAK,yBAAyB;;;;;;;;;EAStE,SAAS,SAAS,YAAY,WAAW,QAAQ;;;;;;;;;;;;EAYjD,mBAAmB;;;;;;;;;;;;EAYnB,eAAe;;;;;;;;;;wBAWD,mBACd,UAAS,oBACP,SAAS,YAAY,QAAQ;;;;;;;;wBAsDjB,UAAU,UAAS,mBAAwB"}
package/dist/serve.js CHANGED
@@ -1,6 +1,6 @@
1
- import { n as handleServerFn } from "./server-BV3xKmLa.js";
2
1
  import { serve } from "srvx";
3
- //#region src/static.ts
2
+ import { n as handleServerFn } from "./server-DG6jb_NA.js";
3
+ // src/static.ts
4
4
  /** Where the build writes it, inside the client output directory. */
5
5
  const ASSET_MANIFEST_FILE = "barq-assets.json";
6
6
  /** A hashed name never changes its bytes, so a year is the conventional forever. */
@@ -142,8 +142,7 @@ async function load(options) {
142
142
  }
143
143
  };
144
144
  }
145
- //#endregion
146
- //#region src/serve.ts
145
+ // src/serve.ts
147
146
  /**
148
147
  * The production entry — runtime-agnostic.
149
148
  *
@@ -217,7 +216,6 @@ function serveBarq(options = {}) {
217
216
  fetch: createFetchHandler(options)
218
217
  });
219
218
  }
220
- //#endregion
221
219
  export { ASSET_MANIFEST_FILE, assetMiddleware, createFetchHandler, serveBarq };
222
220
 
223
221
  //# sourceMappingURL=serve.js.map