@solidjs/web 2.0.0-rc.6 → 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 (82) hide show
  1. package/dist/{server.cjs → server.dev.js} +274 -272
  2. package/dist/server.js +119 -36
  3. package/dist/{dev.js → web.dev.js} +131 -399
  4. package/dist/web.js +78 -388
  5. package/dist/{web.cjs → web.observe.js} +174 -622
  6. package/frames/dist/client.dev.js +11 -3
  7. package/frames/dist/client.js +11 -3
  8. package/frames/dist/{server.cjs → server.dev.js} +375 -125
  9. package/frames/dist/server.js +253 -32
  10. package/frames/package.json +7 -15
  11. package/package.json +88 -251
  12. package/serialization/decode/package.json +3 -9
  13. package/serialization/dist/decode.js +18 -4
  14. package/serialization/dist/serialization.js +18 -4
  15. package/serialization/package.json +3 -9
  16. package/serialization/types/serializer-decode.d.ts +49 -2
  17. package/server-functions/dist/client.js +13 -14
  18. package/server-functions/dist/server.dev.js +359 -85
  19. package/server-functions/dist/server.js +352 -86
  20. package/server-functions/package.json +6 -24
  21. package/server-functions/rich-args/package.json +3 -9
  22. package/storage/package.json +3 -9
  23. package/types/client.d.ts +17 -3
  24. package/types/frames/frame-client.d.ts +1 -1
  25. package/types/frames/serializer-decode.d.ts +49 -2
  26. package/types/head.d.ts +3 -0
  27. package/types/index.d.ts +18 -7
  28. package/types/index.server.d.ts +31 -9
  29. package/types/render.d.ts +3 -1
  30. package/types/serializer-decode.d.ts +49 -2
  31. package/types/server-functions/flash.d.ts +12 -3
  32. package/types/server-functions/server.d.ts +50 -3
  33. package/types/server-mock.d.ts +43 -7
  34. package/types/server.d.ts +48 -6
  35. package/dist/dev.cjs +0 -2590
  36. package/frames/dist/client.cjs +0 -2035
  37. package/frames/dist/client.dev.cjs +0 -2055
  38. package/serialization/dist/decode.cjs +0 -141
  39. package/serialization/dist/serialization.cjs +0 -261
  40. package/serialization/types-cjs/index.d.cts +0 -101
  41. package/serialization/types-cjs/package.json +0 -3
  42. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  43. package/serialization/types-cjs/serializer.d.cts +0 -101
  44. package/server-functions/dist/client.cjs +0 -1070
  45. package/server-functions/dist/rich-args.cjs +0 -11
  46. package/server-functions/dist/server.cjs +0 -2133
  47. package/server-functions/dist/server.dev.cjs +0 -2153
  48. package/storage/dist/storage.cjs +0 -12
  49. package/storage/types-cjs/index.d.cts +0 -28
  50. package/storage/types-cjs/package.json +0 -3
  51. package/types/patch-driver.d.ts +0 -3
  52. package/types-cjs/client.d.cts +0 -200
  53. package/types-cjs/constants.d.cts +0 -20
  54. package/types-cjs/cookies.d.cts +0 -41
  55. package/types-cjs/frames/client.d.cts +0 -36
  56. package/types-cjs/frames/frame-client.d.cts +0 -370
  57. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  58. package/types-cjs/frames/frame-sink.d.cts +0 -92
  59. package/types-cjs/frames/frame-transport.d.cts +0 -189
  60. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  61. package/types-cjs/frames/serializer.d.cts +0 -101
  62. package/types-cjs/frames/server.d.cts +0 -52
  63. package/types-cjs/head.d.cts +0 -16
  64. package/types-cjs/index.d.cts +0 -180
  65. package/types-cjs/index.server.d.cts +0 -125
  66. package/types-cjs/jsx-properties.d.cts +0 -93
  67. package/types-cjs/jsx.d.cts +0 -4146
  68. package/types-cjs/package.json +0 -3
  69. package/types-cjs/patch-driver.d.cts +0 -3
  70. package/types-cjs/reconcile.d.cts +0 -1
  71. package/types-cjs/render.d.cts +0 -4
  72. package/types-cjs/response.d.cts +0 -81
  73. package/types-cjs/serializer-decode.d.cts +0 -172
  74. package/types-cjs/serializer.d.cts +0 -101
  75. package/types-cjs/server-functions/client.d.cts +0 -184
  76. package/types-cjs/server-functions/flash.d.cts +0 -27
  77. package/types-cjs/server-functions/registry.d.cts +0 -100
  78. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  79. package/types-cjs/server-functions/server.d.cts +0 -522
  80. package/types-cjs/server-functions/shared.d.cts +0 -283
  81. package/types-cjs/server-mock.d.cts +0 -301
  82. package/types-cjs/server.d.cts +0 -366
@@ -1,1070 +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)) 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
- const clone = source.clone();
334
- switch (true) {
335
- case format === BodyFormat.Serialized:
336
- return await deserializeStream(clone, codecOptions);
337
- case format === BodyFormat.Json:
338
- return JSON.parse(await clone.text());
339
- case format === BodyFormat.String:
340
- return await clone.text();
341
- case format === BodyFormat.File:
342
- {
343
- const formData = await clone.formData();
344
- return formData.get(FILE_FORM_KEY);
345
- }
346
- case format === BodyFormat.FormData:
347
- case contentType && contentType.startsWith("multipart/form-data"):
348
- return await clone.formData();
349
- case format === BodyFormat.URLSearchParams:
350
- case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
351
- return new URLSearchParams(await clone.text());
352
- case format === BodyFormat.Blob:
353
- return await clone.blob();
354
- case format === BodyFormat.ArrayBuffer:
355
- return await clone.arrayBuffer();
356
- case format === BodyFormat.Uint8Array:
357
- return new Uint8Array(await clone.arrayBuffer());
358
- }
359
- return undefined;
360
- }
361
- function createChunk(data) {
362
- const encoder = new TextEncoder();
363
- const encodeData = encoder.encode(data);
364
- const bytes = encodeData.length;
365
- const chunk = new Uint8Array(12 + bytes);
366
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
367
- chunk.set(encodeData, 12);
368
- return chunk;
369
- }
370
- class ChunkReader {
371
- constructor(stream) {
372
- this.reader = stream.getReader();
373
- this.store = new Uint8Array(0);
374
- this.buffer = this.store;
375
- this.done = false;
376
- }
377
- async readChunk() {
378
- const chunk = await this.reader.read();
379
- if (chunk.done) {
380
- this.done = true;
381
- return;
382
- }
383
- const incoming = chunk.value;
384
- const store = this.store;
385
- const start = this.buffer.byteOffset;
386
- const end = start + this.buffer.length;
387
- const needed = this.buffer.length + incoming.length;
388
- if (end + incoming.length <= store.length) {
389
- store.set(incoming, end);
390
- this.buffer = store.subarray(start, end + incoming.length);
391
- } else if (needed <= store.length) {
392
- store.copyWithin(0, start, end);
393
- store.set(incoming, this.buffer.length);
394
- this.buffer = store.subarray(0, needed);
395
- } else {
396
- const grown = new Uint8Array(Math.max(needed, store.length * 2));
397
- grown.set(this.buffer);
398
- grown.set(incoming, this.buffer.length);
399
- this.store = grown;
400
- this.buffer = grown.subarray(0, needed);
401
- }
402
- }
403
- async next() {
404
- while (this.buffer.length < 12) {
405
- if (this.done) {
406
- if (this.buffer.length === 0) return {
407
- done: true,
408
- value: undefined
409
- };
410
- throw new Error("Malformed server function stream.");
411
- }
412
- await this.readChunk();
413
- }
414
- const decoder = new TextDecoder();
415
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
416
- if (Number.isNaN(bytes)) {
417
- throw new Error("Malformed server function stream.");
418
- }
419
- while (bytes > this.buffer.length - 12) {
420
- if (this.done) {
421
- throw new Error("Malformed server function stream.");
422
- }
423
- await this.readChunk();
424
- }
425
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
426
- this.buffer = this.buffer.subarray(12 + bytes);
427
- return {
428
- done: false,
429
- value: partial
430
- };
431
- }
432
- async drain(interpret) {
433
- while (true) {
434
- const result = await this.next();
435
- if (result.done) {
436
- break;
437
- }
438
- interpret(result.value);
439
- }
440
- }
441
- }
442
- const ERROR_TRAILER_PREFIX = "!";
443
- function errorFromTrailer(payload) {
444
- let shape;
445
- try {
446
- shape = JSON.parse(payload.slice(1));
447
- } catch {
448
- shape = null;
449
- }
450
- const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
451
- if (shape && typeof shape.name === "string") error.name = shape.name;
452
- return error;
453
- }
454
- function serializeStream(value, codecOptions) {
455
- return new ReadableStream({
456
- async start(controller) {
457
- const {
458
- serializeJSON
459
- } = await import('@solidjs/web/serialization');
460
- serializeJSON(value, {
461
- ...codecOptions,
462
- onParse(node) {
463
- controller.enqueue(createChunk(JSON.stringify(node)));
464
- },
465
- onDone() {
466
- controller.close();
467
- },
468
- onError(error) {
469
- controller.error(error);
470
- }
471
- });
472
- }
473
- });
474
- }
475
- async function serializeString(value, codecOptions) {
476
- const response = new Response(serializeStream(value, codecOptions));
477
- return await response.text();
478
- }
479
- async function deserializeStream(source, codecOptions) {
480
- if (!source.body) {
481
- throw new Error("missing body");
482
- }
483
- const reader = new ChunkReader(source.body);
484
- const result = await reader.next();
485
- if (!result.done) {
486
- if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
487
- throw errorFromTrailer(result.value);
488
- }
489
- const {
490
- createJSONDeserializer
491
- } = await import('@solidjs/web/serialization/decode');
492
- const deserializeChunk = createJSONDeserializer(codecOptions);
493
- function interpretChunk(chunk) {
494
- if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
495
- throw errorFromTrailer(chunk);
496
- }
497
- return deserializeChunk(JSON.parse(chunk));
498
- }
499
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
500
- return interpretChunk(result.value);
501
- }
502
- return undefined;
503
- }
504
- async function decodeResponse(response, codecOptions) {
505
- if (!response.body) return undefined;
506
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
507
- }
508
- async function decodeResponsePayload(response, codecOptions) {
509
- const decoded = await decodeResponse(response, codecOptions);
510
- if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
511
- return {
512
- value: decoded.value,
513
- flightData: decoded.data
514
- };
515
- }
516
- return {
517
- value: decoded
518
- };
519
- }
520
-
521
- const config = {
522
- endpoint: "/_server",
523
- fetch: undefined,
524
- prepareRequest: undefined,
525
- responseHandler: undefined,
526
- serializeArgs: undefined
527
- };
528
- const CALL_OBSERVERS = new Set();
529
- function notifyCallObservers(type, id, instance, value, meta) {
530
- if (CALL_OBSERVERS.size === 0) return;
531
- const field = type === "request" ? "request" : "response";
532
- const time = performance.now();
533
- for (const observer of new Set(CALL_OBSERVERS)) {
534
- try {
535
- observer({
536
- type,
537
- id,
538
- instance,
539
- [field]: value.clone(),
540
- meta,
541
- time
542
- });
543
- } catch (error) {
544
- console.error(error);
545
- }
546
- }
547
- }
548
- function observeServerFunctionCalls(observer) {
549
- CALL_OBSERVERS.add(observer);
550
- return () => CALL_OBSERVERS.delete(observer);
551
- }
552
- function serverFunctionUrl(id, boundArgs) {
553
- const address = serverFunctionAddress(config.endpoint, id);
554
- if (!boundArgs || !boundArgs.length) return address;
555
- if (!isJSONSafe(boundArgs)) {
556
- 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.");
557
- }
558
- return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
559
- }
560
- function parseServerFunctionUrl(url) {
561
- const parsed = parseServerFunctionAddress(new URL(url, globalThis.location?.href || "http://localhost").pathname, config.endpoint);
562
- return parsed && parsed.id;
563
- }
564
- function serializeArguments(args) {
565
- if (!config.serializeArgs) {
566
- 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.");
567
- }
568
- return config.serializeArgs(args);
569
- }
570
- function configureServerFunctionsClient({
571
- endpoint,
572
- codec,
573
- fetch,
574
- prepareRequest,
575
- responseHandler,
576
- serializeArgs
577
- } = {}) {
578
- if (endpoint !== undefined) config.endpoint = endpoint;
579
- if (codec !== undefined) configureServerFunctionsCodec(codec);
580
- if (fetch !== undefined) config.fetch = fetch;
581
- if (prepareRequest !== undefined) config.prepareRequest = prepareRequest;
582
- if (responseHandler !== undefined) config.responseHandler = responseHandler;
583
- if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
584
- }
585
- let INSTANCE = 0;
586
- const MAX_GET_URL_LENGTH = 2000;
587
- let rpcProvided = false;
588
- function provideRPC() {
589
- if (rpcProvided) return;
590
- rpcProvided = true;
591
- provideServerFunctionRPC({
592
- GET,
593
- decodeResponse
594
- });
595
- }
596
- function dataAddressFor(base) {
597
- const splitAt = base.search(/[?#]/);
598
- const path = splitAt < 0 ? base : base.slice(0, splitAt);
599
- const rest = splitAt < 0 ? "" : base.slice(splitAt);
600
- const slash = path.lastIndexOf("/");
601
- if (path.endsWith("/data/", slash + 1)) return base;
602
- return `${path.slice(0, slash + 1)}data/${path.slice(slash + 1)}${rest}`;
603
- }
604
- function serverFunctionFailure(response, value) {
605
- const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
606
- 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}`);
607
- if (error instanceof Error && !("status" in error)) {
608
- error.status = response.status;
609
- const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
610
- if (retryAfter !== undefined) error.retryAfter = retryAfter;
611
- }
612
- if (unknown && error instanceof Error) error.unknownFunction = true;
613
- return error;
614
- }
615
- function parseRetryAfter(header) {
616
- if (!header) return undefined;
617
- const trimmed = header.trim();
618
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
619
- const date = Date.parse(trimmed);
620
- if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
621
- return undefined;
622
- }
623
- async function createRequest(base, id, instance, options, meta) {
624
- const headers = {
625
- ...options.headers,
626
- [INSTANCE_HEADER]: instance
627
- };
628
- const flightSources = getFlightDataSourceIds();
629
- if (flightSources.length > 0 && !options.read && (!options.method || options.method.toUpperCase() !== "GET")) {
630
- headers[SINGLE_FLIGHT_HEADER] = flightSources.join(",");
631
- }
632
- let init = {
633
- method: "POST",
634
- ...options,
635
- headers
636
- };
637
- if (config.prepareRequest) {
638
- const prepared = await config.prepareRequest(init, {
639
- id,
640
- meta
641
- });
642
- if (prepared && prepared !== init) {
643
- if (typeof prepared !== "object") {
644
- 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, ... } })");
645
- }
646
- if (!new Headers(prepared.headers).has(INSTANCE_HEADER)) {
647
- 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, ... } })");
648
- }
649
- }
650
- init = prepared || init;
651
- }
652
- const send = config.fetch || fetch;
653
- if (CALL_OBSERVERS.size === 0) return send(base, init);
654
- const request = new Request(new URL(base, globalThis.location?.href || "http://localhost"), {
655
- ...init,
656
- body: init.body instanceof ReadableStream ? undefined : init.body
657
- });
658
- notifyCallObservers("request", id, instance, request, meta);
659
- const response = await send(base, init);
660
- notifyCallObservers("response", id, instance, response, meta);
661
- return response;
662
- }
663
- async function initializeResponse(base, id, instance, options, args, meta) {
664
- if (args.length === 0) {
665
- return createRequest(base, id, instance, options, meta);
666
- }
667
- if (args.length === 1) {
668
- const result = getHeadersAndBody(args[0]);
669
- if (result) {
670
- return createRequest(base, id, instance, {
671
- ...options,
672
- body: result.body,
673
- headers: {
674
- ...options.headers,
675
- ...result.headers
676
- }
677
- }, meta);
678
- }
679
- }
680
- try {
681
- if (isJSONSafe(args)) {
682
- return createRequest(base, id, instance, {
683
- ...options,
684
- body: JSON.stringify(args),
685
- headers: {
686
- ...options.headers,
687
- "Content-Type": "application/json",
688
- [BODY_FORMAT_HEADER]: BodyFormat.Json
689
- }
690
- }, meta);
691
- }
692
- } catch {
693
- }
694
- if (args.length > 1) {
695
- try {
696
- const trailing = getHeadersAndBody(args[args.length - 1]);
697
- const leading = args.slice(0, -1).map(arg => arg === undefined ? null : arg);
698
- if (trailing && isJSONSafe(leading)) {
699
- const target = base + (base.includes("?") ? "&" : "?") + "args=" + encodeURIComponent(JSON.stringify(leading));
700
- return createRequest(target, id, instance, {
701
- ...options,
702
- body: trailing.body,
703
- headers: {
704
- ...options.headers,
705
- ...trailing.headers
706
- }
707
- }, meta);
708
- }
709
- } catch {
710
- }
711
- }
712
- return createRequest(base, id, instance, {
713
- ...options,
714
- body: await serializeArguments(args),
715
- headers: {
716
- ...options.headers,
717
- "Content-Type": "text/plain",
718
- [BODY_FORMAT_HEADER]: BodyFormat.Serialized
719
- }
720
- }, meta);
721
- }
722
- async function fetchServerFunction(base, id, options, args, meta, callArgs = args) {
723
- const instance = `server-function:${INSTANCE++}`;
724
- const handler = config.responseHandler;
725
- const context = handler && handler.capture ? handler.capture({
726
- id,
727
- meta
728
- }) : undefined;
729
- const controller = options.signal ? undefined : new AbortController();
730
- if (controller) options = {
731
- ...options,
732
- signal: controller.signal
733
- };
734
- const response = await initializeResponse(base, id, instance, options, args, meta);
735
- if (handler) {
736
- const handled = handler.handle(response, {
737
- id,
738
- meta,
739
- args: callArgs,
740
- context
741
- });
742
- if (handled !== undefined) return handled;
743
- }
744
- if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
745
- throw serverFunctionFailure(response, undefined);
746
- }
747
- const failed = response.headers.has(ERROR_HEADER);
748
- if (response.headers.has(SINGLE_FLIGHT_HEADER)) {
749
- const folded = response.headers.get(SINGLE_FLIGHT_HEADER).split(",");
750
- const consumers = folded.map(source => [source, getFlightDataConsumer(source)]).filter(([, consumer]) => consumer);
751
- if (consumers.length > 0) {
752
- const payload = await decodeResponse(response);
753
- for (const [source, consumer] of consumers) {
754
- await consumer(payload.data[source], {
755
- response
756
- });
757
- }
758
- if (failed && !response.headers.has(REDIRECT_HEADER) && !response.headers.has(REVALIDATE_HEADER)) {
759
- throw serverFunctionFailure(response, payload.value);
760
- }
761
- return payload.value;
762
- }
763
- }
764
- 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) {
765
- return response;
766
- }
767
- if (response.status < 300 && !response.headers.has(BODY_FORMAT_HEADER) && !response.headers.has("X-Content-Raw")) {
768
- 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`));
769
- }
770
- const result = await decodeResponse(response.clone());
771
- if (failed) {
772
- throw serverFunctionFailure(response, result);
773
- }
774
- if (controller && result?.[Symbol.asyncIterator]) {
775
- return {
776
- [Symbol.asyncIterator]() {
777
- const it = result[Symbol.asyncIterator]();
778
- return {
779
- next: () => it.next(),
780
- return: value => (controller.abort(), Promise.resolve({
781
- done: true,
782
- value
783
- }))
784
- };
785
- }
786
- };
787
- }
788
- return result;
789
- }
790
- function createServerReference(id, name, base) {
791
- provideRPC();
792
- const metadata = name === undefined ? {} : {
793
- name
794
- };
795
- const run = (args, invokeOptions) => {
796
- const handler = config.responseHandler;
797
- if (handler && handler.intercept) {
798
- const hit = handler.intercept({
799
- id,
800
- meta: metadata,
801
- args
802
- });
803
- if (hit !== undefined) return hit;
804
- }
805
- return fetchServerFunction(base ? dataAddressFor(base) : serverFunctionDataAddress(config.endpoint, id), id, invokeOptions ? {
806
- ...invokeOptions
807
- } : {}, args, metadata);
808
- };
809
- const fn = (...args) => run(args);
810
- fn[SERVER_FUNCTION_METADATA] = metadata;
811
- fn[SERVER_FUNCTION_INVOKE] = run;
812
- return new Proxy(fn, {
813
- get(target, prop) {
814
- if (prop === "id") return id;
815
- if (prop === "url") {
816
- return base || serverFunctionAddress(config.endpoint, id);
817
- }
818
- return target[prop];
819
- }
820
- });
821
- }
822
- function GET(fn) {
823
- if (!isServerFunction(fn)) {
824
- throw new Error("GET expects a server function reference");
825
- }
826
- provideRPC();
827
- const id = fn.id;
828
- const metadata = {
829
- ...getServerFunctionMetadata(fn)
830
- };
831
- const run = async (args, invokeOptions) => {
832
- const handler = config.responseHandler;
833
- if (handler && handler.intercept) {
834
- const hit = handler.intercept({
835
- id,
836
- meta: metadata,
837
- args
838
- });
839
- if (hit !== undefined) return hit;
840
- }
841
- const opts = invokeOptions || {};
842
- const address = serverFunctionDataAddress(config.endpoint, id);
843
- if (!args.length) {
844
- return fetchServerFunction(address, id, {
845
- ...opts,
846
- method: "GET"
847
- }, [], metadata, args);
848
- }
849
- const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
850
- const url = `${address}?args=${encodeURIComponent(encoded)}`;
851
- const absolute = new URL(url, globalThis.location?.href || "http://localhost").href;
852
- if (absolute.length > MAX_GET_URL_LENGTH) {
853
- return fetchServerFunction(address, id, {
854
- ...opts,
855
- read: true
856
- }, args, metadata);
857
- }
858
- return fetchServerFunction(url, id, {
859
- ...opts,
860
- method: "GET"
861
- }, [], metadata, args);
862
- };
863
- const wrapped = (...args) => run(args);
864
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
865
- wrapped[SERVER_FUNCTION_INVOKE] = run;
866
- wrapped.id = id;
867
- Object.defineProperty(wrapped, "url", {
868
- get: () => serverFunctionAddress(config.endpoint, id),
869
- configurable: true
870
- });
871
- return withMeta(wrapped, {
872
- method: "GET"
873
- });
874
- }
875
- function live(fn) {
876
- if (!isServerFunction(fn)) {
877
- throw new Error("live expects a server function reference");
878
- }
879
- const id = fn.id;
880
- const metadata = {
881
- ...getServerFunctionMetadata(fn),
882
- live: true
883
- };
884
- const makeIterable = (args, invokeOptions) => {
885
- const iterable = {
886
- [LIVE_SOURCE]: true,
887
- [Symbol.asyncIterator]() {
888
- let it;
889
- let connected = false;
890
- let attempts = 0;
891
- let stopped = false;
892
- let ended = false;
893
- let timer, wake;
894
- const DONE = {
895
- done: true,
896
- value: undefined
897
- };
898
- const invokeSignal = invokeOptions && invokeOptions.signal;
899
- const controller = new AbortController();
900
- const wireOptions = {
901
- ...invokeOptions,
902
- signal: invokeSignal ? AbortSignal.any([invokeSignal, controller.signal]) : controller.signal
903
- };
904
- const emit = (state, error) => {
905
- try {
906
- iterable.onstatus && iterable.onstatus(state, error);
907
- } catch {}
908
- };
909
- const emitClosed = error => {
910
- if (ended) return;
911
- ended = true;
912
- emit("closed", error);
913
- };
914
- const closeIt = value => {
915
- const current = it;
916
- it = undefined;
917
- if (current) {
918
- try {
919
- const r = current.return && current.return(value);
920
- if (r && typeof r.then === "function") r.then(undefined, () => {});
921
- } catch {}
922
- }
923
- };
924
- const callOnce = () => {
925
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
926
- const handler = config.responseHandler;
927
- if (handler && handler.intercept) {
928
- const hit = handler.intercept({
929
- id,
930
- meta: metadata,
931
- args
932
- });
933
- if (hit !== undefined) return hit;
934
- }
935
- return fetchServerFunction(fn.url, id, {
936
- ...wireOptions,
937
- read: true
938
- }, args, metadata, args);
939
- };
940
- const pull = async () => {
941
- while (!stopped) {
942
- try {
943
- if (!it) {
944
- const result = await callOnce();
945
- connected = true;
946
- it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : async function* () {
947
- yield result;
948
- }();
949
- if (stopped) {
950
- closeIt();
951
- controller.abort();
952
- return DONE;
953
- }
954
- emit("connected");
955
- }
956
- const r = await it.next();
957
- if (r.done) {
958
- emitClosed();
959
- return DONE;
960
- }
961
- if (stopped) return DONE;
962
- attempts = 0;
963
- return r;
964
- } catch (error) {
965
- if (stopped) return DONE;
966
- if (!connected) throw error;
967
- if (invokeSignal && invokeSignal.aborted) {
968
- stopped = true;
969
- emitClosed(error);
970
- throw error;
971
- }
972
- 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") {
973
- stopped = true;
974
- emitClosed(error);
975
- throw error;
976
- }
977
- it = undefined;
978
- emit("reconnecting", error);
979
- await new Promise(resolve => {
980
- wake = resolve;
981
- const named = error !== null && typeof error === "object" && typeof error.retryAfter === "number" ? Math.min(error.retryAfter * 1000, 60000) : undefined;
982
- timer = setTimeout(resolve, named ?? Math.min(500 * 2 ** attempts++, 10000));
983
- if (typeof addEventListener === "function") addEventListener("online", resolve, {
984
- once: true
985
- });
986
- if (invokeSignal) invokeSignal.addEventListener("abort", resolve, {
987
- once: true
988
- });
989
- });
990
- clearTimeout(timer);
991
- if (typeof removeEventListener === "function") removeEventListener("online", wake);
992
- if (invokeSignal) invokeSignal.removeEventListener("abort", wake);
993
- timer = wake = undefined;
994
- }
995
- }
996
- return DONE;
997
- };
998
- return {
999
- next: () => pull(),
1000
- return(value) {
1001
- stopped = true;
1002
- if (timer !== undefined) clearTimeout(timer);
1003
- if (wake) wake();
1004
- closeIt(value);
1005
- controller.abort();
1006
- emitClosed();
1007
- return Promise.resolve({
1008
- done: true,
1009
- value
1010
- });
1011
- }
1012
- };
1013
- }
1014
- };
1015
- return iterable;
1016
- };
1017
- const wrapped = (...args) => makeIterable(args);
1018
- wrapped[SERVER_FUNCTION_METADATA] = metadata;
1019
- wrapped[SERVER_FUNCTION_INVOKE] = makeIterable;
1020
- wrapped.id = id;
1021
- Object.defineProperty(wrapped, "url", {
1022
- get: () => fn.url,
1023
- configurable: true
1024
- });
1025
- return wrapped;
1026
- }
1027
- function registerServerReference() {
1028
- throw new Error("registerServerReference must not be called in the client build");
1029
- }
1030
- function getServerFunctionInvocation() {
1031
- return undefined;
1032
- }
1033
-
1034
- exports.ChunkReader = ChunkReader;
1035
- exports.ERROR_HEADER = ERROR_HEADER;
1036
- exports.FLASH_COOKIE = FLASH_COOKIE;
1037
- exports.GET = GET;
1038
- exports.INSTANCE_HEADER = INSTANCE_HEADER;
1039
- exports.REDIRECT_HEADER = REDIRECT_HEADER;
1040
- exports.REVALIDATE_HEADER = REVALIDATE_HEADER;
1041
- exports.SERVER_FUNCTION_INVOKE = SERVER_FUNCTION_INVOKE;
1042
- exports.SINGLE_FLIGHT_HEADER = SINGLE_FLIGHT_HEADER;
1043
- exports.UNKNOWN_HEADER = UNKNOWN_HEADER;
1044
- exports.clearFlashCookie = clearFlashCookie;
1045
- exports.configureServerFunctionsClient = configureServerFunctionsClient;
1046
- exports.createChunk = createChunk;
1047
- exports.createServerReference = createServerReference;
1048
- exports.decodeErrorHeaderValue = decodeErrorHeaderValue;
1049
- exports.decodeRedirectHeaderValue = decodeRedirectHeaderValue;
1050
- exports.decodeResponse = decodeResponse;
1051
- exports.decodeResponsePayload = decodeResponsePayload;
1052
- exports.deserializeStream = deserializeStream;
1053
- exports.encodeErrorHeaderValue = encodeErrorHeaderValue;
1054
- exports.frameAddress = frameAddress;
1055
- exports.getFlightDataConsumer = getFlightDataConsumer;
1056
- exports.getFlightDataSourceIds = getFlightDataSourceIds;
1057
- exports.getServerFunctionInvocation = getServerFunctionInvocation;
1058
- exports.getServerFunctionMetadata = getServerFunctionMetadata;
1059
- exports.getServerFunctionsCodec = getServerFunctionsCodec;
1060
- exports.hasFlashCookie = hasFlashCookie;
1061
- exports.invoke = invoke;
1062
- exports.isServerFunction = isServerFunction;
1063
- exports.live = live;
1064
- exports.observeServerFunctionCalls = observeServerFunctionCalls;
1065
- exports.parseServerFunctionUrl = parseServerFunctionUrl;
1066
- exports.registerServerReference = registerServerReference;
1067
- exports.serializeString = serializeString;
1068
- exports.serverFunctionUrl = serverFunctionUrl;
1069
- exports.subscribeFlightData = subscribeFlightData;
1070
- exports.withMeta = withMeta;