@solidjs/web 2.0.0-rc.7 → 2.0.0-rc.8

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 (72) hide show
  1. package/dist/server.dev.js +15 -2
  2. package/dist/server.js +15 -2
  3. package/dist/web.dev.js +41 -9
  4. package/dist/web.js +39 -8
  5. package/dist/{web.cjs → web.observe.js} +137 -239
  6. package/frames/dist/server.dev.js +19 -0
  7. package/frames/dist/server.js +19 -0
  8. package/frames/package.json +6 -24
  9. package/package.json +81 -314
  10. package/serialization/decode/package.json +3 -9
  11. package/serialization/package.json +3 -9
  12. package/serialization/types/serializer-decode.d.ts +49 -2
  13. package/server-functions/dist/server.dev.js +28 -10
  14. package/server-functions/dist/server.js +28 -10
  15. package/server-functions/package.json +6 -24
  16. package/server-functions/rich-args/package.json +3 -9
  17. package/storage/package.json +3 -9
  18. package/types/client.d.ts +17 -0
  19. package/types/frames/serializer-decode.d.ts +49 -2
  20. package/types/serializer-decode.d.ts +49 -2
  21. package/types/server-functions/server.d.ts +27 -4
  22. package/types/server.d.ts +1 -1
  23. package/dist/server.cjs +0 -3708
  24. package/dist/server.dev.cjs +0 -3794
  25. package/dist/web.dev.cjs +0 -2285
  26. package/frames/dist/client.cjs +0 -2043
  27. package/frames/dist/client.dev.cjs +0 -2063
  28. package/frames/dist/server.cjs +0 -4542
  29. package/frames/dist/server.dev.cjs +0 -4584
  30. package/serialization/dist/decode.cjs +0 -155
  31. package/serialization/dist/serialization.cjs +0 -275
  32. package/serialization/types-cjs/index.d.cts +0 -101
  33. package/serialization/types-cjs/package.json +0 -3
  34. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  35. package/serialization/types-cjs/serializer.d.cts +0 -101
  36. package/server-functions/dist/client.cjs +0 -1069
  37. package/server-functions/dist/rich-args.cjs +0 -11
  38. package/server-functions/dist/server.cjs +0 -2381
  39. package/server-functions/dist/server.dev.cjs +0 -2409
  40. package/storage/dist/storage.cjs +0 -12
  41. package/storage/types-cjs/index.d.cts +0 -28
  42. package/storage/types-cjs/package.json +0 -3
  43. package/types-cjs/client.d.cts +0 -197
  44. package/types-cjs/constants.d.cts +0 -20
  45. package/types-cjs/cookies.d.cts +0 -41
  46. package/types-cjs/frames/client.d.cts +0 -36
  47. package/types-cjs/frames/frame-client.d.cts +0 -370
  48. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  49. package/types-cjs/frames/frame-sink.d.cts +0 -92
  50. package/types-cjs/frames/frame-transport.d.cts +0 -189
  51. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  52. package/types-cjs/frames/serializer.d.cts +0 -101
  53. package/types-cjs/frames/server.d.cts +0 -52
  54. package/types-cjs/head.d.cts +0 -19
  55. package/types-cjs/index.d.cts +0 -191
  56. package/types-cjs/index.server.d.cts +0 -147
  57. package/types-cjs/jsx-properties.d.cts +0 -93
  58. package/types-cjs/jsx.d.cts +0 -4146
  59. package/types-cjs/package.json +0 -3
  60. package/types-cjs/reconcile.d.cts +0 -1
  61. package/types-cjs/render.d.cts +0 -6
  62. package/types-cjs/response.d.cts +0 -81
  63. package/types-cjs/serializer-decode.d.cts +0 -172
  64. package/types-cjs/serializer.d.cts +0 -101
  65. package/types-cjs/server-functions/client.d.cts +0 -184
  66. package/types-cjs/server-functions/flash.d.cts +0 -36
  67. package/types-cjs/server-functions/registry.d.cts +0 -100
  68. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  69. package/types-cjs/server-functions/server.d.cts +0 -546
  70. package/types-cjs/server-functions/shared.d.cts +0 -283
  71. package/types-cjs/server-mock.d.cts +0 -337
  72. package/types-cjs/server.d.cts +0 -408
@@ -1,2381 +0,0 @@
1
- 'use strict';
2
-
3
- var solidJs = require('solid-js');
4
-
5
- const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
6
- function isHttpNavigationTarget(target) {
7
- try {
8
- const protocol = new URL(target, "http://base.invalid").protocol;
9
- return protocol === "http:" || protocol === "https:";
10
- } catch {
11
- return false;
12
- }
13
- }
14
-
15
- const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
16
- function isResponseEnvelope(value) {
17
- return !!(value && typeof value === "object" && value[ENVELOPE]);
18
- }
19
- const SAFE_ERROR = Symbol.for("solid.SafeError");
20
- function isSafeError(value) {
21
- return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
22
- }
23
- const REVALIDATE_HEADER = "X-Revalidate";
24
- const RESPONSE_HEADER_VALUE_LIMIT = 4096;
25
- const NULL_BODY_STATUSES = new Set([204, 205, 304]);
26
-
27
- const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
28
- function getServerFunctionMetadata(fn) {
29
- if (typeof fn !== "function") return undefined;
30
- return fn[SERVER_FUNCTION_METADATA] || undefined;
31
- }
32
- function isServerFunction(fn) {
33
- return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
34
- }
35
- function withMeta(fn, meta) {
36
- const metadata = getServerFunctionMetadata(fn);
37
- if (!metadata) {
38
- throw new Error("withMeta expects a server function reference");
39
- }
40
- Object.assign(metadata, meta);
41
- return fn;
42
- }
43
- const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
44
- const INVOKE_OPTION_REDIRECTS = {
45
- headers: "Session-dynamic headers belong to the prepareRequest hook, declaration metadata to " + "withMeta(fn, meta), and data belongs in the arguments, where it is serialized, typed, " + "and part of the cache key.",
46
- method: "The method is declaration-scoped: declare the function with GET(fn).",
47
- body: "The arguments are the body: pass them in the args array.",
48
- timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
49
- };
50
- function invoke(fn, options, ...args) {
51
- const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
52
- if (!channel) {
53
- throw new Error(isServerFunction(fn) ? "invoke: this wrapper does not forward the invocation channel " + "(SERVER_FUNCTION_INVOKE). Wrappers that share calls (caches, channels) opt in " + "deliberately — a caller's signal cannot own a wire other callers share. Invoke " + "the underlying reference directly, or use the wrapper's own per-call idioms." : "invoke expects a server function reference (or a wrapper that forwards its " + "invocation channel). Per-call options apply at the transport; for a data " + "layer's calls, use its per-call options instead.");
54
- }
55
- if (options === null || typeof options !== "object") {
56
- throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
57
- }
58
- const picked = {};
59
- for (const key in options) {
60
- if (key !== "signal" && key !== "keepalive" && key !== "priority") {
61
- throw new Error(`\`${key}\` is not an invocation option. ` + (INVOKE_OPTION_REDIRECTS[key] || "Options here are strictly invocation-scoped (they vary between calls of the " + "same function): signal, keepalive, priority."));
62
- }
63
- }
64
- if (options.signal !== undefined) picked.signal = options.signal;
65
- if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
66
- if (options.priority !== undefined) picked.priority = options.priority;
67
- return channel(args, picked);
68
- }
69
- const LIVE_SOURCE = Symbol.for("solid.LiveSource");
70
- const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
71
- function provideServerFunctionRPC(rpc) {
72
- globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
73
- }
74
-
75
- function parseCookieHeader(header) {
76
- const cookies = {};
77
- if (!header) return cookies;
78
- for (const part of header.split(";")) {
79
- const eq = part.indexOf("=");
80
- if (eq < 0) continue;
81
- const name = decodeSafe(part.slice(0, eq).trim());
82
- let value = part.slice(eq + 1).trim();
83
- if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
84
- value = value.slice(1, -1);
85
- }
86
- cookies[name] = decodeSafe(value);
87
- }
88
- return cookies;
89
- }
90
- function decodeSafe(text) {
91
- try {
92
- return decodeURIComponent(text);
93
- } catch {
94
- return text;
95
- }
96
- }
97
- function serializeCookie(name, value, options = {}) {
98
- let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
99
- cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
100
- if (options.domain) cookie += `; Domain=${options.domain}`;
101
- if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
102
- if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
103
- if (options.httpOnly) cookie += "; HttpOnly";
104
- if (options.secure) cookie += "; Secure";
105
- if (options.partitioned) cookie += "; Partitioned";
106
- if (options.sameSite) {
107
- const sameSite = options.sameSite.toLowerCase();
108
- cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
109
- }
110
- return cookie;
111
- }
112
- const FLASH_COOKIE = "flash";
113
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
114
- function hasFlashCookie(cookieHeader) {
115
- return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
116
- }
117
- function clearFlashCookie() {
118
- return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
119
- }
120
-
121
- const codecConfig = {
122
- codec: undefined
123
- };
124
- function configureServerFunctionsCodec(codec) {
125
- codecConfig.codec = codec;
126
- }
127
- function getServerFunctionsCodec() {
128
- return codecConfig.codec;
129
- }
130
- const UNNAMED_FLIGHT_SOURCE = "true";
131
- const flightConfig = {
132
- consumers: new Map()
133
- };
134
- function assertFlightSource(source) {
135
- if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
136
- throw new TypeError(`Invalid flight data source id "${source}": ids ride the ` + `${SINGLE_FLIGHT_HEADER} header as a comma-separated list, and "true" is ` + `reserved for the unnamed registration (the bare consumer/hook signatures).`);
137
- }
138
- }
139
- function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
140
- const named = typeof sourceOrConsumer === "string";
141
- if (named) assertFlightSource(sourceOrConsumer);
142
- const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
143
- const consumer = named ? maybeConsumer : sourceOrConsumer;
144
- flightConfig.consumers.set(source, consumer);
145
- return () => {
146
- if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
147
- };
148
- }
149
- function serverFunctionAddress(endpoint, id) {
150
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
151
- return `${mount}/${encodeURIComponent(id)}`;
152
- }
153
- function parseServerFunctionAddress(pathname, endpoint) {
154
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
155
- if (!pathname.startsWith(mount)) return null;
156
- const rest = pathname.slice(mount.length);
157
- if (!rest.startsWith("/")) return null;
158
- let segment = rest.slice(1);
159
- let data = false;
160
- if (segment.startsWith("data/")) {
161
- segment = segment.slice(5);
162
- data = true;
163
- }
164
- if (!segment || segment.includes("/")) return null;
165
- try {
166
- return {
167
- id: decodeURIComponent(segment),
168
- data
169
- };
170
- } catch {
171
- return null;
172
- }
173
- }
174
- const ERROR_HEADER = "X-Server-Function-Error";
175
- const ERROR_HEADER_MARKER = "=?1?";
176
- const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
177
- function encodeErrorHeaderValue(value) {
178
- let stripped = String(value).replace(/[\r\n]+/g, "");
179
- if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
180
- return stripped;
181
- }
182
- if (typeof stripped.toWellFormed === "function") {
183
- stripped = stripped.toWellFormed();
184
- } else {
185
- stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
186
- }
187
- return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
188
- }
189
- function decodeErrorHeaderValue(value) {
190
- if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
191
- return value;
192
- }
193
- try {
194
- return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
195
- } catch {
196
- return value;
197
- }
198
- }
199
- const INSTANCE_HEADER = "X-Server-Function-Instance";
200
- const BODY_FORMAT_HEADER = "X-Server-Function-Format";
201
- const UNKNOWN_HEADER = "X-Server-Function-Unknown";
202
- const REDIRECT_HEADER = "X-Server-Function-Redirect";
203
- function decodeRedirectHeaderValue(value) {
204
- if (typeof value !== "string") return undefined;
205
- const at = value.indexOf(" ");
206
- if (at < 0) return undefined;
207
- const status = Number(value.slice(0, at));
208
- const url = value.slice(at + 1);
209
- if (!Number.isInteger(status) || !url) return undefined;
210
- if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
211
- let parsed;
212
- try {
213
- parsed = new URL(url);
214
- } catch {
215
- return undefined;
216
- }
217
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
218
- return {
219
- status,
220
- url
221
- };
222
- }
223
- const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
224
- const FILE_FORM_KEY = "__server_function_file__";
225
- const BodyFormat = {
226
- Serialized: "0",
227
- String: "1",
228
- FormData: "2",
229
- URLSearchParams: "3",
230
- Blob: "4",
231
- File: "5",
232
- ArrayBuffer: "6",
233
- Uint8Array: "7",
234
- Json: "8",
235
- Void: "9"
236
- };
237
- const JSON_SAFE_DEPTH_LIMIT = 4096;
238
- const EXIT = {};
239
- function isJSONSafe(value) {
240
- const stack = [value];
241
- const ancestors = new Set();
242
- while (stack.length) {
243
- const v = stack.pop();
244
- if (v === EXIT) {
245
- ancestors.delete(stack.pop());
246
- continue;
247
- }
248
- if (v === null) continue;
249
- const t = typeof v;
250
- if (t === "string" || t === "boolean") continue;
251
- if (t === "number") {
252
- if (!Number.isFinite(v) || Object.is(v, -0)) return false;
253
- continue;
254
- }
255
- if (t !== "object") return false;
256
- if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
257
- ancestors.add(v);
258
- stack.push(v, EXIT);
259
- if (Array.isArray(v)) {
260
- for (let i = 0; i < v.length; i++) stack.push(v[i]);
261
- } else {
262
- const proto = Object.getPrototypeOf(v);
263
- if (proto !== Object.prototype && proto !== null) return false;
264
- if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
265
- for (const k in v) {
266
- const descriptor = Object.getOwnPropertyDescriptor(v, k);
267
- if (descriptor === undefined || !("value" in descriptor)) return false;
268
- stack.push(descriptor.value);
269
- }
270
- }
271
- }
272
- return true;
273
- }
274
- function getHeadersAndBody(body) {
275
- switch (true) {
276
- case typeof body === "string":
277
- return {
278
- headers: {
279
- "Content-Type": "text/plain",
280
- [BODY_FORMAT_HEADER]: BodyFormat.String
281
- },
282
- body
283
- };
284
- case body instanceof FormData:
285
- return {
286
- headers: {
287
- [BODY_FORMAT_HEADER]: BodyFormat.FormData
288
- },
289
- body
290
- };
291
- case body instanceof URLSearchParams:
292
- return {
293
- headers: {
294
- "Content-Type": "application/x-www-form-urlencoded",
295
- [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
296
- },
297
- body
298
- };
299
- case typeof File !== "undefined" && body instanceof File:
300
- {
301
- const formData = new FormData();
302
- formData.append(FILE_FORM_KEY, body, body.name);
303
- return {
304
- headers: {
305
- [BODY_FORMAT_HEADER]: BodyFormat.File
306
- },
307
- body: formData
308
- };
309
- }
310
- case body instanceof Blob:
311
- return {
312
- headers: {
313
- [BODY_FORMAT_HEADER]: BodyFormat.Blob
314
- },
315
- body
316
- };
317
- case body instanceof ArrayBuffer:
318
- return {
319
- headers: {
320
- [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
321
- },
322
- body
323
- };
324
- case body instanceof Uint8Array:
325
- return {
326
- headers: {
327
- [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
328
- },
329
- body: new Uint8Array(body)
330
- };
331
- default:
332
- return undefined;
333
- }
334
- }
335
- async function extractBody(source, codecOptions) {
336
- const contentType = source.headers.get("content-type");
337
- const format = source.headers.get(BODY_FORMAT_HEADER);
338
- switch (true) {
339
- case format === BodyFormat.Serialized:
340
- return await deserializeStream(source, codecOptions);
341
- case format === BodyFormat.Json:
342
- return JSON.parse(await source.text());
343
- case format === BodyFormat.String:
344
- return await source.text();
345
- case format === BodyFormat.File:
346
- {
347
- const formData = await source.formData();
348
- return formData.get(FILE_FORM_KEY);
349
- }
350
- case format === BodyFormat.FormData:
351
- case contentType && contentType.startsWith("multipart/form-data"):
352
- return await source.formData();
353
- case format === BodyFormat.URLSearchParams:
354
- case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
355
- return new URLSearchParams(await source.text());
356
- case format === BodyFormat.Blob:
357
- return await source.blob();
358
- case format === BodyFormat.ArrayBuffer:
359
- return await source.arrayBuffer();
360
- case format === BodyFormat.Uint8Array:
361
- return new Uint8Array(await source.arrayBuffer());
362
- }
363
- return undefined;
364
- }
365
- function createChunk(data) {
366
- const encoder = new TextEncoder();
367
- const encodeData = encoder.encode(data);
368
- const bytes = encodeData.length;
369
- const chunk = new Uint8Array(12 + bytes);
370
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
371
- chunk.set(encodeData, 12);
372
- return chunk;
373
- }
374
- class ChunkReader {
375
- constructor(stream) {
376
- this.reader = stream.getReader();
377
- this.store = new Uint8Array(0);
378
- this.buffer = this.store;
379
- this.done = false;
380
- }
381
- async readChunk() {
382
- const chunk = await this.reader.read();
383
- if (chunk.done) {
384
- this.done = true;
385
- return;
386
- }
387
- const incoming = chunk.value;
388
- const store = this.store;
389
- const start = this.buffer.byteOffset;
390
- const end = start + this.buffer.length;
391
- const needed = this.buffer.length + incoming.length;
392
- if (end + incoming.length <= store.length) {
393
- store.set(incoming, end);
394
- this.buffer = store.subarray(start, end + incoming.length);
395
- } else if (needed <= store.length) {
396
- store.copyWithin(0, start, end);
397
- store.set(incoming, this.buffer.length);
398
- this.buffer = store.subarray(0, needed);
399
- } else {
400
- const grown = new Uint8Array(Math.max(needed, store.length * 2));
401
- grown.set(this.buffer);
402
- grown.set(incoming, this.buffer.length);
403
- this.store = grown;
404
- this.buffer = grown.subarray(0, needed);
405
- }
406
- }
407
- async next() {
408
- while (this.buffer.length < 12) {
409
- if (this.done) {
410
- if (this.buffer.length === 0) return {
411
- done: true,
412
- value: undefined
413
- };
414
- throw new Error("Malformed server function stream.");
415
- }
416
- await this.readChunk();
417
- }
418
- const decoder = new TextDecoder();
419
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
420
- if (Number.isNaN(bytes)) {
421
- throw new Error("Malformed server function stream.");
422
- }
423
- while (bytes > this.buffer.length - 12) {
424
- if (this.done) {
425
- throw new Error("Malformed server function stream.");
426
- }
427
- await this.readChunk();
428
- }
429
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
430
- this.buffer = this.buffer.subarray(12 + bytes);
431
- return {
432
- done: false,
433
- value: partial
434
- };
435
- }
436
- async drain(interpret) {
437
- while (true) {
438
- const result = await this.next();
439
- if (result.done) {
440
- break;
441
- }
442
- interpret(result.value);
443
- }
444
- }
445
- }
446
- const ERROR_TRAILER_PREFIX = "!";
447
- function encodeErrorTrailer(error) {
448
- const shaped = error instanceof Error ? error : new Error(String(error));
449
- return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
450
- name: shaped.name,
451
- message: shaped.message
452
- } : {
453
- message: shaped.message
454
- });
455
- }
456
- function errorFromTrailer(payload) {
457
- let shape;
458
- try {
459
- shape = JSON.parse(payload.slice(1));
460
- } catch {
461
- shape = null;
462
- }
463
- const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
464
- if (shape && typeof shape.name === "string") error.name = shape.name;
465
- return error;
466
- }
467
- async function deserializeStream(source, codecOptions) {
468
- if (!source.body) {
469
- throw new Error("missing body");
470
- }
471
- const reader = new ChunkReader(source.body);
472
- const result = await reader.next();
473
- if (!result.done) {
474
- if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
475
- throw errorFromTrailer(result.value);
476
- }
477
- const {
478
- createJSONDeserializer
479
- } = await import('@solidjs/web/serialization/decode');
480
- const deserializeChunk = createJSONDeserializer(codecOptions);
481
- function interpretChunk(chunk) {
482
- if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
483
- throw errorFromTrailer(chunk);
484
- }
485
- return deserializeChunk(JSON.parse(chunk));
486
- }
487
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
488
- return interpretChunk(result.value);
489
- }
490
- return undefined;
491
- }
492
- async function deserializeString(text, codecOptions) {
493
- return await deserializeStream(new Response(text), codecOptions);
494
- }
495
- async function decodeResponse(response, codecOptions) {
496
- if (!response.body) return undefined;
497
- return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
498
- }
499
- async function decodeResponsePayload(response, codecOptions) {
500
- const decoded = await decodeResponse(response, codecOptions);
501
- if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
502
- return {
503
- value: decoded.value,
504
- flightData: decoded.data
505
- };
506
- }
507
- return {
508
- value: decoded
509
- };
510
- }
511
-
512
- typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
513
- const RequestContext = Symbol.for("solid.RequestContext");
514
- function getRequestEvent() {
515
- return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || solidJs.sharedConfig.context && solidJs.sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
516
- }
517
- function reportLostHeaderWrite(method, name) {
518
- const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
519
- console.error(message);
520
- }
521
- function commitResponseStub(stub, {
522
- allowLateLocation = false
523
- } = {}) {
524
- if (!stub || stub.committed) return stub;
525
- stub.committed = true;
526
- const headers = stub.headers;
527
- if (!headers || typeof headers.set !== "function") return stub;
528
- for (const method of ["set", "append", "delete"]) {
529
- const original = headers[method].bind(headers);
530
- headers[method] = function (name, ...rest) {
531
- if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
532
- return original(name, ...rest);
533
- }
534
- reportLostHeaderWrite(method, name);
535
- };
536
- }
537
- return stub;
538
- }
539
- function copyInitHeaders(init) {
540
- if (!init || !init.getSetCookie) return new Headers(init);
541
- const headers = new Headers();
542
- init.forEach((value, key) => {
543
- if (key !== "set-cookie") headers.append(key, value);
544
- });
545
- for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
546
- return headers;
547
- }
548
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
549
- ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
550
- function fillsStubGap(key, headers, response) {
551
- if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
552
- if (response.body === null && (key === "content-type" || key === "content-length")) return false;
553
- return !headers.has(key);
554
- }
555
- function commitEventResponse(response, event = getRequestEvent()) {
556
- const stub = event && event.response;
557
- if (!stub || !stub.headers || stub.committed) return response;
558
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
559
- commitResponseStub(stub);
560
- let hasGaps = false;
561
- stub.headers.forEach((value, key) => {
562
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
563
- });
564
- if (!cookies.length && !hasGaps) return response;
565
- const headers = copyInitHeaders(response.headers);
566
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
567
- stub.headers.forEach((value, key) => {
568
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
569
- });
570
- return new Response(response.body, {
571
- status: response.status,
572
- statusText: response.statusText,
573
- headers
574
- });
575
- }
576
-
577
- let configuredSecret;
578
- function setFlashSecret(secret) {
579
- configuredSecret = secret;
580
- }
581
- function resolveSecret() {
582
- return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
583
- }
584
- const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
585
- let cachedSecret;
586
- let cachedKey;
587
- function resolveFlashKey() {
588
- const secret = resolveSecret();
589
- if (typeof secret !== "string" || secret.length === 0) return null;
590
- if (secret !== cachedSecret) {
591
- cachedSecret = secret;
592
- cachedKey = crypto.subtle.digest("SHA-256", new TextEncoder().encode(FLASH_KEY_DOMAIN + secret)).then(digest => crypto.subtle.importKey("raw", digest, {
593
- name: "AES-GCM"
594
- }, false, ["encrypt", "decrypt"]));
595
- }
596
- return cachedKey;
597
- }
598
- const FLASH_FORMAT_VERSION = "1.";
599
- const IV_BYTES = 12;
600
- const GCM_TAG_BYTES = 16;
601
- function toBase64url(bytes) {
602
- let binary = "";
603
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
604
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
605
- }
606
- function fromBase64url(text) {
607
- const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
608
- const bytes = new Uint8Array(binary.length);
609
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
610
- return bytes;
611
- }
612
- async function encryptFlashValue(key, json) {
613
- const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
614
- const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
615
- name: "AES-GCM",
616
- iv
617
- }, key, new TextEncoder().encode(json)));
618
- const packed = new Uint8Array(IV_BYTES + ciphertext.length);
619
- packed.set(iv);
620
- packed.set(ciphertext, IV_BYTES);
621
- return FLASH_FORMAT_VERSION + toBase64url(packed);
622
- }
623
- async function decryptFlashValue(key, value) {
624
- if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
625
- const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
626
- if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
627
- const plain = await crypto.subtle.decrypt({
628
- name: "AES-GCM",
629
- iv: packed.subarray(0, IV_BYTES)
630
- }, key, packed.subarray(IV_BYTES));
631
- return new TextDecoder().decode(plain);
632
- }
633
- function encodeInputValue(value) {
634
- if (value instanceof FormData) return {
635
- $f: [...value.entries()].filter(([, v]) => typeof v === "string")
636
- };
637
- if (value instanceof URLSearchParams) return {
638
- $u: [...value.entries()]
639
- };
640
- return value;
641
- }
642
- function decodeInputValue(value) {
643
- if (value && typeof value === "object") {
644
- if (Array.isArray(value.$f)) {
645
- const form = new FormData();
646
- for (const [k, v] of value.$f) form.append(k, v);
647
- return form;
648
- }
649
- if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
650
- }
651
- return value;
652
- }
653
- async function encodeFlashCookie(url, result, input, thrown) {
654
- const key = resolveFlashKey();
655
- if (!key) {
656
- return null;
657
- }
658
- const isError = result instanceof Error;
659
- const payload = {
660
- url,
661
- result: isError ? result.message : result,
662
- error: isError,
663
- thrown: !!thrown,
664
- input: input.map(encodeInputValue)
665
- };
666
- if (fitsCookie(payload)) return flashCookie(payload, await key);
667
- payload.truncated = true;
668
- payload.input = [];
669
- if (!fitsCookie(payload)) {
670
- if (typeof payload.result === "string") {
671
- let prefix = payload.result;
672
- while (prefix.length > 0 && !fitsCookie({
673
- ...payload,
674
- result: prefix
675
- })) {
676
- prefix = prefix.slice(0, prefix.length >> 1);
677
- }
678
- payload.result = prefix.length > 0 ? prefix : true;
679
- } else {
680
- payload.result = true;
681
- }
682
- }
683
- if (!fitsCookie(payload)) return null;
684
- return flashCookie(payload, await key);
685
- }
686
- const FLASH_MAX_AGE_SECONDS = 60;
687
- async function flashCookie(payload, key) {
688
- return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
689
- secure: true,
690
- httpOnly: true,
691
- sameSite: "lax",
692
- maxAge: FLASH_MAX_AGE_SECONDS
693
- });
694
- }
695
- const COOKIE_PAIR_BUDGET = 4000;
696
- function fitsCookie(payload) {
697
- const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
698
- const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
699
- const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
700
- return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
701
- }
702
- async function decodeFlashCookie(cookieHeader) {
703
- const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
704
- if (!match) return;
705
- try {
706
- const key = resolveFlashKey();
707
- if (!key) return;
708
- const json = await decryptFlashValue(await key, match);
709
- if (json === undefined) return;
710
- const payload = JSON.parse(json);
711
- if (!payload || typeof payload !== "object" || !("result" in payload)) return;
712
- const result = payload.error ? new Error(payload.result) : payload.result;
713
- const submission = {
714
- input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
715
- url: payload.url,
716
- result: payload.thrown ? undefined : result,
717
- error: payload.thrown ? result : undefined
718
- };
719
- if (payload.truncated) submission.truncated = true;
720
- return submission;
721
- } catch (error) {
722
- }
723
- }
724
-
725
- const config = {
726
- provideEvent: undefined,
727
- wrapInvocation: undefined,
728
- collectFlightData: undefined,
729
- transformResult: undefined,
730
- transformFlightResult: undefined,
731
- transformDirectResult: undefined,
732
- handleNoJS: undefined,
733
- endpoint: "/_server",
734
- csrf: true,
735
- bodySizeLimit: 1_048_576,
736
- maxArguments: 1000
737
- };
738
- function configureServerFunctionsServer({
739
- provideEvent,
740
- wrapInvocation,
741
- collectFlightData,
742
- transformResult,
743
- transformFlightResult,
744
- transformDirectResult,
745
- handleNoJS,
746
- endpoint,
747
- csrf,
748
- codec,
749
- bodySizeLimit,
750
- maxArguments,
751
- secret
752
- } = {}) {
753
- if (provideEvent !== undefined) config.provideEvent = provideEvent;
754
- if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
755
- if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
756
- if (transformResult !== undefined) config.transformResult = transformResult;
757
- if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
758
- if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
759
- if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
760
- if (endpoint !== undefined) config.endpoint = endpoint;
761
- if (csrf !== undefined) config.csrf = csrf;
762
- if (codec !== undefined) configureServerFunctionsCodec(codec);
763
- if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
764
- if (maxArguments !== undefined) config.maxArguments = maxArguments;
765
- if (secret !== undefined) setFlashSecret(secret);
766
- }
767
- const flightSources = new Map();
768
- function registerFlightDataSource(source, hook) {
769
- assertFlightSource(source);
770
- flightSources.set(source, hook);
771
- return () => {
772
- if (flightSources.get(source) === hook) flightSources.delete(source);
773
- };
774
- }
775
- function resolveWrapInvocation(hook) {
776
- if (hook === undefined || typeof hook === "function") return hook;
777
- throw new Error(`Invalid wrapInvocation: expected a function, received ${hook === null ? "null" : typeof hook}. A hook that is not callable cannot wrap the call - configure a function, or leave ` + `wrapInvocation undefined.`);
778
- }
779
- function provideEvent(event, fn) {
780
- if (config.provideEvent) return config.provideEvent(event, fn);
781
- const ctx = globalThis[RequestContext];
782
- if (ctx) return ctx.run(event, fn);
783
- throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
784
- }
785
- const PROVIDE_EVENT_TWICE = "provideEvent invoked the server function callback more than once: a second invocation " + "would commit the call's side effects twice. The hook must call fn exactly once and return " + "its result.";
786
- const PROVIDE_EVENT_NEVER = "provideEvent returned without invoking the server function callback: the call would have " + "answered as a void success without running the function. The hook must call fn exactly once " + "and return its result.";
787
- function provideEventOnce(provide, event, run) {
788
- let invocations = 0;
789
- const settle = () => {
790
- if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
791
- };
792
- const result = provide(event, () => {
793
- if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
794
- return run();
795
- });
796
- const promised = nativePromise(result);
797
- if (promised) {
798
- return promised.then(value => {
799
- settle();
800
- return value;
801
- });
802
- }
803
- settle();
804
- return result;
805
- }
806
- function scopeDeferredResult(value, scope) {
807
- const bound = bindDeferredBody(value, scope);
808
- if (bound !== value || value === null || typeof value !== "object") return bound;
809
- return scopeDeferredContents(value, scope);
810
- }
811
- class ScopeFrame {
812
- constructor(value, next, keys, descriptors) {
813
- this.value = value;
814
- this.next = next;
815
- this.keys = keys;
816
- this.descriptors = descriptors;
817
- this.i = 0;
818
- this.changed = false;
819
- }
820
- }
821
- function enterScopeCarrier(value, state) {
822
- if (value === null || typeof value !== "object" && typeof value !== "function") return value;
823
- if (state.seen.has(value)) {
824
- state.cyclic.add(value);
825
- return state.seen.get(value);
826
- }
827
- const bound = bindDeferredBody(value, state.scope);
828
- if (bound !== value) {
829
- state.seen.set(value, bound);
830
- return bound;
831
- }
832
- if (typeof value !== "object") return value;
833
- if (Array.isArray(value)) {
834
- if (Object.isFrozen(value)) {
835
- state.seen.set(value, value);
836
- return value;
837
- }
838
- const next = value.slice();
839
- state.seen.set(value, next);
840
- return new ScopeFrame(value, next, null, null);
841
- }
842
- const prototype = Object.getPrototypeOf(value);
843
- if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
844
- state.seen.set(value, value);
845
- return value;
846
- }
847
- const descriptors = Object.getOwnPropertyDescriptors(value);
848
- const next = Object.create(prototype, descriptors);
849
- state.seen.set(value, next);
850
- return new ScopeFrame(value, next, Object.keys(value), descriptors);
851
- }
852
- function scopeDeferredContents(root, scope) {
853
- const state = {
854
- seen: new Map(),
855
- cyclic: new Set(),
856
- scope
857
- };
858
- const entered = enterScopeCarrier(root, state);
859
- if (!(entered instanceof ScopeFrame)) return entered;
860
- const stack = [entered];
861
- let delivered = NOTHING;
862
- for (;;) {
863
- const top = stack[stack.length - 1];
864
- const length = top.keys ? top.keys.length : top.value.length;
865
- let pushed = null;
866
- while (top.i < length) {
867
- const i = top.i;
868
- let original;
869
- let writable = true;
870
- if (top.keys) {
871
- const descriptor = top.descriptors[top.keys[i]];
872
- writable = "value" in descriptor && descriptor.writable === true;
873
- original = writable ? descriptor.value : undefined;
874
- } else {
875
- original = top.value[i];
876
- }
877
- if (!writable) {
878
- top.i++;
879
- continue;
880
- }
881
- let bound;
882
- if (delivered !== NOTHING) {
883
- bound = delivered;
884
- delivered = NOTHING;
885
- } else {
886
- bound = enterScopeCarrier(original, state);
887
- if (bound instanceof ScopeFrame) {
888
- pushed = bound;
889
- break;
890
- }
891
- }
892
- if (bound !== original) {
893
- if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
894
- top.changed = true;
895
- }
896
- top.i++;
897
- }
898
- if (pushed !== null) {
899
- stack.push(pushed);
900
- continue;
901
- }
902
- stack.pop();
903
- let out;
904
- if (top.changed || state.cyclic.has(top.value)) {
905
- out = top.next;
906
- } else {
907
- state.seen.set(top.value, top.value);
908
- out = top.value;
909
- }
910
- if (stack.length === 0) return out;
911
- delivered = out;
912
- }
913
- }
914
- function bindDeferredBody(value, scope) {
915
- if (value === null || typeof value !== "object" && typeof value !== "function") return value;
916
- const promised = scope(() => nativePromise(value));
917
- if (promised) {
918
- return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
919
- }
920
- if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
921
- let reader;
922
- return new ReadableStream({
923
- async pull(controller) {
924
- try {
925
- const step = await scope(() => {
926
- if (!reader) reader = value.getReader();
927
- return reader.read();
928
- });
929
- if (step.done) controller.close();else controller.enqueue(step.value);
930
- } catch (error) {
931
- controller.error(error);
932
- }
933
- },
934
- cancel(reason) {
935
- return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
936
- }
937
- }, {
938
- highWaterMark: 0
939
- });
940
- }
941
- const scopedIterator = symbol => ({
942
- [symbol]() {
943
- const iterator = scope(() => value[symbol]());
944
- return new Proxy(iterator, {
945
- get(target, property) {
946
- const member = Reflect.get(target, property, target);
947
- return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
948
- }
949
- });
950
- }
951
- });
952
- if (typeof value[Symbol.asyncIterator] === "function") {
953
- return scopedIterator(Symbol.asyncIterator);
954
- }
955
- if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
956
- return scopedIterator(Symbol.iterator);
957
- }
958
- return value;
959
- }
960
- const REGISTRATIONS = new Map();
961
- const METHODS = new Map();
962
- const REFERENCE_BINDINGS = new WeakMap();
963
- function declaresRead(id) {
964
- const granted = METHODS.get(id);
965
- return granted !== undefined && granted === REGISTRATIONS.get(id);
966
- }
967
- const INVOCATIONS = new WeakMap();
968
- let rpcProvided = false;
969
- function provideRPC() {
970
- if (rpcProvided) return;
971
- rpcProvided = true;
972
- provideServerFunctionRPC({
973
- GET,
974
- decodeResponse
975
- });
976
- }
977
- function registerServerFunction(id, callback) {
978
- provideRPC();
979
- if (REGISTRATIONS.get(id) !== callback) METHODS.delete(id);
980
- REGISTRATIONS.set(id, callback);
981
- return callback;
982
- }
983
- function getServerFunction(id) {
984
- const fn = REGISTRATIONS.get(id);
985
- if (fn) {
986
- return fn;
987
- }
988
- throw new Error("invalid server function: " + id);
989
- }
990
- function registerServerReference(id, fn, name) {
991
- if (typeof fn !== "function") {
992
- throw new Error(`Server function${name ? ` \`${name}\`` : ""} (${id}) is not a function: a module-level ` + `"use server" export must evaluate to a server function (got ${fn === null ? "null" : typeof fn}). Move non-function exports out of the directive module.`);
993
- }
994
- registerServerFunction(id, fn);
995
- return {
996
- id,
997
- fn,
998
- name
999
- };
1000
- }
1001
- function inProcessInvoker(call) {
1002
- return (args, options) => {
1003
- const signal = options && options.signal;
1004
- if (!signal) return call(...args);
1005
- if (signal.aborted) return Promise.reject(signal.reason);
1006
- return new Promise((resolve, reject) => {
1007
- const onAbort = () => reject(signal.reason);
1008
- signal.addEventListener("abort", onAbort, {
1009
- once: true
1010
- });
1011
- let result;
1012
- try {
1013
- result = call(...args);
1014
- } catch (error) {
1015
- signal.removeEventListener("abort", onAbort);
1016
- return reject(error);
1017
- }
1018
- Promise.resolve(result).then(value => {
1019
- signal.removeEventListener("abort", onAbort);
1020
- resolve(value);
1021
- }, error => {
1022
- signal.removeEventListener("abort", onAbort);
1023
- reject(error);
1024
- });
1025
- });
1026
- };
1027
- }
1028
- function createServerReference({
1029
- id,
1030
- fn,
1031
- name
1032
- }) {
1033
- if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
1034
- provideRPC();
1035
- const metadata = name === undefined ? {} : {
1036
- name
1037
- };
1038
- const invokeChannel = inProcessInvoker((...args) => proxy(...args));
1039
- const proxy = new Proxy(fn, {
1040
- get(target, prop) {
1041
- if (prop === "id") return id;
1042
- if (prop === "url") {
1043
- return serverFunctionAddress(config.endpoint, id);
1044
- }
1045
- if (prop === SERVER_FUNCTION_METADATA) return metadata;
1046
- if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
1047
- return target[prop];
1048
- },
1049
- apply(target, thisArg, args) {
1050
- const ogEvt = getRequestEvent();
1051
- if (!ogEvt) throw new Error("Cannot call server function outside of a request");
1052
- const evt = {
1053
- ...ogEvt,
1054
- locals: {
1055
- ...ogEvt.locals
1056
- }
1057
- };
1058
- INVOCATIONS.set(evt, {
1059
- id
1060
- });
1061
- evt.serverOnly = true;
1062
- const scope = run => provideEvent(evt, run);
1063
- const wrap = resolveWrapInvocation(config.wrapInvocation);
1064
- let result = provideEventOnce(provideEvent, evt, () => {
1065
- const run = () => fn.apply(thisArg, args);
1066
- return wrap ? wrap(run, {
1067
- id,
1068
- args,
1069
- event: evt,
1070
- direct: true
1071
- }) : run();
1072
- });
1073
- result = scopeDeferredResult(result, scope);
1074
- const transform = config.transformDirectResult;
1075
- if (transform && result && typeof result.then === "function") {
1076
- return result.then(value => scopeDeferredResult(transform(value, {
1077
- id,
1078
- args,
1079
- event: evt
1080
- }), scope));
1081
- }
1082
- return transform ? scopeDeferredResult(transform(result, {
1083
- id,
1084
- args,
1085
- event: evt
1086
- }), scope) : result;
1087
- }
1088
- });
1089
- REFERENCE_BINDINGS.set(proxy, fn);
1090
- return proxy;
1091
- }
1092
- function GET(fn) {
1093
- if (!isServerFunction(fn) || typeof fn.id !== "string") {
1094
- throw new Error("GET expects a server function reference");
1095
- }
1096
- const id = fn.id;
1097
- const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1098
- const existing = METHODS.get(id);
1099
- if (existing !== undefined && existing !== binding) {
1100
- if (DEV) {
1101
- throw new Error(`GET() would rebind the existing grant for server function "${id}" to a different ` + `function. A GET declaration is made about a function, not an id - two references ` + `sharing one id cannot both hold it. Give the functions distinct ids, or drop the ` + `stale declaration.`);
1102
- }
1103
- METHODS.delete(id);
1104
- return fn;
1105
- }
1106
- METHODS.set(id, binding);
1107
- const reference = withMeta(fn, {
1108
- method: "GET"
1109
- });
1110
- guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1111
- return reference;
1112
- }
1113
- function guardDeclaredMethod(metadata, id) {
1114
- let declared = metadata.method;
1115
- Object.defineProperty(metadata, "method", {
1116
- configurable: true,
1117
- enumerable: true,
1118
- get: () => declared,
1119
- set(next) {
1120
- if (next === declared) return;
1121
- if (DEV) {
1122
- throw new Error(`withMeta({ method }) cannot change the GET() declaration of server function ` + `"${id}". The method is declaration-scoped: it was granted about the function ` + `by GET(fn), and a metadata write cannot re-shape the wire grant.`);
1123
- }
1124
- METHODS.delete(id);
1125
- declared = next;
1126
- }
1127
- });
1128
- }
1129
- function live(fn) {
1130
- if (!isServerFunction(fn) || typeof fn.id !== "string") {
1131
- throw new Error("live expects a server function reference");
1132
- }
1133
- const metadata = {
1134
- ...getServerFunctionMetadata(fn),
1135
- live: true
1136
- };
1137
- const wrapped = async (...args) => {
1138
- const result = await fn(...args);
1139
- if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
1140
- result[LIVE_SOURCE] = true;
1141
- }
1142
- return result;
1143
- };
1144
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
1145
- wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
1146
- wrapped.id = fn.id;
1147
- Object.defineProperty(wrapped, "url", {
1148
- get: () => fn.url,
1149
- configurable: true
1150
- });
1151
- return wrapped;
1152
- }
1153
- function getServerFunctionInvocation() {
1154
- return getEventServerFunctionInvocation(getRequestEvent());
1155
- }
1156
- function getEventServerFunctionInvocation(event) {
1157
- return event && INVOCATIONS.get(event);
1158
- }
1159
- function resolveAddress(url) {
1160
- return parseServerFunctionAddress(url.pathname, config.endpoint);
1161
- }
1162
- const DECODE_DEPTH_LIMIT = 64;
1163
- function assertDecodeDepth(value) {
1164
- let level = [value];
1165
- for (let depth = 0; level.length > 0; depth++) {
1166
- if (depth > DECODE_DEPTH_LIMIT) {
1167
- throw new TypeError("Server function arguments exceed the decode depth limit");
1168
- }
1169
- const next = [];
1170
- for (const node of level) {
1171
- if (node === null || typeof node !== "object") continue;
1172
- if (Array.isArray(node)) {
1173
- for (const child of node) next.push(child);
1174
- } else {
1175
- for (const key of Object.keys(node)) next.push(node[key]);
1176
- }
1177
- }
1178
- level = next;
1179
- }
1180
- }
1181
- const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1182
- function stripUnsafeArgumentKeys(value) {
1183
- const stack = [value];
1184
- const seen = new Set();
1185
- while (stack.length) {
1186
- const v = stack.pop();
1187
- if (v === null || typeof v !== "object" || seen.has(v)) continue;
1188
- seen.add(v);
1189
- for (const key of UNSAFE_ARGUMENT_KEYS) {
1190
- delete v[key];
1191
- }
1192
- for (const key of Object.keys(v)) stack.push(v[key]);
1193
- if (v instanceof Map) {
1194
- for (const [k, entry] of v) stack.push(k, entry);
1195
- } else if (v instanceof Set) {
1196
- for (const member of v) stack.push(member);
1197
- }
1198
- }
1199
- return value;
1200
- }
1201
- async function bufferBodyWithin(request, limit) {
1202
- const reader = request.body.getReader();
1203
- const signal = request.signal;
1204
- const chunks = [];
1205
- let total = 0;
1206
- const onAbort = () => {
1207
- reader.cancel(signal.reason).catch(() => {});
1208
- };
1209
- if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1210
- once: true
1211
- });
1212
- try {
1213
- for (;;) {
1214
- const {
1215
- done,
1216
- value
1217
- } = await reader.read();
1218
- if (signal.aborted) throw signal.reason;
1219
- if (done) break;
1220
- total += value.byteLength;
1221
- if (total > limit) {
1222
- reader.cancel().catch(() => {});
1223
- return null;
1224
- }
1225
- chunks.push(value);
1226
- }
1227
- } catch (error) {
1228
- reader.cancel(error).catch(() => {});
1229
- throw error;
1230
- } finally {
1231
- signal.removeEventListener("abort", onAbort);
1232
- reader.releaseLock();
1233
- }
1234
- const body = new Uint8Array(total);
1235
- let offset = 0;
1236
- for (const chunk of chunks) {
1237
- body.set(chunk, offset);
1238
- offset += chunk.byteLength;
1239
- }
1240
- return new Request(request, {
1241
- body
1242
- });
1243
- }
1244
- const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1245
- const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1246
- function unknownFormatError(tag) {
1247
- const error = new TypeError(`Server function body carries an unrecognized ${BODY_FORMAT_HEADER} tag ("${tag}"): the ` + "caller encodes a newer wire format than this build can decode (version skew), or an " + "intermediary duplicated the header. The body was refused rather than reinterpreted.");
1248
- error[FORMAT_SKEW] = true;
1249
- return error;
1250
- }
1251
- async function parseArguments(request, url, scripted, codec) {
1252
- const parsed = [];
1253
- const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
1254
- const args = url.searchParams.get("args");
1255
- if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1256
- let result;
1257
- if (args.startsWith(";0x")) {
1258
- result = await deserializeString(args, codec);
1259
- } else {
1260
- result = JSON.parse(args);
1261
- assertDecodeDepth(result);
1262
- }
1263
- if (!Array.isArray(result)) {
1264
- throw new TypeError("Server function arguments must encode an array");
1265
- }
1266
- stripUnsafeArgumentKeys(result);
1267
- for (const arg of result) {
1268
- parsed.push(arg);
1269
- }
1270
- } else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
1271
- parsed.push(url.searchParams);
1272
- }
1273
- if (request.method === "POST" && request.body !== null) {
1274
- if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1275
- throw unknownFormatError(bodyFormat);
1276
- }
1277
- const body = request.clone();
1278
- const decoded = await extractBody(body, codec);
1279
- if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1280
- if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1281
- if (!Array.isArray(decoded)) {
1282
- throw new TypeError("Server function arguments must encode an array");
1283
- }
1284
- return stripUnsafeArgumentKeys(decoded);
1285
- }
1286
- if (decoded === undefined) {
1287
- if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1288
- return parsed;
1289
- }
1290
- throw new TypeError("Server function body carries no usable encoding");
1291
- }
1292
- parsed.push(decoded);
1293
- }
1294
- return parsed;
1295
- }
1296
- async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1297
- if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
1298
- digestOutcome(event, outcome);
1299
- const folded = [];
1300
- for (const [source, hook] of hooks) {
1301
- try {
1302
- const slice = await hook(event, outcome);
1303
- if (slice !== undefined) folded.push([source, slice]);
1304
- } catch (error) {
1305
- console.error(`Error collecting flight data for source "${source}"`, error);
1306
- }
1307
- }
1308
- if (folded.length === 0) return outcome.value;
1309
- const data = Object.fromEntries(folded);
1310
- headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
1311
- if (context.transformFlightResult) {
1312
- const transformed = await context.transformFlightResult(event, {
1313
- value: outcome.value,
1314
- data
1315
- }, context);
1316
- if (transformed !== undefined) {
1317
- const owned = ownResponse(transformed);
1318
- for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
1319
- headers.forEach((value, key) => {
1320
- if (key !== "set-cookie" && !owned.headers.has(key)) {
1321
- owned.headers.set(key, value);
1322
- }
1323
- });
1324
- return owned;
1325
- }
1326
- }
1327
- return outcome.value === undefined ? {
1328
- data
1329
- } : {
1330
- value: outcome.value,
1331
- data
1332
- };
1333
- }
1334
- function digestOutcome(event, outcome) {
1335
- const {
1336
- request,
1337
- response
1338
- } = outcome;
1339
- outcome.revalidateKeys = response?.headers.get(REVALIDATE_HEADER)?.split(",");
1340
- outcome.foldedHeaders = foldSetCookies(request.headers, [...(event.response?.headers?.getSetCookie() ?? []), ...(response?.headers?.getSetCookie() ?? [])]);
1341
- try {
1342
- const referrer = request.headers.get("referer");
1343
- if (referrer) {
1344
- const location = response?.headers.get("Location");
1345
- const target = location ? new URL(location, request.url) : new URL(referrer);
1346
- if (target.origin === new URL(request.url).origin) outcome.targetUrl = target.toString();
1347
- }
1348
- } catch {
1349
- }
1350
- }
1351
- function parseSetCookie(setCookie) {
1352
- const [pair, ...attributes] = setCookie.split(";");
1353
- const eq = pair.indexOf("=");
1354
- if (eq < 0) return undefined;
1355
- const parsed = {
1356
- name: pair.slice(0, eq).trim(),
1357
- value: pair.slice(eq + 1).trim()
1358
- };
1359
- for (const attribute of attributes) {
1360
- const attrEq = attribute.indexOf("=");
1361
- const key = (attrEq < 0 ? attribute : attribute.slice(0, attrEq)).trim().toLowerCase();
1362
- const value = attrEq < 0 ? "" : attribute.slice(attrEq + 1).trim();
1363
- if (key === "max-age") parsed.maxAge = Number(value);else if (key === "expires") parsed.expires = new Date(value);
1364
- }
1365
- return parsed;
1366
- }
1367
- function foldSetCookies(headers, setCookies) {
1368
- const folded = new Headers(headers);
1369
- if (!setCookies.length) return folded;
1370
- const cookies = {};
1371
- for (const pair of folded.get("cookie")?.split(";") ?? []) {
1372
- const eq = pair.indexOf("=");
1373
- if (eq > -1) cookies[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
1374
- }
1375
- for (const setCookie of setCookies) {
1376
- const parsed = parseSetCookie(setCookie);
1377
- if (!parsed) continue;
1378
- if (parsed.maxAge != null && parsed.maxAge <= 0 || parsed.expires != null && parsed.expires.getTime() <= Date.now()) {
1379
- delete cookies[parsed.name];
1380
- } else {
1381
- cookies[parsed.name] = parsed.value;
1382
- }
1383
- }
1384
- folded.delete("cookie");
1385
- const serialized = Object.entries(cookies).map(([name, value]) => `${name}=${value}`).join("; ");
1386
- if (serialized) folded.set("cookie", serialized);
1387
- return folded;
1388
- }
1389
- function mergeResponseHeaders(target, source) {
1390
- source.forEach((value, key) => {
1391
- if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1392
- });
1393
- if (source.getSetCookie) {
1394
- for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
1395
- } else if (source.has("set-cookie")) {
1396
- target.append("Set-Cookie", source.get("set-cookie"));
1397
- }
1398
- }
1399
- const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
1400
- function maskRedirect(headers, response, requestUrl) {
1401
- const target = response.headers && response.headers.get("Location");
1402
- if (target) {
1403
- headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
1404
- }
1405
- headers.delete("Location");
1406
- }
1407
- const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1408
- function enforceComposedHeaderInvariants(response) {
1409
- for (const name of BOUNDED_COMPOSED_HEADERS) {
1410
- const value = response.headers.get(name);
1411
- if (value === null) continue;
1412
- if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
1413
- return refuseComposedHeader(response, name, `${name} response header refused at ${value.length} characters`, DEV ? `The ${name} response header is ${value.length} characters; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} it would overflow receivers (an 8 KiB proxy ` + `buffer holds the whole header block) and the response dies at the socket after ` + `the mutation committed. Refused rather than trimmed: a cut redirect target is a ` + `different address, a dropped revalidate key is a silently stale cache. The ` + `redirect()/reload() helpers enforce this bound with the full reasoning at the ` + `call site.` : null);
1414
- }
1415
- if (name === REVALIDATE_HEADER) continue;
1416
- const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1417
- if (!isHttpNavigationTarget(target)) {
1418
- return refuseComposedHeader(response, name, `${name} response header refused: non-http(s) navigation target`, DEV ? `The ${name} response header carries a navigation target with a non-http(s) ` + `scheme ("${target.slice(0, 64)}"). A javascript: target is same-origin script ` + `execution in any integration that navigates to it, so only http(s) and ` + `relative targets leave this transport. If the target came from request data ` + `(?next= and friends), validate it against your own origin before redirecting.` : null);
1419
- }
1420
- }
1421
- return response;
1422
- }
1423
- function refuseComposedHeader(response, name, headerMessage, body) {
1424
- if (response.body) {
1425
- try {
1426
- const cancelled = response.body.cancel();
1427
- if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1428
- } catch {}
1429
- }
1430
- const headers = new Headers();
1431
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
1432
- return new Response(body, {
1433
- status: 500,
1434
- headers
1435
- });
1436
- }
1437
- function warnScripted304(functionId) {
1438
- if (DEV) {
1439
- console.warn(`Server function "${functionId}" answered a scripted call with 304 Not Modified. ` + `The client transport sends no conditional headers, so nothing was asked to be ` + `revalidated: the call resolves to undefined, not "unchanged". For conditional ` + `reads, declare the function GET and set ETag/Cache-Control response headers - ` + `the browser owns that exchange and replays its cached answer on a 304.`);
1440
- }
1441
- }
1442
- function createNoJSHandler({
1443
- base = ""
1444
- } = {}) {
1445
- return async function handleNoJS(result, request, args, thrown) {
1446
- const url = new URL(request.url);
1447
- let back = new URL(base || "/", url.origin).toString();
1448
- try {
1449
- const referer = request.headers.get("referer");
1450
- if (referer) back = new URL(referer).toString();
1451
- } catch {}
1452
- let status = 303;
1453
- let headers;
1454
- if (result instanceof Response) {
1455
- headers = new Headers();
1456
- mergeResponseHeaders(headers, result.headers);
1457
- if (result.headers.has("Location")) {
1458
- headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
1459
- if (validRedirectStatuses.has(result.status)) status = result.status;
1460
- } else {
1461
- headers.set("Location", back);
1462
- }
1463
- headers.delete("Content-Type");
1464
- headers.delete("Content-Length");
1465
- } else {
1466
- headers = new Headers({
1467
- Location: back
1468
- });
1469
- }
1470
- if (result !== undefined && !(result instanceof Response)) {
1471
- const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1472
- if (flash !== null) headers.append("Set-Cookie", flash);
1473
- }
1474
- return new Response(null, {
1475
- status,
1476
- headers
1477
- });
1478
- };
1479
- }
1480
- let defaultNoJSHandler;
1481
- function isFormPost(request) {
1482
- if (request.method !== "POST" || request.headers.has(BODY_FORMAT_HEADER)) return false;
1483
- const type = request.headers.get("content-type") || "";
1484
- return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
1485
- }
1486
- function guardFailures(value, state) {
1487
- if (!state) state = {
1488
- seen: new WeakMap(),
1489
- cyclic: new WeakSet()
1490
- };
1491
- const entered = enterGuard(value, state);
1492
- if (!(entered instanceof Frame)) return entered;
1493
- const stack = [entered];
1494
- let delivered = NOTHING;
1495
- for (;;) {
1496
- const top = stack[stack.length - 1];
1497
- const items = top.items;
1498
- let pushed = null;
1499
- while (top.i < items.length) {
1500
- const i = top.i;
1501
- let original;
1502
- if (top.kind === OBJECT) {
1503
- const descriptor = top.descriptors[items[i]];
1504
- if ("value" in descriptor) {
1505
- original = descriptor.value;
1506
- } else if (typeof descriptor.get === "function") {
1507
- if (top.accessorRead !== i) {
1508
- try {
1509
- top.accessorValue = descriptor.get.call(top.value);
1510
- } catch (error) {
1511
- throw sanitizeServerError(error);
1512
- }
1513
- top.accessorRead = i;
1514
- }
1515
- original = top.accessorValue;
1516
- } else {
1517
- top.i++;
1518
- continue;
1519
- }
1520
- } else {
1521
- original = items[i];
1522
- }
1523
- let guarded;
1524
- if (delivered !== NOTHING) {
1525
- guarded = delivered;
1526
- delivered = NOTHING;
1527
- } else {
1528
- guarded = enterGuard(original, state);
1529
- if (guarded instanceof Frame) {
1530
- pushed = guarded;
1531
- break;
1532
- }
1533
- }
1534
- if (top.kind === ARRAY) {
1535
- if (guarded !== original) {
1536
- top.next[i] = guarded;
1537
- top.changed = true;
1538
- }
1539
- } else if (top.kind === MAP) {
1540
- if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
1541
- if (guarded !== original) top.changed = true;
1542
- } else if (top.kind === SET) {
1543
- top.next.add(guarded);
1544
- if (guarded !== original) top.changed = true;
1545
- } else if (guarded !== original || top.accessorRead === i) {
1546
- Object.defineProperty(top.next, items[i], {
1547
- value: guarded,
1548
- writable: true,
1549
- configurable: true,
1550
- enumerable: top.descriptors[items[i]].enumerable
1551
- });
1552
- top.changed = true;
1553
- }
1554
- top.i++;
1555
- }
1556
- if (pushed !== null) {
1557
- stack.push(pushed);
1558
- continue;
1559
- }
1560
- stack.pop();
1561
- const out = keepGuarded(top.value, top.next, top.changed, state);
1562
- if (stack.length === 0) return out;
1563
- delivered = out;
1564
- }
1565
- }
1566
- const NOTHING = Symbol();
1567
- const ARRAY = 0;
1568
- const MAP = 1;
1569
- const SET = 2;
1570
- const OBJECT = 3;
1571
- class Frame {
1572
- constructor(kind, value, next, items, descriptors) {
1573
- this.kind = kind;
1574
- this.value = value;
1575
- this.next = next;
1576
- this.items = items;
1577
- this.descriptors = descriptors;
1578
- this.i = 0;
1579
- this.changed = false;
1580
- this.accessorRead = -1;
1581
- this.accessorValue = undefined;
1582
- this.pendingKey = undefined;
1583
- }
1584
- }
1585
- function guardOperation(state, run) {
1586
- return state.scope ? state.scope(run) : run();
1587
- }
1588
- function enterGuard(value, state) {
1589
- if (value === null || typeof value !== "object") return value;
1590
- if (state.seen.has(value)) {
1591
- state.cyclic.add(value);
1592
- return state.seen.get(value);
1593
- }
1594
- if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1595
- let reader;
1596
- const gate = state.gate;
1597
- let finished = false;
1598
- const close = () => {
1599
- if (finished) return;
1600
- finished = true;
1601
- try {
1602
- const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1603
- if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1604
- } catch {}
1605
- };
1606
- const guardedStream = new ReadableStream({
1607
- async pull(controller) {
1608
- try {
1609
- if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
1610
- if (finished) {
1611
- controller.close();
1612
- return;
1613
- }
1614
- if (!reader) reader = guardOperation(state, () => value.getReader());
1615
- const {
1616
- done,
1617
- value: chunk
1618
- } = await guardOperation(state, () => reader.read());
1619
- done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1620
- } catch (error) {
1621
- controller.error(guardOperation(state, () => sanitizeServerError(error)));
1622
- }
1623
- },
1624
- cancel(reason) {
1625
- finished = true;
1626
- return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1627
- }
1628
- });
1629
- if (gate) gate.onOpen(close);
1630
- state.seen.set(value, guardedStream);
1631
- return guardedStream;
1632
- }
1633
- if (typeof value.then === "function") {
1634
- const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1635
- throw guardOperation(state, () => sanitizeServerError(error));
1636
- });
1637
- guardedPromise.catch(() => {});
1638
- state.seen.set(value, guardedPromise);
1639
- return guardedPromise;
1640
- }
1641
- if (typeof value[Symbol.asyncIterator] === "function") {
1642
- const source = value;
1643
- const gate = state.gate;
1644
- const guardedIterable = {
1645
- [Symbol.asyncIterator]() {
1646
- const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1647
- let finished = false;
1648
- const close = () => {
1649
- if (finished) return;
1650
- finished = true;
1651
- try {
1652
- const returned = iterator.return && guardOperation(state, () => iterator.return());
1653
- if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1654
- } catch {}
1655
- };
1656
- if (gate) gate.onOpen(close);
1657
- const step = () => finished ? Promise.resolve({
1658
- done: true,
1659
- value: undefined
1660
- }) : guardOperation(state, () => iterator.next()).then(step => {
1661
- if (step.done) {
1662
- finished = true;
1663
- return step;
1664
- }
1665
- return {
1666
- done: false,
1667
- value: guardOperation(state, () => guardFailures(step.value, state))
1668
- };
1669
- }, error => {
1670
- throw guardOperation(state, () => sanitizeServerError(error));
1671
- });
1672
- return {
1673
- next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
1674
- return: () => {
1675
- close();
1676
- return Promise.resolve({
1677
- done: true,
1678
- value: undefined
1679
- });
1680
- }
1681
- };
1682
- }
1683
- };
1684
- state.seen.set(value, guardedIterable);
1685
- return guardedIterable;
1686
- }
1687
- if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1688
- const scopedIterable = scopeDeferredResult(value, state.scope);
1689
- state.seen.set(value, scopedIterable);
1690
- return scopedIterable;
1691
- }
1692
- if (Array.isArray(value)) {
1693
- const next = value.slice();
1694
- state.seen.set(value, next);
1695
- return new Frame(ARRAY, value, next, value, null);
1696
- }
1697
- if (value instanceof Map) {
1698
- const next = new Map();
1699
- state.seen.set(value, next);
1700
- const items = [];
1701
- for (const entry of value) items.push(entry[0], entry[1]);
1702
- return new Frame(MAP, value, next, items, null);
1703
- }
1704
- if (value instanceof Set) {
1705
- const next = new Set();
1706
- state.seen.set(value, next);
1707
- return new Frame(SET, value, next, [...value], null);
1708
- }
1709
- const prototype = Object.getPrototypeOf(value);
1710
- if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
1711
- state.seen.set(value, value);
1712
- return value;
1713
- }
1714
- const descriptors = Object.getOwnPropertyDescriptors(value);
1715
- for (const key of Object.keys(descriptors)) {
1716
- descriptors[key].configurable = true;
1717
- if ("value" in descriptors[key]) descriptors[key].writable = true;
1718
- }
1719
- const next = Object.create(prototype, descriptors);
1720
- state.seen.set(value, next);
1721
- const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
1722
- const descriptor = descriptors[key];
1723
- return descriptor.enumerable || "value" in descriptor;
1724
- });
1725
- return new Frame(OBJECT, value, next, children, descriptors);
1726
- }
1727
- function keepGuarded(value, next, changed, state) {
1728
- if (changed || state.cyclic.has(value)) return next;
1729
- state.seen.set(value, value);
1730
- return value;
1731
- }
1732
- function serializeResponseStream(value, codecOptions, signal, scope) {
1733
- let closed = false;
1734
- let streamController = null;
1735
- let demandWaiters = null;
1736
- const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
1737
- const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
1738
- const supplyDemand = () => {
1739
- const resolvers = demandWaiters;
1740
- demandWaiters = null;
1741
- if (resolvers) for (const resolve of resolvers) resolve();
1742
- };
1743
- const sourceClosers = new Set();
1744
- const gate = {
1745
- wantsMore,
1746
- awaitDemand,
1747
- onOpen(close) {
1748
- if (closed) close();else sourceClosers.add(close);
1749
- }
1750
- };
1751
- const guardState = {
1752
- seen: new WeakMap(),
1753
- cyclic: new WeakSet(),
1754
- gate,
1755
- scope
1756
- };
1757
- value = guardOperation(guardState, () => guardFailures(value, guardState));
1758
- let cancelSerialize = null;
1759
- let onAbort = null;
1760
- const finishSource = () => {
1761
- for (const close of sourceClosers) close();
1762
- sourceClosers.clear();
1763
- supplyDemand();
1764
- };
1765
- const teardown = () => {
1766
- if (closed) return;
1767
- closed = true;
1768
- if (onAbort) signal.removeEventListener("abort", onAbort);
1769
- if (cancelSerialize) cancelSerialize();
1770
- finishSource();
1771
- };
1772
- return new ReadableStream({
1773
- async start(controller) {
1774
- streamController = controller;
1775
- if (signal) {
1776
- if (signal.aborted) {
1777
- teardown();
1778
- controller.close();
1779
- return;
1780
- }
1781
- onAbort = () => {
1782
- const alreadyClosed = closed;
1783
- teardown();
1784
- if (!alreadyClosed) {
1785
- try {
1786
- controller.error(signal.reason || new Error("The operation was aborted."));
1787
- } catch {}
1788
- }
1789
- };
1790
- signal.addEventListener("abort", onAbort);
1791
- }
1792
- const {
1793
- serializeJSON
1794
- } = await import('@solidjs/web/serialization');
1795
- if (closed) {
1796
- try {
1797
- controller.close();
1798
- } catch {}
1799
- return;
1800
- }
1801
- cancelSerialize = serializeJSON(value, {
1802
- ...codecOptions,
1803
- onParse(node) {
1804
- if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
1805
- },
1806
- onDone() {
1807
- if (closed) return;
1808
- closed = true;
1809
- if (onAbort) signal.removeEventListener("abort", onAbort);
1810
- finishSource();
1811
- controller.close();
1812
- },
1813
- onError(error) {
1814
- if (closed) return;
1815
- closed = true;
1816
- if (onAbort) signal.removeEventListener("abort", onAbort);
1817
- finishSource();
1818
- try {
1819
- const delivered = sanitizeServerError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error);
1820
- controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
1821
- controller.close();
1822
- } catch {
1823
- try {
1824
- controller.error(error);
1825
- } catch {}
1826
- }
1827
- }
1828
- });
1829
- },
1830
- pull() {
1831
- supplyDemand();
1832
- },
1833
- cancel() {
1834
- teardown();
1835
- }
1836
- });
1837
- }
1838
- function serializedResponse(value, headers, codec, signal, scope) {
1839
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
1840
- headers.set("Content-Type", "text/plain");
1841
- return new Response(serializeResponseStream(value, codec, signal, scope), {
1842
- headers
1843
- });
1844
- }
1845
- function encodeResult(value, headers, status, codec, signal, scope) {
1846
- if (NULL_BODY_STATUSES.has(status)) {
1847
- if (value === undefined || value === null) {
1848
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
1849
- return new Response(null, {
1850
- status,
1851
- headers
1852
- });
1853
- }
1854
- const error = new Error(`Server function answered status ${status}, which forbids a response body, with a value. ` + `Return respond(undefined, { status: ${status} }) for a bodiless answer, or drop the ` + `status to send the value.`);
1855
- headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
1856
- return encodeResult(error, headers, 500, codec, signal, scope);
1857
- }
1858
- const direct = getHeadersAndBody(value);
1859
- if (direct) {
1860
- for (const [key, val] of Object.entries(direct.headers || {})) {
1861
- headers.set(key, val);
1862
- }
1863
- return new Response(direct.body, {
1864
- status,
1865
- headers
1866
- });
1867
- }
1868
- if (value === undefined) {
1869
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
1870
- return new Response(null, {
1871
- status,
1872
- headers
1873
- });
1874
- }
1875
- try {
1876
- const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
1877
- if (jsonSafe) {
1878
- headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
1879
- headers.set("Content-Type", "application/json");
1880
- const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
1881
- return new Response(body, {
1882
- status,
1883
- headers
1884
- });
1885
- }
1886
- } catch {
1887
- }
1888
- try {
1889
- const response = serializedResponse(value, headers, codec, signal, scope);
1890
- return status === 200 ? response : new Response(response.body, {
1891
- status,
1892
- headers
1893
- });
1894
- } catch (error) {
1895
- throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
1896
- }
1897
- }
1898
- const ERROR_HEADER_VALUE_LIMIT = 1024;
1899
- function boundedErrorHeaderValue(message) {
1900
- let label = message.length > 256 ? message.slice(0, 256) : message;
1901
- let encoded = encodeErrorHeaderValue(label);
1902
- while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
1903
- label = label.slice(0, Math.ceil(label.length / 2));
1904
- encoded = encodeErrorHeaderValue(label);
1905
- }
1906
- return encoded;
1907
- }
1908
- const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
1909
- let DEV = false === true;
1910
- function setServerFunctionsDev(dev) {
1911
- DEV = !!dev;
1912
- }
1913
- function sanitizeServerError(value) {
1914
- if (DEV) return value;
1915
- if (isSafeError(value)) return value;
1916
- return new Error(GENERIC_SERVER_ERROR_MESSAGE);
1917
- }
1918
- function observeServerFunctionCalls() {
1919
- return () => {};
1920
- }
1921
- function serverFunctionUrl(id, boundArgs) {
1922
- const address = serverFunctionAddress(config.endpoint, id);
1923
- if (!boundArgs || !boundArgs.length) return address;
1924
- if (!isJSONSafe(boundArgs)) {
1925
- throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
1926
- }
1927
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
1928
- }
1929
- function parseServerFunctionUrl(url) {
1930
- const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
1931
- return parsed && parsed.id;
1932
- }
1933
- async function matchesOrigin(origin, request, matcher) {
1934
- if (matcher === undefined) return origin === new URL(request.url).origin;
1935
- if (typeof matcher === "function") return (await matcher(origin, request)) === true;
1936
- return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
1937
- }
1938
- async function allowsServerFunctionRequest(request, options) {
1939
- const fetchSite = request.headers.get("Sec-Fetch-Site");
1940
- if (fetchSite === "same-origin") return true;
1941
- if (fetchSite === "same-site" || fetchSite === "cross-site" || fetchSite === "none") {
1942
- return false;
1943
- }
1944
- const origin = request.headers.get("Origin");
1945
- if (origin !== null) return matchesOrigin(origin, request, options.origin);
1946
- const referer = request.headers.get("Referer");
1947
- if (referer !== null) {
1948
- try {
1949
- return matchesOrigin(new URL(referer).origin, request, options.origin);
1950
- } catch {
1951
- return false;
1952
- }
1953
- }
1954
- return options.allowRequestsWithoutOriginCheck === true;
1955
- }
1956
- const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
1957
- function withCSRFVary(response) {
1958
- const current = response.headers.get("Vary");
1959
- if (current === "*") return response;
1960
- const values = current ? current.split(",").map(value => value.trim()) : [];
1961
- const names = new Set(values.map(value => value.toLowerCase()));
1962
- for (const value of CSRF_VARY) {
1963
- if (!names.has(value.toLowerCase())) values.push(value);
1964
- }
1965
- const vary = values.join(", ");
1966
- try {
1967
- response.headers.set("Vary", vary);
1968
- return response;
1969
- } catch {
1970
- const headers = new Headers(response.headers);
1971
- headers.set("Vary", vary);
1972
- return new Response(response.body, {
1973
- status: response.status,
1974
- statusText: response.statusText,
1975
- headers
1976
- });
1977
- }
1978
- }
1979
- function forbiddenResponse() {
1980
- return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
1981
- status: 403,
1982
- headers: {
1983
- "Cache-Control": "no-store"
1984
- }
1985
- }));
1986
- }
1987
- function nativePromise(value) {
1988
- if (value instanceof Promise) return value;
1989
- try {
1990
- if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
1991
- } catch {}
1992
- }
1993
- async function handleServerFunctionRequest(request, options = {}) {
1994
- const codec = {
1995
- ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
1996
- };
1997
- codec.serializeErrorStacks ??= DEV;
1998
- const url = new URL(request.url);
1999
- const method = request.method;
2000
- const address = resolveAddress(url);
2001
- const functionId = address && address.id;
2002
- const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
2003
- const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
2004
- const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
2005
- let serverFunction;
2006
- if (functionId) {
2007
- try {
2008
- serverFunction = getServerFunction(functionId);
2009
- } catch {
2010
- return finalizeTransportResponse(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
2011
- status: 404,
2012
- headers: {
2013
- [UNKNOWN_HEADER]: "true"
2014
- }
2015
- }), method);
2016
- }
2017
- }
2018
- if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
2019
- return finalizeTransportResponse(forbiddenResponse(), method);
2020
- }
2021
- const instance = request.headers.get(INSTANCE_HEADER);
2022
- if (!functionId) {
2023
- const response = new Response(DEV ? "Server function not found" : null, {
2024
- status: 404
2025
- });
2026
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2027
- }
2028
- const scripted = address.data;
2029
- if (method !== "POST" && !declaredRead) {
2030
- const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
2031
- status: 405,
2032
- headers: {
2033
- Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
2034
- }
2035
- });
2036
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2037
- }
2038
- const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
2039
- const argsEncoding = url.searchParams.get("args");
2040
- if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
2041
- const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
2042
- status: 413
2043
- });
2044
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2045
- }
2046
- if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
2047
- const raw = request.headers.get("content-length");
2048
- const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
2049
- if (declared > bodySizeLimit) {
2050
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2051
- status: 413
2052
- });
2053
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2054
- }
2055
- let bounded;
2056
- try {
2057
- bounded = await bufferBodyWithin(request, bodySizeLimit);
2058
- } catch {
2059
- const response = new Response(DEV ? "Malformed server function arguments" : null, {
2060
- status: 400
2061
- });
2062
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2063
- }
2064
- if (bounded === null) {
2065
- const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2066
- status: 413
2067
- });
2068
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2069
- }
2070
- request = bounded;
2071
- }
2072
- let event;
2073
- try {
2074
- event = options.createEvent ? options.createEvent(request) : {
2075
- request,
2076
- locals: {}
2077
- };
2078
- const promised = nativePromise(event);
2079
- if (promised) event = await promised;
2080
- } catch (error) {
2081
- const safe = sanitizeServerError(error);
2082
- const message = safe instanceof Error ? safe.message : String(safe);
2083
- const headers = new Headers();
2084
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2085
- const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2086
- status: 500
2087
- });
2088
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2089
- }
2090
- const refuseCommitted = raw => {
2091
- const response = commitEventResponse(raw, event);
2092
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2093
- };
2094
- const provide = options.provideEvent || provideEvent;
2095
- const scope = run => provide(event, run);
2096
- const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
2097
- const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
2098
- const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
2099
- const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
2100
- let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
2101
- if (handleNoJS === undefined && !scripted && isFormPost(request)) {
2102
- const fetchMode = request.headers.get("Sec-Fetch-Mode");
2103
- if (fetchMode === null || fetchMode === "navigate") {
2104
- handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
2105
- } else {
2106
- const response = new Response(DEV ? "The bare server-function address answers form navigations with the " + "no-JS redirect convention. Scripted callers use the data address " + `(…/data/${functionId}) or send the ${BODY_FORMAT_HEADER} tag.` : null, {
2107
- status: 400
2108
- });
2109
- return refuseCommitted(response);
2110
- }
2111
- }
2112
- const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
2113
- const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
2114
- const hook = source === "true" ? flightHook : flightSources.get(source);
2115
- return hook ? [[source, hook]] : [];
2116
- }) : [];
2117
- const collectsFlight = flightHooks.length > 0;
2118
- let parsed;
2119
- try {
2120
- parsed = await parseArguments(request, url, scripted, codec);
2121
- } catch (error) {
2122
- const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2123
- const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
2124
- status: 400
2125
- });
2126
- return refuseCommitted(response);
2127
- }
2128
- const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
2129
- if (parsed.length > maxArguments) {
2130
- const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
2131
- status: 400
2132
- });
2133
- return refuseCommitted(response);
2134
- }
2135
- const flightContext = {
2136
- id: functionId,
2137
- args: parsed,
2138
- instance,
2139
- request,
2140
- collectsFlight,
2141
- codec,
2142
- transformFlightResult
2143
- };
2144
- const headers = new Headers();
2145
- const dispatch = async () => {
2146
- try {
2147
- const invokeOnce = async () => {
2148
- INVOCATIONS.set(event, {
2149
- id: functionId
2150
- });
2151
- const run = () => serverFunction(...parsed);
2152
- return wrapInvocation ? wrapInvocation(run, {
2153
- id: functionId,
2154
- args: parsed,
2155
- event,
2156
- request,
2157
- direct: false
2158
- }) : run();
2159
- };
2160
- let result = await provideEventOnce(provide, event, invokeOnce);
2161
- if (transformResult) {
2162
- result = await transformResult(event, result, flightContext);
2163
- }
2164
- let status = 200;
2165
- let metadata;
2166
- if (isResponseEnvelope(result)) {
2167
- const {
2168
- response,
2169
- value
2170
- } = result;
2171
- if (!scripted && !handleNoJS && response && response.body) {
2172
- return response;
2173
- }
2174
- if (response && response.headers) {
2175
- mergeResponseHeaders(headers, response.headers);
2176
- }
2177
- if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
2178
- status = response.status;
2179
- } else if (response && response.status) {
2180
- maskRedirect(headers, response, request.url);
2181
- }
2182
- metadata = response;
2183
- result = value;
2184
- } else if (result instanceof Response) {
2185
- if (result.headers && result.headers.has("X-Content-Raw")) return result;
2186
- if (scripted) {
2187
- if (result.headers) {
2188
- mergeResponseHeaders(headers, result.headers);
2189
- }
2190
- if (result.status && !validRedirectStatuses.has(result.status)) {
2191
- status = result.status;
2192
- } else if (result.status) {
2193
- maskRedirect(headers, result, request.url);
2194
- }
2195
- metadata = result;
2196
- if (result.body == null) {
2197
- result = null;
2198
- }
2199
- }
2200
- }
2201
- if (collectsFlight) {
2202
- result = await foldFlightData(flightHooks, event, headers, {
2203
- id: functionId,
2204
- value: result,
2205
- response: metadata,
2206
- request,
2207
- thrown: false
2208
- }, flightContext);
2209
- if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
2210
- }
2211
- if (!scripted) {
2212
- if (handleNoJS) {
2213
- return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2214
- }
2215
- if (result instanceof Response) return result;
2216
- return encodeResult(result, headers, status, codec, request.signal, scope);
2217
- }
2218
- if (status === 304) warnScripted304(functionId);
2219
- return encodeResult(result, headers, status, codec, request.signal, scope);
2220
- } catch (x) {
2221
- const respondThrown = value => {
2222
- const safe = sanitizeServerError(value);
2223
- if (!scripted) {
2224
- if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2225
- const message = safe instanceof Error ? safe.message : String(safe);
2226
- return new Response(DEV ? message : null, {
2227
- status: 500
2228
- });
2229
- }
2230
- const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
2231
- headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2232
- return encodeResult(safe, headers, 500, codec, request.signal, scope);
2233
- };
2234
- if (transformResult) {
2235
- try {
2236
- x = await transformResult(event, x, {
2237
- ...flightContext,
2238
- thrown: true
2239
- });
2240
- } catch (hookError) {
2241
- return respondThrown(hookError);
2242
- }
2243
- }
2244
- if (x instanceof Response || isResponseEnvelope(x)) {
2245
- let status = 200;
2246
- let metadata;
2247
- if (isResponseEnvelope(x)) {
2248
- const {
2249
- response,
2250
- value
2251
- } = x;
2252
- if (response && response.headers) {
2253
- mergeResponseHeaders(headers, response.headers);
2254
- }
2255
- if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
2256
- status = response.status;
2257
- } else if (response && response.status) {
2258
- maskRedirect(headers, response, request.url);
2259
- }
2260
- metadata = response;
2261
- x = value;
2262
- } else if (x instanceof Response) {
2263
- if (x.headers) {
2264
- mergeResponseHeaders(headers, x.headers);
2265
- }
2266
- if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
2267
- status = x.status;
2268
- } else if (x.status) {
2269
- maskRedirect(headers, x, request.url);
2270
- }
2271
- metadata = x;
2272
- if (x.body == null) {
2273
- x = null;
2274
- }
2275
- }
2276
- if (collectsFlight) {
2277
- x = await foldFlightData(flightHooks, event, headers, {
2278
- id: functionId,
2279
- value: x,
2280
- response: metadata,
2281
- request,
2282
- thrown: true
2283
- }, flightContext);
2284
- if (x instanceof Response && x.headers.has("X-Content-Raw")) {
2285
- x = ownResponse(x);
2286
- x.headers.set(ERROR_HEADER, "true");
2287
- return x;
2288
- }
2289
- }
2290
- headers.set(ERROR_HEADER, "true");
2291
- if (!scripted) {
2292
- if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
2293
- if (x instanceof Response) return x;
2294
- }
2295
- if (scripted && status === 304) warnScripted304(functionId);
2296
- return encodeResult(x, headers, status, codec, request.signal, scope);
2297
- }
2298
- return respondThrown(x);
2299
- }
2300
- };
2301
- const response = commitEventResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())), event);
2302
- return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2303
- }
2304
- function ownResponse(response) {
2305
- try {
2306
- return new Response(response.body, response);
2307
- } catch {
2308
- return response;
2309
- }
2310
- }
2311
- function finalizeTransportResponse(response, method) {
2312
- const stripBody = method === "HEAD" && response.body !== null;
2313
- const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
2314
- if (stripBody || defaultsCache) {
2315
- try {
2316
- if (defaultsCache) {
2317
- response.headers.set("Cache-Control", "no-store");
2318
- }
2319
- if (!stripBody) return response;
2320
- response.body.cancel().catch(() => {});
2321
- return new Response(null, {
2322
- status: response.status,
2323
- statusText: response.statusText,
2324
- headers: response.headers
2325
- });
2326
- } catch {
2327
- const headers = new Headers(response.headers);
2328
- if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
2329
- if (stripBody) response.body.cancel().catch(() => {});
2330
- return new Response(stripBody ? null : response.body, {
2331
- status: response.status,
2332
- statusText: response.statusText,
2333
- headers
2334
- });
2335
- }
2336
- }
2337
- return response;
2338
- }
2339
-
2340
- exports.ERROR_HEADER = ERROR_HEADER;
2341
- exports.FLASH_COOKIE = FLASH_COOKIE;
2342
- exports.GENERIC_SERVER_ERROR_MESSAGE = GENERIC_SERVER_ERROR_MESSAGE;
2343
- exports.GET = GET;
2344
- exports.INSTANCE_HEADER = INSTANCE_HEADER;
2345
- exports.REDIRECT_HEADER = REDIRECT_HEADER;
2346
- exports.SERVER_FUNCTION_INVOKE = SERVER_FUNCTION_INVOKE;
2347
- exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
2348
- exports.UNKNOWN_HEADER = UNKNOWN_HEADER;
2349
- exports.clearFlashCookie = clearFlashCookie;
2350
- exports.configureServerFunctionsServer = configureServerFunctionsServer;
2351
- exports.createNoJSHandler = createNoJSHandler;
2352
- exports.createServerReference = createServerReference;
2353
- exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
2354
- exports.decodeFlashCookie = decodeFlashCookie;
2355
- exports.decodeRedirectHeaderValue = decodeRedirectHeaderValue;
2356
- exports.decodeResponse = decodeResponse;
2357
- exports.decodeResponsePayload = decodeResponsePayload;
2358
- exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
2359
- exports.encodeFlashCookie = encodeFlashCookie;
2360
- exports.foldSetCookies = foldSetCookies;
2361
- exports.getEventServerFunctionInvocation = getEventServerFunctionInvocation;
2362
- exports.getServerFunction = getServerFunction;
2363
- exports.getServerFunctionInvocation = getServerFunctionInvocation;
2364
- exports.getServerFunctionMetadata = getServerFunctionMetadata;
2365
- exports.guardFailures = guardFailures;
2366
- exports.handleServerFunctionRequest = handleServerFunctionRequest;
2367
- exports.hasFlashCookie = hasFlashCookie;
2368
- exports.invoke = invoke;
2369
- exports.isServerFunction = isServerFunction;
2370
- exports.live = live;
2371
- exports.observeServerFunctionCalls = observeServerFunctionCalls;
2372
- exports.parseServerFunctionUrl = parseServerFunctionUrl;
2373
- exports.registerFlightDataSource = registerFlightDataSource;
2374
- exports.registerServerFunction = registerServerFunction;
2375
- exports.registerServerReference = registerServerReference;
2376
- exports.sanitizeServerError = sanitizeServerError;
2377
- exports.serializeResponseStream = serializeResponseStream;
2378
- exports.serverFunctionUrl = serverFunctionUrl;
2379
- exports.setServerFunctionsDev = setServerFunctionsDev;
2380
- exports.subscribeFlightData = subscribeFlightData;
2381
- exports.withMeta = withMeta;