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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/server.dev.js +15 -2
  2. package/dist/server.js +15 -2
  3. package/dist/web.dev.js +41 -9
  4. package/dist/web.js +39 -8
  5. package/dist/{web.cjs → web.observe.js} +137 -239
  6. package/frames/dist/server.dev.js +19 -0
  7. package/frames/dist/server.js +19 -0
  8. package/frames/package.json +6 -24
  9. package/package.json +81 -314
  10. package/serialization/decode/package.json +3 -9
  11. package/serialization/package.json +3 -9
  12. package/serialization/types/serializer-decode.d.ts +49 -2
  13. package/server-functions/dist/server.dev.js +28 -10
  14. package/server-functions/dist/server.js +28 -10
  15. package/server-functions/package.json +6 -24
  16. package/server-functions/rich-args/package.json +3 -9
  17. package/storage/package.json +3 -9
  18. package/types/client.d.ts +17 -0
  19. package/types/frames/serializer-decode.d.ts +49 -2
  20. package/types/serializer-decode.d.ts +49 -2
  21. package/types/server-functions/server.d.ts +27 -4
  22. package/types/server.d.ts +1 -1
  23. package/dist/server.cjs +0 -3708
  24. package/dist/server.dev.cjs +0 -3794
  25. package/dist/web.dev.cjs +0 -2285
  26. package/frames/dist/client.cjs +0 -2043
  27. package/frames/dist/client.dev.cjs +0 -2063
  28. package/frames/dist/server.cjs +0 -4542
  29. package/frames/dist/server.dev.cjs +0 -4584
  30. package/serialization/dist/decode.cjs +0 -155
  31. package/serialization/dist/serialization.cjs +0 -275
  32. package/serialization/types-cjs/index.d.cts +0 -101
  33. package/serialization/types-cjs/package.json +0 -3
  34. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  35. package/serialization/types-cjs/serializer.d.cts +0 -101
  36. package/server-functions/dist/client.cjs +0 -1069
  37. package/server-functions/dist/rich-args.cjs +0 -11
  38. package/server-functions/dist/server.cjs +0 -2381
  39. package/server-functions/dist/server.dev.cjs +0 -2409
  40. package/storage/dist/storage.cjs +0 -12
  41. package/storage/types-cjs/index.d.cts +0 -28
  42. package/storage/types-cjs/package.json +0 -3
  43. package/types-cjs/client.d.cts +0 -197
  44. package/types-cjs/constants.d.cts +0 -20
  45. package/types-cjs/cookies.d.cts +0 -41
  46. package/types-cjs/frames/client.d.cts +0 -36
  47. package/types-cjs/frames/frame-client.d.cts +0 -370
  48. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  49. package/types-cjs/frames/frame-sink.d.cts +0 -92
  50. package/types-cjs/frames/frame-transport.d.cts +0 -189
  51. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  52. package/types-cjs/frames/serializer.d.cts +0 -101
  53. package/types-cjs/frames/server.d.cts +0 -52
  54. package/types-cjs/head.d.cts +0 -19
  55. package/types-cjs/index.d.cts +0 -191
  56. package/types-cjs/index.server.d.cts +0 -147
  57. package/types-cjs/jsx-properties.d.cts +0 -93
  58. package/types-cjs/jsx.d.cts +0 -4146
  59. package/types-cjs/package.json +0 -3
  60. package/types-cjs/reconcile.d.cts +0 -1
  61. package/types-cjs/render.d.cts +0 -6
  62. package/types-cjs/response.d.cts +0 -81
  63. package/types-cjs/serializer-decode.d.cts +0 -172
  64. package/types-cjs/serializer.d.cts +0 -101
  65. package/types-cjs/server-functions/client.d.cts +0 -184
  66. package/types-cjs/server-functions/flash.d.cts +0 -36
  67. package/types-cjs/server-functions/registry.d.cts +0 -100
  68. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  69. package/types-cjs/server-functions/server.d.cts +0 -546
  70. package/types-cjs/server-functions/shared.d.cts +0 -283
  71. package/types-cjs/server-mock.d.cts +0 -337
  72. package/types-cjs/server.d.cts +0 -408
@@ -1,1069 +0,0 @@
1
- 'use strict';
2
-
3
- const REVALIDATE_HEADER = "X-Revalidate";
4
-
5
- const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
6
- function getServerFunctionMetadata(fn) {
7
- if (typeof fn !== "function") return undefined;
8
- return fn[SERVER_FUNCTION_METADATA] || undefined;
9
- }
10
- function isServerFunction(fn) {
11
- return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
12
- }
13
- function withMeta(fn, meta) {
14
- const metadata = getServerFunctionMetadata(fn);
15
- if (!metadata) {
16
- throw new Error("withMeta expects a server function reference");
17
- }
18
- Object.assign(metadata, meta);
19
- return fn;
20
- }
21
- const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
22
- const INVOKE_OPTION_REDIRECTS = {
23
- headers: "Session-dynamic headers belong to the prepareRequest hook, declaration metadata to " + "withMeta(fn, meta), and data belongs in the arguments, where it is serialized, typed, " + "and part of the cache key.",
24
- method: "The method is declaration-scoped: declare the function with GET(fn).",
25
- body: "The arguments are the body: pass them in the args array.",
26
- timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
27
- };
28
- function invoke(fn, options, ...args) {
29
- const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
30
- if (!channel) {
31
- throw new Error(isServerFunction(fn) ? "invoke: this wrapper does not forward the invocation channel " + "(SERVER_FUNCTION_INVOKE). Wrappers that share calls (caches, channels) opt in " + "deliberately — a caller's signal cannot own a wire other callers share. Invoke " + "the underlying reference directly, or use the wrapper's own per-call idioms." : "invoke expects a server function reference (or a wrapper that forwards its " + "invocation channel). Per-call options apply at the transport; for a data " + "layer's calls, use its per-call options instead.");
32
- }
33
- if (options === null || typeof options !== "object") {
34
- throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
35
- }
36
- const picked = {};
37
- for (const key in options) {
38
- if (key !== "signal" && key !== "keepalive" && key !== "priority") {
39
- throw new Error(`\`${key}\` is not an invocation option. ` + (INVOKE_OPTION_REDIRECTS[key] || "Options here are strictly invocation-scoped (they vary between calls of the " + "same function): signal, keepalive, priority."));
40
- }
41
- }
42
- if (options.signal !== undefined) picked.signal = options.signal;
43
- if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
44
- if (options.priority !== undefined) picked.priority = options.priority;
45
- return channel(args, picked);
46
- }
47
- const LIVE_SOURCE = Symbol.for("solid.LiveSource");
48
- const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
49
- function provideServerFunctionRPC(rpc) {
50
- globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
51
- }
52
-
53
- const FLASH_COOKIE = "flash";
54
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
55
- function hasFlashCookie(cookieHeader) {
56
- return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
57
- }
58
- function clearFlashCookie() {
59
- return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
60
- }
61
-
62
- const codecConfig = {
63
- codec: undefined
64
- };
65
- function configureServerFunctionsCodec(codec) {
66
- codecConfig.codec = codec;
67
- }
68
- function getServerFunctionsCodec() {
69
- return codecConfig.codec;
70
- }
71
- const UNNAMED_FLIGHT_SOURCE = "true";
72
- const flightConfig = {
73
- consumers: new Map()
74
- };
75
- function assertFlightSource(source) {
76
- if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
77
- throw new TypeError(`Invalid flight data source id "${source}": ids ride the ` + `${SINGLE_FLIGHT_HEADER} header as a comma-separated list, and "true" is ` + `reserved for the unnamed registration (the bare consumer/hook signatures).`);
78
- }
79
- }
80
- function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
81
- const named = typeof sourceOrConsumer === "string";
82
- if (named) assertFlightSource(sourceOrConsumer);
83
- const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
84
- const consumer = named ? maybeConsumer : sourceOrConsumer;
85
- flightConfig.consumers.set(source, consumer);
86
- return () => {
87
- if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
88
- };
89
- }
90
- function getFlightDataConsumer(source) {
91
- return flightConfig.consumers.get(source === undefined ? UNNAMED_FLIGHT_SOURCE : source);
92
- }
93
- function getFlightDataSourceIds() {
94
- return [...flightConfig.consumers.keys()];
95
- }
96
- function frameAddress(id, args) {
97
- return args && args.length ? id + ":" + hashArguments(args) : id;
98
- }
99
- function hashArguments(args) {
100
- let hash = 0;
101
- const text = stableString(args);
102
- for (let i = 0; i < text.length; i++) {
103
- hash = (hash << 5) - hash + text.charCodeAt(i);
104
- hash |= 0;
105
- }
106
- return (hash >>> 0).toString(36);
107
- }
108
- function stableString(value, seen) {
109
- if (value === null || typeof value !== "object") {
110
- return typeof value === "bigint" ? value + "n" : String(value);
111
- }
112
- if (value instanceof Date) return "Date:" + value.getTime();
113
- seen || (seen = new Set());
114
- if (seen.has(value)) return "~";
115
- seen.add(value);
116
- if (value instanceof Map) {
117
- const entries = [];
118
- for (const [k, v] of value) {
119
- entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
120
- }
121
- return "Map{" + entries.sort().join(",") + "}";
122
- }
123
- if (value instanceof Set) {
124
- const members = [];
125
- for (const v of value) members.push(stableString(v, seen));
126
- return "Set{" + members.sort().join(",") + "}";
127
- }
128
- if (Array.isArray(value)) {
129
- let out = "[";
130
- for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
131
- return out + "]";
132
- }
133
- const keys = Object.keys(value).sort();
134
- let out = "{";
135
- for (let i = 0; i < keys.length; i++) {
136
- out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
137
- }
138
- return out + "}";
139
- }
140
- function serverFunctionAddress(endpoint, id) {
141
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
142
- return `${mount}/${encodeURIComponent(id)}`;
143
- }
144
- function serverFunctionDataAddress(endpoint, id) {
145
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
146
- return `${mount}/data/${encodeURIComponent(id)}`;
147
- }
148
- function parseServerFunctionAddress(pathname, endpoint) {
149
- const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
150
- if (!pathname.startsWith(mount)) return null;
151
- const rest = pathname.slice(mount.length);
152
- if (!rest.startsWith("/")) return null;
153
- let segment = rest.slice(1);
154
- let data = false;
155
- if (segment.startsWith("data/")) {
156
- segment = segment.slice(5);
157
- data = true;
158
- }
159
- if (!segment || segment.includes("/")) return null;
160
- try {
161
- return {
162
- id: decodeURIComponent(segment),
163
- data
164
- };
165
- } catch {
166
- return null;
167
- }
168
- }
169
- const ERROR_HEADER = "X-Server-Function-Error";
170
- const ERROR_HEADER_MARKER = "=?1?";
171
- const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
172
- function encodeErrorHeaderValue(value) {
173
- let stripped = String(value).replace(/[\r\n]+/g, "");
174
- if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
175
- return stripped;
176
- }
177
- if (typeof stripped.toWellFormed === "function") {
178
- stripped = stripped.toWellFormed();
179
- } else {
180
- stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
181
- }
182
- return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
183
- }
184
- function decodeErrorHeaderValue(value) {
185
- if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
186
- return value;
187
- }
188
- try {
189
- return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
190
- } catch {
191
- return value;
192
- }
193
- }
194
- const INSTANCE_HEADER = "X-Server-Function-Instance";
195
- const BODY_FORMAT_HEADER = "X-Server-Function-Format";
196
- const UNKNOWN_HEADER = "X-Server-Function-Unknown";
197
- const REDIRECT_HEADER = "X-Server-Function-Redirect";
198
- function decodeRedirectHeaderValue(value) {
199
- if (typeof value !== "string") return undefined;
200
- const at = value.indexOf(" ");
201
- if (at < 0) return undefined;
202
- const status = Number(value.slice(0, at));
203
- const url = value.slice(at + 1);
204
- if (!Number.isInteger(status) || !url) return undefined;
205
- if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
206
- let parsed;
207
- try {
208
- parsed = new URL(url);
209
- } catch {
210
- return undefined;
211
- }
212
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
213
- return {
214
- status,
215
- url
216
- };
217
- }
218
- const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
219
- const FILE_FORM_KEY = "__server_function_file__";
220
- const BodyFormat = {
221
- Serialized: "0",
222
- String: "1",
223
- FormData: "2",
224
- URLSearchParams: "3",
225
- Blob: "4",
226
- File: "5",
227
- ArrayBuffer: "6",
228
- Uint8Array: "7",
229
- Json: "8",
230
- Void: "9"
231
- };
232
- const JSON_SAFE_DEPTH_LIMIT = 4096;
233
- const EXIT = {};
234
- function isJSONSafe(value) {
235
- const stack = [value];
236
- const ancestors = new Set();
237
- while (stack.length) {
238
- const v = stack.pop();
239
- if (v === EXIT) {
240
- ancestors.delete(stack.pop());
241
- continue;
242
- }
243
- if (v === null) continue;
244
- const t = typeof v;
245
- if (t === "string" || t === "boolean") continue;
246
- if (t === "number") {
247
- if (!Number.isFinite(v) || Object.is(v, -0)) return false;
248
- continue;
249
- }
250
- if (t !== "object") return false;
251
- if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
252
- ancestors.add(v);
253
- stack.push(v, EXIT);
254
- if (Array.isArray(v)) {
255
- for (let i = 0; i < v.length; i++) stack.push(v[i]);
256
- } else {
257
- const proto = Object.getPrototypeOf(v);
258
- if (proto !== Object.prototype && proto !== null) return false;
259
- if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
260
- for (const k in v) {
261
- const descriptor = Object.getOwnPropertyDescriptor(v, k);
262
- if (descriptor === undefined || !("value" in descriptor)) return false;
263
- stack.push(descriptor.value);
264
- }
265
- }
266
- }
267
- return true;
268
- }
269
- function getHeadersAndBody(body) {
270
- switch (true) {
271
- case typeof body === "string":
272
- return {
273
- headers: {
274
- "Content-Type": "text/plain",
275
- [BODY_FORMAT_HEADER]: BodyFormat.String
276
- },
277
- body
278
- };
279
- case body instanceof FormData:
280
- return {
281
- headers: {
282
- [BODY_FORMAT_HEADER]: BodyFormat.FormData
283
- },
284
- body
285
- };
286
- case body instanceof URLSearchParams:
287
- return {
288
- headers: {
289
- "Content-Type": "application/x-www-form-urlencoded",
290
- [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
291
- },
292
- body
293
- };
294
- case typeof File !== "undefined" && body instanceof File:
295
- {
296
- const formData = new FormData();
297
- formData.append(FILE_FORM_KEY, body, body.name);
298
- return {
299
- headers: {
300
- [BODY_FORMAT_HEADER]: BodyFormat.File
301
- },
302
- body: formData
303
- };
304
- }
305
- case body instanceof Blob:
306
- return {
307
- headers: {
308
- [BODY_FORMAT_HEADER]: BodyFormat.Blob
309
- },
310
- body
311
- };
312
- case body instanceof ArrayBuffer:
313
- return {
314
- headers: {
315
- [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
316
- },
317
- body
318
- };
319
- case body instanceof Uint8Array:
320
- return {
321
- headers: {
322
- [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
323
- },
324
- body: new Uint8Array(body)
325
- };
326
- default:
327
- return undefined;
328
- }
329
- }
330
- async function extractBody(source, codecOptions) {
331
- const contentType = source.headers.get("content-type");
332
- const format = source.headers.get(BODY_FORMAT_HEADER);
333
- switch (true) {
334
- case format === BodyFormat.Serialized:
335
- return await deserializeStream(source, codecOptions);
336
- case format === BodyFormat.Json:
337
- return JSON.parse(await source.text());
338
- case format === BodyFormat.String:
339
- return await source.text();
340
- case format === BodyFormat.File:
341
- {
342
- const formData = await source.formData();
343
- return formData.get(FILE_FORM_KEY);
344
- }
345
- case format === BodyFormat.FormData:
346
- case contentType && contentType.startsWith("multipart/form-data"):
347
- return await source.formData();
348
- case format === BodyFormat.URLSearchParams:
349
- case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
350
- return new URLSearchParams(await source.text());
351
- case format === BodyFormat.Blob:
352
- return await source.blob();
353
- case format === BodyFormat.ArrayBuffer:
354
- return await source.arrayBuffer();
355
- case format === BodyFormat.Uint8Array:
356
- return new Uint8Array(await source.arrayBuffer());
357
- }
358
- return undefined;
359
- }
360
- function createChunk(data) {
361
- const encoder = new TextEncoder();
362
- const encodeData = encoder.encode(data);
363
- const bytes = encodeData.length;
364
- const chunk = new Uint8Array(12 + bytes);
365
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
366
- chunk.set(encodeData, 12);
367
- return chunk;
368
- }
369
- class ChunkReader {
370
- constructor(stream) {
371
- this.reader = stream.getReader();
372
- this.store = new Uint8Array(0);
373
- this.buffer = this.store;
374
- this.done = false;
375
- }
376
- async readChunk() {
377
- const chunk = await this.reader.read();
378
- if (chunk.done) {
379
- this.done = true;
380
- return;
381
- }
382
- const incoming = chunk.value;
383
- const store = this.store;
384
- const start = this.buffer.byteOffset;
385
- const end = start + this.buffer.length;
386
- const needed = this.buffer.length + incoming.length;
387
- if (end + incoming.length <= store.length) {
388
- store.set(incoming, end);
389
- this.buffer = store.subarray(start, end + incoming.length);
390
- } else if (needed <= store.length) {
391
- store.copyWithin(0, start, end);
392
- store.set(incoming, this.buffer.length);
393
- this.buffer = store.subarray(0, needed);
394
- } else {
395
- const grown = new Uint8Array(Math.max(needed, store.length * 2));
396
- grown.set(this.buffer);
397
- grown.set(incoming, this.buffer.length);
398
- this.store = grown;
399
- this.buffer = grown.subarray(0, needed);
400
- }
401
- }
402
- async next() {
403
- while (this.buffer.length < 12) {
404
- if (this.done) {
405
- if (this.buffer.length === 0) return {
406
- done: true,
407
- value: undefined
408
- };
409
- throw new Error("Malformed server function stream.");
410
- }
411
- await this.readChunk();
412
- }
413
- const decoder = new TextDecoder();
414
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
415
- if (Number.isNaN(bytes)) {
416
- throw new Error("Malformed server function stream.");
417
- }
418
- while (bytes > this.buffer.length - 12) {
419
- if (this.done) {
420
- throw new Error("Malformed server function stream.");
421
- }
422
- await this.readChunk();
423
- }
424
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
425
- this.buffer = this.buffer.subarray(12 + bytes);
426
- return {
427
- done: false,
428
- value: partial
429
- };
430
- }
431
- async drain(interpret) {
432
- while (true) {
433
- const result = await this.next();
434
- if (result.done) {
435
- break;
436
- }
437
- interpret(result.value);
438
- }
439
- }
440
- }
441
- const ERROR_TRAILER_PREFIX = "!";
442
- function errorFromTrailer(payload) {
443
- let shape;
444
- try {
445
- shape = JSON.parse(payload.slice(1));
446
- } catch {
447
- shape = null;
448
- }
449
- const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
450
- if (shape && typeof shape.name === "string") error.name = shape.name;
451
- return error;
452
- }
453
- function serializeStream(value, codecOptions) {
454
- return new ReadableStream({
455
- async start(controller) {
456
- const {
457
- serializeJSON
458
- } = await import('@solidjs/web/serialization');
459
- serializeJSON(value, {
460
- ...codecOptions,
461
- onParse(node) {
462
- controller.enqueue(createChunk(JSON.stringify(node)));
463
- },
464
- onDone() {
465
- controller.close();
466
- },
467
- onError(error) {
468
- controller.error(error);
469
- }
470
- });
471
- }
472
- });
473
- }
474
- async function serializeString(value, codecOptions) {
475
- const response = new Response(serializeStream(value, codecOptions));
476
- return await response.text();
477
- }
478
- async function deserializeStream(source, codecOptions) {
479
- if (!source.body) {
480
- throw new Error("missing body");
481
- }
482
- const reader = new ChunkReader(source.body);
483
- const result = await reader.next();
484
- if (!result.done) {
485
- if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
486
- throw errorFromTrailer(result.value);
487
- }
488
- const {
489
- createJSONDeserializer
490
- } = await import('@solidjs/web/serialization/decode');
491
- const deserializeChunk = createJSONDeserializer(codecOptions);
492
- function interpretChunk(chunk) {
493
- if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
494
- throw errorFromTrailer(chunk);
495
- }
496
- return deserializeChunk(JSON.parse(chunk));
497
- }
498
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
499
- return interpretChunk(result.value);
500
- }
501
- return undefined;
502
- }
503
- async function decodeResponse(response, codecOptions) {
504
- if (!response.body) return undefined;
505
- return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
506
- }
507
- async function decodeResponsePayload(response, codecOptions) {
508
- const decoded = await decodeResponse(response, codecOptions);
509
- if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
510
- return {
511
- value: decoded.value,
512
- flightData: decoded.data
513
- };
514
- }
515
- return {
516
- value: decoded
517
- };
518
- }
519
-
520
- const config = {
521
- endpoint: "/_server",
522
- fetch: undefined,
523
- prepareRequest: undefined,
524
- responseHandler: undefined,
525
- serializeArgs: undefined
526
- };
527
- const CALL_OBSERVERS = new Set();
528
- function notifyCallObservers(type, id, instance, value, meta) {
529
- if (CALL_OBSERVERS.size === 0) return;
530
- const field = type === "request" ? "request" : "response";
531
- const time = performance.now();
532
- for (const observer of new Set(CALL_OBSERVERS)) {
533
- try {
534
- observer({
535
- type,
536
- id,
537
- instance,
538
- [field]: value.clone(),
539
- meta,
540
- time
541
- });
542
- } catch (error) {
543
- console.error(error);
544
- }
545
- }
546
- }
547
- function observeServerFunctionCalls(observer) {
548
- CALL_OBSERVERS.add(observer);
549
- return () => CALL_OBSERVERS.delete(observer);
550
- }
551
- function serverFunctionUrl(id, boundArgs) {
552
- const address = serverFunctionAddress(config.endpoint, id);
553
- if (!boundArgs || !boundArgs.length) return address;
554
- if (!isJSONSafe(boundArgs)) {
555
- throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
556
- }
557
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
558
- }
559
- function parseServerFunctionUrl(url) {
560
- const parsed = parseServerFunctionAddress(new URL(url, globalThis.location?.href || "http://localhost").pathname, config.endpoint);
561
- return parsed && parsed.id;
562
- }
563
- function serializeArguments(args) {
564
- if (!config.serializeArgs) {
565
- throw new Error("Server function arguments are sent as JSON by default and these " + "arguments are not JSON-serializable. Call enableRichArguments() " + '(from "@solidjs/web/server-functions/rich-args") once at startup ' + "to send Dates, Maps, Sets, typed arrays, etc. through the codec — " + "or pass a single Blob/FormData/File argument, which has a native " + "HTTP encoding.");
566
- }
567
- return config.serializeArgs(args);
568
- }
569
- function configureServerFunctionsClient({
570
- endpoint,
571
- codec,
572
- fetch,
573
- prepareRequest,
574
- responseHandler,
575
- serializeArgs
576
- } = {}) {
577
- if (endpoint !== undefined) config.endpoint = endpoint;
578
- if (codec !== undefined) configureServerFunctionsCodec(codec);
579
- if (fetch !== undefined) config.fetch = fetch;
580
- if (prepareRequest !== undefined) config.prepareRequest = prepareRequest;
581
- if (responseHandler !== undefined) config.responseHandler = responseHandler;
582
- if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
583
- }
584
- let INSTANCE = 0;
585
- const MAX_GET_URL_LENGTH = 2000;
586
- let rpcProvided = false;
587
- function provideRPC() {
588
- if (rpcProvided) return;
589
- rpcProvided = true;
590
- provideServerFunctionRPC({
591
- GET,
592
- decodeResponse
593
- });
594
- }
595
- function dataAddressFor(base) {
596
- const splitAt = base.search(/[?#]/);
597
- const path = splitAt < 0 ? base : base.slice(0, splitAt);
598
- const rest = splitAt < 0 ? "" : base.slice(splitAt);
599
- const slash = path.lastIndexOf("/");
600
- if (path.endsWith("/data/", slash + 1)) return base;
601
- return `${path.slice(0, slash + 1)}data/${path.slice(slash + 1)}${rest}`;
602
- }
603
- function serverFunctionFailure(response, value) {
604
- const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
605
- const error = value ?? new Error(unknown ? "Server function is not part of the deployment that answered (version skew or removed function)" : `Server function call failed with status ${response.status}`);
606
- if (error instanceof Error && !("status" in error)) {
607
- error.status = response.status;
608
- const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
609
- if (retryAfter !== undefined) error.retryAfter = retryAfter;
610
- }
611
- if (unknown && error instanceof Error) error.unknownFunction = true;
612
- return error;
613
- }
614
- function parseRetryAfter(header) {
615
- if (!header) return undefined;
616
- const trimmed = header.trim();
617
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
618
- const date = Date.parse(trimmed);
619
- if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
620
- return undefined;
621
- }
622
- async function createRequest(base, id, instance, options, meta) {
623
- const headers = {
624
- ...options.headers,
625
- [INSTANCE_HEADER]: instance
626
- };
627
- const flightSources = getFlightDataSourceIds();
628
- if (flightSources.length > 0 && !options.read && (!options.method || options.method.toUpperCase() !== "GET")) {
629
- headers[SINGLE_FLIGHT_HEADER] = flightSources.join(",");
630
- }
631
- let init = {
632
- method: "POST",
633
- ...options,
634
- headers
635
- };
636
- if (config.prepareRequest) {
637
- const prepared = await config.prepareRequest(init, {
638
- id,
639
- meta
640
- });
641
- if (prepared && prepared !== init) {
642
- if (typeof prepared !== "object") {
643
- throw new Error("prepareRequest must return (or mutate and return) the RequestInit it received; " + `it returned a ${typeof prepared}. Spread the init: ` + "init => ({ ...init, headers: { ...init.headers, ... } })");
644
- }
645
- if (!new Headers(prepared.headers).has(INSTANCE_HEADER)) {
646
- throw new Error("prepareRequest returned an init without the transport headers " + `(${INSTANCE_HEADER}), which would send the call without its payload or ` + "protocol. Spread the init it received: " + "init => ({ ...init, headers: { ...init.headers, ... } })");
647
- }
648
- }
649
- init = prepared || init;
650
- }
651
- const send = config.fetch || fetch;
652
- if (CALL_OBSERVERS.size === 0) return send(base, init);
653
- const request = new Request(new URL(base, globalThis.location?.href || "http://localhost"), {
654
- ...init,
655
- body: init.body instanceof ReadableStream ? undefined : init.body
656
- });
657
- notifyCallObservers("request", id, instance, request, meta);
658
- const response = await send(base, init);
659
- notifyCallObservers("response", id, instance, response, meta);
660
- return response;
661
- }
662
- async function initializeResponse(base, id, instance, options, args, meta) {
663
- if (args.length === 0) {
664
- return createRequest(base, id, instance, options, meta);
665
- }
666
- if (args.length === 1) {
667
- const result = getHeadersAndBody(args[0]);
668
- if (result) {
669
- return createRequest(base, id, instance, {
670
- ...options,
671
- body: result.body,
672
- headers: {
673
- ...options.headers,
674
- ...result.headers
675
- }
676
- }, meta);
677
- }
678
- }
679
- try {
680
- if (isJSONSafe(args)) {
681
- return createRequest(base, id, instance, {
682
- ...options,
683
- body: JSON.stringify(args),
684
- headers: {
685
- ...options.headers,
686
- "Content-Type": "application/json",
687
- [BODY_FORMAT_HEADER]: BodyFormat.Json
688
- }
689
- }, meta);
690
- }
691
- } catch {
692
- }
693
- if (args.length > 1) {
694
- try {
695
- const trailing = getHeadersAndBody(args[args.length - 1]);
696
- const leading = args.slice(0, -1).map(arg => arg === undefined ? null : arg);
697
- if (trailing && isJSONSafe(leading)) {
698
- const target = base + (base.includes("?") ? "&" : "?") + "args=" + encodeURIComponent(JSON.stringify(leading));
699
- return createRequest(target, id, instance, {
700
- ...options,
701
- body: trailing.body,
702
- headers: {
703
- ...options.headers,
704
- ...trailing.headers
705
- }
706
- }, meta);
707
- }
708
- } catch {
709
- }
710
- }
711
- return createRequest(base, id, instance, {
712
- ...options,
713
- body: await serializeArguments(args),
714
- headers: {
715
- ...options.headers,
716
- "Content-Type": "text/plain",
717
- [BODY_FORMAT_HEADER]: BodyFormat.Serialized
718
- }
719
- }, meta);
720
- }
721
- async function fetchServerFunction(base, id, options, args, meta, callArgs = args) {
722
- const instance = `server-function:${INSTANCE++}`;
723
- const handler = config.responseHandler;
724
- const context = handler && handler.capture ? handler.capture({
725
- id,
726
- meta
727
- }) : undefined;
728
- const controller = options.signal ? undefined : new AbortController();
729
- if (controller) options = {
730
- ...options,
731
- signal: controller.signal
732
- };
733
- const response = await initializeResponse(base, id, instance, options, args, meta);
734
- if (handler) {
735
- const handled = handler.handle(response, {
736
- id,
737
- meta,
738
- args: callArgs,
739
- context
740
- });
741
- if (handled !== undefined) return handled;
742
- }
743
- if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
744
- throw serverFunctionFailure(response, undefined);
745
- }
746
- const failed = response.headers.has(ERROR_HEADER);
747
- if (response.headers.has(SINGLE_FLIGHT_HEADER)) {
748
- const folded = response.headers.get(SINGLE_FLIGHT_HEADER).split(",");
749
- const consumers = folded.map(source => [source, getFlightDataConsumer(source)]).filter(([, consumer]) => consumer);
750
- if (consumers.length > 0) {
751
- const payload = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
752
- for (const [source, consumer] of consumers) {
753
- await consumer(payload.data[source], {
754
- response
755
- });
756
- }
757
- if (failed && !response.headers.has(REDIRECT_HEADER) && !response.headers.has(REVALIDATE_HEADER)) {
758
- throw serverFunctionFailure(response, payload.value);
759
- }
760
- return payload.value;
761
- }
762
- }
763
- if (response.headers.has(REDIRECT_HEADER) || response.headers.has(REVALIDATE_HEADER) || response.headers.has(SINGLE_FLIGHT_HEADER) || response.status >= 300 && response.status < 400 && response.status !== 304) {
764
- return response;
765
- }
766
- if (response.status < 300 && !response.headers.has(BODY_FORMAT_HEADER) && !response.headers.has("X-Content-Raw")) {
767
- throw serverFunctionFailure(response, new Error(`Server function response carries no recognized encoding (status ${response.status}` + `${response.headers.get("Content-Type") ? `, content-type ${response.headers.get("Content-Type")}` : ""}): answered by something other than the server function runtime`));
768
- }
769
- const result = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
770
- if (failed) {
771
- throw serverFunctionFailure(response, result);
772
- }
773
- if (controller && result?.[Symbol.asyncIterator]) {
774
- return {
775
- [Symbol.asyncIterator]() {
776
- const it = result[Symbol.asyncIterator]();
777
- return {
778
- next: () => it.next(),
779
- return: value => (controller.abort(), Promise.resolve({
780
- done: true,
781
- value
782
- }))
783
- };
784
- }
785
- };
786
- }
787
- return result;
788
- }
789
- function createServerReference(id, name, base) {
790
- provideRPC();
791
- const metadata = name === undefined ? {} : {
792
- name
793
- };
794
- const run = (args, invokeOptions) => {
795
- const handler = config.responseHandler;
796
- if (handler && handler.intercept) {
797
- const hit = handler.intercept({
798
- id,
799
- meta: metadata,
800
- args
801
- });
802
- if (hit !== undefined) return hit;
803
- }
804
- return fetchServerFunction(base ? dataAddressFor(base) : serverFunctionDataAddress(config.endpoint, id), id, invokeOptions ? {
805
- ...invokeOptions
806
- } : {}, args, metadata);
807
- };
808
- const fn = (...args) => run(args);
809
- fn[SERVER_FUNCTION_METADATA] = metadata;
810
- fn[SERVER_FUNCTION_INVOKE] = run;
811
- return new Proxy(fn, {
812
- get(target, prop) {
813
- if (prop === "id") return id;
814
- if (prop === "url") {
815
- return base || serverFunctionAddress(config.endpoint, id);
816
- }
817
- return target[prop];
818
- }
819
- });
820
- }
821
- function GET(fn) {
822
- if (!isServerFunction(fn)) {
823
- throw new Error("GET expects a server function reference");
824
- }
825
- provideRPC();
826
- const id = fn.id;
827
- const metadata = {
828
- ...getServerFunctionMetadata(fn)
829
- };
830
- const run = async (args, invokeOptions) => {
831
- const handler = config.responseHandler;
832
- if (handler && handler.intercept) {
833
- const hit = handler.intercept({
834
- id,
835
- meta: metadata,
836
- args
837
- });
838
- if (hit !== undefined) return hit;
839
- }
840
- const opts = invokeOptions || {};
841
- const address = serverFunctionDataAddress(config.endpoint, id);
842
- if (!args.length) {
843
- return fetchServerFunction(address, id, {
844
- ...opts,
845
- method: "GET"
846
- }, [], metadata, args);
847
- }
848
- const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
849
- const url = `${address}?args=${encodeURIComponent(encoded)}`;
850
- const absolute = new URL(url, globalThis.location?.href || "http://localhost").href;
851
- if (absolute.length > MAX_GET_URL_LENGTH) {
852
- return fetchServerFunction(address, id, {
853
- ...opts,
854
- read: true
855
- }, args, metadata);
856
- }
857
- return fetchServerFunction(url, id, {
858
- ...opts,
859
- method: "GET"
860
- }, [], metadata, args);
861
- };
862
- const wrapped = (...args) => run(args);
863
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
864
- wrapped[SERVER_FUNCTION_INVOKE] = run;
865
- wrapped.id = id;
866
- Object.defineProperty(wrapped, "url", {
867
- get: () => serverFunctionAddress(config.endpoint, id),
868
- configurable: true
869
- });
870
- return withMeta(wrapped, {
871
- method: "GET"
872
- });
873
- }
874
- function live(fn) {
875
- if (!isServerFunction(fn)) {
876
- throw new Error("live expects a server function reference");
877
- }
878
- const id = fn.id;
879
- const metadata = {
880
- ...getServerFunctionMetadata(fn),
881
- live: true
882
- };
883
- const makeIterable = (args, invokeOptions) => {
884
- const iterable = {
885
- [LIVE_SOURCE]: true,
886
- [Symbol.asyncIterator]() {
887
- let it;
888
- let connected = false;
889
- let attempts = 0;
890
- let stopped = false;
891
- let ended = false;
892
- let timer, wake;
893
- const DONE = {
894
- done: true,
895
- value: undefined
896
- };
897
- const invokeSignal = invokeOptions && invokeOptions.signal;
898
- const controller = new AbortController();
899
- const wireOptions = {
900
- ...invokeOptions,
901
- signal: invokeSignal ? AbortSignal.any([invokeSignal, controller.signal]) : controller.signal
902
- };
903
- const emit = (state, error) => {
904
- try {
905
- iterable.onstatus && iterable.onstatus(state, error);
906
- } catch {}
907
- };
908
- const emitClosed = error => {
909
- if (ended) return;
910
- ended = true;
911
- emit("closed", error);
912
- };
913
- const closeIt = value => {
914
- const current = it;
915
- it = undefined;
916
- if (current) {
917
- try {
918
- const r = current.return && current.return(value);
919
- if (r && typeof r.then === "function") r.then(undefined, () => {});
920
- } catch {}
921
- }
922
- };
923
- const callOnce = () => {
924
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
925
- const handler = config.responseHandler;
926
- if (handler && handler.intercept) {
927
- const hit = handler.intercept({
928
- id,
929
- meta: metadata,
930
- args
931
- });
932
- if (hit !== undefined) return hit;
933
- }
934
- return fetchServerFunction(fn.url, id, {
935
- ...wireOptions,
936
- read: true
937
- }, args, metadata, args);
938
- };
939
- const pull = async () => {
940
- while (!stopped) {
941
- try {
942
- if (!it) {
943
- const result = await callOnce();
944
- connected = true;
945
- it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : async function* () {
946
- yield result;
947
- }();
948
- if (stopped) {
949
- closeIt();
950
- controller.abort();
951
- return DONE;
952
- }
953
- emit("connected");
954
- }
955
- const r = await it.next();
956
- if (r.done) {
957
- emitClosed();
958
- return DONE;
959
- }
960
- if (stopped) return DONE;
961
- attempts = 0;
962
- return r;
963
- } catch (error) {
964
- if (stopped) return DONE;
965
- if (!connected) throw error;
966
- if (invokeSignal && invokeSignal.aborted) {
967
- stopped = true;
968
- emitClosed(error);
969
- throw error;
970
- }
971
- if (error !== null && typeof error === "object" && typeof error.status === "number" && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 425 && error.status !== 429 && typeof error.retryAfter !== "number") {
972
- stopped = true;
973
- emitClosed(error);
974
- throw error;
975
- }
976
- it = undefined;
977
- emit("reconnecting", error);
978
- await new Promise(resolve => {
979
- wake = resolve;
980
- const named = error !== null && typeof error === "object" && typeof error.retryAfter === "number" ? Math.min(error.retryAfter * 1000, 60000) : undefined;
981
- timer = setTimeout(resolve, named ?? Math.min(500 * 2 ** attempts++, 10000));
982
- if (typeof addEventListener === "function") addEventListener("online", resolve, {
983
- once: true
984
- });
985
- if (invokeSignal) invokeSignal.addEventListener("abort", resolve, {
986
- once: true
987
- });
988
- });
989
- clearTimeout(timer);
990
- if (typeof removeEventListener === "function") removeEventListener("online", wake);
991
- if (invokeSignal) invokeSignal.removeEventListener("abort", wake);
992
- timer = wake = undefined;
993
- }
994
- }
995
- return DONE;
996
- };
997
- return {
998
- next: () => pull(),
999
- return(value) {
1000
- stopped = true;
1001
- if (timer !== undefined) clearTimeout(timer);
1002
- if (wake) wake();
1003
- closeIt(value);
1004
- controller.abort();
1005
- emitClosed();
1006
- return Promise.resolve({
1007
- done: true,
1008
- value
1009
- });
1010
- }
1011
- };
1012
- }
1013
- };
1014
- return iterable;
1015
- };
1016
- const wrapped = (...args) => makeIterable(args);
1017
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
1018
- wrapped[SERVER_FUNCTION_INVOKE] = makeIterable;
1019
- wrapped.id = id;
1020
- Object.defineProperty(wrapped, "url", {
1021
- get: () => fn.url,
1022
- configurable: true
1023
- });
1024
- return wrapped;
1025
- }
1026
- function registerServerReference() {
1027
- throw new Error("registerServerReference must not be called in the client build");
1028
- }
1029
- function getServerFunctionInvocation() {
1030
- return undefined;
1031
- }
1032
-
1033
- exports.ChunkReader = ChunkReader;
1034
- exports.ERROR_HEADER = ERROR_HEADER;
1035
- exports.FLASH_COOKIE = FLASH_COOKIE;
1036
- exports.GET = GET;
1037
- exports.INSTANCE_HEADER = INSTANCE_HEADER;
1038
- exports.REDIRECT_HEADER = REDIRECT_HEADER;
1039
- exports.REVALIDATE_HEADER = REVALIDATE_HEADER;
1040
- exports.SERVER_FUNCTION_INVOKE = SERVER_FUNCTION_INVOKE;
1041
- exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
1042
- exports.UNKNOWN_HEADER = UNKNOWN_HEADER;
1043
- exports.clearFlashCookie = clearFlashCookie;
1044
- exports.configureServerFunctionsClient = configureServerFunctionsClient;
1045
- exports.createChunk = createChunk;
1046
- exports.createServerReference = createServerReference;
1047
- exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
1048
- exports.decodeRedirectHeaderValue = decodeRedirectHeaderValue;
1049
- exports.decodeResponse = decodeResponse;
1050
- exports.decodeResponsePayload = decodeResponsePayload;
1051
- exports.deserializeStream = deserializeStream;
1052
- exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
1053
- exports.frameAddress = frameAddress;
1054
- exports.getFlightDataConsumer = getFlightDataConsumer;
1055
- exports.getFlightDataSourceIds = getFlightDataSourceIds;
1056
- exports.getServerFunctionInvocation = getServerFunctionInvocation;
1057
- exports.getServerFunctionMetadata = getServerFunctionMetadata;
1058
- exports.getServerFunctionsCodec = getServerFunctionsCodec;
1059
- exports.hasFlashCookie = hasFlashCookie;
1060
- exports.invoke = invoke;
1061
- exports.isServerFunction = isServerFunction;
1062
- exports.live = live;
1063
- exports.observeServerFunctionCalls = observeServerFunctionCalls;
1064
- exports.parseServerFunctionUrl = parseServerFunctionUrl;
1065
- exports.registerServerReference = registerServerReference;
1066
- exports.serializeString = serializeString;
1067
- exports.serverFunctionUrl = serverFunctionUrl;
1068
- exports.subscribeFlightData = subscribeFlightData;
1069
- exports.withMeta = withMeta;