@solidjs/web 2.0.0-beta.31 → 2.0.0-beta.32

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