@solidjs/web 2.0.0-experimental.9 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +22 -4
  2. package/dist/dev.cjs +1588 -224
  3. package/dist/dev.js +1513 -200
  4. package/dist/server.cjs +2722 -254
  5. package/dist/server.js +2659 -245
  6. package/dist/web.cjs +1524 -218
  7. package/dist/web.js +1449 -194
  8. package/frames/dist/client.cjs +1916 -0
  9. package/frames/dist/client.dev.cjs +1933 -0
  10. package/frames/dist/client.dev.js +1921 -0
  11. package/frames/dist/client.js +1904 -0
  12. package/frames/dist/server.cjs +3756 -0
  13. package/frames/dist/server.js +3743 -0
  14. package/frames/package.json +30 -0
  15. package/package.json +350 -37
  16. package/serialization/decode/package.json +20 -0
  17. package/serialization/dist/decode.cjs +122 -0
  18. package/serialization/dist/decode.js +116 -0
  19. package/serialization/dist/serialization.cjs +244 -0
  20. package/serialization/dist/serialization.js +227 -0
  21. package/serialization/package.json +20 -0
  22. package/serialization/types/index.d.ts +182 -0
  23. package/serialization/types/serializer-decode.d.ts +182 -0
  24. package/serialization/types-cjs/index.d.cts +182 -0
  25. package/serialization/types-cjs/package.json +3 -0
  26. package/serialization/types-cjs/serializer-decode.d.cts +182 -0
  27. package/server-functions/dist/client.cjs +793 -0
  28. package/server-functions/dist/client.js +763 -0
  29. package/server-functions/dist/rich-args.cjs +11 -0
  30. package/server-functions/dist/rich-args.js +9 -0
  31. package/server-functions/dist/server.cjs +1171 -0
  32. package/server-functions/dist/server.dev.cjs +1171 -0
  33. package/server-functions/dist/server.dev.js +1137 -0
  34. package/server-functions/dist/server.js +1137 -0
  35. package/server-functions/package.json +40 -0
  36. package/server-functions/rich-args/package.json +20 -0
  37. package/storage/package.json +8 -3
  38. package/storage/types/index.d.ts +26 -0
  39. package/storage/types-cjs/index.d.cts +28 -0
  40. package/storage/types-cjs/package.json +3 -0
  41. package/types/client.d.ts +290 -27
  42. package/types/cookies.d.ts +93 -0
  43. package/types/core.d.ts +6 -2
  44. package/types/frames/client.d.ts +36 -0
  45. package/types/frames/frame-client.d.ts +338 -0
  46. package/types/frames/frame-sink.d.ts +194 -0
  47. package/types/frames/frame-transport.d.ts +222 -0
  48. package/types/frames/serializer.d.ts +182 -0
  49. package/types/frames/server.d.ts +52 -0
  50. package/types/index.d.ts +223 -24
  51. package/types/jsx-properties.d.ts +93 -0
  52. package/types/jsx.d.ts +4159 -1
  53. package/types/response.d.ts +174 -0
  54. package/types/serializer-decode.d.ts +182 -0
  55. package/types/serializer.d.ts +182 -0
  56. package/types/server-functions/client.d.ts +231 -0
  57. package/types/server-functions/flash.d.ts +38 -0
  58. package/types/server-functions/rich-args.d.ts +10 -0
  59. package/types/server-functions/server.d.ts +616 -0
  60. package/types/server-functions/shared.d.ts +523 -0
  61. package/types/server-mock.d.ts +249 -12
  62. package/types/server.d.ts +424 -51
  63. package/types-cjs/client.d.cts +337 -0
  64. package/types-cjs/cookies.d.cts +93 -0
  65. package/types-cjs/core.d.cts +6 -0
  66. package/types-cjs/frames/client.d.cts +36 -0
  67. package/types-cjs/frames/frame-client.d.cts +338 -0
  68. package/types-cjs/frames/frame-sink.d.cts +194 -0
  69. package/types-cjs/frames/frame-transport.d.cts +222 -0
  70. package/types-cjs/frames/serializer.d.cts +182 -0
  71. package/types-cjs/frames/server.d.cts +52 -0
  72. package/types-cjs/index.d.cts +244 -0
  73. package/types-cjs/jsx-properties.d.cts +93 -0
  74. package/types-cjs/jsx.d.cts +4159 -0
  75. package/types-cjs/package.json +3 -0
  76. package/types-cjs/response.d.cts +174 -0
  77. package/types-cjs/serializer-decode.d.cts +182 -0
  78. package/types-cjs/serializer.d.cts +182 -0
  79. package/types-cjs/server-functions/client.d.cts +231 -0
  80. package/types-cjs/server-functions/flash.d.cts +38 -0
  81. package/types-cjs/server-functions/rich-args.d.cts +10 -0
  82. package/types-cjs/server-functions/server.d.cts +616 -0
  83. package/types-cjs/server-functions/shared.d.cts +523 -0
  84. package/types-cjs/server-mock.d.cts +277 -0
  85. package/types-cjs/server.d.cts +523 -0
@@ -0,0 +1,1137 @@
1
+ import { sharedConfig } from 'solid-js';
2
+
3
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
4
+ function isResponseEnvelope(value) {
5
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
6
+ }
7
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
8
+ function isSafeError(value) {
9
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
10
+ }
11
+ const REVALIDATE_HEADER = "X-Revalidate";
12
+
13
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
14
+ function getServerFunctionMetadata(fn) {
15
+ if (typeof fn !== "function") return undefined;
16
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
17
+ }
18
+ function isServerFunction(fn) {
19
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
20
+ }
21
+ function withMeta(fn, meta) {
22
+ const metadata = getServerFunctionMetadata(fn);
23
+ if (!metadata) {
24
+ throw new Error("withMeta expects a server function reference");
25
+ }
26
+ Object.assign(metadata, meta);
27
+ return fn;
28
+ }
29
+ const LIVE_SOURCE = Symbol.for("solid.LiveSource");
30
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
31
+ function provideServerFunctionRPC(rpc) {
32
+ globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
33
+ }
34
+
35
+ function parseCookieHeader(header) {
36
+ const cookies = {};
37
+ if (!header) return cookies;
38
+ for (const part of header.split(";")) {
39
+ const eq = part.indexOf("=");
40
+ if (eq < 0) continue;
41
+ const name = decodeSafe(part.slice(0, eq).trim());
42
+ let value = part.slice(eq + 1).trim();
43
+ if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
44
+ value = value.slice(1, -1);
45
+ }
46
+ cookies[name] = decodeSafe(value);
47
+ }
48
+ return cookies;
49
+ }
50
+ function decodeSafe(text) {
51
+ try {
52
+ return decodeURIComponent(text);
53
+ } catch {
54
+ return text;
55
+ }
56
+ }
57
+ function serializeCookie(name, value, options = {}) {
58
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
59
+ cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
60
+ if (options.domain) cookie += `; Domain=${options.domain}`;
61
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
62
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
63
+ if (options.httpOnly) cookie += "; HttpOnly";
64
+ if (options.secure) cookie += "; Secure";
65
+ if (options.sameSite) {
66
+ const sameSite = options.sameSite.toLowerCase();
67
+ cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
68
+ }
69
+ return cookie;
70
+ }
71
+ const FLASH_COOKIE = "flash";
72
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
73
+ function hasFlashCookie(cookieHeader) {
74
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
75
+ }
76
+ function clearFlashCookie() {
77
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
78
+ }
79
+
80
+ const codecConfig = {
81
+ codec: undefined
82
+ };
83
+ function configureServerFunctionsCodec(codec) {
84
+ codecConfig.codec = codec;
85
+ }
86
+ function getServerFunctionsCodec() {
87
+ return codecConfig.codec;
88
+ }
89
+ function subscribeFlightData(consumer) {
90
+ return () => {
91
+ };
92
+ }
93
+ const FUNCTION_HEADER = "X-Server-Function-Id";
94
+ const ERROR_HEADER = "X-Server-Function-Error";
95
+ const ERROR_HEADER_MARKER = "=?1?";
96
+ const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
97
+ function encodeErrorHeaderValue(value) {
98
+ let stripped = String(value).replace(/[\r\n]+/g, "");
99
+ if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
100
+ return stripped;
101
+ }
102
+ if (typeof stripped.toWellFormed === "function") {
103
+ stripped = stripped.toWellFormed();
104
+ } else {
105
+ stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
106
+ }
107
+ return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
108
+ }
109
+ function decodeErrorHeaderValue(value) {
110
+ if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
111
+ return value;
112
+ }
113
+ try {
114
+ return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
115
+ } catch {
116
+ return value;
117
+ }
118
+ }
119
+ const INSTANCE_HEADER = "X-Server-Function-Instance";
120
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
121
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
122
+ const FILE_FORM_KEY = "__server_function_file__";
123
+ const BodyFormat = {
124
+ Serialized: "0",
125
+ String: "1",
126
+ FormData: "2",
127
+ URLSearchParams: "3",
128
+ Blob: "4",
129
+ File: "5",
130
+ ArrayBuffer: "6",
131
+ Uint8Array: "7",
132
+ Json: "8"
133
+ };
134
+ const JSON_SAFE_DEPTH_LIMIT = 4096;
135
+ const EXIT = {};
136
+ function isJSONSafe(value) {
137
+ const stack = [value];
138
+ const ancestors = new Set();
139
+ while (stack.length) {
140
+ const v = stack.pop();
141
+ if (v === EXIT) {
142
+ ancestors.delete(stack.pop());
143
+ continue;
144
+ }
145
+ if (v === null) continue;
146
+ const t = typeof v;
147
+ if (t === "string" || t === "boolean") continue;
148
+ if (t === "number") {
149
+ if (!Number.isFinite(v)) return false;
150
+ continue;
151
+ }
152
+ if (t !== "object") return false;
153
+ if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
154
+ ancestors.add(v);
155
+ stack.push(v, EXIT);
156
+ if (Array.isArray(v)) {
157
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
158
+ } else {
159
+ const proto = Object.getPrototypeOf(v);
160
+ if (proto !== Object.prototype && proto !== null) return false;
161
+ if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
162
+ for (const k in v) stack.push(v[k]);
163
+ }
164
+ }
165
+ return true;
166
+ }
167
+ function getHeadersAndBody(body) {
168
+ switch (true) {
169
+ case typeof body === "string":
170
+ return {
171
+ headers: {
172
+ "Content-Type": "text/plain",
173
+ [BODY_FORMAT_HEADER]: BodyFormat.String
174
+ },
175
+ body
176
+ };
177
+ case body instanceof FormData:
178
+ return {
179
+ headers: {
180
+ [BODY_FORMAT_HEADER]: BodyFormat.FormData
181
+ },
182
+ body
183
+ };
184
+ case body instanceof URLSearchParams:
185
+ return {
186
+ headers: {
187
+ "Content-Type": "application/x-www-form-urlencoded",
188
+ [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
189
+ },
190
+ body
191
+ };
192
+ case typeof File !== "undefined" && body instanceof File:
193
+ {
194
+ const formData = new FormData();
195
+ formData.append(FILE_FORM_KEY, body, body.name);
196
+ return {
197
+ headers: {
198
+ [BODY_FORMAT_HEADER]: BodyFormat.File
199
+ },
200
+ body: formData
201
+ };
202
+ }
203
+ case body instanceof Blob:
204
+ return {
205
+ headers: {
206
+ [BODY_FORMAT_HEADER]: BodyFormat.Blob
207
+ },
208
+ body
209
+ };
210
+ case body instanceof ArrayBuffer:
211
+ return {
212
+ headers: {
213
+ [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
214
+ },
215
+ body
216
+ };
217
+ case body instanceof Uint8Array:
218
+ return {
219
+ headers: {
220
+ [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
221
+ },
222
+ body: new Uint8Array(body)
223
+ };
224
+ default:
225
+ return undefined;
226
+ }
227
+ }
228
+ async function extractBody(source, codecOptions) {
229
+ const contentType = source.headers.get("content-type");
230
+ const format = source.headers.get(BODY_FORMAT_HEADER);
231
+ const clone = source.clone();
232
+ switch (true) {
233
+ case format === BodyFormat.Serialized:
234
+ return await deserializeStream(clone, codecOptions);
235
+ case format === BodyFormat.Json:
236
+ return JSON.parse(await clone.text());
237
+ case format === BodyFormat.String:
238
+ return await clone.text();
239
+ case format === BodyFormat.File:
240
+ {
241
+ const formData = await clone.formData();
242
+ return formData.get(FILE_FORM_KEY);
243
+ }
244
+ case format === BodyFormat.FormData:
245
+ case contentType && contentType.startsWith("multipart/form-data"):
246
+ return await clone.formData();
247
+ case format === BodyFormat.URLSearchParams:
248
+ case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
249
+ return new URLSearchParams(await clone.text());
250
+ case format === BodyFormat.Blob:
251
+ return await clone.blob();
252
+ case format === BodyFormat.ArrayBuffer:
253
+ return await clone.arrayBuffer();
254
+ case format === BodyFormat.Uint8Array:
255
+ return new Uint8Array(await clone.arrayBuffer());
256
+ }
257
+ return undefined;
258
+ }
259
+ function createChunk(data) {
260
+ const encoder = new TextEncoder();
261
+ const encodeData = encoder.encode(data);
262
+ const bytes = encodeData.length;
263
+ const chunk = new Uint8Array(12 + bytes);
264
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
265
+ chunk.set(encodeData, 12);
266
+ return chunk;
267
+ }
268
+ class ChunkReader {
269
+ constructor(stream) {
270
+ this.reader = stream.getReader();
271
+ this.buffer = new Uint8Array(0);
272
+ this.done = false;
273
+ }
274
+ async readChunk() {
275
+ const chunk = await this.reader.read();
276
+ if (!chunk.done) {
277
+ const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
278
+ newBuffer.set(this.buffer);
279
+ newBuffer.set(chunk.value, this.buffer.length);
280
+ this.buffer = newBuffer;
281
+ } else {
282
+ this.done = true;
283
+ }
284
+ }
285
+ async next() {
286
+ while (this.buffer.length < 12) {
287
+ if (this.done) {
288
+ if (this.buffer.length === 0) return {
289
+ done: true,
290
+ value: undefined
291
+ };
292
+ throw new Error("Malformed server function stream.");
293
+ }
294
+ await this.readChunk();
295
+ }
296
+ const decoder = new TextDecoder();
297
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
298
+ if (Number.isNaN(bytes)) {
299
+ throw new Error("Malformed server function stream.");
300
+ }
301
+ while (bytes > this.buffer.length - 12) {
302
+ if (this.done) {
303
+ throw new Error("Malformed server function stream.");
304
+ }
305
+ await this.readChunk();
306
+ }
307
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
308
+ this.buffer = this.buffer.subarray(12 + bytes);
309
+ return {
310
+ done: false,
311
+ value: partial
312
+ };
313
+ }
314
+ async drain(interpret) {
315
+ while (true) {
316
+ const result = await this.next();
317
+ if (result.done) {
318
+ break;
319
+ }
320
+ interpret(result.value);
321
+ }
322
+ }
323
+ }
324
+ async function deserializeStream(source, codecOptions) {
325
+ if (!source.body) {
326
+ throw new Error("missing body");
327
+ }
328
+ const reader = new ChunkReader(source.body);
329
+ const result = await reader.next();
330
+ if (!result.done) {
331
+ const {
332
+ createJSONDeserializer
333
+ } = await import('@solidjs/web/serialization/decode');
334
+ const deserializeChunk = createJSONDeserializer(codecOptions);
335
+ function interpretChunk(chunk) {
336
+ return deserializeChunk(JSON.parse(chunk));
337
+ }
338
+ reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
339
+ return interpretChunk(result.value);
340
+ }
341
+ return undefined;
342
+ }
343
+ async function deserializeString(text, codecOptions) {
344
+ return await deserializeStream(new Response(text), codecOptions);
345
+ }
346
+ async function decodeResponse(response, codecOptions) {
347
+ if (!response.body) return undefined;
348
+ return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
349
+ }
350
+ async function decodeResponsePayload(response, codecOptions) {
351
+ const decoded = await decodeResponse(response, codecOptions);
352
+ if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
353
+ return {
354
+ value: decoded.value,
355
+ flightData: decoded.data
356
+ };
357
+ }
358
+ return {
359
+ value: decoded
360
+ };
361
+ }
362
+
363
+ const RequestContext = Symbol.for("solid.RequestContext");
364
+ function getRequestEvent() {
365
+ return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && 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;
366
+ }
367
+ function reportLostHeaderWrite(method, name) {
368
+ 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).";
369
+ throw new Error(message);
370
+ }
371
+ function commitResponseStub(stub, {
372
+ allowLateLocation = false
373
+ } = {}) {
374
+ if (!stub || stub.committed) return stub;
375
+ stub.committed = true;
376
+ const headers = stub.headers;
377
+ if (!headers || typeof headers.set !== "function") return stub;
378
+ for (const method of ["set", "append", "delete"]) {
379
+ const original = headers[method].bind(headers);
380
+ headers[method] = function (name, ...rest) {
381
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
382
+ return original(name, ...rest);
383
+ }
384
+ reportLostHeaderWrite(method, name);
385
+ };
386
+ }
387
+ return stub;
388
+ }
389
+ function copyInitHeaders(init) {
390
+ if (!init || !init.getSetCookie) return new Headers(init);
391
+ const headers = new Headers();
392
+ init.forEach((value, key) => {
393
+ if (key !== "set-cookie") headers.append(key, value);
394
+ });
395
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
396
+ return headers;
397
+ }
398
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
399
+ function fillsStubGap(key, headers, response) {
400
+ if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
401
+ if (response.body === null && (key === "content-type" || key === "content-length")) return false;
402
+ return !headers.has(key);
403
+ }
404
+ function commitEventResponse(response, event = getRequestEvent()) {
405
+ const stub = event && event.response;
406
+ if (!stub || !stub.headers || stub.committed) return response;
407
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
408
+ commitResponseStub(stub);
409
+ let hasGaps = false;
410
+ stub.headers.forEach((value, key) => {
411
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
412
+ });
413
+ if (!cookies.length && !hasGaps) return response;
414
+ try {
415
+ for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
416
+ stub.headers.forEach((value, key) => {
417
+ if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
418
+ });
419
+ return response;
420
+ } catch {
421
+ const headers = copyInitHeaders(response.headers);
422
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
423
+ stub.headers.forEach((value, key) => {
424
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
425
+ });
426
+ return new Response(response.body, {
427
+ status: response.status,
428
+ statusText: response.statusText,
429
+ headers
430
+ });
431
+ }
432
+ }
433
+
434
+ function encodeInputValue(value) {
435
+ if (value instanceof FormData) return {
436
+ $f: [...value.entries()].filter(([, v]) => typeof v === "string")
437
+ };
438
+ if (value instanceof URLSearchParams) return {
439
+ $u: [...value.entries()]
440
+ };
441
+ return value;
442
+ }
443
+ function decodeInputValue(value) {
444
+ if (value && typeof value === "object") {
445
+ if (Array.isArray(value.$f)) {
446
+ const form = new FormData();
447
+ for (const [k, v] of value.$f) form.append(k, v);
448
+ return form;
449
+ }
450
+ if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
451
+ }
452
+ return value;
453
+ }
454
+ function encodeFlashCookie(url, result, input, thrown) {
455
+ const isError = result instanceof Error;
456
+ const payload = {
457
+ url,
458
+ result: isError ? result.message : result,
459
+ error: isError,
460
+ thrown: !!thrown,
461
+ input: input.map(encodeInputValue)
462
+ };
463
+ return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
464
+ secure: true,
465
+ httpOnly: true
466
+ });
467
+ }
468
+ function decodeFlashCookie(cookieHeader) {
469
+ const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
470
+ if (!match) return;
471
+ try {
472
+ const payload = JSON.parse(match);
473
+ if (!payload || !payload.result) return;
474
+ const result = payload.error ? new Error(payload.result) : payload.result;
475
+ return {
476
+ input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
477
+ url: payload.url,
478
+ result: payload.thrown ? undefined : result,
479
+ error: payload.thrown ? result : undefined
480
+ };
481
+ } catch (error) {
482
+ console.error(error);
483
+ }
484
+ }
485
+
486
+ const config = {
487
+ provideEvent: undefined,
488
+ wrapInvocation: undefined,
489
+ collectFlightData: undefined,
490
+ transformResult: undefined,
491
+ transformFlightResult: undefined,
492
+ transformDirectResult: undefined,
493
+ handleNoJS: undefined,
494
+ endpoint: "/_server"
495
+ };
496
+ function configureServerFunctionsServer({
497
+ provideEvent,
498
+ wrapInvocation,
499
+ collectFlightData,
500
+ transformResult,
501
+ transformFlightResult,
502
+ transformDirectResult,
503
+ handleNoJS,
504
+ endpoint,
505
+ codec
506
+ } = {}) {
507
+ if (provideEvent !== undefined) config.provideEvent = provideEvent;
508
+ if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
509
+ if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
510
+ if (transformResult !== undefined) config.transformResult = transformResult;
511
+ if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
512
+ if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
513
+ if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
514
+ if (endpoint !== undefined) config.endpoint = endpoint;
515
+ if (codec !== undefined) configureServerFunctionsCodec(codec);
516
+ }
517
+ function provideEvent(event, fn) {
518
+ if (config.provideEvent) return config.provideEvent(event, fn);
519
+ const ctx = globalThis[RequestContext];
520
+ if (ctx) return ctx.run(event, fn);
521
+ throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
522
+ }
523
+ const REGISTRATIONS = new Map();
524
+ const METHODS = new Map();
525
+ const INVOCATIONS = new WeakMap();
526
+ let rpcProvided = false;
527
+ function provideRPC() {
528
+ if (rpcProvided) return;
529
+ rpcProvided = true;
530
+ provideServerFunctionRPC({
531
+ GET,
532
+ decodeResponse
533
+ });
534
+ }
535
+ function registerServerFunction(id, callback) {
536
+ provideRPC();
537
+ REGISTRATIONS.set(id, callback);
538
+ return callback;
539
+ }
540
+ function getServerFunction(id) {
541
+ const fn = REGISTRATIONS.get(id);
542
+ if (fn) {
543
+ return fn;
544
+ }
545
+ throw new Error("invalid server function: " + id);
546
+ }
547
+ function registerServerReference(id, fn, name) {
548
+ registerServerFunction(id, fn);
549
+ return {
550
+ id,
551
+ fn,
552
+ name
553
+ };
554
+ }
555
+ function createServerReference({
556
+ id,
557
+ fn,
558
+ name
559
+ }) {
560
+ if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
561
+ provideRPC();
562
+ const metadata = name === undefined ? {} : {
563
+ name
564
+ };
565
+ return new Proxy(fn, {
566
+ get(target, prop) {
567
+ if (prop === "id") return id;
568
+ if (prop === "url") {
569
+ return `${config.endpoint}?id=${encodeURIComponent(id)}`;
570
+ }
571
+ if (prop === SERVER_FUNCTION_METADATA) return metadata;
572
+ return target[prop];
573
+ },
574
+ apply(target, thisArg, args) {
575
+ const ogEvt = getRequestEvent();
576
+ if (!ogEvt) throw new Error("Cannot call server function outside of a request");
577
+ const evt = {
578
+ ...ogEvt
579
+ };
580
+ INVOCATIONS.set(evt, {
581
+ id
582
+ });
583
+ evt.serverOnly = true;
584
+ const result = provideEvent(evt, () => {
585
+ const run = () => fn.apply(thisArg, args);
586
+ return config.wrapInvocation ? config.wrapInvocation(run, {
587
+ id,
588
+ args,
589
+ event: evt,
590
+ direct: true
591
+ }) : run();
592
+ });
593
+ const transform = config.transformDirectResult;
594
+ if (transform && result && typeof result.then === "function") {
595
+ return result.then(value => transform(value, {
596
+ id,
597
+ args,
598
+ event: evt
599
+ }));
600
+ }
601
+ return transform ? transform(result, {
602
+ id,
603
+ args,
604
+ event: evt
605
+ }) : result;
606
+ }
607
+ });
608
+ }
609
+ function GET(fn) {
610
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
611
+ throw new Error("GET expects a server function reference");
612
+ }
613
+ METHODS.set(fn.id, "GET");
614
+ return withMeta(fn, {
615
+ method: "GET"
616
+ });
617
+ }
618
+ function live(fn) {
619
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
620
+ throw new Error("live expects a server function reference");
621
+ }
622
+ const metadata = {
623
+ ...getServerFunctionMetadata(fn),
624
+ live: true
625
+ };
626
+ const wrapped = async (...args) => {
627
+ const result = await fn(...args);
628
+ if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
629
+ result[LIVE_SOURCE] = true;
630
+ }
631
+ return result;
632
+ };
633
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
634
+ wrapped.id = fn.id;
635
+ Object.defineProperty(wrapped, "url", {
636
+ get: () => fn.url,
637
+ configurable: true
638
+ });
639
+ return wrapped;
640
+ }
641
+ function getServerFunctionInvocation() {
642
+ return getEventServerFunctionInvocation(getRequestEvent());
643
+ }
644
+ function getEventServerFunctionInvocation(event) {
645
+ return event && INVOCATIONS.get(event);
646
+ }
647
+ function resolveFunctionId(request, url) {
648
+ const reference = request.headers.get(FUNCTION_HEADER);
649
+ if (reference) {
650
+ return reference.split("#")[0];
651
+ }
652
+ return url.searchParams.get("id");
653
+ }
654
+ async function parseArguments(request, url, instance, codec) {
655
+ const parsed = [];
656
+ const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
657
+ if (!instance || request.method === "GET" || bodyFormat !== BodyFormat.Serialized) {
658
+ const args = url.searchParams.get("args");
659
+ if (args) {
660
+ const result = args.startsWith(";0x") ? await deserializeString(args, codec) : JSON.parse(args);
661
+ for (const arg of result) {
662
+ parsed.push(arg);
663
+ }
664
+ }
665
+ }
666
+ if (request.method === "POST" && request.body !== null) {
667
+ const decoded = await extractBody(request.clone(), codec);
668
+ if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
669
+ return decoded;
670
+ }
671
+ parsed.push(decoded);
672
+ }
673
+ return parsed;
674
+ }
675
+ async function foldFlightData(hook, event, headers, outcome, context = {}) {
676
+ if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
677
+ digestOutcome(event, outcome);
678
+ const data = await hook(event, outcome);
679
+ if (data === undefined) return outcome.value;
680
+ headers.set(SINGLE_FLIGHT_HEADER, "true");
681
+ if (context.transformFlightResult) {
682
+ const transformed = await context.transformFlightResult(event, {
683
+ value: outcome.value,
684
+ data
685
+ }, context);
686
+ if (transformed !== undefined) {
687
+ for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
688
+ headers.forEach((value, key) => {
689
+ if (key !== "set-cookie" && !transformed.headers.has(key)) {
690
+ transformed.headers.set(key, value);
691
+ }
692
+ });
693
+ return transformed;
694
+ }
695
+ }
696
+ return outcome.value === undefined ? {
697
+ data
698
+ } : {
699
+ value: outcome.value,
700
+ data
701
+ };
702
+ }
703
+ function digestOutcome(event, outcome) {
704
+ const {
705
+ request,
706
+ response
707
+ } = outcome;
708
+ outcome.revalidateKeys = response?.headers.get(REVALIDATE_HEADER)?.split(",");
709
+ outcome.foldedHeaders = foldSetCookies(request.headers, [...(event.response?.headers?.getSetCookie() ?? []), ...(response?.headers?.getSetCookie() ?? [])]);
710
+ try {
711
+ const referrer = request.headers.get("referer");
712
+ if (referrer) {
713
+ const location = response?.headers.get("Location");
714
+ const target = location ? new URL(location, request.url) : new URL(referrer);
715
+ if (target.origin === new URL(request.url).origin) outcome.targetUrl = target.toString();
716
+ }
717
+ } catch {
718
+ }
719
+ }
720
+ function parseSetCookie(setCookie) {
721
+ const [pair, ...attributes] = setCookie.split(";");
722
+ const eq = pair.indexOf("=");
723
+ if (eq < 0) return undefined;
724
+ const parsed = {
725
+ name: pair.slice(0, eq).trim(),
726
+ value: pair.slice(eq + 1).trim()
727
+ };
728
+ for (const attribute of attributes) {
729
+ const attrEq = attribute.indexOf("=");
730
+ const key = (attrEq < 0 ? attribute : attribute.slice(0, attrEq)).trim().toLowerCase();
731
+ const value = attrEq < 0 ? "" : attribute.slice(attrEq + 1).trim();
732
+ if (key === "max-age") parsed.maxAge = Number(value);else if (key === "expires") parsed.expires = new Date(value);
733
+ }
734
+ return parsed;
735
+ }
736
+ function foldSetCookies(headers, setCookies) {
737
+ const folded = new Headers(headers);
738
+ if (!setCookies.length) return folded;
739
+ const cookies = {};
740
+ for (const pair of folded.get("cookie")?.split(";") ?? []) {
741
+ const eq = pair.indexOf("=");
742
+ if (eq > -1) cookies[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
743
+ }
744
+ for (const setCookie of setCookies) {
745
+ const parsed = parseSetCookie(setCookie);
746
+ if (!parsed) continue;
747
+ if (parsed.maxAge != null && parsed.maxAge <= 0 || parsed.expires != null && parsed.expires.getTime() <= Date.now()) {
748
+ delete cookies[parsed.name];
749
+ } else {
750
+ cookies[parsed.name] = parsed.value;
751
+ }
752
+ }
753
+ folded.delete("cookie");
754
+ const serialized = Object.entries(cookies).map(([name, value]) => `${name}=${value}`).join("; ");
755
+ if (serialized) folded.set("cookie", serialized);
756
+ return folded;
757
+ }
758
+ function mergeResponseHeaders(target, source) {
759
+ source.forEach((value, key) => {
760
+ if (key !== "set-cookie") target.append(key, value);
761
+ });
762
+ if (source.getSetCookie) {
763
+ for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
764
+ } else if (source.has("set-cookie")) {
765
+ target.append("Set-Cookie", source.get("set-cookie"));
766
+ }
767
+ }
768
+ const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
769
+ function createNoJSHandler({
770
+ base = ""
771
+ } = {}) {
772
+ return function handleNoJS(result, request, args, thrown) {
773
+ const url = new URL(request.url);
774
+ let back = new URL(base || "/", url.origin).toString();
775
+ try {
776
+ const referer = request.headers.get("referer");
777
+ if (referer) back = new URL(referer).toString();
778
+ } catch {}
779
+ let status = 303;
780
+ let headers;
781
+ if (result instanceof Response) {
782
+ headers = new Headers();
783
+ mergeResponseHeaders(headers, result.headers);
784
+ if (result.headers.has("Location")) {
785
+ headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
786
+ if (validRedirectStatuses.has(result.status)) status = result.status;
787
+ } else {
788
+ headers.set("Location", back);
789
+ }
790
+ headers.delete("Content-Type");
791
+ headers.delete("Content-Length");
792
+ } else {
793
+ headers = new Headers({
794
+ Location: back
795
+ });
796
+ }
797
+ if (result && !(result instanceof Response)) {
798
+ headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
799
+ }
800
+ return new Response(null, {
801
+ status,
802
+ headers
803
+ });
804
+ };
805
+ }
806
+ let defaultNoJSHandler;
807
+ function isFormPost(request) {
808
+ if (request.method !== "POST" || request.headers.has(BODY_FORMAT_HEADER)) return false;
809
+ const type = request.headers.get("content-type") || "";
810
+ return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
811
+ }
812
+ function serializeResponseStream(value, codecOptions, signal) {
813
+ let closeIterator = null;
814
+ let closed = false;
815
+ let cancelSerialize = null;
816
+ let onAbort = null;
817
+ const teardown = () => {
818
+ if (closed) return;
819
+ closed = true;
820
+ if (onAbort) signal.removeEventListener("abort", onAbort);
821
+ if (cancelSerialize) cancelSerialize();
822
+ if (closeIterator) closeIterator();
823
+ };
824
+ if (value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
825
+ const source = value;
826
+ value = {
827
+ [Symbol.asyncIterator]() {
828
+ const it = source[Symbol.asyncIterator]();
829
+ let finished = false;
830
+ closeIterator = () => {
831
+ if (finished) return;
832
+ finished = true;
833
+ try {
834
+ const returned = it.return && it.return();
835
+ if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
836
+ } catch {}
837
+ };
838
+ if (closed) closeIterator();
839
+ return {
840
+ next: () => finished ? Promise.resolve({
841
+ done: true,
842
+ value: undefined
843
+ }) : it.next()
844
+ };
845
+ }
846
+ };
847
+ }
848
+ return new ReadableStream({
849
+ async start(controller) {
850
+ if (signal) {
851
+ if (signal.aborted) {
852
+ teardown();
853
+ controller.close();
854
+ return;
855
+ }
856
+ onAbort = () => {
857
+ const alreadyClosed = closed;
858
+ teardown();
859
+ if (!alreadyClosed) {
860
+ try {
861
+ controller.error(signal.reason || new Error("The operation was aborted."));
862
+ } catch {}
863
+ }
864
+ };
865
+ signal.addEventListener("abort", onAbort);
866
+ }
867
+ const {
868
+ serializeJSON
869
+ } = await import('@solidjs/web/serialization');
870
+ if (closed) {
871
+ try {
872
+ controller.close();
873
+ } catch {}
874
+ return;
875
+ }
876
+ cancelSerialize = serializeJSON(value, {
877
+ ...codecOptions,
878
+ onParse(node) {
879
+ if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
880
+ },
881
+ onDone() {
882
+ if (closed) return;
883
+ closed = true;
884
+ if (onAbort) signal.removeEventListener("abort", onAbort);
885
+ controller.close();
886
+ },
887
+ onError(error) {
888
+ if (closed) return;
889
+ closed = true;
890
+ if (onAbort) signal.removeEventListener("abort", onAbort);
891
+ controller.error(error);
892
+ }
893
+ });
894
+ },
895
+ cancel() {
896
+ teardown();
897
+ }
898
+ });
899
+ }
900
+ function serializedResponse(value, headers, codec, signal) {
901
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
902
+ headers.set("Content-Type", "text/plain");
903
+ return new Response(serializeResponseStream(value, codec, signal), {
904
+ headers
905
+ });
906
+ }
907
+ function encodeResult(value, headers, status, codec, signal) {
908
+ const direct = getHeadersAndBody(value);
909
+ if (direct) {
910
+ for (const [key, val] of Object.entries(direct.headers || {})) {
911
+ headers.set(key, val);
912
+ }
913
+ return new Response(direct.body, {
914
+ status,
915
+ headers
916
+ });
917
+ }
918
+ if (value === undefined) {
919
+ return new Response(null, {
920
+ status,
921
+ headers
922
+ });
923
+ }
924
+ try {
925
+ if (isJSONSafe(value)) {
926
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
927
+ headers.set("Content-Type", "application/json");
928
+ return new Response(JSON.stringify(value), {
929
+ status,
930
+ headers
931
+ });
932
+ }
933
+ } catch {
934
+ }
935
+ const response = serializedResponse(value, headers, codec, signal);
936
+ return status === 200 ? response : new Response(response.body, {
937
+ status,
938
+ headers
939
+ });
940
+ }
941
+ const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
942
+ let DEV = true === true;
943
+ function setServerFunctionsDev(dev) {
944
+ DEV = !!dev;
945
+ }
946
+ function sanitizeServerError(value) {
947
+ if (DEV) return value;
948
+ if (isSafeError(value)) return value;
949
+ return new Error(GENERIC_SERVER_ERROR_MESSAGE);
950
+ }
951
+ async function handleServerFunctionRequest(request, options = {}) {
952
+ const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
953
+ const url = new URL(request.url);
954
+ const instance = request.headers.get(INSTANCE_HEADER);
955
+ const functionId = resolveFunctionId(request, url);
956
+ if (!functionId) {
957
+ return new Response(DEV ? "Server function not found" : null, {
958
+ status: 404
959
+ });
960
+ }
961
+ let serverFunction;
962
+ try {
963
+ serverFunction = getServerFunction(functionId);
964
+ } catch {
965
+ return new Response(DEV ? `Unknown server function: ${functionId}` : null, {
966
+ status: 404
967
+ });
968
+ }
969
+ if (request.method === "GET" && METHODS.get(functionId) !== "GET") {
970
+ return new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
971
+ status: 405,
972
+ headers: {
973
+ Allow: "POST"
974
+ }
975
+ });
976
+ }
977
+ const event = options.createEvent ? options.createEvent(request) : {
978
+ request,
979
+ locals: {}
980
+ };
981
+ const provide = options.provideEvent || provideEvent;
982
+ const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
983
+ const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
984
+ const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
985
+ const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
986
+ const handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS !== undefined ? config.handleNoJS : isFormPost(request) ? defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler()) : undefined;
987
+ const collectsFlight = !!(flightHook && instance && request.headers.has(SINGLE_FLIGHT_HEADER));
988
+ const parsed = await parseArguments(request, url, instance, codec);
989
+ const flightContext = {
990
+ id: functionId,
991
+ args: parsed,
992
+ instance,
993
+ request,
994
+ collectsFlight,
995
+ codec,
996
+ transformFlightResult
997
+ };
998
+ const headers = new Headers();
999
+ const dispatch = async () => {
1000
+ try {
1001
+ let result = await provide(event, async () => {
1002
+ INVOCATIONS.set(event, {
1003
+ id: functionId
1004
+ });
1005
+ const run = () => serverFunction(...parsed);
1006
+ return wrapInvocation ? wrapInvocation(run, {
1007
+ id: functionId,
1008
+ args: parsed,
1009
+ event,
1010
+ request,
1011
+ direct: false
1012
+ }) : run();
1013
+ });
1014
+ if (transformResult) {
1015
+ result = await transformResult(event, result, flightContext);
1016
+ }
1017
+ let status = 200;
1018
+ let metadata;
1019
+ if (isResponseEnvelope(result)) {
1020
+ const {
1021
+ response,
1022
+ value
1023
+ } = result;
1024
+ if (!instance && !handleNoJS && response && response.body) {
1025
+ return response;
1026
+ }
1027
+ if (response && response.headers) {
1028
+ mergeResponseHeaders(headers, response.headers);
1029
+ }
1030
+ if (response && response.status && (response.status < 300 || response.status >= 400)) {
1031
+ status = response.status;
1032
+ }
1033
+ metadata = response;
1034
+ result = value;
1035
+ } else if (result instanceof Response) {
1036
+ if (result.headers && result.headers.has("X-Content-Raw")) return result;
1037
+ if (instance) {
1038
+ if (result.headers) {
1039
+ mergeResponseHeaders(headers, result.headers);
1040
+ }
1041
+ if (result.status && (result.status < 300 || result.status >= 400)) {
1042
+ status = result.status;
1043
+ }
1044
+ metadata = result;
1045
+ if (result.body == null) {
1046
+ result = null;
1047
+ }
1048
+ }
1049
+ }
1050
+ if (collectsFlight) {
1051
+ result = await foldFlightData(flightHook, event, headers, {
1052
+ id: functionId,
1053
+ value: result,
1054
+ response: metadata,
1055
+ request,
1056
+ thrown: false
1057
+ }, flightContext);
1058
+ if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1059
+ }
1060
+ if (!instance) {
1061
+ if (handleNoJS) return handleNoJS(result, request, parsed);
1062
+ if (result instanceof Response) return result;
1063
+ return encodeResult(result, headers, 200, codec, request.signal);
1064
+ }
1065
+ return encodeResult(result, headers, status, codec, request.signal);
1066
+ } catch (x) {
1067
+ if (x instanceof Response || isResponseEnvelope(x)) {
1068
+ if (transformResult) {
1069
+ x = await transformResult(event, x, {
1070
+ ...flightContext,
1071
+ thrown: true
1072
+ });
1073
+ }
1074
+ let status = 200;
1075
+ let metadata;
1076
+ if (isResponseEnvelope(x)) {
1077
+ const {
1078
+ response,
1079
+ value
1080
+ } = x;
1081
+ if (response && response.headers) {
1082
+ mergeResponseHeaders(headers, response.headers);
1083
+ }
1084
+ if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
1085
+ status = response.status;
1086
+ }
1087
+ metadata = response;
1088
+ x = value;
1089
+ } else if (x instanceof Response) {
1090
+ if (x.headers) {
1091
+ mergeResponseHeaders(headers, x.headers);
1092
+ }
1093
+ if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
1094
+ status = x.status;
1095
+ }
1096
+ metadata = x;
1097
+ if (x.body == null) {
1098
+ x = null;
1099
+ }
1100
+ }
1101
+ if (collectsFlight) {
1102
+ x = await foldFlightData(flightHook, event, headers, {
1103
+ id: functionId,
1104
+ value: x,
1105
+ response: metadata,
1106
+ request,
1107
+ thrown: true
1108
+ }, flightContext);
1109
+ if (x instanceof Response && x.headers.has("X-Content-Raw")) {
1110
+ x.headers.set(ERROR_HEADER, "true");
1111
+ return x;
1112
+ }
1113
+ }
1114
+ headers.set(ERROR_HEADER, "true");
1115
+ if (!instance) {
1116
+ if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
1117
+ if (x instanceof Response) return x;
1118
+ }
1119
+ return encodeResult(x, headers, status, codec, request.signal);
1120
+ }
1121
+ const safe = sanitizeServerError(x);
1122
+ if (!instance) {
1123
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1124
+ const message = safe instanceof Error ? safe.message : String(safe);
1125
+ return new Response(DEV ? message : null, {
1126
+ status: 500
1127
+ });
1128
+ }
1129
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1130
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
1131
+ return encodeResult(safe, headers, 200, codec, request.signal);
1132
+ }
1133
+ };
1134
+ return commitEventResponse(await dispatch(), event);
1135
+ }
1136
+
1137
+ export { ERROR_HEADER, FLASH_COOKIE, FUNCTION_HEADER, GENERIC_SERVER_ERROR_MESSAGE, GET, INSTANCE_HEADER, SINGLE_FLIGHT_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, handleServerFunctionRequest, hasFlashCookie, isServerFunction, live, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, setServerFunctionsDev, subscribeFlightData, withMeta };