@solidjs/web 2.0.0-beta.3 → 2.0.0-beta.30

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