@barqjs/start 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +817 -2
  3. package/dist/client-BsyxVCyu.js +1554 -0
  4. package/dist/client-BsyxVCyu.js.map +1 -0
  5. package/dist/client-DidH0F2e.d.ts +450 -0
  6. package/dist/client-DidH0F2e.d.ts.map +1 -0
  7. package/dist/client.d.ts +25 -0
  8. package/dist/client.js +4 -0
  9. package/dist/env-Bhk_aIkx.d.ts +47 -0
  10. package/dist/env-Bhk_aIkx.d.ts.map +1 -0
  11. package/dist/env.d.ts +2 -0
  12. package/dist/env.js +43 -0
  13. package/dist/env.js.map +1 -0
  14. package/dist/index-B4o7eyCr.d.ts +925 -0
  15. package/dist/index-B4o7eyCr.d.ts.map +1 -0
  16. package/dist/index.d.ts +18 -0
  17. package/dist/index.js +6 -0
  18. package/dist/middleware-B-tI8QHQ.d.ts +574 -0
  19. package/dist/middleware-B-tI8QHQ.d.ts.map +1 -0
  20. package/dist/middleware.d.ts +2 -0
  21. package/dist/middleware.js +281 -0
  22. package/dist/middleware.js.map +1 -0
  23. package/dist/prerender.d.ts +118 -0
  24. package/dist/prerender.d.ts.map +1 -0
  25. package/dist/prerender.js +289 -0
  26. package/dist/prerender.js.map +1 -0
  27. package/dist/protocol.d.ts +56 -0
  28. package/dist/protocol.d.ts.map +1 -0
  29. package/dist/protocol.js +25 -0
  30. package/dist/protocol.js.map +1 -0
  31. package/dist/serve.d.ts +144 -0
  32. package/dist/serve.d.ts.map +1 -0
  33. package/dist/serve.js +221 -0
  34. package/dist/serve.js.map +1 -0
  35. package/dist/server-DG6jb_NA.js +1253 -0
  36. package/dist/server-DG6jb_NA.js.map +1 -0
  37. package/dist/server.d.ts +159 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1 -0
  40. package/dist/src-odXG7kLA.js +1151 -0
  41. package/dist/src-odXG7kLA.js.map +1 -0
  42. package/dist/static-fn-CXjJi-It.js +122 -0
  43. package/dist/static-fn-CXjJi-It.js.map +1 -0
  44. package/package.json +106 -4
  45. package/src/client.ts +698 -0
  46. package/src/context.ts +699 -0
  47. package/src/cookies.ts +229 -0
  48. package/src/env.ts +86 -0
  49. package/src/fn-error.ts +121 -0
  50. package/src/frames-client.ts +1220 -0
  51. package/src/frames-server.ts +464 -0
  52. package/src/frames.ts +285 -0
  53. package/src/index.ts +740 -0
  54. package/src/live-client.ts +50 -0
  55. package/src/live-server.ts +292 -0
  56. package/src/middleware.ts +994 -0
  57. package/src/prerender.ts +477 -0
  58. package/src/protocol.ts +61 -0
  59. package/src/rate-limit.ts +202 -0
  60. package/src/serve.ts +153 -0
  61. package/src/server.ts +1026 -0
  62. package/src/session.ts +449 -0
  63. package/src/start-instance.ts +147 -0
  64. package/src/static-fn.ts +181 -0
  65. package/src/static.ts +302 -0
  66. package/src/stubs.ts +32 -0
  67. package/src/timing.ts +29 -0
  68. package/src/wire-types.ts +138 -0
package/src/server.ts ADDED
@@ -0,0 +1,1026 @@
1
+ /**
2
+ * The request handler: one URL shape, one lookup, and the checks that run
3
+ * before a handler body does.
4
+ *
5
+ * Every default here is the strict one, because the survey found the same four
6
+ * failures composing across shipping frameworks — an unvalidated, CSRF-unchecked,
7
+ * publicly-mounted endpoint reached by an id enumerable from the client bundle.
8
+ * Each is cheap to close and expensive to retrofit.
9
+ */
10
+
11
+ import { isDev, isSafeError } from "@barqjs/core";
12
+ import {
13
+ commitEventResponse,
14
+ commitResponseStub,
15
+ createRequestEvent,
16
+ isNavigable,
17
+ } from "@barqjs/web/internal";
18
+ import { diagnosticsEnabled, emitDiagnostic } from "@barqjs/core/internal";
19
+ import { decodeWire, encodeWire } from "@barqjs/server/codec";
20
+ import { provideRequestEvent } from "@barqjs/server/storage";
21
+ import { createBodyTooLargeError, limitBodyStream } from "srvx/body-limit";
22
+
23
+ import {
24
+ type ResponseDraft,
25
+ applyResponseDraft,
26
+ createResponseDraft,
27
+ draftedStatus,
28
+ invalidatedFrames,
29
+ setRequestMiddlewareContext,
30
+ } from "./context.ts";
31
+ import {
32
+ BUILD_HEADER,
33
+ BUNDLED_BUILD,
34
+ NOT_FOUND,
35
+ PAYLOAD_PARAM,
36
+ REDIRECT,
37
+ RPC_CALLER,
38
+ RPC_CONTEXT,
39
+ RPC_CONTROL,
40
+ RPC_RESPONSE,
41
+ RPC_THROWN,
42
+ RPC_STREAM,
43
+ type RpcControl,
44
+ type RpcStreamLine,
45
+ type ServerFnInputAnswer,
46
+ type ServerFnIssue,
47
+ type ServerFnThrown,
48
+ UNKNOWN_HEADER,
49
+ } from "./client.ts";
50
+ import {
51
+ type AnyServerFn,
52
+ DATA_SUFFIX,
53
+ LIVE_SUFFIX,
54
+ type InputError,
55
+ isInputError,
56
+ RPC_PREFIX,
57
+ type ServerFn,
58
+ isServerFn,
59
+ runRequestMiddleware,
60
+ startOptions,
61
+ takeSendContext,
62
+ } from "./index.ts";
63
+ import { serverTiming } from "./timing.ts";
64
+ import {
65
+ type ServerFrame,
66
+ flightResponse,
67
+ frameResponse,
68
+ mountedFrames,
69
+ serverFrame,
70
+ } from "./frames-server.ts";
71
+ import { FRAMES_HEADER, installFrames, isFrame } from "./frames.ts";
72
+ import { broadcastResponse, liveResponse } from "./live-server.ts";
73
+
74
+ installFrames(serverFrame as never);
75
+
76
+ /**
77
+ * id → function, and the ONLY way an id becomes callable.
78
+ *
79
+ * A `Map` rather than an object, because the id comes off the wire and an
80
+ * object's prototype is reachable through one. A client-supplied name used as a
81
+ * raw property access has shipped as a critical RCE elsewhere: asking for
82
+ * `constructor` yields `Function`, and then arbitrary code. `Map.get`
83
+ * has no prototype chain to walk into, so the guard is structural rather than a
84
+ * `hasOwnProperty` call someone can later forget.
85
+ */
86
+ interface Mounted {
87
+ readonly registry: Map<string, ServerFn<unknown, unknown>>;
88
+ /** How to mount the build's manifest, once something has said. */
89
+ manifest: (() => Promise<unknown>) | null;
90
+ }
91
+
92
+ /**
93
+ * ONE registry per process, whichever copy of this module asks.
94
+ *
95
+ * A build compiles this module INTO its server bundle, and a host that serves
96
+ * that bundle through its own `serveBarq` has imported a second copy. Kept in
97
+ * a module variable, each copy had a registry of its own: the bundle mounted
98
+ * every function into one and the host answered 404 out of the other.
99
+ */
100
+ const MOUNTED = ((globalThis as Record<symbol, unknown>)[Symbol.for("barq.start.server-fns")] ??= {
101
+ registry: new Map<string, ServerFn<unknown, unknown>>(),
102
+ manifest: null,
103
+ }) as Mounted;
104
+
105
+ const REGISTRY = MOUNTED.registry;
106
+
107
+ /**
108
+ * Say how the build's manifest is mounted, so a call can ask for it.
109
+ *
110
+ * The server entry imports the manifest when it first renders a page, which is
111
+ * late for a function called before any page has been asked for: a server that
112
+ * has just started and a browser tab that was already open. The id it names
113
+ * was in no registry yet, and the answer was a 404 for a function that exists.
114
+ */
115
+ export function mountOnDemand(manifest: () => Promise<unknown>): void {
116
+ MOUNTED.manifest = manifest;
117
+ }
118
+
119
+ /**
120
+ * Mount a server function. The compiler emits one call per EXPORTED server
121
+ * function in a module compiled for the server.
122
+ *
123
+ * Export-ness is what decides reachability, which is SvelteKit's rule and the
124
+ * only genuine notion of an internal server function in the survey: a
125
+ * non-exported one is never registered, so it has no id and no endpoint, and is
126
+ * still callable from its siblings.
127
+ */
128
+ export function mount(id: string, fn: AnyServerFn): void {
129
+ if (!isServerFn(fn))
130
+ throw new TypeError(
131
+ `[barq] \`mount(${JSON.stringify(id)}, fn)\` was given something that is not a server function, so there is nothing to answer calls with. Pass a function built with \`createServerFn().handler(...)\`.`,
132
+ );
133
+ if (id === "")
134
+ throw new TypeError(
135
+ "[barq] `mount(id, fn)` was given an empty `id`, so no request could reach the function. Pass a non-empty string that is unique in the application.",
136
+ );
137
+ // RE-MOUNTING AN ID REPLACES, and refusing it was a dev-server bug rather
138
+ // than a safeguard. The generated manifest is invalidated whenever a
139
+ // server-function module is transformed and re-imported on the next request,
140
+ // while this registry lives in a module nothing invalidates — so the second
141
+ // evaluation was refusing ids the first had legitimately claimed, and every
142
+ // page answered 500 after the first edit.
143
+ //
144
+ // Nothing is lost by replacing: an id is `<root-relative file>#<export>`, so
145
+ // two DISTINCT functions can only collide if two paths normalise to one, and
146
+ // the manifest generator refuses that where it can see the whole set at once.
147
+ // Here there is no second set to compare against — only the same module,
148
+ // again, newer.
149
+ // Stamped rather than read. The compiler leaves the SERVER half of a module
150
+ // alone — it is the module, compiled — so the builder has no id of its own;
151
+ // the id lives in the manifest the build generates, and mounting is where the
152
+ // two meet. `formAttr` reads it back off the function to write a form's
153
+ // action, so a function that is mounted has a URL and one that is not has
154
+ // neither an id nor an endpoint.
155
+ fn.meta.id = id;
156
+ REGISTRY.set(id, fn);
157
+ }
158
+
159
+ /** The mounted surface, for the build to record and a reviewer to read. */
160
+ export function mounted(): string[] {
161
+ return [...REGISTRY.keys()].toSorted();
162
+ }
163
+
164
+ /**
165
+ * The function mounted at an id, or `undefined`.
166
+ *
167
+ * Exported for the BUILD's chain check, which has to ask each reachable id what
168
+ * middleware it actually carries. It reads the registry inside whichever bundle
169
+ * it is called from, which is why the check runs through the server entry
170
+ * rather than from the Vite plugin: `resolve.noExternal` compiles `@barqjs/*`
171
+ * INTO the ssr bundle, so a plugin importing this module would be asking a
172
+ * second, empty registry.
173
+ */
174
+ export function mountedFn(id: string): ServerFn<unknown, unknown> | undefined {
175
+ return REGISTRY.get(id);
176
+ }
177
+
178
+ /** Test seam. Not for application use. */
179
+ export function unmountAll(): void {
180
+ REGISTRY.clear();
181
+ MOUNTED.manifest = null;
182
+ }
183
+
184
+ export interface HandlerOptions {
185
+ /**
186
+ * Origins allowed to call, beyond the request's own. Same-origin is always
187
+ * allowed; this widens it.
188
+ */
189
+ allowedOrigins?: readonly string[];
190
+ /**
191
+ * The largest body a call may send, in bytes. 1 MiB when omitted.
192
+ *
193
+ * Enforced on the bytes as they are read, and answered with a 413. The body
194
+ * is parsed BEFORE the chain runs, so this is the only thing standing between
195
+ * a caller no middleware has seen yet and the server's memory.
196
+ *
197
+ * srvx's `maxRequestBodySize` is the same idea for the whole server and has
198
+ * no default; this one is for the server-function channel alone, so it holds
199
+ * under a handler that srvx is not in front of.
200
+ */
201
+ maxBodySize?: number;
202
+ /**
203
+ * The largest FORM body, multipart or urlencoded. `maxBodySize` when omitted.
204
+ *
205
+ * Apart from it because a file upload is the one body that legitimately
206
+ * outgrows the default, and raising `maxBodySize` to admit one would widen
207
+ * the value channel by the same amount for no caller that needs it. A form is
208
+ * parsed whole into memory, so this is what one request can make the server
209
+ * hold.
210
+ */
211
+ maxFormSize?: number;
212
+ /**
213
+ * What a failed call may tell its caller about the error, beyond its status.
214
+ *
215
+ * Only the development server passes it, so a production server answers a
216
+ * handler's failure with the status and a fixed line and nothing of the
217
+ * error: its message can name a table, a column or a path. In development the
218
+ * caller is the developer, and the error's name, message and stack (mapped
219
+ * to source by the dev server) are what make the failure debuggable from the
220
+ * browser.
221
+ */
222
+ revealError?: (error: unknown) => ServerFnThrown;
223
+ /**
224
+ * The build this server is, such as a commit hash. A call whose
225
+ * `x-barq-build` header names another build is answered `409` and its
226
+ * function does not run, which catches the skew an unknown id cannot: a
227
+ * function whose id survived a deploy while its arguments or result changed
228
+ * shape. The build `@barqjs/vite` stamped the bundle with when omitted, so
229
+ * a built application needs nothing here; a call with no header is not
230
+ * checked.
231
+ */
232
+ buildId?: string;
233
+ /**
234
+ * Whether some route in this application can reach this id.
235
+ *
236
+ * The narrow half of the route-action manifest. Export-ness already decides
237
+ * what is MOUNTED, and that is deliberately generous — a server function
238
+ * exported for a sibling to import is mounted whether or not any page calls
239
+ * it. Next.js concedes the consequence in its own release notes: "Even if a
240
+ * Server Action or utility function is not imported elsewhere in your code,
241
+ * it's still a publicly accessible HTTP endpoint."
242
+ *
243
+ * This closes that: an id no route reaches answers the 404 an unknown id
244
+ * already answers, so the two are indistinguishable from outside.
245
+ *
246
+ * It takes NO route from the caller, deliberately. A client-supplied route
247
+ * selecting a policy lets the caller pick the weakest one that reaches the
248
+ * action, and this file's own rule says why that is not allowed — values
249
+ * derived from the request are fine to navigate to and never fine to
250
+ * authorize with. Which CHAIN runs is decided at build time by
251
+ * `@barqjs/router`, not here and not per request.
252
+ */
253
+ reachable?: (id: string) => boolean;
254
+ }
255
+
256
+ /**
257
+ * Is this request allowed to invoke a server function?
258
+ *
259
+ * `Origin` first, then `Sec-Fetch-Site` when `Origin` is absent. That fallback
260
+ * is Waku's post-CVE shape and it is the strictest default found: `Origin` is
261
+ * legitimately absent on some same-origin requests and on non-browser clients,
262
+ * while `Sec-Fetch-Site` is sent by every modern browser and cannot be forged
263
+ * from script. Next.js warns and PROCEEDS on a missing `Origin`; this refuses.
264
+ */
265
+ export function originAllowed(request: Request, options?: HandlerOptions): boolean {
266
+ const origin = request.headers.get("origin");
267
+ if (origin !== null) {
268
+ // A sandboxed iframe sends the literal string, so it is refused rather than
269
+ // read as absent and fallen through.
270
+ if (origin === "null") return false;
271
+ if (origin === new URL(request.url).origin) return true;
272
+ return options?.allowedOrigins?.includes(origin) ?? false;
273
+ }
274
+ const site = request.headers.get("sec-fetch-site");
275
+ if (site === null) return false;
276
+ return site === "same-origin" || site === "none";
277
+ }
278
+
279
+ /** Methods that cannot change state, so CSRF does not apply to them. */
280
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
281
+
282
+ /**
283
+ * Is this a request a BROWSER made from another origin?
284
+ *
285
+ * A DIFFERENT QUESTION FROM `originAllowed`, and the difference is the whole
286
+ * design. `originAllowed` guards `/_barq/fn/*`, which only ever exists to be
287
+ * called by this application's own pages — so a request with no origin signal at
288
+ * all is refused there, because there is no legitimate caller that omits one.
289
+ *
290
+ * A route handler is the opposite: an API route exists so that something OTHER
291
+ * than a browser can call it. A Stripe webhook, a GitHub delivery, a cron
292
+ * hitting it with curl — none of them send `Origin` or `Sec-Fetch-Site`, and
293
+ * refusing on their absence would refuse the main reason API routes exist.
294
+ *
295
+ * So this answers the narrower question, and the narrower question is the one
296
+ * CSRF actually asks. A cross-site forgery is by definition made BY A BROWSER
297
+ * with the victim's cookies attached, and a browser making a cross-origin
298
+ * state-changing request always says so — `Origin` on any cross-origin POST
299
+ * since forever, `Sec-Fetch-Site` on everything in every current browser. So:
300
+ * refuse when a signal is present and says cross-origin; allow when there is no
301
+ * signal, because then it is not a browser and cannot be a forgery.
302
+ *
303
+ * `null` origin — a sandboxed iframe, a `data:` URL — is refused rather than
304
+ * read as absent, which is a bypass that has shipped.
305
+ */
306
+ export function crossOriginRefused(request: Request, allowedOrigins?: readonly string[]): boolean {
307
+ if (SAFE_METHODS.has(request.method.toUpperCase())) return false;
308
+
309
+ const origin = request.headers.get("origin");
310
+ if (origin !== null) {
311
+ if (origin === "null") return true;
312
+ if (origin === new URL(request.url).origin) return false;
313
+ return !(allowedOrigins?.includes(origin) ?? false);
314
+ }
315
+
316
+ const site = request.headers.get("sec-fetch-site");
317
+ // No signal at all: not a browser, so not a forgery.
318
+ if (site === null) return false;
319
+ return site !== "same-origin" && site !== "none";
320
+ }
321
+
322
+ /** The labelled 404: the client reports it as skew rather than as a failed call. */
323
+ function unknownFunction(): Response {
324
+ return new Response("not found", { status: 404, headers: { [UNKNOWN_HEADER]: "true" } });
325
+ }
326
+
327
+ /**
328
+ * Handle one server-function request, or return null if the URL is not one.
329
+ *
330
+ * Returning null rather than a 404 is what lets this compose as middleware in
331
+ * front of a page handler.
332
+ */
333
+ export async function handleServerFn(
334
+ request: Request,
335
+ options?: HandlerOptions,
336
+ ): Promise<Response | null> {
337
+ const url = new URL(request.url);
338
+ if (!url.pathname.startsWith(RPC_PREFIX)) return null;
339
+
340
+ // A mutation must not be reachable by navigation. RedwoodSDK shipped server
341
+ // functions invocable over GET, which made a plain link a one-click mutation
342
+ // carrying SameSite=Lax cookies. A GET reaches only a function that asked for
343
+ // it, and only with the header no link can send; both are checked below.
344
+ const method = request.method;
345
+ if (method !== "POST" && method !== "GET") {
346
+ return new Response("method not allowed", { status: 405, headers: { allow: "GET, POST" } });
347
+ }
348
+ if (!originAllowed(request, options)) return new Response("forbidden", { status: 403 });
349
+
350
+ // The URL decides the shape, so a form and an RPC call cannot be confused for
351
+ // one another by a header either of them can set.
352
+ const path = url.pathname.slice(RPC_PREFIX.length);
353
+ // The live address answers what the data address does, framed as events for
354
+ // as long as the answer stands. Only `live`'s loop calls it.
355
+ const isLive = path.endsWith(LIVE_SUFFIX);
356
+ const isData = isLive || path.endsWith(DATA_SUFFIX);
357
+ let id: string;
358
+ try {
359
+ id = decodeURIComponent(
360
+ isLive
361
+ ? path.slice(0, -LIVE_SUFFIX.length)
362
+ : isData
363
+ ? path.slice(0, -DATA_SUFFIX.length)
364
+ : path,
365
+ );
366
+ } catch {
367
+ // Not percent-encoding at all, so it names nothing.
368
+ return new Response("bad request", { status: 400 });
369
+ }
370
+
371
+ let fn = REGISTRY.get(id);
372
+ if (fn === undefined && MOUNTED.manifest !== null) {
373
+ await MOUNTED.manifest();
374
+ fn = REGISTRY.get(id);
375
+ }
376
+ if (fn === undefined) return unknownFunction();
377
+ // Same answer as an unknown id, so a caller cannot tell a function that
378
+ // exists but is unrouted from one that does not exist.
379
+ if (options?.reachable?.(id) === false) return unknownFunction();
380
+ const build = options?.buildId ?? BUNDLED_BUILD;
381
+ const callerBuild = request.headers.get(BUILD_HEADER);
382
+ if (build !== undefined && callerBuild !== null && callerBuild !== build) {
383
+ return new Response(`call from build ${JSON.stringify(callerBuild)} refused`, {
384
+ status: 409,
385
+ headers: { [UNKNOWN_HEADER]: "true", [BUILD_HEADER]: build, "cache-control": "no-store" },
386
+ });
387
+ }
388
+ // The function's own method, and only on the channel that can carry it: a
389
+ // form is a POST, so a GET function has the data channel alone.
390
+ const expected = fn.meta.method ?? "POST";
391
+ if (method !== expected) {
392
+ return new Response("method not allowed", { status: 405, headers: { allow: expected } });
393
+ }
394
+ if (method === "GET") {
395
+ if (!isData) return new Response("not found", { status: 404 });
396
+ if (request.headers.get(RPC_CALLER) === null) return new Response("forbidden", { status: 403 });
397
+ }
398
+
399
+ const bodyLimit = options?.maxBodySize ?? DEFAULT_BODY_LIMIT;
400
+ const target = fn;
401
+ // The draft the handler writes to through `setCookie` / `setResponseHeader`,
402
+ // held HERE because the response is built after the handler has returned.
403
+ const draft = createResponseDraft();
404
+
405
+ /**
406
+ * The call itself: read the body, run the function, build the answer. The
407
+ * innermost step of the request middleware chain, so a global middleware
408
+ * that refuses does so before a byte of the payload has been parsed.
409
+ */
410
+ const respond = async (): Promise<Response> => {
411
+ let input: unknown;
412
+ let clientContext: Record<string, unknown> | undefined;
413
+ // The arguments as they arrived: a broadcast's share key. Encoded rather
414
+ // than decoded, because two values the codec tells apart can decode to the
415
+ // same JSON; encodings that differ for equal values only cost sharing.
416
+ let encoded: string | undefined;
417
+ if (isData && (method === "GET" || !isFormBody(request))) {
418
+ try {
419
+ if (method === "POST") encoded = await capped(request, bodyLimit).text();
420
+ else encoded = url.searchParams.get(PAYLOAD_PARAM) ?? "";
421
+ const body = (method === "GET" ? queryPayload(url, bodyLimit) : JSON.parse(encoded)) as {
422
+ input?: unknown;
423
+ context?: unknown;
424
+ };
425
+ input = body?.input === undefined ? undefined : decodeWire(body.input);
426
+ // WHAT THE CLIENT HALVES SENT, and it is UNTRUSTED — a caller writes this
427
+ // body by hand as readily as the stub does. It reaches a server half as
428
+ // `clientContext` and is never merged into `context`; `serverRpc` says
429
+ // what merging it would let through. Spread, so a body that put a string
430
+ // or a list here still hands the chain an object.
431
+ clientContext =
432
+ body?.context === undefined ? undefined : { ...decodeWire<object>(body.context) };
433
+ } catch (error) {
434
+ return unreadable(error);
435
+ }
436
+ } else {
437
+ try {
438
+ input = await capped(request, options?.maxFormSize ?? bodyLimit).formData();
439
+ } catch (error) {
440
+ return unreadable(error);
441
+ }
442
+ }
443
+
444
+ try {
445
+ // `{ data }` on the value channel; a bare `FormData` on the form one, which
446
+ // is the shape `<form action={fn}>` hands the function on the enhanced path
447
+ // — so a handler sees the same input type whether or not JS ran.
448
+ // `sendContext` is taken INSIDE the request context, because that is where
449
+ // the function's chain left it: each request has its own, so two calls that
450
+ // settle together cannot read one another's.
451
+ const result = await (input instanceof FormData
452
+ ? target(input)
453
+ : (target as (o: unknown, c?: Record<string, unknown>) => Promise<unknown>)(
454
+ { data: input },
455
+ clientContext,
456
+ ));
457
+ const sendContext = takeSendContext();
458
+ if (isLive) {
459
+ if (result instanceof Response) return applyResponseDraft(result, draft);
460
+ if (target.meta.broadcast === true && encoded !== undefined) {
461
+ return applyResponseDraft(
462
+ broadcastResponse(`${id}\0${method}\0${encoded}`, result, request),
463
+ draft,
464
+ );
465
+ }
466
+ return applyResponseDraft(liveResponse(result, request), draft);
467
+ }
468
+ // A RETURNED RESPONSE IS HONOURED ON BOTH CHANNELS, and it did not used to
469
+ // be: the value channel handed it to `encodeWire`, which answered
470
+ // `Seroval Error (step: 1)` and a 500 with nothing in it. So a function that
471
+ // set a cookie by returning a response worked with JS disabled and crashed
472
+ // with JS enabled — the one divergence the form path exists to prevent.
473
+ if (result instanceof Response) {
474
+ // The data channel's client reads every other answer as a wire value, so
475
+ // this one says it is not. A browser following a form needs no telling.
476
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_RESPONSE);
477
+ return applyResponseDraft(result, draft);
478
+ }
479
+ // A component is a frame: the region it renders, for the page to apply.
480
+ // A browser following a form has no page to apply it to.
481
+ if (isFrame(result)) {
482
+ if (isData) return applyResponseDraft(await frameResponse(result as ServerFrame), draft);
483
+ return applyResponseDraft(seeOther(request), draft);
484
+ }
485
+ if (isIterable(result)) {
486
+ if (isData) {
487
+ return applyResponseDraft(streamed(result, sendContext, id, revealerOf(options)), draft);
488
+ }
489
+ // A browser following a form has nothing to read a stream with, so the
490
+ // function is told nobody is listening and the form goes back.
491
+ void result[Symbol.asyncIterator]().return?.();
492
+ return applyResponseDraft(seeOther(request), draft);
493
+ }
494
+ if (isData) {
495
+ // `draftedStatus` here and NOT inside `applyResponseDraft`, because the
496
+ // two answer different questions: this response is the framework's to
497
+ // build, so `setResponseStatus(201)` decides it — where a response the
498
+ // handler RETURNED has already decided for itself.
499
+ const answer = draftedStatus(draft, 200);
500
+ // SINGLE FLIGHT: a mutation that said which frames it changed answers
501
+ // with them, rendered again for the arguments the page has them
502
+ // mounted with, beside its value. Each is asked for through its own
503
+ // function, so its validator and its middleware decide as for a call.
504
+ const mountedHere = mountedFrames(request.headers.get(FRAMES_HEADER));
505
+ const changed = invalidatedFrames();
506
+ if (mountedHere.length > 0 && changed.size > 0) {
507
+ const flight = await flightResponse(
508
+ Object.keys(sendContext).length === 0 ? result : { result, context: sendContext },
509
+ mountedHere,
510
+ changed,
511
+ async (frame) => {
512
+ const asked = REGISTRY.get(frame.id);
513
+ if (asked === undefined || options?.reachable?.(frame.id) === false) return undefined;
514
+ try {
515
+ return await (asked as (o: unknown) => Promise<unknown>)({
516
+ data: frame.args === undefined ? undefined : decodeWire(frame.args),
517
+ });
518
+ } catch (error) {
519
+ console.error(
520
+ `[barq] The frame of ${JSON.stringify(frame.id)} could not be rendered again for the mutation ${JSON.stringify(id)}, so its answer leaves it out. The error:`,
521
+ error,
522
+ );
523
+ return undefined;
524
+ }
525
+ },
526
+ );
527
+ if (Object.keys(sendContext).length > 0) flight.headers.set(RPC_CONTEXT, "1");
528
+ return applyResponseDraft(
529
+ new Response(flight.body, { ...answer, headers: flight.headers }),
530
+ draft,
531
+ );
532
+ }
533
+ // The ordinary shape is the RESULT and nothing around it. A chain that
534
+ // sent something back gets the envelope instead, flagged by a header, so
535
+ // a call that sends nothing pays neither the wrapper nor a second parse.
536
+ if (Object.keys(sendContext).length === 0) {
537
+ return applyResponseDraft(Response.json(encodeWire(result), answer), draft);
538
+ }
539
+ return applyResponseDraft(
540
+ Response.json(encodeWire({ result, context: sendContext }), {
541
+ ...answer,
542
+ headers: { [RPC_CONTEXT]: "1" },
543
+ }),
544
+ draft,
545
+ );
546
+ }
547
+ // Otherwise the browser goes back where it came from, which is what makes
548
+ // the no-JS path a round trip rather than a dead end.
549
+ return applyResponseDraft(seeOther(request), draft);
550
+ } catch (error) {
551
+ // A middleware rejects by throwing a Response — `throw new Response("", {
552
+ // status: 401 })` — and it is returned as it stands.
553
+ // The draft rides an error out as well. A middleware that rotated a session
554
+ // cookie and THEN refused must not lose the rotation — the browser would
555
+ // keep replaying a token the server has already retired.
556
+ if (error instanceof Response) return thrownAnswer(error, isData, draft);
557
+ // `throw redirect(...)` and `throw notFound()` are ANSWERS, and a server
558
+ // function is entitled to both — a handler that finds the session expired
559
+ // redirects to the login page, and one asked for a row that is gone says
560
+ // so. Left to the catch-all below they would be a 500 with nothing in it,
561
+ // and the two most ordinary control-flow throws in the framework would be
562
+ // the two it could not carry.
563
+ const control = controlOf(error);
564
+ if (control !== null) {
565
+ return applyResponseDraft(
566
+ controlResponse(control, isData, (error as { headers?: unknown }).headers),
567
+ draft,
568
+ );
569
+ }
570
+ // A validation failure is the caller's fault and says so, with what was
571
+ // wrong with each field: the issues describe the caller's own input, so a
572
+ // form can show them. Anything else is reported without a body: a
573
+ // handler's message can name a table, a column or a path, and none of that
574
+ // is the caller's business.
575
+ if (isInputError(error)) {
576
+ return applyResponseDraft(
577
+ isData
578
+ ? Response.json(inputAnswer(error), { status: 400 })
579
+ : new Response("invalid input", { status: 400 }),
580
+ draft,
581
+ );
582
+ }
583
+ return applyResponseDraft(failed(id, error, isData, options, "threw"), draft);
584
+ }
585
+ };
586
+
587
+ // AFTER the method, the origin and the id have been checked, never before: a
588
+ // forged or mistyped call is refused above without a middleware having run
589
+ // for it, so it costs nothing and reaches nothing.
590
+ const context: Record<string, unknown> = {};
591
+ const timing = isDev ? serverTiming() : undefined;
592
+ const event = createRequestEvent(request, { response: draft });
593
+ try {
594
+ const response = await provideRequestEvent(event, () => {
595
+ setRequestMiddlewareContext(context);
596
+ return runRequestMiddleware(
597
+ startOptions().requestMiddleware ?? [],
598
+ { request, pathname: url.pathname, handlerType: "serverFn", context },
599
+ respond,
600
+ );
601
+ });
602
+ if (timing !== undefined) {
603
+ timing.phase("barq-fn", id);
604
+ draft.headers.append("server-timing", timing.header());
605
+ }
606
+ return commitEventResponse(response, event);
607
+ } catch (error) {
608
+ // A request middleware refuses the way a function's own does.
609
+ if (error instanceof Response)
610
+ return commitEventResponse(thrownAnswer(error, isData, draft), event);
611
+ return commitEventResponse(failed(id, error, isData, options, "middleware"), event);
612
+ } finally {
613
+ commitResponseStub(draft, { event });
614
+ }
615
+ }
616
+
617
+ /**
618
+ * The 400 a refused input answers with: the refusal and each issue with the
619
+ * path to the field it is about.
620
+ */
621
+ function inputAnswer(error: InputError): ServerFnInputAnswer {
622
+ const issues = (error as { issues?: ReadonlyArray<unknown> }).issues ?? [];
623
+ return {
624
+ error: "invalid input",
625
+ message: error.message,
626
+ issues: issues.map((issue): ServerFnIssue => {
627
+ const { message, path } = (issue ?? {}) as { message?: unknown; path?: unknown };
628
+ const keys = Array.isArray(path)
629
+ ? path.map((segment: unknown) => {
630
+ const key =
631
+ typeof segment === "object" && segment !== null && "key" in segment
632
+ ? segment.key
633
+ : segment;
634
+ return typeof key === "number" ? key : String(key);
635
+ })
636
+ : [];
637
+ return keys.length === 0
638
+ ? { message: String(message) }
639
+ : { message: String(message), path: keys };
640
+ }),
641
+ };
642
+ }
643
+
644
+ /**
645
+ * What a failed call may tell its caller: everything the development server
646
+ * asks for, and in production only an error the application branded with
647
+ * `markSafeError`, by its name and message.
648
+ */
649
+ function revealerOf(
650
+ options: HandlerOptions | undefined,
651
+ ): (error: unknown) => ServerFnThrown | undefined {
652
+ const reveal = options?.revealError;
653
+ return (error) => {
654
+ if (reveal !== undefined) return reveal(error);
655
+ if (!(error instanceof Error) || !isSafeError(error)) return undefined;
656
+ return { name: error.name, message: error.message };
657
+ };
658
+ }
659
+
660
+ /**
661
+ * A call that failed on the server: logged there, reported on the diagnostics
662
+ * channel, and answered 500. The caller learns what was thrown only when the
663
+ * development server asked for it.
664
+ */
665
+ function failed(
666
+ id: string,
667
+ error: unknown,
668
+ isData: boolean,
669
+ options: HandlerOptions | undefined,
670
+ where: "threw" | "middleware",
671
+ ): Response {
672
+ const thrown = revealerOf(options)(error);
673
+ const happened =
674
+ where === "threw"
675
+ ? `The server function ${JSON.stringify(id)} threw`
676
+ : `A request middleware threw before the server function ${JSON.stringify(id)} ran`;
677
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
678
+ console.error(
679
+ `[barq] ${happened}, so the call answered 500${thrown === undefined ? " without the error's text" : ""}. The error:`,
680
+ error,
681
+ );
682
+ if (thrown === undefined) return new Response("internal server error", { status: 500 });
683
+ return isData
684
+ ? Response.json({ error: "internal server error", thrown }, { status: 500 })
685
+ : new Response(
686
+ `internal server error\n\n${thrown.stack ?? `${thrown.name}: ${thrown.message}`}`,
687
+ {
688
+ status: 500,
689
+ },
690
+ );
691
+ }
692
+
693
+ function reportFailure(id: string, error: unknown, happened: string): void {
694
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
695
+ emitDiagnostic(
696
+ {
697
+ code: "SERVER_FUNCTION_FAILED",
698
+ kind: "ssr",
699
+ severity: "error",
700
+ message:
701
+ `${happened}: \`${text}\`. The caller received a 500. Fix the throw at the top of the ` +
702
+ "stack, or throw a `Response`, `redirect()` or `notFound()` to answer the caller on purpose.",
703
+ data: { id, error },
704
+ },
705
+ null,
706
+ );
707
+ }
708
+
709
+ /**
710
+ * A `Response` the chain or the handler threw, as the answer. The data
711
+ * channel's client rejects the call with it, so the header says it was thrown
712
+ * rather than returned; a browser following a form needs no telling.
713
+ */
714
+ function thrownAnswer(error: Response, isData: boolean, draft: ResponseDraft): Response {
715
+ if (isData) draft.headers.set(RPC_CONTROL, RPC_THROWN);
716
+ return applyResponseDraft(error, draft);
717
+ }
718
+
719
+ /**
720
+ * Read a thrown value as a control answer, by BRAND rather than by class.
721
+ *
722
+ * The classes are `@barqjs/router`'s and this package cannot import them; see
723
+ * {@link REDIRECT}. A brand check is also what lets the same code recognise a
724
+ * redirect the router threw and one `@barqjs/start/client` rebuilt off the
725
+ * wire, which matters when a server function calls another one.
726
+ */
727
+ function controlOf(error: unknown): RpcControl | null {
728
+ if (typeof error !== "object" || error === null) return null;
729
+ const branded = error as Record<symbol, unknown> & {
730
+ to?: unknown;
731
+ status?: unknown;
732
+ options?: unknown;
733
+ data?: unknown;
734
+ routeId?: unknown;
735
+ };
736
+ if (branded[REDIRECT] === true) {
737
+ // The shape is checked rather than trusted: the brand says what this claims
738
+ // to be, and a `to` that is not a string would put `undefined` in a
739
+ // `Location` header.
740
+ if (typeof branded.to !== "string") return null;
741
+ const status = typeof branded.status === "number" ? branded.status : 302;
742
+ const options = describedNavigation(branded.options);
743
+ return {
744
+ kind: "redirect",
745
+ to: branded.to,
746
+ status,
747
+ ...(options === undefined ? {} : { options: encodeWire(options) }),
748
+ };
749
+ }
750
+ if (branded[NOT_FOUND] === true) {
751
+ const message = (error as { message?: unknown }).message;
752
+ return {
753
+ kind: "not-found",
754
+ message: typeof message === "string" ? message : "not found",
755
+ ...(branded.data === undefined ? {} : { data: encodeWire(branded.data) }),
756
+ ...(typeof branded.routeId === "string" ? { routeId: branded.routeId } : {}),
757
+ };
758
+ }
759
+ return null;
760
+ }
761
+
762
+ /** The parts of a navigation that are values, and so can be sent. */
763
+ const NAVIGATION = ["to", "from", "params", "search", "hash", "replace", "reloadDocument", "href"];
764
+
765
+ /**
766
+ * The navigation an options-form redirect described, as far as it can cross.
767
+ *
768
+ * A function among them cannot: `search: (current) => ...` is asked about a
769
+ * location only the browser has. A redirect holding one is sent as its resolved
770
+ * target alone, which is what every redirect was sent as before this existed.
771
+ * `statusCode` and `headers` are the answer rather than the navigation, and
772
+ * travel as the status and on the response.
773
+ */
774
+ function describedNavigation(described: unknown): Record<string, unknown> | undefined {
775
+ if (typeof described !== "object" || described === null) return undefined;
776
+ const given = described as Record<string, unknown>;
777
+ const out: Record<string, unknown> = {};
778
+ for (const name of NAVIGATION) {
779
+ const value = given[name];
780
+ if (value === undefined) continue;
781
+ if (typeof value === "function") return undefined;
782
+ out[name] = value;
783
+ }
784
+ if (typeof given.statusCode === "number") out.statusCode = given.statusCode;
785
+ return out;
786
+ }
787
+
788
+ /**
789
+ * A control answer, on whichever channel asked.
790
+ *
791
+ * THE TWO CHANNELS DIVERGE HERE ON PURPOSE, because their clients are different
792
+ * programs. The form channel's client is a BROWSER following the response
793
+ * itself, so a redirect has to be a real 3xx with a `Location`. The data
794
+ * channel's client is `clientRpc`, and a real 3xx there would be FOLLOWED by
795
+ * `fetch` — the caller would receive the target page's HTML instead of a
796
+ * navigation. So the data channel answers 200 and describes the redirect in the
797
+ * body, and the client re-throws it for the router to act on. That is a soft
798
+ * navigation rather than a document load, which is both correct and faster;
799
+ * TanStack returns the raw 3xx and the fetch follows it.
800
+ *
801
+ * `not-found` is a 404 on both, because 404 is the honest status and no client
802
+ * follows one.
803
+ *
804
+ * `extra` is the thrown value's own `headers`, which are the response's on
805
+ * either channel: a redirect that signs a visitor out carries the cookie that
806
+ * does it.
807
+ */
808
+ function controlResponse(control: RpcControl, isData: boolean, extra?: unknown): Response {
809
+ const headers = answerHeaders(extra);
810
+ if (control.kind === "not-found") {
811
+ if (!isData) return new Response(control.message, { status: 404, headers });
812
+ headers.set(RPC_CONTROL, control.kind);
813
+ return Response.json(control, { status: 404, headers });
814
+ }
815
+ if (!isNavigable(control.to)) {
816
+ reportRefusedRedirect(control.to);
817
+ return new Response("bad redirect", { status: 500 });
818
+ }
819
+ if (isData) {
820
+ headers.set(RPC_CONTROL, control.kind);
821
+ return Response.json(control, { status: 200, headers });
822
+ }
823
+ // 303 unless the handler asked for something else, so the browser re-issues
824
+ // as GET and a reload does not repost — the same reason `seeOther` below is
825
+ // 303. A handler that set an explicit status gets the one it set.
826
+ const status = control.status === 302 ? 303 : control.status;
827
+ headers.set("location", control.to);
828
+ return new Response(null, { status, headers });
829
+ }
830
+
831
+ /** A thrown answer's `headers`, or none when it carried nothing a response can take. */
832
+ function answerHeaders(extra: unknown): Headers {
833
+ if (extra === undefined || extra === null) return new Headers();
834
+ try {
835
+ return new Headers(extra as HeadersInit);
836
+ } catch {
837
+ return new Headers();
838
+ }
839
+ }
840
+
841
+ function reportRefusedRedirect(to: string): void {
842
+ console.error(
843
+ `[barq] A server function threw \`redirect(${JSON.stringify(to)})\`, which is not a path or an \`http(s)\` URL, so the redirect was refused and the call answered 500. ` +
844
+ "Validate the value passed to `redirect()` before using it, especially when it comes from the request.",
845
+ );
846
+ }
847
+
848
+ function isIterable(value: unknown): value is AsyncIterable<unknown> {
849
+ return (
850
+ typeof value === "object" &&
851
+ value !== null &&
852
+ typeof (value as Partial<AsyncIterable<unknown>>)[Symbol.asyncIterator] === "function"
853
+ );
854
+ }
855
+
856
+ /**
857
+ * An answer that arrives over time: one JSON line for each value yielded.
858
+ *
859
+ * Produced from `start`, so the function keeps running inside the request it
860
+ * was called for: a `pull` is made from wherever the body is read, where there
861
+ * is no request. It waits to be asked all the same, so a reader that falls
862
+ * behind holds the function at its next `yield` rather than filling memory.
863
+ *
864
+ * A failure after the first value cannot become a status, so it is one last
865
+ * line that says so and nothing else: a handler's message can name a table, a
866
+ * column or a path.
867
+ */
868
+ function streamed(
869
+ values: AsyncIterable<unknown>,
870
+ sendContext: Record<string, unknown>,
871
+ id: string,
872
+ reveal: (error: unknown) => ServerFnThrown | undefined,
873
+ ): Response {
874
+ const encoder = new TextEncoder();
875
+ const line = (payload: RpcStreamLine): Uint8Array =>
876
+ encoder.encode(`${JSON.stringify(payload)}\n`);
877
+ const source = values[Symbol.asyncIterator]();
878
+ let wanted: (() => void) | null = null;
879
+ let cancelled = false;
880
+
881
+ const produce = async (
882
+ controller: ReadableStreamDefaultController<Uint8Array>,
883
+ ): Promise<void> => {
884
+ try {
885
+ if (Object.keys(sendContext).length > 0) {
886
+ controller.enqueue(line({ c: encodeWire(sendContext) }));
887
+ }
888
+ for (;;) {
889
+ if ((controller.desiredSize ?? 1) <= 0) {
890
+ await new Promise<void>((resolve) => {
891
+ wanted = resolve;
892
+ });
893
+ }
894
+ if (cancelled) return;
895
+ const next = await source.next();
896
+ if (cancelled || next.done === true) break;
897
+ controller.enqueue(line({ v: encodeWire(next.value) }));
898
+ }
899
+ if (!cancelled) controller.close();
900
+ } catch (error) {
901
+ if (cancelled) return;
902
+ const thrown = reveal(error);
903
+ const happened = `The server function ${JSON.stringify(id)} threw while streaming its result`;
904
+ if (diagnosticsEnabled()) reportFailure(id, error, happened);
905
+ console.error(
906
+ `[barq] ${happened}, so the stream ended early and the caller receives a \`ServerFnError\`. The error:`,
907
+ error,
908
+ );
909
+ controller.enqueue(line(thrown === undefined ? { e: 1 } : { e: 1, t: thrown }));
910
+ controller.close();
911
+ }
912
+ };
913
+
914
+ const body = new ReadableStream<Uint8Array>({
915
+ start(controller) {
916
+ void produce(controller);
917
+ },
918
+ pull() {
919
+ const waiting = wanted;
920
+ wanted = null;
921
+ waiting?.();
922
+ },
923
+ cancel() {
924
+ cancelled = true;
925
+ const waiting = wanted;
926
+ wanted = null;
927
+ waiting?.();
928
+ void source.return?.();
929
+ },
930
+ });
931
+ return new Response(body, {
932
+ headers: {
933
+ "content-type": "application/x-ndjson; charset=utf-8",
934
+ "cache-control": "no-store",
935
+ [RPC_CONTROL]: RPC_STREAM,
936
+ },
937
+ });
938
+ }
939
+
940
+ const DEFAULT_BODY_LIMIT = 1024 * 1024;
941
+
942
+ /**
943
+ * The request's body behind a cap, as something that can still be parsed.
944
+ *
945
+ * The declared length is only the early exit. A chunked request declares none
946
+ * and a header can understate, so the stream is counted as it is read and
947
+ * errors the moment it passes the limit, with the rest left unread.
948
+ *
949
+ * A `Response` carrying the content type, because that is what parses a
950
+ * multipart body: the boundary is in the header, and srvx's own
951
+ * `limitRequestBody` drops it and so cannot read a form.
952
+ */
953
+ function capped(request: Request, limit: number): Response {
954
+ if (Number(request.headers.get("content-length")) > limit) throw createBodyTooLargeError(limit);
955
+ const type = request.headers.get("content-type");
956
+ return new Response(
957
+ request.body === null ? null : limitBodyStream(request.body, limit),
958
+ type === null ? undefined : { headers: { "content-type": type } },
959
+ );
960
+ }
961
+
962
+ /**
963
+ * A GET call's payload: the body a POST would have sent, in `?payload=`.
964
+ *
965
+ * Held to the body limit, since a URL is a body a caller chose the size of,
966
+ * and refused as a 413 the way an oversized body is.
967
+ */
968
+ function queryPayload(url: URL, limit: number): unknown {
969
+ const payload = url.searchParams.get(PAYLOAD_PARAM);
970
+ if (payload === null) return {};
971
+ if (payload.length > limit) throw createBodyTooLargeError(limit);
972
+ return JSON.parse(payload);
973
+ }
974
+
975
+ /**
976
+ * What a body that could not be read is answered with.
977
+ *
978
+ * By the error's code and not by who threw it: a server in front that enforces
979
+ * `maxRequestBodySize` fails the read with the same error, and that caller is
980
+ * owed the same 413.
981
+ */
982
+ function unreadable(error: unknown): Response {
983
+ return (error as { code?: unknown } | null)?.code === "ERR_BODY_TOO_LARGE"
984
+ ? new Response("payload too large", { status: 413 })
985
+ : new Response("bad request", { status: 400 });
986
+ }
987
+
988
+ /**
989
+ * Whether the body is a form rather than a value. The enhanced path posts
990
+ * `FormData` to the data channel so that a handler sees the SAME input type
991
+ * whether or not JS ran.
992
+ */
993
+ function isFormBody(request: Request): boolean {
994
+ const type = request.headers.get("content-type") ?? "";
995
+ return type.includes("multipart/form-data") || type.includes("application/x-www-form-urlencoded");
996
+ }
997
+
998
+ /**
999
+ * Back where the form was. 303 and not 302, so the browser re-issues as GET and
1000
+ * a reload does not repost — the POST/redirect/GET the no-JS path exists for.
1001
+ *
1002
+ * `Referer` is used only as a destination and never as a decision. SvelteKit's
1003
+ * docs make the distinction for the same reason: values derived from the
1004
+ * request are fine to navigate to and never fine to authorize with.
1005
+ */
1006
+ function seeOther(request: Request): Response {
1007
+ const referer = request.headers.get("referer");
1008
+ const origin = new URL(request.url).origin;
1009
+ let location = "/";
1010
+ if (referer !== null) {
1011
+ try {
1012
+ const target = new URL(referer);
1013
+ // An off-site Referer would make this an open redirect.
1014
+ if (target.origin === origin) {
1015
+ const path = target.pathname + target.search;
1016
+ // A path that opens `//` is another HOST to a browser handed it alone,
1017
+ // and `/\` parses to the same thing. Written with its origin it can only
1018
+ // be what it was: a path on this one.
1019
+ location = path.startsWith("//") ? origin + path : path;
1020
+ }
1021
+ } catch {
1022
+ // A malformed Referer is not a destination.
1023
+ }
1024
+ }
1025
+ return new Response(null, { status: 303, headers: { location } });
1026
+ }