@solidjs/web 2.0.0-rc.0 → 2.0.0-rc.10

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 (108) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +4472 -0
  3. package/dist/server.js +1363 -224
  4. package/dist/{server.cjs → server.observe.js} +1563 -424
  5. package/dist/{dev.cjs → web.dev.js} +708 -365
  6. package/dist/web.js +460 -144
  7. package/dist/{dev.js → web.observe.js} +511 -213
  8. package/frames/dist/client.dev.js +464 -72
  9. package/frames/dist/client.js +364 -71
  10. package/frames/dist/{client.dev.cjs → client.observe.js} +487 -134
  11. package/frames/dist/server.dev.js +1713 -0
  12. package/frames/dist/server.js +553 -2495
  13. package/frames/dist/server.observe.js +1713 -0
  14. package/frames/package.json +2 -25
  15. package/package.json +214 -254
  16. package/performance-tracks/dist/performance-tracks.dev.js +678 -0
  17. package/performance-tracks/dist/performance-tracks.js +6 -0
  18. package/performance-tracks/dist/performance-tracks.observe.js +666 -0
  19. package/performance-tracks/package.json +7 -0
  20. package/performance-tracks/types/index.d.ts +67 -0
  21. package/serialization/decode/package.json +2 -15
  22. package/serialization/dist/decode.js +101 -12
  23. package/serialization/dist/serialization.js +112 -20
  24. package/serialization/package.json +2 -15
  25. package/serialization/types/index.d.ts +76 -157
  26. package/serialization/types/serializer-decode.d.ts +149 -112
  27. package/serialization/types/serializer.d.ts +101 -0
  28. package/server-functions/dist/client.dev.js +1364 -0
  29. package/server-functions/dist/client.js +745 -85
  30. package/server-functions/dist/client.observe.js +1343 -0
  31. package/server-functions/dist/server.dev.js +2203 -175
  32. package/server-functions/dist/server.js +2111 -176
  33. package/server-functions/dist/server.observe.js +3043 -0
  34. package/server-functions/package.json +2 -35
  35. package/server-functions/rich-args/package.json +2 -15
  36. package/storage/package.json +2 -15
  37. package/types/client.d.ts +193 -288
  38. package/types/constants.d.ts +20 -0
  39. package/types/cookies.d.ts +32 -84
  40. package/types/diagnostics.d.ts +56 -0
  41. package/types/frames/client.d.ts +1 -1
  42. package/types/frames/frame-client.d.ts +323 -259
  43. package/types/frames/frame-container-plugin.d.ts +72 -0
  44. package/types/frames/frame-sink.d.ts +101 -158
  45. package/types/frames/frame-transport.d.ts +192 -190
  46. package/types/frames/serializer-decode.d.ts +219 -0
  47. package/types/frames/serializer.d.ts +76 -157
  48. package/types/frames/server.d.ts +1 -1
  49. package/types/head.d.ts +19 -0
  50. package/types/index.d.ts +62 -76
  51. package/types/index.server.d.ts +174 -0
  52. package/types/jsx.d.ts +33 -26
  53. package/types/observe.d.ts +358 -0
  54. package/types/reconcile.d.ts +1 -0
  55. package/types/render.d.ts +9 -0
  56. package/types/response.d.ts +75 -150
  57. package/types/serializer-decode.d.ts +149 -112
  58. package/types/serializer.d.ts +76 -157
  59. package/types/server-functions/client.d.ts +202 -174
  60. package/types/server-functions/flash.d.ts +28 -30
  61. package/types/server-functions/registry.d.ts +102 -0
  62. package/types/server-functions/rich-args.d.ts +1 -10
  63. package/types/server-functions/server.d.ts +518 -454
  64. package/types/server-functions/shared.d.ts +366 -425
  65. package/types/server-mock.d.ts +110 -13
  66. package/types/server-observe.d.ts +77 -0
  67. package/types/server.d.ts +425 -425
  68. package/types/trace.d.ts +127 -0
  69. package/LICENSE +0 -21
  70. package/dist/web.cjs +0 -2007
  71. package/frames/dist/client.cjs +0 -1916
  72. package/frames/dist/server.cjs +0 -3667
  73. package/serialization/dist/decode.cjs +0 -110
  74. package/serialization/dist/serialization.cjs +0 -232
  75. package/serialization/types-cjs/index.d.cts +0 -182
  76. package/serialization/types-cjs/package.json +0 -3
  77. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  78. package/server-functions/dist/client.cjs +0 -646
  79. package/server-functions/dist/rich-args.cjs +0 -11
  80. package/server-functions/dist/server.cjs +0 -1077
  81. package/server-functions/dist/server.dev.cjs +0 -1077
  82. package/storage/dist/storage.cjs +0 -12
  83. package/storage/types-cjs/index.d.cts +0 -28
  84. package/storage/types-cjs/package.json +0 -3
  85. package/types/core.d.ts +0 -6
  86. package/types-cjs/client.d.cts +0 -337
  87. package/types-cjs/cookies.d.cts +0 -93
  88. package/types-cjs/core.d.cts +0 -6
  89. package/types-cjs/frames/client.d.cts +0 -36
  90. package/types-cjs/frames/frame-client.d.cts +0 -338
  91. package/types-cjs/frames/frame-sink.d.cts +0 -194
  92. package/types-cjs/frames/frame-transport.d.cts +0 -222
  93. package/types-cjs/frames/serializer.d.cts +0 -182
  94. package/types-cjs/frames/server.d.cts +0 -52
  95. package/types-cjs/index.d.cts +0 -230
  96. package/types-cjs/jsx-properties.d.cts +0 -93
  97. package/types-cjs/jsx.d.cts +0 -4150
  98. package/types-cjs/package.json +0 -3
  99. package/types-cjs/response.d.cts +0 -174
  100. package/types-cjs/serializer-decode.d.cts +0 -182
  101. package/types-cjs/serializer.d.cts +0 -182
  102. package/types-cjs/server-functions/client.d.cts +0 -201
  103. package/types-cjs/server-functions/flash.d.cts +0 -38
  104. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  105. package/types-cjs/server-functions/server.d.cts +0 -588
  106. package/types-cjs/server-functions/shared.d.cts +0 -523
  107. package/types-cjs/server-mock.d.cts +0 -277
  108. package/types-cjs/server.d.cts +0 -523
@@ -0,0 +1,1364 @@
1
+ const REVALIDATE_HEADER = "X-Revalidate";
2
+
3
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
4
+ const ATTRIBUTION = Symbol.for("@solidjs/signals/observe/attribution");
5
+ function records() {
6
+ return globalThis[RECORDS];
7
+ }
8
+ function currentOrigin() {
9
+ const hooks = globalThis[ATTRIBUTION];
10
+ return hooks === undefined ? undefined : hooks.currentOrigin();
11
+ }
12
+ function isDeferredBody(value) {
13
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
14
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
15
+ const v = value;
16
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
17
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
18
+ }
19
+ function observeCall(id, method, args) {
20
+ const channel = records();
21
+ if (channel === undefined || !channel.observed("call")) return undefined;
22
+ const at = performance.now();
23
+ const origin = currentOrigin();
24
+ let response;
25
+ let settled = false;
26
+ return {
27
+ response(r) {
28
+ response = r;
29
+ },
30
+ settle(outcome, value) {
31
+ if (settled) return;
32
+ settled = true;
33
+ const event = {
34
+ id,
35
+ at,
36
+ durationMs: performance.now() - at,
37
+ method,
38
+ outcome
39
+ };
40
+ if (response !== undefined) event.status = response.status;
41
+ if (origin !== undefined) event.origin = origin;
42
+ const live = {
43
+ args
44
+ };
45
+ if (response !== undefined) live.response = response;
46
+ if (outcome === "ok") {
47
+ live.result = value;
48
+ if (isDeferredBody(value)) event.deferred = true;
49
+ } else live.error = value;
50
+ channel.emit("call", event, live);
51
+ }
52
+ };
53
+ }
54
+
55
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
56
+ function getServerFunctionMetadata(fn) {
57
+ if (typeof fn !== "function") return undefined;
58
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
59
+ }
60
+ function isServerFunction(fn) {
61
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
62
+ }
63
+ function withMeta(fn, meta) {
64
+ const metadata = getServerFunctionMetadata(fn);
65
+ if (!metadata) {
66
+ throw new Error("withMeta expects a server function reference");
67
+ }
68
+ Object.assign(metadata, meta);
69
+ return fn;
70
+ }
71
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
72
+ const INVOKE_OPTION_REDIRECTS = {
73
+ 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.",
74
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
75
+ body: "The arguments are the body: pass them in the args array.",
76
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
77
+ };
78
+ function invoke(fn, options, ...args) {
79
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
80
+ if (!channel) {
81
+ 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.");
82
+ }
83
+ if (options === null || typeof options !== "object") {
84
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
85
+ }
86
+ const picked = {};
87
+ for (const key in options) {
88
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
89
+ 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."));
90
+ }
91
+ }
92
+ if (options.signal !== undefined) picked.signal = options.signal;
93
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
94
+ if (options.priority !== undefined) picked.priority = options.priority;
95
+ return channel(args, picked);
96
+ }
97
+ const LIVE_SOURCE = Symbol.for("solid.LiveSource");
98
+ const LIVE_RESUME_FROM = Symbol.for("solid.LiveResumeFrom");
99
+ const LIVE_LOCAL = Symbol.for("solid.LiveLocal");
100
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
101
+ function provideServerFunctionRPC(rpc) {
102
+ globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
103
+ }
104
+
105
+ const FLASH_COOKIE = "flash";
106
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
107
+ function hasFlashCookie(cookieHeader) {
108
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
109
+ }
110
+ function clearFlashCookie() {
111
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
112
+ }
113
+
114
+ const codecConfig = {
115
+ codec: undefined
116
+ };
117
+ function configureServerFunctionsCodec(codec) {
118
+ codecConfig.codec = codec;
119
+ }
120
+ function getServerFunctionsCodec() {
121
+ return codecConfig.codec;
122
+ }
123
+ const UNNAMED_FLIGHT_SOURCE = "true";
124
+ const flightConfig = {
125
+ consumers: new Map()
126
+ };
127
+ function assertFlightSource(source) {
128
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
129
+ 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).`);
130
+ }
131
+ }
132
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
133
+ const named = typeof sourceOrConsumer === "string";
134
+ if (named) assertFlightSource(sourceOrConsumer);
135
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
136
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
137
+ flightConfig.consumers.set(source, consumer);
138
+ return () => {
139
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
140
+ };
141
+ }
142
+ function getFlightDataConsumer(source) {
143
+ return flightConfig.consumers.get(source === undefined ? UNNAMED_FLIGHT_SOURCE : source);
144
+ }
145
+ function getFlightDataSourceIds() {
146
+ return [...flightConfig.consumers.keys()];
147
+ }
148
+ function hasFlightMetadata(response) {
149
+ return response.headers.has(REDIRECT_HEADER) || response.headers.has(REVALIDATE_HEADER);
150
+ }
151
+ async function deliverFlightData(response, data) {
152
+ const folded = (response.headers.get(SINGLE_FLIGHT_HEADER) || "").split(",");
153
+ const metadata = hasFlightMetadata(response);
154
+ for (const source of getFlightDataSourceIds()) {
155
+ if (!metadata && !folded.includes(source)) continue;
156
+ const consumer = getFlightDataConsumer(source);
157
+ if (consumer) await consumer(data ? data[source] : undefined, {
158
+ response
159
+ });
160
+ }
161
+ }
162
+ function frameAddress(id, args) {
163
+ return args && args.length ? id + ":" + hashArguments(args) : id;
164
+ }
165
+ function hashArguments(args) {
166
+ let hash = 0;
167
+ const text = stableString(args);
168
+ for (let i = 0; i < text.length; i++) {
169
+ hash = (hash << 5) - hash + text.charCodeAt(i);
170
+ hash |= 0;
171
+ }
172
+ return (hash >>> 0).toString(36);
173
+ }
174
+ function stableString(value, seen) {
175
+ if (value === null || typeof value !== "object") {
176
+ return typeof value === "bigint" ? value + "n" : String(value);
177
+ }
178
+ if (value instanceof Date) return "Date:" + value.getTime();
179
+ seen || (seen = new Set());
180
+ if (seen.has(value)) return "~";
181
+ seen.add(value);
182
+ if (value instanceof Map) {
183
+ const entries = [];
184
+ for (const [k, v] of value) {
185
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
186
+ }
187
+ return "Map{" + entries.sort().join(",") + "}";
188
+ }
189
+ if (value instanceof Set) {
190
+ const members = [];
191
+ for (const v of value) members.push(stableString(v, seen));
192
+ return "Set{" + members.sort().join(",") + "}";
193
+ }
194
+ if (Array.isArray(value)) {
195
+ let out = "[";
196
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
197
+ return out + "]";
198
+ }
199
+ const keys = Object.keys(value).sort();
200
+ let out = "{";
201
+ for (let i = 0; i < keys.length; i++) {
202
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
203
+ }
204
+ return out + "}";
205
+ }
206
+ function serverFunctionAddress(endpoint, id) {
207
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
208
+ return `${mount}/${encodeURIComponent(id)}`;
209
+ }
210
+ function serverFunctionDataAddress(endpoint, id) {
211
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
212
+ return `${mount}/data/${encodeURIComponent(id)}`;
213
+ }
214
+ function serverFunctionLiveAddress(endpoint, id) {
215
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
216
+ return `${mount}/live/${encodeURIComponent(id)}`;
217
+ }
218
+ function parseServerFunctionAddress(pathname, endpoint) {
219
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
220
+ if (!pathname.startsWith(mount)) return null;
221
+ const rest = pathname.slice(mount.length);
222
+ if (!rest.startsWith("/")) return null;
223
+ let segment = rest.slice(1);
224
+ let data = false;
225
+ let live = false;
226
+ if (segment.startsWith("data/")) {
227
+ segment = segment.slice(5);
228
+ data = true;
229
+ } else if (segment.startsWith("live/")) {
230
+ segment = segment.slice(5);
231
+ live = true;
232
+ }
233
+ if (!segment || segment.includes("/")) return null;
234
+ try {
235
+ return {
236
+ id: decodeURIComponent(segment),
237
+ data,
238
+ live
239
+ };
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+ const MAX_GET_URL_LENGTH = 2000;
245
+ function urlTargetId(target, helper) {
246
+ if (typeof target === "string") return target;
247
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
248
+ throw new Error(`${helper} expects a server function reference (or its id).`);
249
+ }
250
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
251
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
252
+ if (!boundArgs.length) return address;
253
+ if (!isJSONSafe(boundArgs)) {
254
+ 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.");
255
+ }
256
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
257
+ }
258
+ function serverFunctionUrlFor(endpoint, fn, args) {
259
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
260
+ throw new Error("serverFunctionUrl expects a server function reference.");
261
+ }
262
+ const metadata = getServerFunctionMetadata(fn);
263
+ if (!metadata || metadata.method !== "GET") {
264
+ throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
265
+ }
266
+ const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
267
+ if (!args.length) return address;
268
+ if (!isJSONSafe(args)) {
269
+ throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
270
+ }
271
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
272
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
273
+ if (length > MAX_GET_URL_LENGTH) {
274
+ throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
275
+ }
276
+ return url;
277
+ }
278
+ const ERROR_HEADER = "X-Server-Function-Error";
279
+ const ERROR_HEADER_MARKER = "=?1?";
280
+ const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
281
+ function encodeErrorHeaderValue(value) {
282
+ let stripped = String(value).replace(/[\r\n]+/g, "");
283
+ if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
284
+ return stripped;
285
+ }
286
+ if (typeof stripped.toWellFormed === "function") {
287
+ stripped = stripped.toWellFormed();
288
+ } else {
289
+ stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
290
+ }
291
+ return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
292
+ }
293
+ function decodeErrorHeaderValue(value) {
294
+ if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
295
+ return value;
296
+ }
297
+ try {
298
+ return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
299
+ } catch {
300
+ return value;
301
+ }
302
+ }
303
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
304
+ const LAST_EVENT_ID_HEADER = "Last-Event-ID";
305
+ const LIVE_WIRE = Symbol("solid.LiveWire");
306
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
307
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
308
+ function decodeRedirectHeaderValue(value) {
309
+ if (typeof value !== "string") return undefined;
310
+ const at = value.indexOf(" ");
311
+ if (at < 0) return undefined;
312
+ const status = Number(value.slice(0, at));
313
+ const url = value.slice(at + 1);
314
+ if (!Number.isInteger(status) || !url) return undefined;
315
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
316
+ let parsed;
317
+ try {
318
+ parsed = new URL(url);
319
+ } catch {
320
+ return undefined;
321
+ }
322
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
323
+ return {
324
+ status,
325
+ url
326
+ };
327
+ }
328
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
329
+ const FILE_FORM_KEY = "__server_function_file__";
330
+ const BodyFormat = {
331
+ Serialized: "0",
332
+ String: "1",
333
+ FormData: "2",
334
+ URLSearchParams: "3",
335
+ Blob: "4",
336
+ File: "5",
337
+ ArrayBuffer: "6",
338
+ Uint8Array: "7",
339
+ Json: "8",
340
+ Void: "9"
341
+ };
342
+ const JSON_SAFE_DEPTH_LIMIT = 4096;
343
+ const EXIT = {};
344
+ function isJSONSafe(value) {
345
+ const stack = [value];
346
+ const ancestors = new Set();
347
+ while (stack.length) {
348
+ const v = stack.pop();
349
+ if (v === EXIT) {
350
+ ancestors.delete(stack.pop());
351
+ continue;
352
+ }
353
+ if (v === null) continue;
354
+ const t = typeof v;
355
+ if (t === "string" || t === "boolean") continue;
356
+ if (t === "number") {
357
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
358
+ continue;
359
+ }
360
+ if (t !== "object") return false;
361
+ if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
362
+ ancestors.add(v);
363
+ stack.push(v, EXIT);
364
+ if (Array.isArray(v)) {
365
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
366
+ } else {
367
+ const proto = Object.getPrototypeOf(v);
368
+ if (proto !== Object.prototype && proto !== null) return false;
369
+ if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
370
+ for (const k in v) {
371
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
372
+ if (descriptor === undefined || !("value" in descriptor)) return false;
373
+ stack.push(descriptor.value);
374
+ }
375
+ }
376
+ }
377
+ return true;
378
+ }
379
+ function getHeadersAndBody(body) {
380
+ switch (true) {
381
+ case typeof body === "string":
382
+ return {
383
+ headers: {
384
+ "Content-Type": "text/plain",
385
+ [BODY_FORMAT_HEADER]: BodyFormat.String
386
+ },
387
+ body
388
+ };
389
+ case body instanceof FormData:
390
+ return {
391
+ headers: {
392
+ [BODY_FORMAT_HEADER]: BodyFormat.FormData
393
+ },
394
+ body
395
+ };
396
+ case body instanceof URLSearchParams:
397
+ return {
398
+ headers: {
399
+ "Content-Type": "application/x-www-form-urlencoded",
400
+ [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
401
+ },
402
+ body
403
+ };
404
+ case typeof File !== "undefined" && body instanceof File:
405
+ {
406
+ const formData = new FormData();
407
+ formData.append(FILE_FORM_KEY, body, body.name);
408
+ return {
409
+ headers: {
410
+ [BODY_FORMAT_HEADER]: BodyFormat.File
411
+ },
412
+ body: formData
413
+ };
414
+ }
415
+ case body instanceof Blob:
416
+ return {
417
+ headers: {
418
+ [BODY_FORMAT_HEADER]: BodyFormat.Blob
419
+ },
420
+ body
421
+ };
422
+ case body instanceof ArrayBuffer:
423
+ return {
424
+ headers: {
425
+ [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
426
+ },
427
+ body
428
+ };
429
+ case body instanceof Uint8Array:
430
+ return {
431
+ headers: {
432
+ [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
433
+ },
434
+ body: new Uint8Array(body)
435
+ };
436
+ default:
437
+ return undefined;
438
+ }
439
+ }
440
+ async function extractBody(source, codecOptions, wire) {
441
+ const contentType = source.headers.get("content-type");
442
+ const format = source.headers.get(BODY_FORMAT_HEADER);
443
+ switch (true) {
444
+ case format === BodyFormat.Serialized:
445
+ return await deserializeStream(source, codecOptions, wire);
446
+ case format === BodyFormat.Json:
447
+ return JSON.parse(await source.text());
448
+ case format === BodyFormat.String:
449
+ return await source.text();
450
+ case format === BodyFormat.File:
451
+ {
452
+ const formData = await source.formData();
453
+ return formData.get(FILE_FORM_KEY);
454
+ }
455
+ case format === BodyFormat.FormData:
456
+ case contentType && contentType.startsWith("multipart/form-data"):
457
+ return await source.formData();
458
+ case format === BodyFormat.URLSearchParams:
459
+ case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
460
+ return new URLSearchParams(await source.text());
461
+ case format === BodyFormat.Blob:
462
+ return await source.blob();
463
+ case format === BodyFormat.ArrayBuffer:
464
+ return await source.arrayBuffer();
465
+ case format === BodyFormat.Uint8Array:
466
+ return new Uint8Array(await source.arrayBuffer());
467
+ }
468
+ return undefined;
469
+ }
470
+ function createChunk(data) {
471
+ const encoder = new TextEncoder();
472
+ const encodeData = encoder.encode(data);
473
+ const bytes = encodeData.length;
474
+ const chunk = new Uint8Array(12 + bytes);
475
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
476
+ chunk.set(encodeData, 12);
477
+ return chunk;
478
+ }
479
+ class ChunkReader {
480
+ constructor(stream) {
481
+ this.reader = stream.getReader();
482
+ this.store = new Uint8Array(0);
483
+ this.buffer = this.store;
484
+ this.done = false;
485
+ }
486
+ async readChunk() {
487
+ const chunk = await this.reader.read();
488
+ if (chunk.done) {
489
+ this.done = true;
490
+ return;
491
+ }
492
+ const incoming = chunk.value;
493
+ const store = this.store;
494
+ const start = this.buffer.byteOffset;
495
+ const end = start + this.buffer.length;
496
+ const needed = this.buffer.length + incoming.length;
497
+ if (end + incoming.length <= store.length) {
498
+ store.set(incoming, end);
499
+ this.buffer = store.subarray(start, end + incoming.length);
500
+ } else if (needed <= store.length) {
501
+ store.copyWithin(0, start, end);
502
+ store.set(incoming, this.buffer.length);
503
+ this.buffer = store.subarray(0, needed);
504
+ } else {
505
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
506
+ grown.set(this.buffer);
507
+ grown.set(incoming, this.buffer.length);
508
+ this.store = grown;
509
+ this.buffer = grown.subarray(0, needed);
510
+ }
511
+ }
512
+ async next() {
513
+ while (this.buffer.length < 12) {
514
+ if (this.done) {
515
+ if (this.buffer.length === 0) return {
516
+ done: true,
517
+ value: undefined
518
+ };
519
+ throw new Error("Malformed server function stream.");
520
+ }
521
+ await this.readChunk();
522
+ }
523
+ const decoder = new TextDecoder();
524
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
525
+ if (Number.isNaN(bytes)) {
526
+ throw new Error("Malformed server function stream.");
527
+ }
528
+ while (bytes > this.buffer.length - 12) {
529
+ if (this.done) {
530
+ throw new Error("Malformed server function stream.");
531
+ }
532
+ await this.readChunk();
533
+ }
534
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
535
+ this.buffer = this.buffer.subarray(12 + bytes);
536
+ return {
537
+ done: false,
538
+ value: partial
539
+ };
540
+ }
541
+ async drain(interpret) {
542
+ while (true) {
543
+ const result = await this.next();
544
+ if (result.done) {
545
+ break;
546
+ }
547
+ interpret(result.value);
548
+ }
549
+ }
550
+ cancel(reason) {
551
+ return this.reader.cancel(reason);
552
+ }
553
+ }
554
+ function createEventChunk(data, id) {
555
+ let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
556
+ for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
557
+ return new TextEncoder().encode(event + "\n");
558
+ }
559
+ const EVENT_STREAM_HEARTBEAT = new TextEncoder().encode(":\n\n");
560
+ function isEventStream(source) {
561
+ const contentType = source.headers.get("content-type");
562
+ return !!contentType && contentType.startsWith("text/event-stream");
563
+ }
564
+ class EventStreamReader {
565
+ constructor(stream, wire) {
566
+ this.reader = stream.getReader();
567
+ this.decoder = new TextDecoder();
568
+ this.wire = wire;
569
+ this.buffer = "";
570
+ this.done = false;
571
+ this.data = null;
572
+ this.id = undefined;
573
+ }
574
+ async read() {
575
+ const chunk = await this.reader.read();
576
+ if (chunk.done) {
577
+ this.done = true;
578
+ this.buffer += this.decoder.decode();
579
+ } else {
580
+ this.buffer += this.decoder.decode(chunk.value, {
581
+ stream: true
582
+ });
583
+ }
584
+ }
585
+ takeLine() {
586
+ const buffer = this.buffer;
587
+ const cr = buffer.indexOf("\r");
588
+ const lf = buffer.indexOf("\n");
589
+ const end = cr < 0 ? lf : lf < 0 ? cr : Math.min(cr, lf);
590
+ if (end < 0) return null;
591
+ let skip = 1;
592
+ if (buffer[end] === "\r") {
593
+ if (end + 1 === buffer.length) {
594
+ if (!this.done) return null;
595
+ } else if (buffer[end + 1] === "\n") skip = 2;
596
+ }
597
+ this.buffer = buffer.slice(end + skip);
598
+ return buffer.slice(0, end);
599
+ }
600
+ async next() {
601
+ while (true) {
602
+ const line = this.takeLine();
603
+ if (line === null) {
604
+ if (this.done) return {
605
+ done: true,
606
+ value: undefined
607
+ };
608
+ await this.read();
609
+ continue;
610
+ }
611
+ if (line === "") {
612
+ const data = this.data;
613
+ const id = this.id;
614
+ this.data = null;
615
+ this.id = undefined;
616
+ if (data === null) continue;
617
+ if (id !== undefined && this.wire) this.wire.position = id;
618
+ return {
619
+ done: false,
620
+ value: data.join("\n")
621
+ };
622
+ }
623
+ if (line[0] === ":") continue;
624
+ const colon = line.indexOf(":");
625
+ const field = colon < 0 ? line : line.slice(0, colon);
626
+ let value = colon < 0 ? "" : line.slice(colon + 1);
627
+ if (value[0] === " ") value = value.slice(1);
628
+ if (field === "data") (this.data ??= []).push(value);else if (field === "id" && !value.includes("\0")) this.id = value;
629
+ }
630
+ }
631
+ async drain(interpret) {
632
+ while (true) {
633
+ const result = await this.next();
634
+ if (result.done) {
635
+ break;
636
+ }
637
+ interpret(result.value);
638
+ }
639
+ }
640
+ cancel(reason) {
641
+ return this.reader.cancel(reason);
642
+ }
643
+ }
644
+ function positionDigest(value) {
645
+ if (value === undefined || !isJSONSafe(value)) return undefined;
646
+ const text = JSON.stringify(value);
647
+ if (typeof text !== "string") return undefined;
648
+ return textDigest(text);
649
+ }
650
+ function textDigest(text) {
651
+ let a = 0x811c9dc5;
652
+ let b = 0x050c5d1f;
653
+ for (let i = 0; i < text.length; i++) {
654
+ const code = text.charCodeAt(i);
655
+ a = Math.imul(a ^ code, 0x01000193);
656
+ b = Math.imul(b ^ code, 0x01000193);
657
+ }
658
+ return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
659
+ }
660
+ const ERROR_TRAILER_PREFIX = "!";
661
+ function errorFromTrailer(payload) {
662
+ let shape;
663
+ try {
664
+ shape = JSON.parse(payload.slice(1));
665
+ } catch {
666
+ shape = null;
667
+ }
668
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
669
+ if (shape && typeof shape.name === "string") error.name = shape.name;
670
+ return error;
671
+ }
672
+ function serializeStream(value, codecOptions) {
673
+ return new ReadableStream({
674
+ async start(controller) {
675
+ const {
676
+ serializeJSON
677
+ } = await import('@solidjs/web/serialization');
678
+ serializeJSON(value, {
679
+ ...codecOptions,
680
+ onParse(node) {
681
+ controller.enqueue(createChunk(JSON.stringify(node)));
682
+ },
683
+ onDone() {
684
+ controller.close();
685
+ },
686
+ onError(error) {
687
+ controller.error(error);
688
+ }
689
+ });
690
+ }
691
+ });
692
+ }
693
+ async function serializeString(value, codecOptions) {
694
+ const response = new Response(serializeStream(value, codecOptions));
695
+ return await response.text();
696
+ }
697
+ async function deserializeStream(source, codecOptions, wire) {
698
+ if (!source.body) {
699
+ throw new Error("missing body");
700
+ }
701
+ const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
702
+ const result = await reader.next();
703
+ if (!result.done) {
704
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
705
+ throw errorFromTrailer(result.value);
706
+ }
707
+ const {
708
+ createJSONDeserializer
709
+ } = await import('@solidjs/web/serialization/decode');
710
+ const deserializeChunk = createJSONDeserializer(codecOptions);
711
+ function interpretChunk(chunk) {
712
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
713
+ throw errorFromTrailer(chunk);
714
+ }
715
+ return deserializeChunk(JSON.parse(chunk));
716
+ }
717
+ const connection = wire && wire.connection;
718
+ let endConnection;
719
+ if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
720
+ const end = error => {
721
+ const sweep = () => deserializeChunk.abort(error);
722
+ if (connection) {
723
+ const close = () => deserializeChunk.close();
724
+ endConnection({
725
+ open: deserializeChunk.open(),
726
+ error,
727
+ sweep,
728
+ close
729
+ });
730
+ } else sweep();
731
+ };
732
+ reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
733
+ return interpretChunk(result.value);
734
+ }
735
+ return undefined;
736
+ }
737
+ async function decodeResponse(response, codecOptions) {
738
+ if (!response.body) return undefined;
739
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
740
+ }
741
+ async function decodeResponsePayload(response, codecOptions) {
742
+ const decoded = await decodeResponse(response, codecOptions);
743
+ if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
744
+ return {
745
+ value: decoded.value,
746
+ flightData: decoded.data
747
+ };
748
+ }
749
+ return {
750
+ value: decoded
751
+ };
752
+ }
753
+
754
+ const config = {
755
+ endpoint: "/_server",
756
+ fetch: undefined,
757
+ prepareRequest: undefined,
758
+ responseHandler: undefined,
759
+ serializeArgs: undefined
760
+ };
761
+ function serverFunctionUrl(fn, ...args) {
762
+ return serverFunctionUrlFor(config.endpoint, fn, args);
763
+ }
764
+ function serverFunctionActionUrl(fn, ...boundArgs) {
765
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
766
+ }
767
+ function parseServerFunctionActionUrl(url) {
768
+ const parsed = parseServerFunctionAddress(new URL(url, globalThis.location?.href || "http://localhost").pathname, config.endpoint);
769
+ return parsed && parsed.id;
770
+ }
771
+ function serializeArguments(args) {
772
+ if (!config.serializeArgs) {
773
+ 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.");
774
+ }
775
+ return config.serializeArgs(args);
776
+ }
777
+ function configureServerFunctionsClient({
778
+ endpoint,
779
+ codec,
780
+ fetch,
781
+ prepareRequest,
782
+ responseHandler,
783
+ serializeArgs
784
+ } = {}) {
785
+ if (endpoint !== undefined) config.endpoint = endpoint;
786
+ if (codec !== undefined) configureServerFunctionsCodec(codec);
787
+ if (fetch !== undefined) config.fetch = fetch;
788
+ if (prepareRequest !== undefined) config.prepareRequest = prepareRequest;
789
+ if (responseHandler !== undefined) config.responseHandler = responseHandler;
790
+ if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
791
+ }
792
+ let rpcProvided = false;
793
+ function provideRPC() {
794
+ if (rpcProvided) return;
795
+ rpcProvided = true;
796
+ provideServerFunctionRPC({
797
+ GET,
798
+ decodeResponse
799
+ });
800
+ }
801
+ function siblingAddressFor(base, kind) {
802
+ const splitAt = base.search(/[?#]/);
803
+ const path = splitAt < 0 ? base : base.slice(0, splitAt);
804
+ const rest = splitAt < 0 ? "" : base.slice(splitAt);
805
+ const slash = path.lastIndexOf("/");
806
+ if (path.endsWith(`/${kind}/`, slash + 1)) return base;
807
+ return `${path.slice(0, slash + 1)}${kind}/${path.slice(slash + 1)}${rest}`;
808
+ }
809
+ const dataAddressFor = base => siblingAddressFor(base, "data");
810
+ const liveAddressFor = base => siblingAddressFor(base, "live");
811
+ function serverFunctionFailure(response, value) {
812
+ const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
813
+ 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}`);
814
+ if (error instanceof Error && !("status" in error)) {
815
+ error.status = response.status;
816
+ const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
817
+ if (retryAfter !== undefined) error.retryAfter = retryAfter;
818
+ }
819
+ if (unknown && error instanceof Error) error.unknownFunction = true;
820
+ return error;
821
+ }
822
+ function parseRetryAfter(header) {
823
+ if (!header) return undefined;
824
+ const trimmed = header.trim();
825
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
826
+ const date = Date.parse(trimmed);
827
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
828
+ return undefined;
829
+ }
830
+ function isReadCall(options) {
831
+ return !!options.read || !!options.method && options.method.toUpperCase() === "GET";
832
+ }
833
+ async function createRequest(base, id, options, meta) {
834
+ const headers = {
835
+ ...options.headers
836
+ };
837
+ const wire = options[LIVE_WIRE];
838
+ if (wire) {
839
+ options = {
840
+ ...options
841
+ };
842
+ delete options[LIVE_WIRE];
843
+ if (wire.position !== undefined) headers[LAST_EVENT_ID_HEADER] = wire.position;
844
+ if (wire.headers) Object.assign(headers, wire.headers);
845
+ }
846
+ const flightSources = getFlightDataSourceIds();
847
+ if (flightSources.length > 0 && !isReadCall(options)) {
848
+ headers[SINGLE_FLIGHT_HEADER] = flightSources.join(",");
849
+ }
850
+ let init = {
851
+ method: "POST",
852
+ ...options,
853
+ headers
854
+ };
855
+ if (config.prepareRequest) {
856
+ const prepared = await config.prepareRequest(init, {
857
+ id,
858
+ meta
859
+ });
860
+ if (prepared && prepared !== init) {
861
+ if (typeof prepared !== "object") {
862
+ 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, ... } })");
863
+ }
864
+ if (typeof prepared.method !== "string" || prepared.method.toUpperCase() !== init.method.toUpperCase()) {
865
+ throw new Error(`prepareRequest returned an init without the transport's ${init.method} method, ` + "which would send the call without its payload or protocol. Spread the init it " + "received: init => ({ ...init, headers: { ...init.headers, ... } })");
866
+ }
867
+ }
868
+ init = prepared || init;
869
+ }
870
+ const send = config.fetch || fetch;
871
+ return send(base, init);
872
+ }
873
+ async function initializeResponse(base, id, options, args, meta) {
874
+ if (args.length === 0) {
875
+ return createRequest(base, id, options, meta);
876
+ }
877
+ if (args.length === 1) {
878
+ const result = getHeadersAndBody(args[0]);
879
+ if (result) {
880
+ return createRequest(base, id, {
881
+ ...options,
882
+ body: result.body,
883
+ headers: {
884
+ ...options.headers,
885
+ ...result.headers
886
+ }
887
+ }, meta);
888
+ }
889
+ }
890
+ try {
891
+ if (isJSONSafe(args)) {
892
+ return createRequest(base, id, {
893
+ ...options,
894
+ body: JSON.stringify(args),
895
+ headers: {
896
+ ...options.headers,
897
+ "Content-Type": "application/json",
898
+ [BODY_FORMAT_HEADER]: BodyFormat.Json
899
+ }
900
+ }, meta);
901
+ }
902
+ } catch {
903
+ }
904
+ if (args.length > 1) {
905
+ try {
906
+ const last = args[args.length - 1];
907
+ const trailing = typeof last !== "string" && getHeadersAndBody(last);
908
+ const leading = args.slice(0, -1).map(arg => arg === undefined ? null : arg);
909
+ if (trailing && isJSONSafe(leading)) {
910
+ const target = base + (base.includes("?") ? "&" : "?") + "args=" + encodeURIComponent(JSON.stringify(leading));
911
+ return createRequest(target, id, {
912
+ ...options,
913
+ body: trailing.body,
914
+ headers: {
915
+ ...options.headers,
916
+ ...trailing.headers
917
+ }
918
+ }, meta);
919
+ }
920
+ } catch {
921
+ }
922
+ }
923
+ return createRequest(base, id, {
924
+ ...options,
925
+ body: await serializeArguments(args),
926
+ headers: {
927
+ ...options.headers,
928
+ "Content-Type": "text/plain",
929
+ [BODY_FORMAT_HEADER]: BodyFormat.Serialized
930
+ }
931
+ }, meta);
932
+ }
933
+ async function observedFetch(base, id, options, args, meta, callArgs = args) {
934
+ const observation = observeCall(id, options.method && options.method.toUpperCase() === "GET" ? "GET" : "POST", callArgs);
935
+ if (!observation) return dispatchServerFunction(base, id, options, args, meta, callArgs);
936
+ let result;
937
+ try {
938
+ result = await dispatchServerFunction(base, id, options, args, meta, callArgs, observation);
939
+ } catch (error) {
940
+ observation.settle("error", error);
941
+ throw error;
942
+ }
943
+ observation.settle("ok", result);
944
+ return result;
945
+ }
946
+ const fetchServerFunction = observedFetch ;
947
+ async function dispatchServerFunction(base, id, options, args, meta, callArgs = args, observation) {
948
+ const handler = config.responseHandler;
949
+ const context = handler && handler.capture ? handler.capture({
950
+ id,
951
+ meta
952
+ }) : undefined;
953
+ const controller = options.signal ? undefined : new AbortController();
954
+ if (controller) options = {
955
+ ...options,
956
+ signal: controller.signal
957
+ };
958
+ const response = await initializeResponse(base, id, options, args, meta);
959
+ if (observation) observation.response(response);
960
+ if (handler) {
961
+ const ctx = {
962
+ id,
963
+ meta,
964
+ args: callArgs,
965
+ context
966
+ };
967
+ if (options[LIVE_WIRE]) ctx[LIVE_WIRE] = options[LIVE_WIRE];
968
+ const handled = handler.handle(response, ctx);
969
+ if (handled !== undefined) return handled;
970
+ }
971
+ if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
972
+ throw serverFunctionFailure(response, undefined);
973
+ }
974
+ const failed = response.headers.has(ERROR_HEADER);
975
+ if (!isReadCall(options) && getFlightDataSourceIds().length > 0) {
976
+ const folded = response.headers.has(SINGLE_FLIGHT_HEADER);
977
+ const metadata = hasFlightMetadata(response);
978
+ if (metadata || folded) {
979
+ const decoded = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
980
+ const enveloped = folded && decoded !== undefined;
981
+ const value = enveloped ? decoded.value : decoded;
982
+ await deliverFlightData(response, enveloped ? decoded.data : undefined);
983
+ if (failed && !metadata) {
984
+ throw serverFunctionFailure(response, value);
985
+ }
986
+ return value;
987
+ }
988
+ }
989
+ 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) {
990
+ return response;
991
+ }
992
+ if (response.status < 300 && !response.headers.has(BODY_FORMAT_HEADER) && !response.headers.has("X-Content-Raw")) {
993
+ 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`));
994
+ }
995
+ const result = response.body ? await extractBody(response, getServerFunctionsCodec(), options[LIVE_WIRE]) : undefined;
996
+ if (failed) {
997
+ throw serverFunctionFailure(response, result);
998
+ }
999
+ if (controller && result?.[Symbol.asyncIterator]) {
1000
+ return {
1001
+ [Symbol.asyncIterator]() {
1002
+ const it = result[Symbol.asyncIterator]();
1003
+ return {
1004
+ next: () => it.next(),
1005
+ return: value => (controller.abort(), Promise.resolve({
1006
+ done: true,
1007
+ value
1008
+ }))
1009
+ };
1010
+ }
1011
+ };
1012
+ }
1013
+ return result;
1014
+ }
1015
+ function createServerReference(id, name, base) {
1016
+ provideRPC();
1017
+ const metadata = name === undefined ? {} : {
1018
+ name
1019
+ };
1020
+ const run = (args, invokeOptions) => {
1021
+ const send = () => fetchServerFunction(base ? dataAddressFor(base) : serverFunctionDataAddress(config.endpoint, id), id, invokeOptions ? {
1022
+ ...invokeOptions
1023
+ } : {}, args, metadata);
1024
+ const handler = config.responseHandler;
1025
+ if (handler && handler.intercept && !adoptedCall(invokeOptions)) {
1026
+ const hit = handler.intercept({
1027
+ id,
1028
+ meta: metadata,
1029
+ args
1030
+ });
1031
+ if (hit !== undefined) return localOrSend(hit, send);
1032
+ }
1033
+ return send();
1034
+ };
1035
+ const fn = (...args) => run(args);
1036
+ fn[SERVER_FUNCTION_METADATA] = metadata;
1037
+ fn[SERVER_FUNCTION_INVOKE] = run;
1038
+ return new Proxy(fn, {
1039
+ get(target, prop) {
1040
+ if (prop === "id") return id;
1041
+ if (prop === "url") {
1042
+ return base || serverFunctionAddress(config.endpoint, id);
1043
+ }
1044
+ return target[prop];
1045
+ }
1046
+ });
1047
+ }
1048
+ function GET(fn) {
1049
+ if (!isServerFunction(fn)) {
1050
+ throw new Error("GET expects a server function reference");
1051
+ }
1052
+ provideRPC();
1053
+ const id = fn.id;
1054
+ const metadata = {
1055
+ ...getServerFunctionMetadata(fn)
1056
+ };
1057
+ const run = async (args, invokeOptions) => {
1058
+ const handler = config.responseHandler;
1059
+ if (handler && handler.intercept && !adoptedCall(invokeOptions)) {
1060
+ const hit = handler.intercept({
1061
+ id,
1062
+ meta: metadata,
1063
+ args
1064
+ });
1065
+ if (hit !== undefined) return localOrSend(hit, () => send(args, invokeOptions));
1066
+ }
1067
+ return send(args, invokeOptions);
1068
+ };
1069
+ const send = async (args, invokeOptions) => {
1070
+ const opts = invokeOptions || {};
1071
+ const address = opts[LIVE_WIRE] ? serverFunctionLiveAddress(config.endpoint, id) : serverFunctionDataAddress(config.endpoint, id);
1072
+ if (!args.length) {
1073
+ return fetchServerFunction(address, id, {
1074
+ ...opts,
1075
+ method: "GET"
1076
+ }, [], metadata, args);
1077
+ }
1078
+ const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
1079
+ const url = `${address}?args=${encodeURIComponent(encoded)}`;
1080
+ const absolute = new URL(url, globalThis.location?.href || "http://localhost").href;
1081
+ if (absolute.length > MAX_GET_URL_LENGTH) {
1082
+ return fetchServerFunction(address, id, {
1083
+ ...opts,
1084
+ read: true
1085
+ }, args, metadata);
1086
+ }
1087
+ return fetchServerFunction(url, id, {
1088
+ ...opts,
1089
+ method: "GET"
1090
+ }, [], metadata, args);
1091
+ };
1092
+ const wrapped = (...args) => run(args);
1093
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
1094
+ wrapped[SERVER_FUNCTION_INVOKE] = run;
1095
+ wrapped.id = id;
1096
+ Object.defineProperty(wrapped, "url", {
1097
+ get: () => serverFunctionAddress(config.endpoint, id),
1098
+ configurable: true
1099
+ });
1100
+ return withMeta(wrapped, {
1101
+ method: "GET"
1102
+ });
1103
+ }
1104
+ const openLiveConnections = new Map() ;
1105
+ let warnedHttp1 = false;
1106
+ function trackLiveConnection(id, open) {
1107
+ const count = openLiveConnections.get(id) || 0;
1108
+ if (open) openLiveConnections.set(id, count + 1);else if (count > 1) openLiveConnections.set(id, count - 1);else openLiveConnections.delete(id);
1109
+ if (!open || warnedHttp1) return;
1110
+ let total = 0;
1111
+ for (const n of openLiveConnections.values()) total += n;
1112
+ if (total <= 5) return;
1113
+ const navigation = typeof performance !== "undefined" && typeof performance.getEntriesByType === "function" ? performance.getEntriesByType("navigation")[0] : undefined;
1114
+ const protocol = navigation && navigation.nextHopProtocol;
1115
+ if (typeof protocol !== "string" || !/^http\/1(\.[01])?$/.test(protocol)) return;
1116
+ warnedHttp1 = true;
1117
+ const names = [...openLiveConnections].map(([fnId, n]) => n > 1 ? `${fnId} ×${n}` : fnId);
1118
+ console.warn(`live: ${total} live connections are open (${names.join(", ")}) and this page was served ` + `over ${protocol}. Browsers allow six connections per origin under HTTP/1.1, so the next ` + `request to this origin — a navigation, a fetch, an image — waits behind them. live ` + `requires HTTP/2: the dev server speaks it with \`server.https\`; production hosts do by default.`);
1119
+ }
1120
+ function localOrSend(hit, send) {
1121
+ if (hit === null || typeof hit.then !== "function") return hit;
1122
+ return hit.then(answer => answer === undefined ? send() : answer);
1123
+ }
1124
+ function adoptedCall(options) {
1125
+ const wire = options && options[LIVE_WIRE];
1126
+ return !!(wire && wire.adopted);
1127
+ }
1128
+ function live(fn) {
1129
+ if (!isServerFunction(fn)) {
1130
+ throw new Error("live expects a server function reference");
1131
+ }
1132
+ const id = fn.id;
1133
+ const metadata = {
1134
+ ...getServerFunctionMetadata(fn),
1135
+ live: true
1136
+ };
1137
+ const makeIterable = (args, invokeOptions) => {
1138
+ const handler = config.responseHandler;
1139
+ const local = handler && handler.intercept ? handler.intercept({
1140
+ id,
1141
+ meta: metadata,
1142
+ args
1143
+ }) : undefined;
1144
+ const iterable = {
1145
+ [LIVE_SOURCE]: true,
1146
+ [Symbol.asyncIterator]() {
1147
+ let it;
1148
+ let connected = false;
1149
+ let attempts = 0;
1150
+ let stopped = false;
1151
+ let closed = false;
1152
+ let ended;
1153
+ let timer, wake;
1154
+ const DONE = {
1155
+ done: true,
1156
+ value: undefined
1157
+ };
1158
+ const invokeSignal = invokeOptions && invokeOptions.signal;
1159
+ const controller = new AbortController();
1160
+ let resume = iterable[LIVE_RESUME_FROM];
1161
+ let seed = iterable[LIVE_LOCAL];
1162
+ const wire = {
1163
+ position: resume !== undefined ? positionDigest(resume) : undefined,
1164
+ connection: undefined,
1165
+ adopted: resume !== undefined,
1166
+ open: body => new EventStreamReader(body, wire)
1167
+ };
1168
+ const ends = [];
1169
+ const settle = (end, error) => {
1170
+ try {
1171
+ error !== undefined ? end.sweep() : end.close();
1172
+ } catch {}
1173
+ };
1174
+ const settleAll = error => {
1175
+ while (ends.length) settle(ends.pop(), error);
1176
+ };
1177
+ const wireOptions = {
1178
+ ...invokeOptions,
1179
+ [LIVE_WIRE]: wire,
1180
+ signal: invokeSignal ? AbortSignal.any([invokeSignal, controller.signal]) : controller.signal
1181
+ };
1182
+ const emit = (state, error) => {
1183
+ try {
1184
+ iterable.onstatus && iterable.onstatus(state, error);
1185
+ } catch {}
1186
+ };
1187
+ let counted = false;
1188
+ const track = open => {
1189
+ if (open === counted) return;
1190
+ counted = open;
1191
+ trackLiveConnection(id, open);
1192
+ };
1193
+ const emitClosed = error => {
1194
+ track(false);
1195
+ settleAll(error);
1196
+ if (ended) ended.then(end => settle(end, error));
1197
+ if (closed) return;
1198
+ closed = true;
1199
+ emit("closed", error);
1200
+ };
1201
+ const closeIt = value => {
1202
+ track(false);
1203
+ const current = it;
1204
+ it = undefined;
1205
+ if (current) {
1206
+ try {
1207
+ const r = current.return && current.return(value);
1208
+ if (r && typeof r.then === "function") r.then(undefined, () => {});
1209
+ } catch {}
1210
+ }
1211
+ };
1212
+ const callOnce = () => {
1213
+ const handler = config.responseHandler;
1214
+ if (handler && handler.resume) {
1215
+ const from = handler.resume({
1216
+ id,
1217
+ meta: metadata,
1218
+ args
1219
+ });
1220
+ wire.headers = from ? from.headers : undefined;
1221
+ if (from && from.position !== undefined) wire.position = from.position;
1222
+ }
1223
+ if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1224
+ if (handler && handler.intercept && !wire.adopted) {
1225
+ const hit = handler.intercept({
1226
+ id,
1227
+ meta: metadata,
1228
+ args
1229
+ });
1230
+ if (hit !== undefined) return hit;
1231
+ }
1232
+ return fetchServerFunction(liveAddressFor(fn.url), id, {
1233
+ ...wireOptions,
1234
+ read: true
1235
+ }, args, metadata, args);
1236
+ };
1237
+ const pull = async () => {
1238
+ if (resume !== undefined) {
1239
+ const value = resume;
1240
+ resume = undefined;
1241
+ if (!stopped) return {
1242
+ done: false,
1243
+ value
1244
+ };
1245
+ }
1246
+ if (seed !== undefined) {
1247
+ const value = typeof seed.then === "function" ? await seed : seed;
1248
+ seed = undefined;
1249
+ if (value !== undefined) {
1250
+ wire.adopted = true;
1251
+ if (!stopped) return {
1252
+ done: false,
1253
+ value
1254
+ };
1255
+ }
1256
+ }
1257
+ while (!stopped) {
1258
+ try {
1259
+ if (!it) {
1260
+ const connection = wire.connection = {
1261
+ ended: undefined
1262
+ };
1263
+ const result = await callOnce();
1264
+ connected = true;
1265
+ ended = connection.ended;
1266
+ it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : async function* () {
1267
+ yield result;
1268
+ }();
1269
+ if (stopped) {
1270
+ closeIt();
1271
+ controller.abort();
1272
+ return DONE;
1273
+ }
1274
+ track(true);
1275
+ emit("connected");
1276
+ }
1277
+ const r = await (ended ? Promise.race([it.next(), ended.then(end => ({
1278
+ end
1279
+ }))]) : it.next());
1280
+ if (r.end || r.done) {
1281
+ const end = r.end || ended && (await ended);
1282
+ if (end && end.open > 0) {
1283
+ ends.push(end);
1284
+ throw end.error;
1285
+ }
1286
+ if (end) settle(end);
1287
+ emitClosed();
1288
+ return DONE;
1289
+ }
1290
+ if (stopped) return DONE;
1291
+ attempts = 0;
1292
+ return r;
1293
+ } catch (error) {
1294
+ if (stopped) return DONE;
1295
+ if (!connected) throw error;
1296
+ if (invokeSignal && invokeSignal.aborted) {
1297
+ stopped = true;
1298
+ emitClosed(error);
1299
+ throw error;
1300
+ }
1301
+ 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") {
1302
+ stopped = true;
1303
+ emitClosed(error);
1304
+ throw error;
1305
+ }
1306
+ closeIt();
1307
+ emit("reconnecting", error);
1308
+ await new Promise(resolve => {
1309
+ wake = resolve;
1310
+ const named = error !== null && typeof error === "object" && typeof error.retryAfter === "number" ? Math.min(error.retryAfter * 1000, 60000) : undefined;
1311
+ timer = setTimeout(resolve, named ?? Math.min(500 * 2 ** attempts++, 10000));
1312
+ if (typeof addEventListener === "function") addEventListener("online", resolve, {
1313
+ once: true
1314
+ });
1315
+ if (invokeSignal) invokeSignal.addEventListener("abort", resolve, {
1316
+ once: true
1317
+ });
1318
+ });
1319
+ clearTimeout(timer);
1320
+ if (typeof removeEventListener === "function") removeEventListener("online", wake);
1321
+ if (invokeSignal) invokeSignal.removeEventListener("abort", wake);
1322
+ timer = wake = undefined;
1323
+ }
1324
+ }
1325
+ return DONE;
1326
+ };
1327
+ return {
1328
+ next: () => pull(),
1329
+ return(value) {
1330
+ stopped = true;
1331
+ if (timer !== undefined) clearTimeout(timer);
1332
+ if (wake) wake();
1333
+ closeIt(value);
1334
+ controller.abort();
1335
+ emitClosed();
1336
+ return Promise.resolve({
1337
+ done: true,
1338
+ value
1339
+ });
1340
+ }
1341
+ };
1342
+ }
1343
+ };
1344
+ if (local !== undefined) iterable[LIVE_LOCAL] = local;
1345
+ return iterable;
1346
+ };
1347
+ const wrapped = (...args) => makeIterable(args);
1348
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
1349
+ wrapped[SERVER_FUNCTION_INVOKE] = makeIterable;
1350
+ wrapped.id = id;
1351
+ Object.defineProperty(wrapped, "url", {
1352
+ get: () => fn.url,
1353
+ configurable: true
1354
+ });
1355
+ return wrapped;
1356
+ }
1357
+ function registerServerReference() {
1358
+ throw new Error("registerServerReference must not be called in the client build");
1359
+ }
1360
+ function getServerFunctionInvocation() {
1361
+ return undefined;
1362
+ }
1363
+
1364
+ export { ChunkReader, ERROR_HEADER, EVENT_STREAM_HEARTBEAT, EventStreamReader, FLASH_COOKIE, GET, LAST_EVENT_ID_HEADER, LIVE_WIRE, REDIRECT_HEADER, REVALIDATE_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsClient, createChunk, createEventChunk, createServerReference, decodeErrorHeaderValue, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, deliverFlightData, deserializeStream, encodeErrorHeaderValue, frameAddress, getFlightDataConsumer, getFlightDataSourceIds, getServerFunctionInvocation, getServerFunctionMetadata, getServerFunctionsCodec, hasFlashCookie, hasFlightMetadata, invoke, isEventStream, isServerFunction, live, parseServerFunctionActionUrl, positionDigest, registerServerReference, serializeString, serverFunctionActionUrl, serverFunctionUrl, subscribeFlightData, withMeta };