@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
package/dist/serve.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"serve.js","names":[],"sources":["../src/static.ts","../src/serve.ts"],"sourcesContent":["/**\n * Serving the build's own files, with the lookup the BUILD already knows.\n *\n * A production request is overwhelmingly a MISS: an SSR page asks this layer\n * about a path that is not a file, and every static server that answers by\n * touching the filesystem pays two syscalls to say \"no\". Measured on this\n * machine by `packages/benchmark/src/static-lookup.ts`, on kitchen-sink's build:\n *\n * MISS existsSync + statSync 1.2634 us this manifest 0.2297 us\n *\n * So the manifest is a NEGATIVE index first and foremost. On a miss nothing\n * touches the disk; on a hit the work is handed to `srvx/static`, which already\n * does compression, precompressed variants, `ETag`, `Last-Modified`, ranges,\n * dotfile rules and symlink containment in 798 lines that barq should not\n * reimplement.\n *\n * WHAT THE MANIFEST CARRIES AND WHY. Not `type`, `size` or `etag`: those are\n * derivable from the file and a copy of them is a second source of truth that\n * goes stale against the bytes. What it carries is exactly the two things the\n * filesystem cannot answer — which request paths exist, and what STATUS and\n * HEADERS a prerendered page was rendered with. That second one was being\n * dropped: `PrerenderedPage` has recorded `status` and `headers` all along, and\n * nothing persisted them, so a prerendered 404 page was served as 200.\n */\n\nimport type { ServerMiddleware, ServerRequest } from \"srvx\";\n\n/** Where the build writes it, inside the client output directory. */\nexport const ASSET_MANIFEST_FILE = \"barq-assets.json\";\n\n/** A page the prerenderer wrote, and the response it was rendered as. */\nexport interface PrerenderedAsset {\n /** Relative to the client output directory. */\n readonly file: string;\n readonly status: number;\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nexport interface AssetManifest {\n /** Request path -> the prerendered page written for it. */\n readonly pages: Readonly<Record<string, PrerenderedAsset>>;\n /** Every other servable path, as request paths. */\n readonly files: readonly string[];\n /**\n * The members of `files` whose NAME changes when their bytes do.\n *\n * The build knows and a directory listing cannot say: a chunk it emitted is\n * `app-8f1c2a.js`, and `robots.txt` copied out of `public/` sits beside it\n * under a name the next deploy reuses. Only the first may be cached without\n * asking again.\n */\n readonly hashed?: readonly string[];\n /**\n * What every request path here starts with and no file on disk does: Vite's\n * `base`, without its trailing slash. Absent for a site served from `/`.\n */\n readonly base?: string;\n}\n\nexport interface StaticOptions {\n /**\n * The client output directory. Default `dist/client`.\n *\n * A `file:` URL is read as one, which is how an entry names a directory beside\n * itself: `new URL(\"../client\", import.meta.url)`. Its `.pathname` is not a\n * path, since a space in it is still `%20`.\n */\n readonly dir?: string | URL;\n /**\n * The manifest. Read from `<dir>/barq-assets.json` when omitted.\n *\n * Passing one is how a runtime with no filesystem serves a build it embedded\n * at deploy time, and how a test avoids writing files.\n */\n readonly manifest?: AssetManifest;\n /**\n * Seconds a hashed asset may be reused without asking. One year when the\n * manifest says which names are hashed, which a build's does.\n *\n * A file under a stable name is answered with a validator and no lifetime, so\n * a browser asks again and is told 304. A prerendered page keeps the\n * `cache-control` it was rendered with and is never given this one.\n *\n * A manifest that does not carry `hashed` cannot tell the two apart, so the\n * lifetime applies to every file it lists and there is none by default.\n */\n readonly maxAge?: number;\n /**\n * Adds `immutable` beside `maxAge`. On when the manifest says which names\n * are hashed, since for those it is true by construction.\n */\n readonly immutable?: boolean;\n}\n\n/** A hashed name never changes its bytes, so a year is the conventional forever. */\nconst HASHED_MAX_AGE = 60 * 60 * 24 * 365;\n\n/**\n * Headers that describe the bytes on the wire rather than the page.\n *\n * `srvx/static` computes them for the response it actually sends: compressed\n * or not, whole or a 304. The ones a page was RENDERED with describe an\n * uncompressed body in a build's memory.\n */\nconst REPRESENTATION = new Set([\n \"accept-ranges\",\n \"content-encoding\",\n \"content-length\",\n \"content-range\",\n \"etag\",\n \"last-modified\",\n]);\n\n/**\n * Just enough of `URL` to find the path.\n *\n * `FastURL` is srvx's own, and it falls back to `new URL` for anything a\n * verbatim parse would get wrong: dot segments, backslashes, control\n * characters, non-ASCII. Using it rather than `new URL` is most of what makes\n * the miss path cheap, since the lookups either side of it are a `Set.has` and\n * a property read.\n */\ntype PathOnly = new (url: string) => { readonly pathname: string };\n\n/**\n * Serve `dist/client` for the paths the build says are there.\n *\n * Returns a `srvx` middleware, so it composes with anything else a project\n * passes in `ServerOptions.middleware` and runs before the page handler.\n *\n * INITIALISATION IS LAZY AND HAPPENS ONCE. `node:fs` and `srvx/static` are\n * imported inside it rather than at module scope, because `@barqjs/start/serve`\n * resolves on workerd too and neither exists there. After the first request the\n * fast path is synchronous — the `await` is not paid per request.\n */\nexport function assetMiddleware(options: StaticOptions = {}): ServerMiddleware {\n let ready: Ready | null | undefined;\n let loading: Promise<void> | undefined;\n\n // `loaded` is a PARAMETER rather than the captured `ready`, because a closure\n // variable cannot be narrowed across the two call sites and the alternative is\n // a non-null assertion on every line of the hot path.\n const answer = (\n loaded: Ready | null,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ): Response | Promise<Response> => {\n if (loaded === null) return next();\n // A file is a file to GET and HEAD alone. A prerendered path may also be a\n // route with a `POST` handler: the page is its GET, and every other method\n // is the application's to answer.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return next();\n\n // The manifest holds NAMES, as the build read them off the disk, and a\n // request holds a URL: `release notes.txt` arrives as `release%20notes.txt`.\n // `decodeURI` because it is what `srvx/static` opens the file by, so the two\n // cannot disagree about which name a path means.\n let { pathname } = new loaded.url(request.url);\n if (pathname.includes(\"%\")) {\n try {\n pathname = decodeURI(pathname);\n } catch {\n return next();\n }\n }\n\n const page = loaded.manifest.pages[pathname];\n if (page !== undefined) return loaded.servePage(page, request);\n\n // The miss, which is every SSR request: one `Set.has` and out, with no\n // syscall behind it. This is the whole point of the manifest.\n if (!loaded.files.has(pathname)) return next();\n\n return loaded.serveFile(pathname, request, next);\n };\n\n return (request, next) => {\n if (ready !== undefined) return answer(ready, request, next);\n loading ??= load(options).then((loaded) => {\n ready = loaded;\n });\n return loading.then(() => answer(ready ?? null, request, next));\n };\n}\n\ninterface Ready {\n readonly manifest: AssetManifest;\n readonly files: ReadonlySet<string>;\n readonly url: PathOnly;\n readonly servePage: (page: PrerenderedAsset, request: ServerRequest) => Promise<Response>;\n readonly serveFile: (\n pathname: string,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ) => Response | Promise<Response>;\n}\n\n/**\n * The request `srvx/static` would have been sent for this FILE.\n *\n * It finds a file by the request's path, and two things here are found by the\n * manifest instead: a page, whose path is `/about` and whose file is\n * `about/index.html`, and anything under a `base`, which is in every request\n * path and in no file name. `encodeURI` because `decodeURI` is what it opens\n * the file by.\n */\nfunction requestFor(file: string, request: ServerRequest): ServerRequest {\n return new Request(`http://asset/${encodeURI(file)}`, {\n method: request.method,\n headers: request.headers,\n });\n}\n\nasync function load(options: StaticOptions): Promise<Ready | null> {\n const [{ readFile }, { staticMiddleware }, { FastURL }, path, { fileURLToPath }] =\n await Promise.all([\n import(\"node:fs/promises\"),\n import(\"srvx/static\"),\n import(\"srvx\"),\n import(\"node:path\"),\n import(\"node:url\"),\n ]);\n\n const dir =\n options.dir instanceof URL ? fileURLToPath(options.dir) : (options.dir ?? \"dist/client\");\n\n let manifest = options.manifest;\n if (manifest === undefined) {\n try {\n manifest = JSON.parse(\n await readFile(path.join(dir, ASSET_MANIFEST_FILE), \"utf8\"),\n ) as AssetManifest;\n } catch {\n // No manifest means no build to serve, which is a legitimate deployment:\n // a server that only answers server functions has no client directory at\n // all. Serving nothing beats guessing at the filesystem.\n return null;\n }\n }\n\n const hashed = manifest.hashed === undefined ? null : new Set(manifest.hashed);\n const revalidated = staticMiddleware({ dir });\n const lifetime = hashed === null ? options.maxAge : (options.maxAge ?? HASHED_MAX_AGE);\n const longLived =\n lifetime === undefined\n ? revalidated\n : staticMiddleware({\n dir,\n maxAge: lifetime,\n immutable: options.immutable ?? hashed !== null,\n });\n const prefix = manifest.base ?? \"\";\n\n /** The page's bytes with nothing negotiated, for what `srvx/static` will not answer. */\n const whole = async (page: PrerenderedAsset): Promise<Response> => {\n const body = await readFile(path.join(dir, page.file));\n const headers = new Headers(page.headers);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"text/html; charset=utf-8\");\n return new Response(body, { status: page.status, headers });\n };\n const declined = (): Response => new Response(null, { status: 404 });\n\n return {\n manifest,\n files: new Set(manifest.files),\n url: FastURL as unknown as PathOnly,\n /**\n * A prerendered page, with the STATUS and HEADERS it was rendered as.\n *\n * A 200 goes through `staticMiddleware` under its file's name, so it gets\n * the validator, the 304 and the encoding a hashed chunk gets. Anything\n * else is read directly: `staticMiddleware` has no way to answer but 200,\n * and a conditional request must not turn a 404 page into a 304.\n */\n servePage: async (page, request) => {\n if (page.status !== 200) return whole(page);\n let found = true;\n const served = await revalidated(requestFor(page.file, request), () => {\n found = false;\n return declined();\n });\n if (!found) return whole(page);\n for (const name in page.headers) {\n const value = page.headers[name];\n if (value === undefined) continue;\n const key = name.toLowerCase();\n if (REPRESENTATION.has(key)) continue;\n // Both are right: the page varies on what it said, and the bytes on\n // the encoding that was negotiated for them.\n if (key === \"vary\") served.headers.append(key, value);\n else served.headers.set(key, value);\n }\n return served;\n },\n serveFile: (pathname, request, next) => {\n const serve = hashed === null || hashed.has(pathname) ? longLived : revalidated;\n return prefix === \"\"\n ? serve(request, next)\n : serve(requestFor(pathname.slice(prefix.length + 1), request), next);\n },\n };\n}\n","/**\n * The production entry — runtime-agnostic.\n *\n * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,\n * `node`, and a generic default), so one entry serves Node, Deno, Bun and\n * Cloudflare without a per-runtime adapter here. The handler below is an\n * ordinary `Request -> Response` function, which is the only shape all of them\n * agree on.\n *\n * The dev half is deliberately NOT this: Vite's middleware pipeline is\n * Connect-shaped and hands over a Node request/response pair, so `vite.ts`\n * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.\n */\n\nimport { type Server, type ServerOptions, serve } from \"srvx\";\n\nimport { type HandlerOptions, handleServerFn } from \"./server.ts\";\nimport { type StaticOptions, assetMiddleware } from \"./static.ts\";\n\nexport type { AssetManifest, PrerenderedAsset, StaticOptions } from \"./static.ts\";\nexport { ASSET_MANIFEST_FILE, assetMiddleware } from \"./static.ts\";\n\nexport interface BarqServeOptions extends Omit<ServerOptions, \"fetch\">, HandlerOptions {\n /**\n * What answers everything that is not a server function — a page render, a\n * static file, an API route.\n *\n * A 404 is the default rather than an error: a server that only exposes\n * server functions is a legitimate deployment, and inventing a page handler\n * for it would be worse than saying nothing is there.\n */\n fetch?: (request: Request) => Response | Promise<Response>;\n /**\n * Serve the build's own files, in front of everything else.\n *\n * `true` serves `dist/client` through the manifest the build wrote. Omitted,\n * nothing static is served — which is right for a deployment whose assets are\n * on a CDN and for a server that only answers server functions, and wrong\n * enough to notice for anything else.\n *\n * `static.ts` explains why a manifest rather than a `stat`: the common request\n * is a MISS, and answering it without touching the disk is worth 0.5 us.\n */\n static?: boolean | StaticOptions;\n /**\n * The document to answer a page request with, for a deployment that renders\n * its pages in the browser.\n *\n * A path to the built `index.html`, or a `file:` URL of it. Consulted only\n * after everything else has declined — the assets, the server functions and\n * the route handlers all run first — so `/api/health` still answers JSON and\n * `/_barq/fn/<id>` is still reserved. Nothing else can do this job: the asset\n * middleware answers what the build WROTE, and an SPA's routes are exactly the\n * paths it did not.\n */\n spa?: string | URL;\n}\n\n/**\n * One request, in the order the checks have to happen.\n *\n * Server functions are matched FIRST. Their URL is reserved, so a page handler\n * that also matched it would be shadowing an endpoint rather than serving a\n * page — and the failure that produces is a mutation quietly answered with\n * HTML.\n */\nexport function createFetchHandler(\n options: BarqServeOptions = {},\n): (request: Request) => Promise<Response> {\n const page = options.fetch ?? (() => new Response(\"not found\", { status: 404 }));\n const document = options.spa;\n // Read once and held, per handler: two in one process have two documents.\n let body: Promise<string> | undefined;\n const spaDocument = async (path: string | URL, missing: Response): Promise<Response> => {\n // `node:fs` is imported here rather than at module scope, for the reason\n // `static.ts` gives: this module resolves on workerd too, where there is none.\n body ??= import(\"node:fs/promises\").then((fs) => fs.readFile(path, \"utf8\"));\n try {\n return new Response(await body, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n } catch {\n // The 404 the handler already produced, rather than a 500 about a file the\n // caller never asked for.\n body = undefined;\n return missing;\n }\n };\n return async (request: Request): Promise<Response> => {\n const answered = await handleServerFn(request, options);\n if (answered !== null) return answered;\n const response = await page(request);\n if (document === undefined || response.status !== 404) return response;\n // Only a navigation. A 404 for a missing asset or an XHR is an answer the\n // caller has to see, and handing it a document instead is the failure every\n // SPA fallback that matches on \"not a file\" eventually produces.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return response;\n if (!(request.headers.get(\"accept\") ?? \"\").includes(\"text/html\")) return response;\n return spaDocument(document, response);\n };\n}\n\n/**\n * What a caller is told when something threw: that it failed, and nothing else.\n *\n * Installed because a runtime's own answer is not that. Bun outside\n * `NODE_ENV=production` answers with the message, the stack and the source\n * around the throw, and a message can name a table, a column or a path. The\n * error goes to the log, where the operator is.\n */\nfunction failed(error: unknown): Response {\n console.error(error);\n return new Response(\"internal server error\", { status: 500 });\n}\n\n/**\n * Serve on whatever runtime this is.\n *\n * Mount the generated manifest before calling this — importing\n * `virtual:barq-server-fns` is what puts the ids in the registry, and without\n * it every call is a 404.\n */\nexport function serveBarq(options: BarqServeOptions = {}): Server {\n // `reachable` and `static` come out too. They were not, so both were handed\n // to `serve()` as options it has never heard of — harmless, and exactly the\n // drift that spreads once one key leaks.\n const {\n fetch: _page,\n allowedOrigins: _origins,\n maxBodySize: _body,\n maxFormSize: _form,\n reachable: _reachable,\n static: assets,\n spa: _spa,\n middleware,\n ...rest\n } = options;\n\n // FIRST in the chain, so a hashed chunk never enters the page handler. Ahead\n // of a project's own middleware too: those exist to shape application\n // responses, and an asset is not one.\n const chain =\n assets === undefined || assets === false\n ? middleware\n : [assetMiddleware(assets === true ? {} : assets), ...(middleware ?? [])];\n\n return serve({\n ...rest,\n error: rest.error ?? failed,\n middleware: chain,\n fetch: createFetchHandler(options),\n });\n}\n"],"mappings":";;;;AA4BA,MAAa,sBAAsB;;AAmEnC,MAAM,iBAAiB;;;;;;;;AASvB,MAAM,iCAAiB,IAAI,IAAI;CAC7B;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AAwBD,SAAgB,gBAAgB,UAAyB,CAAC,GAAqB;CAC7E,IAAI;CACJ,IAAI;CAKJ,MAAM,UACJ,QACA,SACA,SACiC;EACjC,IAAI,WAAW,MAAM,OAAO,KAAK;EAIjC,IAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ,OAAO,KAAK;EAMvE,IAAI,EAAE,aAAa,IAAI,OAAO,IAAI,QAAQ,GAAG;EAC7C,IAAI,SAAS,SAAS,GAAG,GACvB,IAAI;GACF,WAAW,UAAU,QAAQ;EAC/B,QAAQ;GACN,OAAO,KAAK;EACd;EAGF,MAAM,OAAO,OAAO,SAAS,MAAM;EACnC,IAAI,SAAS,KAAA,GAAW,OAAO,OAAO,UAAU,MAAM,OAAO;EAI7D,IAAI,CAAC,OAAO,MAAM,IAAI,QAAQ,GAAG,OAAO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O;CACnC,CAAC;AACH"}
1
+ {"version":3,"file":"serve.js","names":[],"sources":["../src/static.ts","../src/serve.ts"],"sourcesContent":["/**\n * Serving the build's own files, with the lookup the BUILD already knows.\n *\n * A production request is overwhelmingly a MISS: an SSR page asks this layer\n * about a path that is not a file, and every static server that answers by\n * touching the filesystem pays two syscalls to say \"no\". Measured on this\n * machine by `packages/benchmark/src/static-lookup.ts`, on kitchen-sink's build:\n *\n * MISS existsSync + statSync 1.2634 us this manifest 0.2297 us\n *\n * So the manifest is a NEGATIVE index first and foremost. On a miss nothing\n * touches the disk; on a hit the work is handed to `srvx/static`, which already\n * does compression, precompressed variants, `ETag`, `Last-Modified`, ranges,\n * dotfile rules and symlink containment in 798 lines that barq should not\n * reimplement.\n *\n * WHAT THE MANIFEST CARRIES AND WHY. Not `type`, `size` or `etag`: those are\n * derivable from the file and a copy of them is a second source of truth that\n * goes stale against the bytes. What it carries is exactly the two things the\n * filesystem cannot answer — which request paths exist, and what STATUS and\n * HEADERS a prerendered page was rendered with. That second one was being\n * dropped: `PrerenderedPage` has recorded `status` and `headers` all along, and\n * nothing persisted them, so a prerendered 404 page was served as 200.\n */\n\nimport type { ServerMiddleware, ServerRequest } from \"srvx\";\n\n/** Where the build writes it, inside the client output directory. */\nexport const ASSET_MANIFEST_FILE = \"barq-assets.json\";\n\n/** A page the prerenderer wrote, and the response it was rendered as. */\nexport interface PrerenderedAsset {\n /** Relative to the client output directory. */\n readonly file: string;\n readonly status: number;\n readonly headers?: Readonly<Record<string, string>>;\n}\n\nexport interface AssetManifest {\n /** Request path -> the prerendered page written for it. */\n readonly pages: Readonly<Record<string, PrerenderedAsset>>;\n /** Every other servable path, as request paths. */\n readonly files: readonly string[];\n /**\n * The members of `files` whose NAME changes when their bytes do.\n *\n * The build knows and a directory listing cannot say: a chunk it emitted is\n * `app-8f1c2a.js`, and `robots.txt` copied out of `public/` sits beside it\n * under a name the next deploy reuses. Only the first may be cached without\n * asking again.\n */\n readonly hashed?: readonly string[];\n /**\n * What every request path here starts with and no file on disk does: Vite's\n * `base`, without its trailing slash. Absent for a site served from `/`.\n */\n readonly base?: string;\n}\n\nexport interface StaticOptions {\n /**\n * The client output directory. Default `dist/client`.\n *\n * A `file:` URL is read as one, which is how an entry names a directory beside\n * itself: `new URL(\"../client\", import.meta.url)`. Its `.pathname` is not a\n * path, since a space in it is still `%20`.\n */\n readonly dir?: string | URL;\n /**\n * The manifest. Read from `<dir>/barq-assets.json` when omitted.\n *\n * Passing one is how a runtime with no filesystem serves a build it embedded\n * at deploy time, and how a test avoids writing files.\n */\n readonly manifest?: AssetManifest;\n /**\n * Seconds a hashed asset may be reused without asking. One year when the\n * manifest says which names are hashed, which a build's does.\n *\n * A file under a stable name is answered with a validator and no lifetime, so\n * a browser asks again and is told 304. A prerendered page keeps the\n * `cache-control` it was rendered with and is never given this one.\n *\n * A manifest that does not carry `hashed` cannot tell the two apart, so the\n * lifetime applies to every file it lists and there is none by default.\n */\n readonly maxAge?: number;\n /**\n * Adds `immutable` beside `maxAge`. On when the manifest says which names\n * are hashed, since for those it is true by construction.\n */\n readonly immutable?: boolean;\n}\n\n/** A hashed name never changes its bytes, so a year is the conventional forever. */\nconst HASHED_MAX_AGE = 60 * 60 * 24 * 365;\n\n/**\n * Headers that describe the bytes on the wire rather than the page.\n *\n * `srvx/static` computes them for the response it actually sends: compressed\n * or not, whole or a 304. The ones a page was RENDERED with describe an\n * uncompressed body in a build's memory.\n */\nconst REPRESENTATION = new Set([\n \"accept-ranges\",\n \"content-encoding\",\n \"content-length\",\n \"content-range\",\n \"etag\",\n \"last-modified\",\n]);\n\n/**\n * Just enough of `URL` to find the path.\n *\n * `FastURL` is srvx's own, and it falls back to `new URL` for anything a\n * verbatim parse would get wrong: dot segments, backslashes, control\n * characters, non-ASCII. Using it rather than `new URL` is most of what makes\n * the miss path cheap, since the lookups either side of it are a `Set.has` and\n * a property read.\n */\ntype PathOnly = new (url: string) => { readonly pathname: string };\n\n/**\n * Serve `dist/client` for the paths the build says are there.\n *\n * Returns a `srvx` middleware, so it composes with anything else a project\n * passes in `ServerOptions.middleware` and runs before the page handler.\n *\n * INITIALISATION IS LAZY AND HAPPENS ONCE. `node:fs` and `srvx/static` are\n * imported inside it rather than at module scope, because `@barqjs/start/serve`\n * resolves on workerd too and neither exists there. After the first request the\n * fast path is synchronous — the `await` is not paid per request.\n */\nexport function assetMiddleware(options: StaticOptions = {}): ServerMiddleware {\n let ready: Ready | null | undefined;\n let loading: Promise<void> | undefined;\n\n // `loaded` is a PARAMETER rather than the captured `ready`, because a closure\n // variable cannot be narrowed across the two call sites and the alternative is\n // a non-null assertion on every line of the hot path.\n const answer = (\n loaded: Ready | null,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ): Response | Promise<Response> => {\n if (loaded === null) return next();\n // A file is a file to GET and HEAD alone. A prerendered path may also be a\n // route with a `POST` handler: the page is its GET, and every other method\n // is the application's to answer.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return next();\n\n // The manifest holds NAMES, as the build read them off the disk, and a\n // request holds a URL: `release notes.txt` arrives as `release%20notes.txt`.\n // `decodeURI` because it is what `srvx/static` opens the file by, so the two\n // cannot disagree about which name a path means.\n let { pathname } = new loaded.url(request.url);\n if (pathname.includes(\"%\")) {\n try {\n pathname = decodeURI(pathname);\n } catch {\n return next();\n }\n }\n\n const page = loaded.manifest.pages[pathname];\n if (page !== undefined) return loaded.servePage(page, request);\n\n // The miss, which is every SSR request: one `Set.has` and out, with no\n // syscall behind it. This is the whole point of the manifest.\n if (!loaded.files.has(pathname)) return next();\n\n return loaded.serveFile(pathname, request, next);\n };\n\n return (request, next) => {\n if (ready !== undefined) return answer(ready, request, next);\n loading ??= load(options).then((loaded) => {\n ready = loaded;\n });\n return loading.then(() => answer(ready ?? null, request, next));\n };\n}\n\ninterface Ready {\n readonly manifest: AssetManifest;\n readonly files: ReadonlySet<string>;\n readonly url: PathOnly;\n readonly servePage: (page: PrerenderedAsset, request: ServerRequest) => Promise<Response>;\n readonly serveFile: (\n pathname: string,\n request: ServerRequest,\n next: () => Response | Promise<Response>,\n ) => Response | Promise<Response>;\n}\n\n/**\n * The request `srvx/static` would have been sent for this FILE.\n *\n * It finds a file by the request's path, and two things here are found by the\n * manifest instead: a page, whose path is `/about` and whose file is\n * `about/index.html`, and anything under a `base`, which is in every request\n * path and in no file name. `encodeURI` because `decodeURI` is what it opens\n * the file by.\n */\nfunction requestFor(file: string, request: ServerRequest): ServerRequest {\n return new Request(`http://asset/${encodeURI(file)}`, {\n method: request.method,\n headers: request.headers,\n });\n}\n\nasync function load(options: StaticOptions): Promise<Ready | null> {\n const [{ readFile }, { staticMiddleware }, { FastURL }, path, { fileURLToPath }] =\n await Promise.all([\n import(\"node:fs/promises\"),\n import(\"srvx/static\"),\n import(\"srvx\"),\n import(\"node:path\"),\n import(\"node:url\"),\n ]);\n\n const dir =\n options.dir instanceof URL ? fileURLToPath(options.dir) : (options.dir ?? \"dist/client\");\n\n let manifest = options.manifest;\n if (manifest === undefined) {\n try {\n manifest = JSON.parse(\n await readFile(path.join(dir, ASSET_MANIFEST_FILE), \"utf8\"),\n ) as AssetManifest;\n } catch {\n // No manifest means no build to serve, which is a legitimate deployment:\n // a server that only answers server functions has no client directory at\n // all. Serving nothing beats guessing at the filesystem.\n return null;\n }\n }\n\n const hashed = manifest.hashed === undefined ? null : new Set(manifest.hashed);\n const revalidated = staticMiddleware({ dir });\n const lifetime = hashed === null ? options.maxAge : (options.maxAge ?? HASHED_MAX_AGE);\n const longLived =\n lifetime === undefined\n ? revalidated\n : staticMiddleware({\n dir,\n maxAge: lifetime,\n immutable: options.immutable ?? hashed !== null,\n });\n const prefix = manifest.base ?? \"\";\n\n /** The page's bytes with nothing negotiated, for what `srvx/static` will not answer. */\n const whole = async (page: PrerenderedAsset): Promise<Response> => {\n const body = await readFile(path.join(dir, page.file));\n const headers = new Headers(page.headers);\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"text/html; charset=utf-8\");\n return new Response(body, { status: page.status, headers });\n };\n const declined = (): Response => new Response(null, { status: 404 });\n\n return {\n manifest,\n files: new Set(manifest.files),\n url: FastURL as unknown as PathOnly,\n /**\n * A prerendered page, with the STATUS and HEADERS it was rendered as.\n *\n * A 200 goes through `staticMiddleware` under its file's name, so it gets\n * the validator, the 304 and the encoding a hashed chunk gets. Anything\n * else is read directly: `staticMiddleware` has no way to answer but 200,\n * and a conditional request must not turn a 404 page into a 304.\n */\n servePage: async (page, request) => {\n if (page.status !== 200) return whole(page);\n let found = true;\n const served = await revalidated(requestFor(page.file, request), () => {\n found = false;\n return declined();\n });\n if (!found) return whole(page);\n for (const name in page.headers) {\n const value = page.headers[name];\n if (value === undefined) continue;\n const key = name.toLowerCase();\n if (REPRESENTATION.has(key)) continue;\n // Both are right: the page varies on what it said, and the bytes on\n // the encoding that was negotiated for them.\n if (key === \"vary\") served.headers.append(key, value);\n else served.headers.set(key, value);\n }\n return served;\n },\n serveFile: (pathname, request, next) => {\n const serve = hashed === null || hashed.has(pathname) ? longLived : revalidated;\n return prefix === \"\"\n ? serve(request, next)\n : serve(requestFor(pathname.slice(prefix.length + 1), request), next);\n },\n };\n}\n","/**\n * The production entry — runtime-agnostic.\n *\n * `srvx`'s root export resolves by runtime condition (`deno`, `bun`, `workerd`,\n * `node`, and a generic default), so one entry serves Node, Deno, Bun and\n * Cloudflare without a per-runtime adapter here. The handler below is an\n * ordinary `Request -> Response` function, which is the only shape all of them\n * agree on.\n *\n * The dev half is deliberately NOT this: Vite's middleware pipeline is\n * Connect-shaped and hands over a Node request/response pair, so `vite.ts`\n * adapts with `srvx/node`. That is adapting Vite, not choosing a runtime.\n */\n\nimport { type Server, type ServerOptions, serve } from \"srvx\";\n\nimport { type HandlerOptions, handleServerFn } from \"./server.ts\";\nimport { type StaticOptions, assetMiddleware } from \"./static.ts\";\n\nexport type { AssetManifest, PrerenderedAsset, StaticOptions } from \"./static.ts\";\nexport { ASSET_MANIFEST_FILE, assetMiddleware } from \"./static.ts\";\n\nexport interface BarqServeOptions extends Omit<ServerOptions, \"fetch\">, HandlerOptions {\n /**\n * What answers everything that is not a server function — a page render, a\n * static file, an API route.\n *\n * A 404 is the default rather than an error: a server that only exposes\n * server functions is a legitimate deployment, and inventing a page handler\n * for it would be worse than saying nothing is there.\n */\n fetch?: (request: Request) => Response | Promise<Response>;\n /**\n * Serve the build's own files, in front of everything else.\n *\n * `true` serves `dist/client` through the manifest the build wrote. Omitted,\n * nothing static is served — which is right for a deployment whose assets are\n * on a CDN and for a server that only answers server functions, and wrong\n * enough to notice for anything else.\n *\n * `static.ts` explains why a manifest rather than a `stat`: the common request\n * is a MISS, and answering it without touching the disk is worth 0.5 us.\n */\n static?: boolean | StaticOptions;\n /**\n * The document to answer a page request with, for a deployment that renders\n * its pages in the browser.\n *\n * A path to the built `index.html`, or a `file:` URL of it. Consulted only\n * after everything else has declined — the assets, the server functions and\n * the route handlers all run first — so `/api/health` still answers JSON and\n * `/_barq/fn/<id>` is still reserved. Nothing else can do this job: the asset\n * middleware answers what the build WROTE, and an SPA's routes are exactly the\n * paths it did not.\n */\n spa?: string | URL;\n}\n\n/**\n * One request, in the order the checks have to happen.\n *\n * Server functions are matched FIRST. Their URL is reserved, so a page handler\n * that also matched it would be shadowing an endpoint rather than serving a\n * page — and the failure that produces is a mutation quietly answered with\n * HTML.\n */\nexport function createFetchHandler(\n options: BarqServeOptions = {},\n): (request: Request) => Promise<Response> {\n const page = options.fetch ?? (() => new Response(\"not found\", { status: 404 }));\n const document = options.spa;\n // Read once and held, per handler: two in one process have two documents.\n let body: Promise<string> | undefined;\n const spaDocument = async (path: string | URL, missing: Response): Promise<Response> => {\n // `node:fs` is imported here rather than at module scope, for the reason\n // `static.ts` gives: this module resolves on workerd too, where there is none.\n body ??= import(\"node:fs/promises\").then((fs) => fs.readFile(path, \"utf8\"));\n try {\n return new Response(await body, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n } catch {\n // The 404 the handler already produced, rather than a 500 about a file the\n // caller never asked for.\n body = undefined;\n return missing;\n }\n };\n return async (request: Request): Promise<Response> => {\n const answered = await handleServerFn(request, options);\n if (answered !== null) return answered;\n const response = await page(request);\n if (document === undefined || response.status !== 404) return response;\n // Only a navigation. A 404 for a missing asset or an XHR is an answer the\n // caller has to see, and handing it a document instead is the failure every\n // SPA fallback that matches on \"not a file\" eventually produces.\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return response;\n if (!(request.headers.get(\"accept\") ?? \"\").includes(\"text/html\")) return response;\n return spaDocument(document, response);\n };\n}\n\n/**\n * What a caller is told when something threw: that it failed, and nothing else.\n *\n * Installed because a runtime's own answer is not that. Bun outside\n * `NODE_ENV=production` answers with the message, the stack and the source\n * around the throw, and a message can name a table, a column or a path. The\n * error goes to the log, where the operator is.\n */\nfunction failed(error: unknown): Response {\n console.error(error);\n return new Response(\"internal server error\", { status: 500 });\n}\n\n/**\n * Serve on whatever runtime this is.\n *\n * Mount the generated manifest before calling this — importing\n * `virtual:barq-server-fns` is what puts the ids in the registry, and without\n * it every call is a 404.\n */\nexport function serveBarq(options: BarqServeOptions = {}): Server {\n // `reachable` and `static` come out too. They were not, so both were handed\n // to `serve()` as options it has never heard of — harmless, and exactly the\n // drift that spreads once one key leaks.\n const {\n fetch: _page,\n allowedOrigins: _origins,\n maxBodySize: _body,\n maxFormSize: _form,\n reachable: _reachable,\n static: assets,\n spa: _spa,\n middleware,\n ...rest\n } = options;\n\n // FIRST in the chain, so a hashed chunk never enters the page handler. Ahead\n // of a project's own middleware too: those exist to shape application\n // responses, and an asset is not one.\n const chain =\n assets === undefined || assets === false\n ? middleware\n : [assetMiddleware(assets === true ? {} : assets), ...(middleware ?? [])];\n\n return serve({\n ...rest,\n error: rest.error ?? failed,\n middleware: chain,\n fetch: createFetchHandler(options),\n });\n}\n"],"mappings":";;;;AA4BA,MAAa,sBAAsB;;AAmEnC,MAAM,iBAAiB;;;;;;;;AASvB,MAAM,iCAAiB,IAAI,IAAI;CAC7B;CACA;CACA;CACA;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;EACzE,OAAO,YAAY,UAAU,QAAQ;CACvC;AACF;;;;;;;;;AAUA,SAAS,OAAO,OAA0B;CACxC,QAAQ,MAAM,KAAK;CACnB,OAAO,IAAI,SAAS,yBAAyB,EAAE,QAAQ,IAAI,CAAC;AAC9D;;;;;;;;AASA,SAAgB,UAAU,UAA4B,CAAC,GAAW;CAIhE,MAAM,EACJ,OAAO,OACP,gBAAgB,UAChB,aAAa,OACb,aAAa,OACb,WAAW,YACX,QAAQ,QACR,KAAK,MACL,YACA,GAAG,SACD;CAKJ,MAAM,QACJ,WAAW,KAAA,KAAa,WAAW,QAC/B,aACA,CAAC,gBAAgB,WAAW,OAAO,CAAC,IAAI,MAAM,GAAG,GAAI,cAAc,CAAC,CAAE;CAE5E,OAAO,MAAM;EACX,GAAG;EACH,OAAO,KAAK,SAAS;EACrB,YAAY;EACZ,OAAO,mBAAmB,OAAO;CACnC,CAAC;AACH"}
@@ -1,14 +1,14 @@
1
- import { C as draftedStatus, G as setRequestMiddlewareContext, Y as takeSendContext, b as collectRequestCss, s as serverTiming, v as applyResponseDraft, x as createResponseDraft, z as invalidatedFrames } from "./src-ChnB_xug.js";
2
- import { B as regionMarkup, D as FLIGHT_TYPE, F as bindEntries, H as slotOpen, I as frameAddress, L as frameOpen, M as RPC_FLIGHT, N as RPC_FRAME, O as FRAME, R as installFrames, V as slotClose, a as RPC_CONTEXT, c as RPC_RESPONSE, j as FRAME_CLOSE, k as FRAMES_HEADER, l as RPC_STREAM, n as LIVE_SUFFIX, o as RPC_CONTROL, r as PAYLOAD_PARAM, s as RPC_PREFIX, t as DATA_SUFFIX, u as RPC_THROWN, w as startOptions, y as isServerFn, z as isFrame } from "./client-BHyIiYxt.js";
3
- import { NOT_FOUND, REDIRECT, isInputError, runRequestMiddleware } from "./middleware.js";
1
+ import { block, childScope, getOwner, isDev, isSafeError, runWithOwner, untrack } from "@barqjs/core";
4
2
  import { SSR_HTML_BRAND, commitEventResponse, commitResponseStub, createRequestEvent, isNavigable, setHeadSink } from "@barqjs/web/internal";
5
3
  import { SharedSources, diagnosticsEnabled, emitDiagnostic, setHydratable, shareSources, unshareSources } from "@barqjs/core/internal";
6
- import { provideRequestEvent } from "@barqjs/server/storage";
7
4
  import { decodeWire, encodeWire, registerSerializationAdapters, serializationAdapters } from "@barqjs/server/codec";
8
- import { block, childScope, getOwner, isDev, isSafeError, runWithOwner, untrack } from "@barqjs/core";
5
+ import { provideRequestEvent, withoutRequestEvent } from "@barqjs/server/storage";
9
6
  import { createBodyTooLargeError, limitBodyStream } from "srvx/body-limit";
7
+ import { B as invalidatedFrames, K as setRequestMiddlewareContext, X as takeSendContext, b as collectRequestCss, s as serverTiming, v as applyResponseDraft, w as draftedStatus, x as createResponseDraft } from "./src-odXG7kLA.js";
8
+ import { A as FRAME, B as installFrames, E as startOptions, F as RPC_FRAME, H as regionMarkup, J as UNKNOWN_HEADER, L as bindEntries, N as FRAME_CLOSE, P as RPC_FLIGHT, R as frameAddress, U as slotClose, V as isFrame, W as slotOpen, a as PAYLOAD_PARAM, c as RPC_CONTROL, d as RPC_STREAM, f as RPC_THROWN, i as LIVE_SUFFIX, j as FRAMES_HEADER, k as FLIGHT_TYPE, l as RPC_PREFIX, n as BUNDLED_BUILD, r as DATA_SUFFIX, s as RPC_CONTEXT, t as BUILD_HEADER, u as RPC_RESPONSE, x as isServerFn, z as frameOpen } from "./client-BsyxVCyu.js";
9
+ import { NOT_FOUND, REDIRECT, isInputError, runRequestMiddleware } from "./middleware.js";
10
10
  import { SlotValue, esc, html, renderFrame, setServerComponent } from "@barqjs/server";
11
- //#region src/frames-server.ts
11
+ // src/frames-server.ts
12
12
  /**
13
13
  * How a frame crosses inside the page's own seed: by address, as a reference
14
14
  * the browser resolves to the region already on the page. Registered when a
@@ -354,8 +354,7 @@ async function flightResponse(value, mounted, invalidated, ask) {
354
354
  answer.headers.set("x-barq-rpc", RPC_FLIGHT);
355
355
  return answer;
356
356
  }
357
- //#endregion
358
- //#region src/live-server.ts
357
+ // src/live-server.ts
359
358
  /**
360
359
  * The server half of `live`: a call at the live address answered as server-sent
361
360
  * events, for as long as the answer stands.
@@ -375,7 +374,7 @@ const RPC_LIVE = "live";
375
374
  /** How often an idle connection says it is still there, against proxies that time one out. */
376
375
  const HEARTBEAT_MS = 2e4;
377
376
  function digest(text) {
378
- let hash = 2166136261;
377
+ let hash = 0x811c9dc5;
379
378
  for (let at = 0; at < text.length; at++) {
380
379
  hash ^= text.charCodeAt(at);
381
380
  hash = Math.imul(hash, 16777619);
@@ -392,51 +391,19 @@ function isIterable$1(value) {
392
391
  function event(kind, id, data) {
393
392
  return `${kind === "frame" ? "event: frame\n" : ""}id: ${id}\ndata: ${data}\n\n`;
394
393
  }
395
- /** The answer to a call at the live address. */
396
- function liveResponse(result, request) {
397
- const encoder = new TextEncoder();
398
- const last = request.headers.get("last-event-id");
399
- let controller = null;
394
+ /**
395
+ * Drive a live answer: each rendering of a frame, or each value of an
396
+ * iterable, through `emit` until it ends, then `finish(complete)`. Returns
397
+ * what stops it early.
398
+ */
399
+ function produce(result, emit, finish) {
400
400
  let ended = false;
401
401
  const stops = [];
402
402
  const end = (complete) => {
403
403
  if (ended) return;
404
404
  ended = true;
405
405
  for (const stop of stops) stop();
406
- if (controller === null) return;
407
- try {
408
- if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
409
- controller.close();
410
- } catch {}
411
- };
412
- const send = (text) => {
413
- if (ended || controller === null) return;
414
- try {
415
- controller.enqueue(encoder.encode(text));
416
- } catch {
417
- end(false);
418
- }
419
- };
420
- let sentId = last;
421
- const emit = (data, kind = "message") => {
422
- const id = digest(data);
423
- if (id === sentId) return;
424
- sentId = id;
425
- send(event(kind, id, data));
426
- };
427
- const start = () => {
428
- const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
429
- heartbeat.unref?.();
430
- stops.push(() => clearInterval(heartbeat));
431
- const abort = () => end(false);
432
- request.signal.addEventListener("abort", abort, { once: true });
433
- stops.push(() => request.signal.removeEventListener("abort", abort));
434
- if (isFrame(result)) frames(result);
435
- else if (isIterable$1(result)) values(result);
436
- else {
437
- emit(JSON.stringify(encodeWire(result)));
438
- end(true);
439
- }
406
+ finish(complete);
440
407
  };
441
408
  const frames = async (frame) => {
442
409
  const shared = new SharedSources();
@@ -486,7 +453,7 @@ function liveResponse(result, request) {
486
453
  const step = await iterator.next();
487
454
  if (ended) return;
488
455
  if (step.done === true) break;
489
- emit(JSON.stringify(encodeWire(step.value)));
456
+ emit(JSON.stringify(encodeWire(step.value)), "message");
490
457
  }
491
458
  end(true);
492
459
  } catch (error) {
@@ -494,10 +461,65 @@ function liveResponse(result, request) {
494
461
  end(false);
495
462
  }
496
463
  };
464
+ if (isFrame(result)) frames(result);
465
+ else if (isIterable$1(result)) values(result);
466
+ else {
467
+ emit(JSON.stringify(encodeWire(result)), "message");
468
+ end(true);
469
+ }
470
+ return () => {
471
+ if (ended) return;
472
+ ended = true;
473
+ for (const stop of stops) stop();
474
+ };
475
+ }
476
+ /**
477
+ * One server-sent event stream. `attach` is handed the connection when the
478
+ * stream starts and answers with what to run when it ends, either way.
479
+ */
480
+ function connection(request, attach) {
481
+ const encoder = new TextEncoder();
482
+ let controller = null;
483
+ let ended = false;
484
+ const stops = [];
485
+ const end = (complete) => {
486
+ if (ended) return;
487
+ ended = true;
488
+ for (const stop of stops) stop();
489
+ if (controller === null) return;
490
+ try {
491
+ if (complete) controller.enqueue(encoder.encode("event: complete\ndata: \n\n"));
492
+ controller.close();
493
+ } catch {}
494
+ };
495
+ const send = (text) => {
496
+ if (ended || controller === null) return;
497
+ try {
498
+ controller.enqueue(encoder.encode(text));
499
+ } catch {
500
+ end(false);
501
+ }
502
+ };
503
+ let sentId = request.headers.get("last-event-id");
504
+ const emit = (data, kind) => {
505
+ const id = digest(data);
506
+ if (id === sentId) return;
507
+ sentId = id;
508
+ send(event(kind, id, data));
509
+ };
497
510
  const body = new ReadableStream({
498
511
  start(given) {
499
512
  controller = given;
500
- start();
513
+ const heartbeat = setInterval(() => send(": still here\n\n"), HEARTBEAT_MS);
514
+ heartbeat.unref?.();
515
+ stops.push(() => clearInterval(heartbeat));
516
+ const abort = () => end(false);
517
+ request.signal.addEventListener("abort", abort, { once: true });
518
+ stops.push(() => request.signal.removeEventListener("abort", abort));
519
+ stops.push(attach({
520
+ emit,
521
+ end
522
+ }));
501
523
  },
502
524
  cancel() {
503
525
  end(false);
@@ -510,8 +532,71 @@ function liveResponse(result, request) {
510
532
  answer.headers.set("x-barq-rpc", RPC_LIVE);
511
533
  return answer;
512
534
  }
513
- //#endregion
514
- //#region src/server.ts
535
+ /** The answer to a call at the live address. */
536
+ function liveResponse(result, request) {
537
+ return connection(request, (to) => produce(result, to.emit, to.end));
538
+ }
539
+ /** The running shared answers, by function and arguments. */
540
+ const BROADCASTS = /* @__PURE__ */ new Map();
541
+ /**
542
+ * A joiner's own answer, closed without reading it. Only an answer that is
543
+ * already an iterator, a generator object, holds anything: an iterable nobody
544
+ * has asked for an iterator has started nothing, and asking would start it.
545
+ */
546
+ function closeUnread(result) {
547
+ const iterator = result;
548
+ if (typeof iterator?.return !== "function") return;
549
+ try {
550
+ const closing = iterator.return();
551
+ if (closing instanceof Promise) closing.catch(() => {});
552
+ } catch {}
553
+ }
554
+ /**
555
+ * The answer to a live call to a `broadcast` function: one rendering per
556
+ * `key`, every connection asking the same thing a reader of it. The first call
557
+ * starts it, outside its own request, and each later one joins it with the
558
+ * latest event and closes its own answer unread. It stops when its last
559
+ * connection goes.
560
+ */
561
+ function broadcastResponse(key, result, request) {
562
+ let shared = BROADCASTS.get(key);
563
+ if (shared !== void 0 && !shared.ended) closeUnread(result);
564
+ else {
565
+ const started = {
566
+ connections: /* @__PURE__ */ new Set(),
567
+ latest: null,
568
+ ended: false,
569
+ stop: () => {}
570
+ };
571
+ BROADCASTS.set(key, started);
572
+ started.stop = withoutRequestEvent(() => produce(result, (data, kind) => {
573
+ started.latest = {
574
+ data,
575
+ kind
576
+ };
577
+ for (const each of started.connections) each.emit(data, kind);
578
+ }, (complete) => {
579
+ started.ended = true;
580
+ if (BROADCASTS.get(key) === started) BROADCASTS.delete(key);
581
+ for (const each of started.connections) each.end(complete);
582
+ }));
583
+ shared = started;
584
+ }
585
+ const joined = shared;
586
+ return connection(request, (to) => {
587
+ joined.connections.add(to);
588
+ if (joined.latest !== null) to.emit(joined.latest.data, joined.latest.kind);
589
+ if (joined.ended) to.end(true);
590
+ return () => {
591
+ joined.connections.delete(to);
592
+ if (joined.connections.size > 0 || joined.ended) return;
593
+ joined.ended = true;
594
+ if (BROADCASTS.get(key) === joined) BROADCASTS.delete(key);
595
+ joined.stop();
596
+ };
597
+ });
598
+ }
599
+ // src/server.ts
515
600
  /**
516
601
  * The request handler: one URL shape, one lookup, and the checks that run
517
602
  * before a handler body does.
@@ -645,6 +730,13 @@ function crossOriginRefused(request, allowedOrigins) {
645
730
  if (site === null) return false;
646
731
  return site !== "same-origin" && site !== "none";
647
732
  }
733
+ /** The labelled 404: the client reports it as skew rather than as a failed call. */
734
+ function unknownFunction() {
735
+ return new Response("not found", {
736
+ status: 404,
737
+ headers: { [UNKNOWN_HEADER]: "true" }
738
+ });
739
+ }
648
740
  /**
649
741
  * Handle one server-function request, or return null if the URL is not one.
650
742
  *
@@ -674,8 +766,18 @@ async function handleServerFn(request, options) {
674
766
  await MOUNTED.manifest();
675
767
  fn = REGISTRY.get(id);
676
768
  }
677
- if (fn === void 0) return new Response("not found", { status: 404 });
678
- if (options?.reachable?.(id) === false) return new Response("not found", { status: 404 });
769
+ if (fn === void 0) return unknownFunction();
770
+ if (options?.reachable?.(id) === false) return unknownFunction();
771
+ const build = options?.buildId ?? BUNDLED_BUILD;
772
+ const callerBuild = request.headers.get(BUILD_HEADER);
773
+ if (build !== void 0 && callerBuild !== null && callerBuild !== build) return new Response(`call from build ${JSON.stringify(callerBuild)} refused`, {
774
+ status: 409,
775
+ headers: {
776
+ [UNKNOWN_HEADER]: "true",
777
+ [BUILD_HEADER]: build,
778
+ "cache-control": "no-store"
779
+ }
780
+ });
679
781
  const expected = fn.meta.method ?? "POST";
680
782
  if (method !== expected) return new Response("method not allowed", {
681
783
  status: 405,
@@ -696,8 +798,11 @@ async function handleServerFn(request, options) {
696
798
  const respond = async () => {
697
799
  let input;
698
800
  let clientContext;
801
+ let encoded;
699
802
  if (isData && (method === "GET" || !isFormBody(request))) try {
700
- const body = method === "GET" ? queryPayload(url, bodyLimit) : await capped(request, bodyLimit).json();
803
+ if (method === "POST") encoded = await capped(request, bodyLimit).text();
804
+ else encoded = url.searchParams.get("payload") ?? "";
805
+ const body = method === "GET" ? queryPayload(url, bodyLimit) : JSON.parse(encoded);
701
806
  input = body?.input === void 0 ? void 0 : decodeWire(body.input);
702
807
  clientContext = body?.context === void 0 ? void 0 : { ...decodeWire(body.context) };
703
808
  } catch (error) {
@@ -713,6 +818,7 @@ async function handleServerFn(request, options) {
713
818
  const sendContext = takeSendContext();
714
819
  if (isLive) {
715
820
  if (result instanceof Response) return applyResponseDraft(result, draft);
821
+ if (target.meta.broadcast === true && encoded !== void 0) return applyResponseDraft(broadcastResponse(`${id}\0${method}\0${encoded}`, result, request), draft);
716
822
  return applyResponseDraft(liveResponse(result, request), draft);
717
823
  }
718
824
  if (result instanceof Response) {
@@ -1142,7 +1248,6 @@ function seeOther(request) {
1142
1248
  headers: { location }
1143
1249
  });
1144
1250
  }
1145
- //#endregion
1146
1251
  export { mounted as a, unmountAll as c, mountOnDemand as i, handleServerFn as n, mountedFn as o, mount as r, originAllowed as s, crossOriginRefused as t };
1147
1252
 
1148
- //# sourceMappingURL=server-BV3xKmLa.js.map
1253
+ //# sourceMappingURL=server-DG6jb_NA.js.map