@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.20

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