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

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 (36) hide show
  1. package/dist/server.dev.js +626 -125
  2. package/dist/server.js +433 -95
  3. package/dist/server.observe.js +3980 -0
  4. package/dist/web.dev.js +208 -60
  5. package/dist/web.js +175 -58
  6. package/dist/web.observe.js +175 -58
  7. package/frames/dist/client.dev.js +103 -4
  8. package/frames/dist/client.js +5 -2
  9. package/frames/dist/client.observe.js +2123 -0
  10. package/frames/dist/server.dev.js +521 -79
  11. package/frames/dist/server.js +352 -52
  12. package/frames/dist/server.observe.js +4946 -0
  13. package/frames/package.json +12 -0
  14. package/package.json +87 -3
  15. package/server-functions/dist/client.dev.js +1102 -0
  16. package/server-functions/dist/client.js +74 -69
  17. package/server-functions/dist/client.observe.js +1102 -0
  18. package/server-functions/dist/server.dev.js +402 -31
  19. package/server-functions/dist/server.js +339 -30
  20. package/server-functions/dist/server.observe.js +2726 -0
  21. package/server-functions/package.json +12 -0
  22. package/types/client.d.ts +22 -1
  23. package/types/diagnostics.d.ts +24 -0
  24. package/types/frames/frame-transport.d.ts +1 -1
  25. package/types/index.d.ts +25 -15
  26. package/types/index.server.d.ts +35 -8
  27. package/types/jsx.d.ts +15 -4
  28. package/types/observe.d.ts +294 -0
  29. package/types/response.d.ts +18 -0
  30. package/types/server-functions/client.d.ts +32 -22
  31. package/types/server-functions/server.d.ts +28 -37
  32. package/types/server-functions/shared.d.ts +39 -9
  33. package/types/server-mock.d.ts +26 -4
  34. package/types/server-observe.d.ts +39 -0
  35. package/types/server.d.ts +104 -5
  36. package/types/trace.d.ts +79 -0
@@ -0,0 +1,2726 @@
1
+ import { OBSERVE, getOwner, sharedConfig } from 'solid-js';
2
+ import { reportServerError } from 'solid-js/internal';
3
+
4
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
5
+ function isHttpNavigationTarget(target) {
6
+ try {
7
+ const protocol = new URL(target, "http://base.invalid").protocol;
8
+ return protocol === "http:" || protocol === "https:";
9
+ } catch {
10
+ return false;
11
+ }
12
+ }
13
+
14
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
15
+ function isResponseEnvelope(value) {
16
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
17
+ }
18
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
19
+ function isSafeError(value) {
20
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
21
+ }
22
+ const REVALIDATE_HEADER = "X-Revalidate";
23
+ const RESPONSE_HEADER_VALUE_LIMIT = 4096;
24
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
25
+
26
+ const PROVIDER = Symbol.for("solid-js/observe/server/provider");
27
+ function currentProvider() {
28
+ if (OBSERVE === undefined) return undefined;
29
+ const slot = OBSERVE.server.trace;
30
+ return slot && slot[PROVIDER];
31
+ }
32
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
33
+ const ZERO_TRACE = "00000000000000000000000000000000";
34
+ const ZERO_SPAN = "0000000000000000";
35
+ function parseTraceparent(value) {
36
+ if (!value) return undefined;
37
+ const m = TRACEPARENT.exec(value.trim());
38
+ if (!m) return undefined;
39
+ const [, version, traceId, parentId, flags, rest] = m;
40
+ if (version === "ff") return undefined;
41
+ if (version === "00" && rest !== undefined) return undefined;
42
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
43
+ return {
44
+ traceId,
45
+ parentId,
46
+ sampled: (parseInt(flags, 16) & 1) === 1
47
+ };
48
+ }
49
+ function randomHex(bytes) {
50
+ const buffer = new Uint8Array(bytes);
51
+ crypto.getRandomValues(buffer);
52
+ let out = "";
53
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
54
+ return out;
55
+ }
56
+ function randomTraceId() {
57
+ let id = randomHex(16);
58
+ while (id === ZERO_TRACE) id = randomHex(16);
59
+ return id;
60
+ }
61
+ function randomSpanId() {
62
+ let id = randomHex(8);
63
+ while (id === ZERO_SPAN) id = randomHex(8);
64
+ return id;
65
+ }
66
+ function formatTraceparent(context) {
67
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
68
+ }
69
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
70
+ function records$1() {
71
+ const g = globalThis;
72
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
73
+ }
74
+ function traceFor(key, request) {
75
+ const store = records$1();
76
+ let record = store.get(key);
77
+ if (record) return record;
78
+ const headers = request ? request.headers : undefined;
79
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
80
+ const context = {
81
+ traceId: incoming ? incoming.traceId : randomTraceId(),
82
+ spanId: randomSpanId(),
83
+ entries: {}
84
+ };
85
+ if (incoming) {
86
+ context.parentId = incoming.parentId;
87
+ context.sampled = incoming.sampled;
88
+ }
89
+ if (headers) {
90
+ const state = headers.get("tracestate");
91
+ if (state) context.state = state;
92
+ const baggage = headers.get("baggage");
93
+ if (baggage) context.baggage = baggage;
94
+ }
95
+ let answered = false;
96
+ let providedEntries;
97
+ {
98
+ const provider = currentProvider();
99
+ if (provider) {
100
+ let answer;
101
+ try {
102
+ answer = provider(request);
103
+ } catch (error) {
104
+ console.error(error);
105
+ }
106
+ if (answer !== undefined && answer !== null) {
107
+ answered = true;
108
+ if (answer.traceId !== undefined) context.traceId = answer.traceId;
109
+ if (answer.spanId !== undefined) context.spanId = answer.spanId;
110
+ if (answer.parentId !== undefined) context.parentId = answer.parentId;
111
+ if (answer.sampled !== undefined) context.sampled = answer.sampled;
112
+ if (answer.state !== undefined) context.state = answer.state;
113
+ if (answer.baggage !== undefined) context.baggage = answer.baggage;
114
+ providedEntries = answer.entries;
115
+ }
116
+ }
117
+ }
118
+ context.entries.traceparent = formatTraceparent(context);
119
+ if (providedEntries) Object.assign(context.entries, providedEntries);
120
+ record = {
121
+ context,
122
+ emit: incoming !== undefined && incoming.sampled || answered
123
+ };
124
+ store.set(key, record);
125
+ return record;
126
+ }
127
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
128
+ function splitServerTiming(value) {
129
+ const entries = [];
130
+ let start = 0;
131
+ let quoted = false;
132
+ for (let i = 0; i < value.length; i++) {
133
+ const c = value[i];
134
+ if (quoted) {
135
+ if (c === "\\") i++;else if (c === '"') quoted = false;
136
+ } else if (c === '"') quoted = true;else if (c === ",") {
137
+ entries.push(value.slice(start, i));
138
+ start = i + 1;
139
+ }
140
+ }
141
+ entries.push(value.slice(start));
142
+ return entries;
143
+ }
144
+ function metricName(entry) {
145
+ return entry.split(";")[0].trim().toLowerCase();
146
+ }
147
+ function namesOnServerTiming(headers) {
148
+ const names = new Set();
149
+ const existing = headers.get("server-timing");
150
+ if (existing) {
151
+ for (const entry of splitServerTiming(existing)) {
152
+ const name = metricName(entry);
153
+ if (name) names.add(name);
154
+ }
155
+ }
156
+ return names;
157
+ }
158
+ function quoteDesc(value) {
159
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\"]/g, m => "\\" + m);
160
+ }
161
+ function appendTraceServerTiming(headers, record) {
162
+ if (!record.emit) return;
163
+ const entries = record.context.entries;
164
+ let present;
165
+ for (const name in entries) {
166
+ if (!TOKEN.test(name)) continue;
167
+ if (!present) present = namesOnServerTiming(headers);
168
+ if (present.has(name.toLowerCase())) continue;
169
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
170
+ present.add(name.toLowerCase());
171
+ }
172
+ }
173
+ function mergeServerTiming(target, value) {
174
+ const present = namesOnServerTiming(target);
175
+ for (const entry of splitServerTiming(value)) {
176
+ const trimmed = entry.trim();
177
+ const name = metricName(trimmed);
178
+ if (!name || present.has(name)) continue;
179
+ target.append("Server-Timing", trimmed);
180
+ present.add(name);
181
+ }
182
+ }
183
+
184
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
185
+ function getServerFunctionMetadata(fn) {
186
+ if (typeof fn !== "function") return undefined;
187
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
188
+ }
189
+ function isServerFunction(fn) {
190
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
191
+ }
192
+ function withMeta(fn, meta) {
193
+ const metadata = getServerFunctionMetadata(fn);
194
+ if (!metadata) {
195
+ throw new Error("withMeta expects a server function reference");
196
+ }
197
+ Object.assign(metadata, meta);
198
+ return fn;
199
+ }
200
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
201
+ const INVOKE_OPTION_REDIRECTS = {
202
+ 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.",
203
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
204
+ body: "The arguments are the body: pass them in the args array.",
205
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
206
+ };
207
+ function invoke(fn, options, ...args) {
208
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
209
+ if (!channel) {
210
+ 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.");
211
+ }
212
+ if (options === null || typeof options !== "object") {
213
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
214
+ }
215
+ const picked = {};
216
+ for (const key in options) {
217
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
218
+ 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."));
219
+ }
220
+ }
221
+ if (options.signal !== undefined) picked.signal = options.signal;
222
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
223
+ if (options.priority !== undefined) picked.priority = options.priority;
224
+ return channel(args, picked);
225
+ }
226
+ const LIVE_SOURCE = Symbol.for("solid.LiveSource");
227
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
228
+ function provideServerFunctionRPC(rpc) {
229
+ globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
230
+ }
231
+
232
+ function parseCookieHeader(header) {
233
+ const cookies = {};
234
+ if (!header) return cookies;
235
+ for (const part of header.split(";")) {
236
+ const eq = part.indexOf("=");
237
+ if (eq < 0) continue;
238
+ const name = decodeSafe(part.slice(0, eq).trim());
239
+ let value = part.slice(eq + 1).trim();
240
+ if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
241
+ value = value.slice(1, -1);
242
+ }
243
+ cookies[name] = decodeSafe(value);
244
+ }
245
+ return cookies;
246
+ }
247
+ function decodeSafe(text) {
248
+ try {
249
+ return decodeURIComponent(text);
250
+ } catch {
251
+ return text;
252
+ }
253
+ }
254
+ function serializeCookie(name, value, options = {}) {
255
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
256
+ cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
257
+ if (options.domain) cookie += `; Domain=${options.domain}`;
258
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
259
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
260
+ if (options.httpOnly) cookie += "; HttpOnly";
261
+ if (options.secure) cookie += "; Secure";
262
+ if (options.partitioned) cookie += "; Partitioned";
263
+ if (options.sameSite) {
264
+ const sameSite = options.sameSite.toLowerCase();
265
+ cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
266
+ }
267
+ return cookie;
268
+ }
269
+ const FLASH_COOKIE = "flash";
270
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
271
+ function hasFlashCookie(cookieHeader) {
272
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
273
+ }
274
+ function clearFlashCookie() {
275
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
276
+ }
277
+
278
+ const codecConfig = {
279
+ codec: undefined
280
+ };
281
+ function configureServerFunctionsCodec(codec) {
282
+ codecConfig.codec = codec;
283
+ }
284
+ function getServerFunctionsCodec() {
285
+ return codecConfig.codec;
286
+ }
287
+ const UNNAMED_FLIGHT_SOURCE = "true";
288
+ const flightConfig = {
289
+ consumers: new Map()
290
+ };
291
+ function assertFlightSource(source) {
292
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
293
+ 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).`);
294
+ }
295
+ }
296
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
297
+ const named = typeof sourceOrConsumer === "string";
298
+ if (named) assertFlightSource(sourceOrConsumer);
299
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
300
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
301
+ flightConfig.consumers.set(source, consumer);
302
+ return () => {
303
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
304
+ };
305
+ }
306
+ function serverFunctionAddress(endpoint, id) {
307
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
308
+ return `${mount}/${encodeURIComponent(id)}`;
309
+ }
310
+ function serverFunctionDataAddress(endpoint, id) {
311
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
312
+ return `${mount}/data/${encodeURIComponent(id)}`;
313
+ }
314
+ function parseServerFunctionAddress(pathname, endpoint) {
315
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
316
+ if (!pathname.startsWith(mount)) return null;
317
+ const rest = pathname.slice(mount.length);
318
+ if (!rest.startsWith("/")) return null;
319
+ let segment = rest.slice(1);
320
+ let data = false;
321
+ if (segment.startsWith("data/")) {
322
+ segment = segment.slice(5);
323
+ data = true;
324
+ }
325
+ if (!segment || segment.includes("/")) return null;
326
+ try {
327
+ return {
328
+ id: decodeURIComponent(segment),
329
+ data
330
+ };
331
+ } catch {
332
+ return null;
333
+ }
334
+ }
335
+ const MAX_GET_URL_LENGTH = 2000;
336
+ function urlTargetId(target, helper) {
337
+ if (typeof target === "string") return target;
338
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
339
+ throw new Error(`${helper} expects a server function reference (or its id).`);
340
+ }
341
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
342
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
343
+ if (!boundArgs.length) return address;
344
+ if (!isJSONSafe(boundArgs)) {
345
+ 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.");
346
+ }
347
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
348
+ }
349
+ function serverFunctionUrlFor(endpoint, fn, args) {
350
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
351
+ throw new Error("serverFunctionUrl expects a server function reference.");
352
+ }
353
+ const metadata = getServerFunctionMetadata(fn);
354
+ if (!metadata || metadata.method !== "GET") {
355
+ 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).');
356
+ }
357
+ const address = serverFunctionDataAddress(endpoint, fn.id);
358
+ if (!args.length) return address;
359
+ if (!isJSONSafe(args)) {
360
+ 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.");
361
+ }
362
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
363
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
364
+ if (length > MAX_GET_URL_LENGTH) {
365
+ 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.");
366
+ }
367
+ return url;
368
+ }
369
+ const ERROR_HEADER = "X-Server-Function-Error";
370
+ const ERROR_HEADER_MARKER = "=?1?";
371
+ const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
372
+ function encodeErrorHeaderValue(value) {
373
+ let stripped = String(value).replace(/[\r\n]+/g, "");
374
+ if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
375
+ return stripped;
376
+ }
377
+ if (typeof stripped.toWellFormed === "function") {
378
+ stripped = stripped.toWellFormed();
379
+ } else {
380
+ stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
381
+ }
382
+ return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
383
+ }
384
+ function decodeErrorHeaderValue(value) {
385
+ if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
386
+ return value;
387
+ }
388
+ try {
389
+ return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
390
+ } catch {
391
+ return value;
392
+ }
393
+ }
394
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
395
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
396
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
397
+ function decodeRedirectHeaderValue(value) {
398
+ if (typeof value !== "string") return undefined;
399
+ const at = value.indexOf(" ");
400
+ if (at < 0) return undefined;
401
+ const status = Number(value.slice(0, at));
402
+ const url = value.slice(at + 1);
403
+ if (!Number.isInteger(status) || !url) return undefined;
404
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
405
+ let parsed;
406
+ try {
407
+ parsed = new URL(url);
408
+ } catch {
409
+ return undefined;
410
+ }
411
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
412
+ return {
413
+ status,
414
+ url
415
+ };
416
+ }
417
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
418
+ const FILE_FORM_KEY = "__server_function_file__";
419
+ const BodyFormat = {
420
+ Serialized: "0",
421
+ String: "1",
422
+ FormData: "2",
423
+ URLSearchParams: "3",
424
+ Blob: "4",
425
+ File: "5",
426
+ ArrayBuffer: "6",
427
+ Uint8Array: "7",
428
+ Json: "8",
429
+ Void: "9"
430
+ };
431
+ const JSON_SAFE_DEPTH_LIMIT = 4096;
432
+ const EXIT = {};
433
+ function isJSONSafe(value) {
434
+ const stack = [value];
435
+ const ancestors = new Set();
436
+ while (stack.length) {
437
+ const v = stack.pop();
438
+ if (v === EXIT) {
439
+ ancestors.delete(stack.pop());
440
+ continue;
441
+ }
442
+ if (v === null) continue;
443
+ const t = typeof v;
444
+ if (t === "string" || t === "boolean") continue;
445
+ if (t === "number") {
446
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
447
+ continue;
448
+ }
449
+ if (t !== "object") return false;
450
+ if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
451
+ ancestors.add(v);
452
+ stack.push(v, EXIT);
453
+ if (Array.isArray(v)) {
454
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
455
+ } else {
456
+ const proto = Object.getPrototypeOf(v);
457
+ if (proto !== Object.prototype && proto !== null) return false;
458
+ if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
459
+ for (const k in v) {
460
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
461
+ if (descriptor === undefined || !("value" in descriptor)) return false;
462
+ stack.push(descriptor.value);
463
+ }
464
+ }
465
+ }
466
+ return true;
467
+ }
468
+ function getHeadersAndBody(body) {
469
+ switch (true) {
470
+ case typeof body === "string":
471
+ return {
472
+ headers: {
473
+ "Content-Type": "text/plain",
474
+ [BODY_FORMAT_HEADER]: BodyFormat.String
475
+ },
476
+ body
477
+ };
478
+ case body instanceof FormData:
479
+ return {
480
+ headers: {
481
+ [BODY_FORMAT_HEADER]: BodyFormat.FormData
482
+ },
483
+ body
484
+ };
485
+ case body instanceof URLSearchParams:
486
+ return {
487
+ headers: {
488
+ "Content-Type": "application/x-www-form-urlencoded",
489
+ [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
490
+ },
491
+ body
492
+ };
493
+ case typeof File !== "undefined" && body instanceof File:
494
+ {
495
+ const formData = new FormData();
496
+ formData.append(FILE_FORM_KEY, body, body.name);
497
+ return {
498
+ headers: {
499
+ [BODY_FORMAT_HEADER]: BodyFormat.File
500
+ },
501
+ body: formData
502
+ };
503
+ }
504
+ case body instanceof Blob:
505
+ return {
506
+ headers: {
507
+ [BODY_FORMAT_HEADER]: BodyFormat.Blob
508
+ },
509
+ body
510
+ };
511
+ case body instanceof ArrayBuffer:
512
+ return {
513
+ headers: {
514
+ [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
515
+ },
516
+ body
517
+ };
518
+ case body instanceof Uint8Array:
519
+ return {
520
+ headers: {
521
+ [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
522
+ },
523
+ body: new Uint8Array(body)
524
+ };
525
+ default:
526
+ return undefined;
527
+ }
528
+ }
529
+ async function extractBody(source, codecOptions) {
530
+ const contentType = source.headers.get("content-type");
531
+ const format = source.headers.get(BODY_FORMAT_HEADER);
532
+ switch (true) {
533
+ case format === BodyFormat.Serialized:
534
+ return await deserializeStream(source, codecOptions);
535
+ case format === BodyFormat.Json:
536
+ return JSON.parse(await source.text());
537
+ case format === BodyFormat.String:
538
+ return await source.text();
539
+ case format === BodyFormat.File:
540
+ {
541
+ const formData = await source.formData();
542
+ return formData.get(FILE_FORM_KEY);
543
+ }
544
+ case format === BodyFormat.FormData:
545
+ case contentType && contentType.startsWith("multipart/form-data"):
546
+ return await source.formData();
547
+ case format === BodyFormat.URLSearchParams:
548
+ case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
549
+ return new URLSearchParams(await source.text());
550
+ case format === BodyFormat.Blob:
551
+ return await source.blob();
552
+ case format === BodyFormat.ArrayBuffer:
553
+ return await source.arrayBuffer();
554
+ case format === BodyFormat.Uint8Array:
555
+ return new Uint8Array(await source.arrayBuffer());
556
+ }
557
+ return undefined;
558
+ }
559
+ function createChunk(data) {
560
+ const encoder = new TextEncoder();
561
+ const encodeData = encoder.encode(data);
562
+ const bytes = encodeData.length;
563
+ const chunk = new Uint8Array(12 + bytes);
564
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
565
+ chunk.set(encodeData, 12);
566
+ return chunk;
567
+ }
568
+ class ChunkReader {
569
+ constructor(stream) {
570
+ this.reader = stream.getReader();
571
+ this.store = new Uint8Array(0);
572
+ this.buffer = this.store;
573
+ this.done = false;
574
+ }
575
+ async readChunk() {
576
+ const chunk = await this.reader.read();
577
+ if (chunk.done) {
578
+ this.done = true;
579
+ return;
580
+ }
581
+ const incoming = chunk.value;
582
+ const store = this.store;
583
+ const start = this.buffer.byteOffset;
584
+ const end = start + this.buffer.length;
585
+ const needed = this.buffer.length + incoming.length;
586
+ if (end + incoming.length <= store.length) {
587
+ store.set(incoming, end);
588
+ this.buffer = store.subarray(start, end + incoming.length);
589
+ } else if (needed <= store.length) {
590
+ store.copyWithin(0, start, end);
591
+ store.set(incoming, this.buffer.length);
592
+ this.buffer = store.subarray(0, needed);
593
+ } else {
594
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
595
+ grown.set(this.buffer);
596
+ grown.set(incoming, this.buffer.length);
597
+ this.store = grown;
598
+ this.buffer = grown.subarray(0, needed);
599
+ }
600
+ }
601
+ async next() {
602
+ while (this.buffer.length < 12) {
603
+ if (this.done) {
604
+ if (this.buffer.length === 0) return {
605
+ done: true,
606
+ value: undefined
607
+ };
608
+ throw new Error("Malformed server function stream.");
609
+ }
610
+ await this.readChunk();
611
+ }
612
+ const decoder = new TextDecoder();
613
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
614
+ if (Number.isNaN(bytes)) {
615
+ throw new Error("Malformed server function stream.");
616
+ }
617
+ while (bytes > this.buffer.length - 12) {
618
+ if (this.done) {
619
+ throw new Error("Malformed server function stream.");
620
+ }
621
+ await this.readChunk();
622
+ }
623
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
624
+ this.buffer = this.buffer.subarray(12 + bytes);
625
+ return {
626
+ done: false,
627
+ value: partial
628
+ };
629
+ }
630
+ async drain(interpret) {
631
+ while (true) {
632
+ const result = await this.next();
633
+ if (result.done) {
634
+ break;
635
+ }
636
+ interpret(result.value);
637
+ }
638
+ }
639
+ }
640
+ const ERROR_TRAILER_PREFIX = "!";
641
+ function encodeErrorTrailer(error) {
642
+ const shaped = error instanceof Error ? error : new Error(String(error));
643
+ return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
644
+ name: shaped.name,
645
+ message: shaped.message
646
+ } : {
647
+ message: shaped.message
648
+ });
649
+ }
650
+ function errorFromTrailer(payload) {
651
+ let shape;
652
+ try {
653
+ shape = JSON.parse(payload.slice(1));
654
+ } catch {
655
+ shape = null;
656
+ }
657
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
658
+ if (shape && typeof shape.name === "string") error.name = shape.name;
659
+ return error;
660
+ }
661
+ async function deserializeStream(source, codecOptions) {
662
+ if (!source.body) {
663
+ throw new Error("missing body");
664
+ }
665
+ const reader = new ChunkReader(source.body);
666
+ const result = await reader.next();
667
+ if (!result.done) {
668
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
669
+ throw errorFromTrailer(result.value);
670
+ }
671
+ const {
672
+ createJSONDeserializer
673
+ } = await import('@solidjs/web/serialization/decode');
674
+ const deserializeChunk = createJSONDeserializer(codecOptions);
675
+ function interpretChunk(chunk) {
676
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
677
+ throw errorFromTrailer(chunk);
678
+ }
679
+ return deserializeChunk(JSON.parse(chunk));
680
+ }
681
+ reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
682
+ return interpretChunk(result.value);
683
+ }
684
+ return undefined;
685
+ }
686
+ async function deserializeString(text, codecOptions) {
687
+ return await deserializeStream(new Response(text), codecOptions);
688
+ }
689
+ async function decodeResponse(response, codecOptions) {
690
+ if (!response.body) return undefined;
691
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
692
+ }
693
+ async function decodeResponsePayload(response, codecOptions) {
694
+ const decoded = await decodeResponse(response, codecOptions);
695
+ if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
696
+ return {
697
+ value: decoded.value,
698
+ flightData: decoded.data
699
+ };
700
+ }
701
+ return {
702
+ value: decoded
703
+ };
704
+ }
705
+
706
+ function emitFinding(finding, subject = getOwner()) {
707
+ if (OBSERVE === undefined) return;
708
+ OBSERVE.diagnostics.emit(finding, subject);
709
+ }
710
+ function recordFinding(finding, subject = getOwner()) {
711
+ if (OBSERVE !== undefined) OBSERVE.diagnostics.emit(finding, subject);
712
+ }
713
+ function errorText(error) {
714
+ if (error instanceof Error) return error.message ? `${error.name}: ${error.message}` : error.name;
715
+ return String(error);
716
+ }
717
+
718
+ typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
719
+ const RequestContext = Symbol.for("solid.RequestContext");
720
+ function getRequestEvent() {
721
+ return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
722
+ }
723
+ function peekRequestEvent() {
724
+ const store = globalThis[RequestContext];
725
+ return store ? store.getStore() : undefined;
726
+ }
727
+ function traceForEvent(event) {
728
+ return traceFor(event.request || event, event.request);
729
+ }
730
+ function traceForStub(stub, event) {
731
+ if (!event) {
732
+ event = peekRequestEvent();
733
+ if (!event || event.response !== stub) return undefined;
734
+ }
735
+ return traceForEvent(event);
736
+ }
737
+ function reportLostHeaderWrite(method, name) {
738
+ const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
739
+ recordFinding({
740
+ code: "LATE_HEADER_WRITE",
741
+ kind: "head",
742
+ severity: "error",
743
+ message,
744
+ data: {
745
+ method,
746
+ name: String(name)
747
+ }
748
+ });
749
+ console.error(message);
750
+ }
751
+ function commitResponseStub(stub, {
752
+ allowLateLocation = false,
753
+ event
754
+ } = {}) {
755
+ if (!stub || stub.committed) return stub;
756
+ const headers = stub.headers;
757
+ if (headers && typeof headers.append === "function") {
758
+ const trace = traceForStub(stub, event);
759
+ if (trace) appendTraceServerTiming(headers, trace);
760
+ }
761
+ stub.committed = true;
762
+ if (!headers || typeof headers.set !== "function") return stub;
763
+ for (const method of ["set", "append", "delete"]) {
764
+ const original = headers[method].bind(headers);
765
+ headers[method] = function (name, ...rest) {
766
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
767
+ return original(name, ...rest);
768
+ }
769
+ reportLostHeaderWrite(method, name);
770
+ };
771
+ }
772
+ return stub;
773
+ }
774
+ function copyInitHeaders(init) {
775
+ if (!init || !init.getSetCookie) return new Headers(init);
776
+ const headers = new Headers();
777
+ init.forEach((value, key) => {
778
+ if (key !== "set-cookie") headers.append(key, value);
779
+ });
780
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
781
+ return headers;
782
+ }
783
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
784
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
785
+ function fillsStubGap(key, headers, response) {
786
+ if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
787
+ if (response.body === null && (key === "content-type" || key === "content-length")) return false;
788
+ return !headers.has(key);
789
+ }
790
+ function commitEventResponse(response, event = getRequestEvent()) {
791
+ const stub = event && event.response;
792
+ if (!stub || !stub.headers || stub.committed) {
793
+ if (!event || stub) return response;
794
+ const trace = traceForEvent(event);
795
+ if (!trace.emit) return response;
796
+ const headers = copyInitHeaders(response.headers);
797
+ appendTraceServerTiming(headers, trace);
798
+ return new Response(response.body, {
799
+ status: response.status,
800
+ statusText: response.statusText,
801
+ headers
802
+ });
803
+ }
804
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
805
+ commitResponseStub(stub, {
806
+ event
807
+ });
808
+ let hasGaps = false;
809
+ stub.headers.forEach((value, key) => {
810
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
811
+ });
812
+ const timing = stub.headers.get("server-timing");
813
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
814
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
815
+ const headers = copyInitHeaders(response.headers);
816
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
817
+ stub.headers.forEach((value, key) => {
818
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
819
+ });
820
+ if (mergesTiming) mergeServerTiming(headers, timing);
821
+ return new Response(response.body, {
822
+ status: response.status,
823
+ statusText: response.statusText,
824
+ headers
825
+ });
826
+ }
827
+
828
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
829
+ function records() {
830
+ return globalThis[RECORDS];
831
+ }
832
+ function settledPromise(value) {
833
+ if (value instanceof Promise) return value;
834
+ try {
835
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
836
+ } catch {}
837
+ return undefined;
838
+ }
839
+ function isDeferredBody(value) {
840
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
841
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
842
+ const v = value;
843
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
844
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
845
+ }
846
+
847
+ function deliver(context, at, boundary, outcome, value) {
848
+ const record = {
849
+ id: context.id,
850
+ direct: context.direct,
851
+ at,
852
+ durationMs: performance.now() - at,
853
+ outcome
854
+ };
855
+ if (boundary !== undefined) record.boundary = boundary;
856
+ const live = {
857
+ event: context.event,
858
+ args: context.args
859
+ };
860
+ if (context.request !== undefined) live.request = context.request;
861
+ if (outcome === "ok") {
862
+ live.result = value;
863
+ if (isDeferredBody(value)) record.deferred = true;
864
+ } else live.error = value;
865
+ records().emit("invocation", record, live);
866
+ }
867
+ function observeInvocation(context, execute) {
868
+ const channel = records();
869
+ if (channel === undefined || !channel.observed("invocation")) return execute();
870
+ const at = performance.now();
871
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
872
+ let result;
873
+ try {
874
+ result = execute();
875
+ } catch (error) {
876
+ deliver(context, at, boundary, "error", error);
877
+ throw error;
878
+ }
879
+ const promised = settledPromise(result);
880
+ if (promised !== undefined) {
881
+ return promised.then(value => {
882
+ deliver(context, at, boundary, "ok", value);
883
+ return value;
884
+ }, error => {
885
+ deliver(context, at, boundary, "error", error);
886
+ throw error;
887
+ });
888
+ }
889
+ deliver(context, at, boundary, "ok", result);
890
+ return result;
891
+ }
892
+
893
+ let configuredSecret;
894
+ function setFlashSecret(secret) {
895
+ configuredSecret = secret;
896
+ }
897
+ function resolveSecret() {
898
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
899
+ }
900
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
901
+ const FLASH_KEY_ITERATIONS = 100_000;
902
+ let cachedSecret;
903
+ let cachedKey;
904
+ function resolveFlashKey() {
905
+ const secret = resolveSecret();
906
+ if (typeof secret !== "string" || secret.length === 0) return null;
907
+ if (secret !== cachedSecret) {
908
+ cachedSecret = secret;
909
+ const encoder = new TextEncoder();
910
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
911
+ name: "PBKDF2",
912
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
913
+ iterations: FLASH_KEY_ITERATIONS,
914
+ hash: "SHA-256"
915
+ }, material, {
916
+ name: "AES-GCM",
917
+ length: 256
918
+ }, false, ["encrypt", "decrypt"]));
919
+ }
920
+ return cachedKey;
921
+ }
922
+ const FLASH_FORMAT_VERSION = "1.";
923
+ const IV_BYTES = 12;
924
+ const GCM_TAG_BYTES = 16;
925
+ function toBase64url(bytes) {
926
+ let binary = "";
927
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
928
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
929
+ }
930
+ function fromBase64url(text) {
931
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
932
+ const bytes = new Uint8Array(binary.length);
933
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
934
+ return bytes;
935
+ }
936
+ async function encryptFlashValue(key, json) {
937
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
938
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
939
+ name: "AES-GCM",
940
+ iv
941
+ }, key, new TextEncoder().encode(json)));
942
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
943
+ packed.set(iv);
944
+ packed.set(ciphertext, IV_BYTES);
945
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
946
+ }
947
+ async function decryptFlashValue(key, value) {
948
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
949
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
950
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
951
+ const plain = await crypto.subtle.decrypt({
952
+ name: "AES-GCM",
953
+ iv: packed.subarray(0, IV_BYTES)
954
+ }, key, packed.subarray(IV_BYTES));
955
+ return new TextDecoder().decode(plain);
956
+ }
957
+ function encodeInputValue(value) {
958
+ if (value instanceof FormData) return {
959
+ $f: [...value.entries()].filter(([, v]) => typeof v === "string")
960
+ };
961
+ if (value instanceof URLSearchParams) return {
962
+ $u: [...value.entries()]
963
+ };
964
+ return value;
965
+ }
966
+ function decodeInputValue(value) {
967
+ if (value && typeof value === "object") {
968
+ if (Array.isArray(value.$f)) {
969
+ const form = new FormData();
970
+ for (const [k, v] of value.$f) form.append(k, v);
971
+ return form;
972
+ }
973
+ if (Array.isArray(value.$u)) return new URLSearchParams(value.$u);
974
+ }
975
+ return value;
976
+ }
977
+ async function encodeFlashCookie(url, result, input, thrown) {
978
+ const key = resolveFlashKey();
979
+ if (!key) {
980
+ return null;
981
+ }
982
+ const isError = result instanceof Error;
983
+ const payload = {
984
+ url,
985
+ result: isError ? result.message : result,
986
+ error: isError,
987
+ thrown: !!thrown,
988
+ input: input.map(encodeInputValue)
989
+ };
990
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
991
+ payload.truncated = true;
992
+ payload.input = [];
993
+ if (!fitsCookie(payload)) {
994
+ if (typeof payload.result === "string") {
995
+ let prefix = payload.result;
996
+ while (prefix.length > 0 && !fitsCookie({
997
+ ...payload,
998
+ result: prefix
999
+ })) {
1000
+ prefix = prefix.slice(0, prefix.length >> 1);
1001
+ }
1002
+ payload.result = prefix.length > 0 ? prefix : true;
1003
+ } else {
1004
+ payload.result = true;
1005
+ }
1006
+ }
1007
+ if (!fitsCookie(payload)) return null;
1008
+ return flashCookie(payload, await key);
1009
+ }
1010
+ const FLASH_MAX_AGE_SECONDS = 60;
1011
+ async function flashCookie(payload, key) {
1012
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
1013
+ secure: true,
1014
+ httpOnly: true,
1015
+ sameSite: "lax",
1016
+ maxAge: FLASH_MAX_AGE_SECONDS
1017
+ });
1018
+ }
1019
+ const COOKIE_PAIR_BUDGET = 4000;
1020
+ function fitsCookie(payload) {
1021
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
1022
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
1023
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
1024
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
1025
+ }
1026
+ async function decodeFlashCookie(cookieHeader) {
1027
+ const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
1028
+ if (!match) return;
1029
+ try {
1030
+ const key = resolveFlashKey();
1031
+ if (!key) return;
1032
+ const json = await decryptFlashValue(await key, match);
1033
+ if (json === undefined) return;
1034
+ const payload = JSON.parse(json);
1035
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
1036
+ const result = payload.error ? new Error(payload.result) : payload.result;
1037
+ const submission = {
1038
+ input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
1039
+ url: payload.url,
1040
+ result: payload.thrown ? undefined : result,
1041
+ error: payload.thrown ? result : undefined
1042
+ };
1043
+ if (payload.truncated) submission.truncated = true;
1044
+ return submission;
1045
+ } catch (error) {
1046
+ }
1047
+ }
1048
+
1049
+ const config = {
1050
+ provideEvent: undefined,
1051
+ wrapInvocation: undefined,
1052
+ collectFlightData: undefined,
1053
+ transformResult: undefined,
1054
+ transformFlightResult: undefined,
1055
+ transformDirectResult: undefined,
1056
+ handleNoJS: undefined,
1057
+ endpoint: "/_server",
1058
+ csrf: true,
1059
+ bodySizeLimit: 1_048_576,
1060
+ maxArguments: 1000
1061
+ };
1062
+ function configureServerFunctionsServer({
1063
+ provideEvent,
1064
+ wrapInvocation,
1065
+ collectFlightData,
1066
+ transformResult,
1067
+ transformFlightResult,
1068
+ transformDirectResult,
1069
+ handleNoJS,
1070
+ endpoint,
1071
+ csrf,
1072
+ codec,
1073
+ bodySizeLimit,
1074
+ maxArguments,
1075
+ secret
1076
+ } = {}) {
1077
+ if (provideEvent !== undefined) config.provideEvent = provideEvent;
1078
+ if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
1079
+ if (collectFlightData !== undefined) config.collectFlightData = collectFlightData;
1080
+ if (transformResult !== undefined) config.transformResult = transformResult;
1081
+ if (transformFlightResult !== undefined) config.transformFlightResult = transformFlightResult;
1082
+ if (transformDirectResult !== undefined) config.transformDirectResult = transformDirectResult;
1083
+ if (handleNoJS !== undefined) config.handleNoJS = handleNoJS;
1084
+ if (endpoint !== undefined) config.endpoint = endpoint;
1085
+ if (csrf !== undefined) config.csrf = csrf;
1086
+ if (codec !== undefined) configureServerFunctionsCodec(codec);
1087
+ if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
1088
+ if (maxArguments !== undefined) config.maxArguments = maxArguments;
1089
+ if (secret !== undefined) setFlashSecret(secret);
1090
+ }
1091
+ const flightSources = new Map();
1092
+ function registerFlightDataSource(source, hook) {
1093
+ assertFlightSource(source);
1094
+ flightSources.set(source, hook);
1095
+ return () => {
1096
+ if (flightSources.get(source) === hook) flightSources.delete(source);
1097
+ };
1098
+ }
1099
+ function resolveWrapInvocation(hook) {
1100
+ if (hook === undefined || typeof hook === "function") return hook;
1101
+ throw new Error(`Invalid wrapInvocation: expected a function, received ${hook === null ? "null" : typeof hook}. A hook that is not callable cannot wrap the call - configure a function, or leave ` + `wrapInvocation undefined.`);
1102
+ }
1103
+ function provideEvent(event, fn) {
1104
+ if (config.provideEvent) return config.provideEvent(event, fn);
1105
+ const ctx = globalThis[RequestContext];
1106
+ if (ctx) return ctx.run(event, fn);
1107
+ throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
1108
+ }
1109
+ const PROVIDE_EVENT_TWICE = "provideEvent invoked the server function callback more than once: a second invocation " + "would commit the call's side effects twice. The hook must call fn exactly once and return " + "its result.";
1110
+ const PROVIDE_EVENT_NEVER = "provideEvent returned without invoking the server function callback: the call would have " + "answered as a void success without running the function. The hook must call fn exactly once " + "and return its result.";
1111
+ function provideEventOnce(provide, event, run) {
1112
+ let invocations = 0;
1113
+ const settle = () => {
1114
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
1115
+ };
1116
+ const result = provide(event, () => {
1117
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
1118
+ return run();
1119
+ });
1120
+ const promised = nativePromise(result);
1121
+ if (promised) {
1122
+ return promised.then(value => {
1123
+ settle();
1124
+ return value;
1125
+ });
1126
+ }
1127
+ settle();
1128
+ return result;
1129
+ }
1130
+ function scopeDeferredResult(value, scope) {
1131
+ const bound = bindDeferredBody(value, scope);
1132
+ if (bound !== value || value === null || typeof value !== "object") return bound;
1133
+ return scopeDeferredContents(value, scope);
1134
+ }
1135
+ class ScopeFrame {
1136
+ constructor(value, next, keys, descriptors) {
1137
+ this.value = value;
1138
+ this.next = next;
1139
+ this.keys = keys;
1140
+ this.descriptors = descriptors;
1141
+ this.i = 0;
1142
+ this.changed = false;
1143
+ }
1144
+ }
1145
+ function enterScopeCarrier(value, state) {
1146
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
1147
+ if (state.seen.has(value)) {
1148
+ state.cyclic.add(value);
1149
+ return state.seen.get(value);
1150
+ }
1151
+ const bound = bindDeferredBody(value, state.scope);
1152
+ if (bound !== value) {
1153
+ state.seen.set(value, bound);
1154
+ return bound;
1155
+ }
1156
+ if (typeof value !== "object") return value;
1157
+ if (Array.isArray(value)) {
1158
+ if (Object.isFrozen(value)) {
1159
+ state.seen.set(value, value);
1160
+ return value;
1161
+ }
1162
+ const next = value.slice();
1163
+ state.seen.set(value, next);
1164
+ return new ScopeFrame(value, next, null, null);
1165
+ }
1166
+ const prototype = Object.getPrototypeOf(value);
1167
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
1168
+ state.seen.set(value, value);
1169
+ return value;
1170
+ }
1171
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1172
+ const next = Object.create(prototype, descriptors);
1173
+ state.seen.set(value, next);
1174
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
1175
+ }
1176
+ function scopeDeferredContents(root, scope) {
1177
+ const state = {
1178
+ seen: new Map(),
1179
+ cyclic: new Set(),
1180
+ scope
1181
+ };
1182
+ const entered = enterScopeCarrier(root, state);
1183
+ if (!(entered instanceof ScopeFrame)) return entered;
1184
+ const stack = [entered];
1185
+ let delivered = NOTHING;
1186
+ for (;;) {
1187
+ const top = stack[stack.length - 1];
1188
+ const length = top.keys ? top.keys.length : top.value.length;
1189
+ let pushed = null;
1190
+ while (top.i < length) {
1191
+ const i = top.i;
1192
+ let original;
1193
+ let writable = true;
1194
+ if (top.keys) {
1195
+ const descriptor = top.descriptors[top.keys[i]];
1196
+ writable = "value" in descriptor && descriptor.writable === true;
1197
+ original = writable ? descriptor.value : undefined;
1198
+ } else {
1199
+ original = top.value[i];
1200
+ }
1201
+ if (!writable) {
1202
+ top.i++;
1203
+ continue;
1204
+ }
1205
+ let bound;
1206
+ if (delivered !== NOTHING) {
1207
+ bound = delivered;
1208
+ delivered = NOTHING;
1209
+ } else {
1210
+ bound = enterScopeCarrier(original, state);
1211
+ if (bound instanceof ScopeFrame) {
1212
+ pushed = bound;
1213
+ break;
1214
+ }
1215
+ }
1216
+ if (bound !== original) {
1217
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
1218
+ top.changed = true;
1219
+ }
1220
+ top.i++;
1221
+ }
1222
+ if (pushed !== null) {
1223
+ stack.push(pushed);
1224
+ continue;
1225
+ }
1226
+ stack.pop();
1227
+ let out;
1228
+ if (top.changed || state.cyclic.has(top.value)) {
1229
+ out = top.next;
1230
+ } else {
1231
+ state.seen.set(top.value, top.value);
1232
+ out = top.value;
1233
+ }
1234
+ if (stack.length === 0) return out;
1235
+ delivered = out;
1236
+ }
1237
+ }
1238
+ function bindDeferredBody(value, scope) {
1239
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
1240
+ const promised = scope(() => nativePromise(value));
1241
+ if (promised) {
1242
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
1243
+ }
1244
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1245
+ let reader;
1246
+ return new ReadableStream({
1247
+ async pull(controller) {
1248
+ try {
1249
+ const step = await scope(() => {
1250
+ if (!reader) reader = value.getReader();
1251
+ return reader.read();
1252
+ });
1253
+ if (step.done) controller.close();else controller.enqueue(step.value);
1254
+ } catch (error) {
1255
+ controller.error(error);
1256
+ }
1257
+ },
1258
+ cancel(reason) {
1259
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
1260
+ }
1261
+ }, {
1262
+ highWaterMark: 0
1263
+ });
1264
+ }
1265
+ const scopedIterator = symbol => ({
1266
+ [symbol]() {
1267
+ const iterator = scope(() => value[symbol]());
1268
+ return new Proxy(iterator, {
1269
+ get(target, property) {
1270
+ const member = Reflect.get(target, property, target);
1271
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
1272
+ }
1273
+ });
1274
+ }
1275
+ });
1276
+ if (typeof value[Symbol.asyncIterator] === "function") {
1277
+ return scopedIterator(Symbol.asyncIterator);
1278
+ }
1279
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1280
+ return scopedIterator(Symbol.iterator);
1281
+ }
1282
+ return value;
1283
+ }
1284
+ function processState(key, create) {
1285
+ const slot = Symbol.for(key);
1286
+ return globalThis[slot] || (globalThis[slot] = create());
1287
+ }
1288
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
1289
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1290
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
1291
+ function declaresRead(id) {
1292
+ const granted = METHODS.get(id);
1293
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
1294
+ }
1295
+ const INVOCATIONS = new WeakMap();
1296
+ let rpcProvided = false;
1297
+ function provideRPC() {
1298
+ if (rpcProvided) return;
1299
+ rpcProvided = true;
1300
+ provideServerFunctionRPC({
1301
+ GET,
1302
+ decodeResponse
1303
+ });
1304
+ }
1305
+ function registerServerFunction(id, callback) {
1306
+ provideRPC();
1307
+ if (REGISTRATIONS.get(id) !== callback) METHODS.delete(id);
1308
+ REGISTRATIONS.set(id, callback);
1309
+ return callback;
1310
+ }
1311
+ function getServerFunction(id) {
1312
+ const fn = REGISTRATIONS.get(id);
1313
+ if (fn) {
1314
+ return fn;
1315
+ }
1316
+ throw new Error("invalid server function: " + id);
1317
+ }
1318
+ function registerServerReference(id, fn, name) {
1319
+ if (typeof fn !== "function") {
1320
+ throw new Error(`Server function${name ? ` \`${name}\`` : ""} (${id}) is not a function: a module-level ` + `"use server" export must evaluate to a server function (got ${fn === null ? "null" : typeof fn}). Move non-function exports out of the directive module.`);
1321
+ }
1322
+ registerServerFunction(id, fn);
1323
+ return {
1324
+ id,
1325
+ fn,
1326
+ name
1327
+ };
1328
+ }
1329
+ function inProcessInvoker(call) {
1330
+ return (args, options) => {
1331
+ const signal = options && options.signal;
1332
+ if (!signal) return call(...args);
1333
+ if (signal.aborted) return Promise.reject(signal.reason);
1334
+ return new Promise((resolve, reject) => {
1335
+ const onAbort = () => reject(signal.reason);
1336
+ signal.addEventListener("abort", onAbort, {
1337
+ once: true
1338
+ });
1339
+ let result;
1340
+ try {
1341
+ result = call(...args);
1342
+ } catch (error) {
1343
+ signal.removeEventListener("abort", onAbort);
1344
+ return reject(error);
1345
+ }
1346
+ Promise.resolve(result).then(value => {
1347
+ signal.removeEventListener("abort", onAbort);
1348
+ resolve(value);
1349
+ }, error => {
1350
+ signal.removeEventListener("abort", onAbort);
1351
+ reject(error);
1352
+ });
1353
+ });
1354
+ };
1355
+ }
1356
+ function createServerReference({
1357
+ id,
1358
+ fn,
1359
+ name
1360
+ }) {
1361
+ if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
1362
+ provideRPC();
1363
+ const metadata = name === undefined ? {} : {
1364
+ name
1365
+ };
1366
+ const invokeChannel = inProcessInvoker((...args) => proxy(...args));
1367
+ const proxy = new Proxy(fn, {
1368
+ get(target, prop) {
1369
+ if (prop === "id") return id;
1370
+ if (prop === "url") {
1371
+ return serverFunctionAddress(config.endpoint, id);
1372
+ }
1373
+ if (prop === SERVER_FUNCTION_METADATA) return metadata;
1374
+ if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
1375
+ return target[prop];
1376
+ },
1377
+ apply(target, thisArg, args) {
1378
+ const ogEvt = getRequestEvent();
1379
+ if (!ogEvt) throw new Error("Cannot call server function outside of a request");
1380
+ const evt = {
1381
+ ...ogEvt,
1382
+ locals: {
1383
+ ...ogEvt.locals
1384
+ }
1385
+ };
1386
+ INVOCATIONS.set(evt, {
1387
+ id
1388
+ });
1389
+ evt.serverOnly = true;
1390
+ const scope = run => provideEvent(evt, run);
1391
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1392
+ let result = provideEventOnce(provideEvent, evt, () => {
1393
+ const run = () => fn.apply(thisArg, args);
1394
+ return observeInvocation({
1395
+ id,
1396
+ direct: true,
1397
+ event: evt,
1398
+ args
1399
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
1400
+ id,
1401
+ args,
1402
+ event: evt,
1403
+ direct: true
1404
+ }) : run(), id));
1405
+ });
1406
+ result = scopeDeferredResult(result, scope);
1407
+ const transform = config.transformDirectResult;
1408
+ if (transform && result && typeof result.then === "function") {
1409
+ return result.then(value => scopeDeferredResult(transform(value, {
1410
+ id,
1411
+ args,
1412
+ event: evt
1413
+ }), scope));
1414
+ }
1415
+ return transform ? scopeDeferredResult(transform(result, {
1416
+ id,
1417
+ args,
1418
+ event: evt
1419
+ }), scope) : result;
1420
+ }
1421
+ });
1422
+ REFERENCE_BINDINGS.set(proxy, fn);
1423
+ return proxy;
1424
+ }
1425
+ function GET(fn) {
1426
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
1427
+ throw new Error("GET expects a server function reference");
1428
+ }
1429
+ const id = fn.id;
1430
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1431
+ const existing = METHODS.get(id);
1432
+ if (existing !== undefined && existing !== binding) {
1433
+ if (DEV) {
1434
+ throw new Error(`GET() would rebind the existing grant for server function "${id}" to a different ` + `function. A GET declaration is made about a function, not an id - two references ` + `sharing one id cannot both hold it. Give the functions distinct ids, or drop the ` + `stale declaration.`);
1435
+ }
1436
+ METHODS.delete(id);
1437
+ return fn;
1438
+ }
1439
+ METHODS.set(id, binding);
1440
+ const reference = withMeta(fn, {
1441
+ method: "GET"
1442
+ });
1443
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1444
+ return reference;
1445
+ }
1446
+ function guardDeclaredMethod(metadata, id) {
1447
+ let declared = metadata.method;
1448
+ Object.defineProperty(metadata, "method", {
1449
+ configurable: true,
1450
+ enumerable: true,
1451
+ get: () => declared,
1452
+ set(next) {
1453
+ if (next === declared) return;
1454
+ if (DEV) {
1455
+ throw new Error(`withMeta({ method }) cannot change the GET() declaration of server function ` + `"${id}". The method is declaration-scoped: it was granted about the function ` + `by GET(fn), and a metadata write cannot re-shape the wire grant.`);
1456
+ }
1457
+ METHODS.delete(id);
1458
+ declared = next;
1459
+ }
1460
+ });
1461
+ }
1462
+ function live(fn) {
1463
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
1464
+ throw new Error("live expects a server function reference");
1465
+ }
1466
+ const metadata = {
1467
+ ...getServerFunctionMetadata(fn),
1468
+ live: true
1469
+ };
1470
+ const wrapped = async (...args) => {
1471
+ const result = await fn(...args);
1472
+ if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
1473
+ result[LIVE_SOURCE] = true;
1474
+ }
1475
+ return result;
1476
+ };
1477
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
1478
+ wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
1479
+ wrapped.id = fn.id;
1480
+ Object.defineProperty(wrapped, "url", {
1481
+ get: () => fn.url,
1482
+ configurable: true
1483
+ });
1484
+ return wrapped;
1485
+ }
1486
+ function getServerFunctionInvocation() {
1487
+ return getEventServerFunctionInvocation(getRequestEvent());
1488
+ }
1489
+ function getEventServerFunctionInvocation(event) {
1490
+ return event && INVOCATIONS.get(event);
1491
+ }
1492
+ function resolveAddress(url) {
1493
+ return parseServerFunctionAddress(url.pathname, config.endpoint);
1494
+ }
1495
+ const DECODE_DEPTH_LIMIT = 64;
1496
+ function assertDecodeDepth(value) {
1497
+ let level = [value];
1498
+ for (let depth = 0; level.length > 0; depth++) {
1499
+ if (depth > DECODE_DEPTH_LIMIT) {
1500
+ throw new TypeError("Server function arguments exceed the decode depth limit");
1501
+ }
1502
+ const next = [];
1503
+ for (const node of level) {
1504
+ if (node === null || typeof node !== "object") continue;
1505
+ if (Array.isArray(node)) {
1506
+ for (const child of node) next.push(child);
1507
+ } else {
1508
+ for (const key of Object.keys(node)) next.push(node[key]);
1509
+ }
1510
+ }
1511
+ level = next;
1512
+ }
1513
+ }
1514
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1515
+ function stripUnsafeArgumentKeys(value) {
1516
+ const stack = [value];
1517
+ const seen = new Set();
1518
+ while (stack.length) {
1519
+ const v = stack.pop();
1520
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1521
+ seen.add(v);
1522
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1523
+ delete v[key];
1524
+ }
1525
+ for (const key of Object.keys(v)) stack.push(v[key]);
1526
+ if (v instanceof Map) {
1527
+ for (const [k, entry] of v) stack.push(k, entry);
1528
+ } else if (v instanceof Set) {
1529
+ for (const member of v) stack.push(member);
1530
+ }
1531
+ }
1532
+ return value;
1533
+ }
1534
+ async function bufferBodyWithin(request, limit) {
1535
+ const reader = request.body.getReader();
1536
+ const signal = request.signal;
1537
+ const chunks = [];
1538
+ let total = 0;
1539
+ const onAbort = () => {
1540
+ reader.cancel(signal.reason).catch(() => {});
1541
+ };
1542
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1543
+ once: true
1544
+ });
1545
+ try {
1546
+ for (;;) {
1547
+ const {
1548
+ done,
1549
+ value
1550
+ } = await reader.read();
1551
+ if (signal.aborted) throw signal.reason;
1552
+ if (done) break;
1553
+ total += value.byteLength;
1554
+ if (total > limit) {
1555
+ reader.cancel().catch(() => {});
1556
+ return null;
1557
+ }
1558
+ chunks.push(value);
1559
+ }
1560
+ } catch (error) {
1561
+ reader.cancel(error).catch(() => {});
1562
+ throw error;
1563
+ } finally {
1564
+ signal.removeEventListener("abort", onAbort);
1565
+ reader.releaseLock();
1566
+ }
1567
+ const body = new Uint8Array(total);
1568
+ let offset = 0;
1569
+ for (const chunk of chunks) {
1570
+ body.set(chunk, offset);
1571
+ offset += chunk.byteLength;
1572
+ }
1573
+ return body;
1574
+ }
1575
+ function withBufferedBody(request, body) {
1576
+ return new Request(request.url, {
1577
+ method: request.method,
1578
+ headers: request.headers,
1579
+ signal: request.signal,
1580
+ body
1581
+ });
1582
+ }
1583
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
1584
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
1585
+ function unknownFormatError(tag) {
1586
+ const error = new TypeError(`Server function body carries an unrecognized ${BODY_FORMAT_HEADER} tag ("${tag}"): the ` + "caller encodes a newer wire format than this build can decode (version skew), or an " + "intermediary duplicated the header. The body was refused rather than reinterpreted.");
1587
+ error[FORMAT_SKEW] = true;
1588
+ return error;
1589
+ }
1590
+ async function parseArguments(request, url, scripted, codec) {
1591
+ const parsed = [];
1592
+ const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
1593
+ const args = url.searchParams.get("args");
1594
+ if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1595
+ let result;
1596
+ if (args.startsWith(";0x")) {
1597
+ result = await deserializeString(args, codec);
1598
+ } else {
1599
+ result = JSON.parse(args);
1600
+ assertDecodeDepth(result);
1601
+ }
1602
+ if (!Array.isArray(result)) {
1603
+ throw new TypeError("Server function arguments must encode an array");
1604
+ }
1605
+ stripUnsafeArgumentKeys(result);
1606
+ for (const arg of result) {
1607
+ parsed.push(arg);
1608
+ }
1609
+ } else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
1610
+ parsed.push(url.searchParams);
1611
+ }
1612
+ if (request.method === "POST" && request.body !== null) {
1613
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
1614
+ throw unknownFormatError(bodyFormat);
1615
+ }
1616
+ const body = request.clone();
1617
+ const decoded = await extractBody(body, codec);
1618
+ if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1619
+ if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1620
+ if (!Array.isArray(decoded)) {
1621
+ throw new TypeError("Server function arguments must encode an array");
1622
+ }
1623
+ return stripUnsafeArgumentKeys(decoded);
1624
+ }
1625
+ if (decoded === undefined) {
1626
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
1627
+ return parsed;
1628
+ }
1629
+ throw new TypeError("Server function body carries no usable encoding");
1630
+ }
1631
+ parsed.push(decoded);
1632
+ }
1633
+ return parsed;
1634
+ }
1635
+ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
1636
+ if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
1637
+ digestOutcome(event, outcome);
1638
+ const folded = [];
1639
+ for (const [source, hook] of hooks) {
1640
+ try {
1641
+ const slice = await hook(event, outcome);
1642
+ if (slice !== undefined) folded.push([source, slice]);
1643
+ } catch (error) {
1644
+ console.error(`Error collecting flight data for source "${source}"`, error);
1645
+ }
1646
+ }
1647
+ if (folded.length === 0) return outcome.value;
1648
+ const data = Object.fromEntries(folded);
1649
+ headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
1650
+ if (context.transformFlightResult) {
1651
+ const transformed = await context.transformFlightResult(event, {
1652
+ value: outcome.value,
1653
+ data
1654
+ }, context);
1655
+ if (transformed !== undefined) {
1656
+ const owned = ownResponse(transformed);
1657
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
1658
+ headers.forEach((value, key) => {
1659
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
1660
+ owned.headers.set(key, value);
1661
+ }
1662
+ });
1663
+ return owned;
1664
+ }
1665
+ }
1666
+ return outcome.value === undefined ? {
1667
+ data
1668
+ } : {
1669
+ value: outcome.value,
1670
+ data
1671
+ };
1672
+ }
1673
+ function digestOutcome(event, outcome) {
1674
+ const {
1675
+ request,
1676
+ response
1677
+ } = outcome;
1678
+ outcome.revalidateKeys = response?.headers.get(REVALIDATE_HEADER)?.split(",");
1679
+ outcome.foldedHeaders = foldSetCookies(request.headers, [...(event.response?.headers?.getSetCookie() ?? []), ...(response?.headers?.getSetCookie() ?? [])]);
1680
+ try {
1681
+ const referrer = request.headers.get("referer");
1682
+ if (referrer) {
1683
+ const location = response?.headers.get("Location");
1684
+ const target = location ? new URL(location, request.url) : new URL(referrer);
1685
+ if (target.origin === new URL(request.url).origin) outcome.targetUrl = target.toString();
1686
+ }
1687
+ } catch {
1688
+ }
1689
+ }
1690
+ function parseSetCookie(setCookie) {
1691
+ const [pair, ...attributes] = setCookie.split(";");
1692
+ const eq = pair.indexOf("=");
1693
+ if (eq < 0) return undefined;
1694
+ const parsed = {
1695
+ name: pair.slice(0, eq).trim(),
1696
+ value: pair.slice(eq + 1).trim()
1697
+ };
1698
+ for (const attribute of attributes) {
1699
+ const attrEq = attribute.indexOf("=");
1700
+ const key = (attrEq < 0 ? attribute : attribute.slice(0, attrEq)).trim().toLowerCase();
1701
+ const value = attrEq < 0 ? "" : attribute.slice(attrEq + 1).trim();
1702
+ if (key === "max-age") parsed.maxAge = Number(value);else if (key === "expires") parsed.expires = new Date(value);
1703
+ }
1704
+ return parsed;
1705
+ }
1706
+ function foldSetCookies(headers, setCookies) {
1707
+ const folded = new Headers(headers);
1708
+ if (!setCookies.length) return folded;
1709
+ const cookies = {};
1710
+ for (const pair of folded.get("cookie")?.split(";") ?? []) {
1711
+ const eq = pair.indexOf("=");
1712
+ if (eq > -1) cookies[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim();
1713
+ }
1714
+ for (const setCookie of setCookies) {
1715
+ const parsed = parseSetCookie(setCookie);
1716
+ if (!parsed) continue;
1717
+ if (parsed.maxAge != null && parsed.maxAge <= 0 || parsed.expires != null && parsed.expires.getTime() <= Date.now()) {
1718
+ delete cookies[parsed.name];
1719
+ } else {
1720
+ cookies[parsed.name] = parsed.value;
1721
+ }
1722
+ }
1723
+ folded.delete("cookie");
1724
+ const serialized = Object.entries(cookies).map(([name, value]) => `${name}=${value}`).join("; ");
1725
+ if (serialized) folded.set("cookie", serialized);
1726
+ return folded;
1727
+ }
1728
+ function mergeResponseHeaders(target, source) {
1729
+ source.forEach((value, key) => {
1730
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
1731
+ });
1732
+ if (source.getSetCookie) {
1733
+ for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
1734
+ } else if (source.has("set-cookie")) {
1735
+ target.append("Set-Cookie", source.get("set-cookie"));
1736
+ }
1737
+ }
1738
+ const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
1739
+ function maskRedirect(headers, response, requestUrl) {
1740
+ const target = response.headers && response.headers.get("Location");
1741
+ if (target) {
1742
+ headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
1743
+ }
1744
+ headers.delete("Location");
1745
+ }
1746
+ const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
1747
+ function enforceComposedHeaderInvariants(response) {
1748
+ for (const name of BOUNDED_COMPOSED_HEADERS) {
1749
+ const value = response.headers.get(name);
1750
+ if (value === null) continue;
1751
+ if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
1752
+ return refuseComposedHeader(response, name, `${name} response header refused at ${value.length} characters`, DEV ? `The ${name} response header is ${value.length} characters; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} it would overflow receivers (an 8 KiB proxy ` + `buffer holds the whole header block) and the response dies at the socket after ` + `the mutation committed. Refused rather than trimmed: a cut redirect target is a ` + `different address, a dropped revalidate key is a silently stale cache. The ` + `redirect()/reload() helpers enforce this bound with the full reasoning at the ` + `call site.` : null);
1753
+ }
1754
+ if (name === REVALIDATE_HEADER) continue;
1755
+ const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
1756
+ if (!isHttpNavigationTarget(target)) {
1757
+ return refuseComposedHeader(response, name, `${name} response header refused: non-http(s) navigation target`, DEV ? `The ${name} response header carries a navigation target with a non-http(s) ` + `scheme ("${target.slice(0, 64)}"). A javascript: target is same-origin script ` + `execution in any integration that navigates to it, so only http(s) and ` + `relative targets leave this transport. If the target came from request data ` + `(?next= and friends), validate it against your own origin before redirecting.` : null);
1758
+ }
1759
+ }
1760
+ return response;
1761
+ }
1762
+ function refuseComposedHeader(response, name, headerMessage, body) {
1763
+ if (response.body) {
1764
+ try {
1765
+ const cancelled = response.body.cancel();
1766
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1767
+ } catch {}
1768
+ }
1769
+ const headers = new Headers();
1770
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
1771
+ return new Response(body, {
1772
+ status: 500,
1773
+ headers
1774
+ });
1775
+ }
1776
+ function warnScripted304(functionId) {
1777
+ if (DEV) {
1778
+ console.warn(`Server function "${functionId}" answered a scripted call with 304 Not Modified. ` + `The client transport sends no conditional headers, so nothing was asked to be ` + `revalidated: the call resolves to undefined, not "unchanged". For conditional ` + `reads, declare the function GET and set ETag/Cache-Control response headers - ` + `the browser owns that exchange and replays its cached answer on a 304.`);
1779
+ }
1780
+ }
1781
+ function createNoJSHandler({
1782
+ base = ""
1783
+ } = {}) {
1784
+ return async function handleNoJS(result, request, args, thrown) {
1785
+ const url = new URL(request.url);
1786
+ let back = new URL(base || "/", url.origin).toString();
1787
+ try {
1788
+ const referer = request.headers.get("referer");
1789
+ if (referer) back = new URL(referer).toString();
1790
+ } catch {}
1791
+ let status = 303;
1792
+ let headers;
1793
+ if (result instanceof Response) {
1794
+ headers = new Headers();
1795
+ mergeResponseHeaders(headers, result.headers);
1796
+ if (result.headers.has("Location")) {
1797
+ headers.set("Location", new URL(result.headers.get("Location"), url.origin + base).toString());
1798
+ if (validRedirectStatuses.has(result.status)) status = result.status;
1799
+ } else {
1800
+ headers.set("Location", back);
1801
+ }
1802
+ headers.delete("Content-Type");
1803
+ headers.delete("Content-Length");
1804
+ } else {
1805
+ headers = new Headers({
1806
+ Location: back
1807
+ });
1808
+ }
1809
+ if (result !== undefined && !(result instanceof Response)) {
1810
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
1811
+ if (flash !== null) headers.append("Set-Cookie", flash);
1812
+ }
1813
+ return new Response(null, {
1814
+ status,
1815
+ headers
1816
+ });
1817
+ };
1818
+ }
1819
+ let defaultNoJSHandler;
1820
+ function isFormPost(request) {
1821
+ if (request.method !== "POST" || request.headers.has(BODY_FORMAT_HEADER)) return false;
1822
+ const type = request.headers.get("content-type") || "";
1823
+ return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
1824
+ }
1825
+ function guardFailures(value, state) {
1826
+ if (!state) state = {
1827
+ seen: new WeakMap(),
1828
+ cyclic: new WeakSet()
1829
+ };
1830
+ const entered = enterGuard(value, state);
1831
+ if (!(entered instanceof Frame)) return entered;
1832
+ const stack = [entered];
1833
+ let delivered = NOTHING;
1834
+ for (;;) {
1835
+ const top = stack[stack.length - 1];
1836
+ const items = top.items;
1837
+ let pushed = null;
1838
+ while (top.i < items.length) {
1839
+ const i = top.i;
1840
+ let original;
1841
+ if (top.kind === OBJECT) {
1842
+ const descriptor = top.descriptors[items[i]];
1843
+ if ("value" in descriptor) {
1844
+ original = descriptor.value;
1845
+ } else if (typeof descriptor.get === "function") {
1846
+ if (top.accessorRead !== i) {
1847
+ try {
1848
+ top.accessorValue = descriptor.get.call(top.value);
1849
+ } catch (error) {
1850
+ throw wireServerFunctionError(error, "channel");
1851
+ }
1852
+ top.accessorRead = i;
1853
+ }
1854
+ original = top.accessorValue;
1855
+ } else {
1856
+ top.i++;
1857
+ continue;
1858
+ }
1859
+ } else {
1860
+ original = items[i];
1861
+ }
1862
+ let guarded;
1863
+ if (delivered !== NOTHING) {
1864
+ guarded = delivered;
1865
+ delivered = NOTHING;
1866
+ } else {
1867
+ guarded = enterGuard(original, state);
1868
+ if (guarded instanceof Frame) {
1869
+ pushed = guarded;
1870
+ break;
1871
+ }
1872
+ }
1873
+ if (top.kind === ARRAY) {
1874
+ if (guarded !== original) {
1875
+ top.next[i] = guarded;
1876
+ top.changed = true;
1877
+ }
1878
+ } else if (top.kind === MAP) {
1879
+ if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
1880
+ if (guarded !== original) top.changed = true;
1881
+ } else if (top.kind === SET) {
1882
+ top.next.add(guarded);
1883
+ if (guarded !== original) top.changed = true;
1884
+ } else if (guarded !== original || top.accessorRead === i) {
1885
+ Object.defineProperty(top.next, items[i], {
1886
+ value: guarded,
1887
+ writable: true,
1888
+ configurable: true,
1889
+ enumerable: top.descriptors[items[i]].enumerable
1890
+ });
1891
+ top.changed = true;
1892
+ }
1893
+ top.i++;
1894
+ }
1895
+ if (pushed !== null) {
1896
+ stack.push(pushed);
1897
+ continue;
1898
+ }
1899
+ stack.pop();
1900
+ const out = keepGuarded(top.value, top.next, top.changed, state);
1901
+ if (stack.length === 0) return out;
1902
+ delivered = out;
1903
+ }
1904
+ }
1905
+ const NOTHING = Symbol();
1906
+ const ARRAY = 0;
1907
+ const MAP = 1;
1908
+ const SET = 2;
1909
+ const OBJECT = 3;
1910
+ class Frame {
1911
+ constructor(kind, value, next, items, descriptors) {
1912
+ this.kind = kind;
1913
+ this.value = value;
1914
+ this.next = next;
1915
+ this.items = items;
1916
+ this.descriptors = descriptors;
1917
+ this.i = 0;
1918
+ this.changed = false;
1919
+ this.accessorRead = -1;
1920
+ this.accessorValue = undefined;
1921
+ this.pendingKey = undefined;
1922
+ }
1923
+ }
1924
+ function guardOperation(state, run) {
1925
+ return state.scope ? state.scope(run) : run();
1926
+ }
1927
+ function enterGuard(value, state) {
1928
+ if (value === null || typeof value !== "object") return value;
1929
+ if (state.seen.has(value)) {
1930
+ state.cyclic.add(value);
1931
+ return state.seen.get(value);
1932
+ }
1933
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1934
+ let reader;
1935
+ const gate = state.gate;
1936
+ let finished = false;
1937
+ const close = () => {
1938
+ if (finished) return;
1939
+ finished = true;
1940
+ try {
1941
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
1942
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
1943
+ } catch {}
1944
+ };
1945
+ const guardedStream = new ReadableStream({
1946
+ async pull(controller) {
1947
+ try {
1948
+ if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
1949
+ if (finished) {
1950
+ controller.close();
1951
+ return;
1952
+ }
1953
+ if (!reader) reader = guardOperation(state, () => value.getReader());
1954
+ const {
1955
+ done,
1956
+ value: chunk
1957
+ } = await guardOperation(state, () => reader.read());
1958
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
1959
+ } catch (error) {
1960
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
1961
+ }
1962
+ },
1963
+ cancel(reason) {
1964
+ finished = true;
1965
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
1966
+ }
1967
+ });
1968
+ if (gate) gate.onOpen(close);
1969
+ state.seen.set(value, guardedStream);
1970
+ return guardedStream;
1971
+ }
1972
+ if (typeof value.then === "function") {
1973
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
1974
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
1975
+ });
1976
+ guardedPromise.catch(() => {});
1977
+ state.seen.set(value, guardedPromise);
1978
+ return guardedPromise;
1979
+ }
1980
+ if (typeof value[Symbol.asyncIterator] === "function") {
1981
+ const source = value;
1982
+ const gate = state.gate;
1983
+ const guardedIterable = {
1984
+ [Symbol.asyncIterator]() {
1985
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
1986
+ let finished = false;
1987
+ const close = () => {
1988
+ if (finished) return;
1989
+ finished = true;
1990
+ try {
1991
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
1992
+ if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
1993
+ } catch {}
1994
+ };
1995
+ if (gate) gate.onOpen(close);
1996
+ const step = () => finished ? Promise.resolve({
1997
+ done: true,
1998
+ value: undefined
1999
+ }) : guardOperation(state, () => iterator.next()).then(step => {
2000
+ if (step.done) {
2001
+ finished = true;
2002
+ return step;
2003
+ }
2004
+ return {
2005
+ done: false,
2006
+ value: guardOperation(state, () => guardFailures(step.value, state))
2007
+ };
2008
+ }, error => {
2009
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
2010
+ });
2011
+ return {
2012
+ next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
2013
+ return: () => {
2014
+ close();
2015
+ return Promise.resolve({
2016
+ done: true,
2017
+ value: undefined
2018
+ });
2019
+ }
2020
+ };
2021
+ }
2022
+ };
2023
+ state.seen.set(value, guardedIterable);
2024
+ return guardedIterable;
2025
+ }
2026
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
2027
+ const scopedIterable = scopeDeferredResult(value, state.scope);
2028
+ state.seen.set(value, scopedIterable);
2029
+ return scopedIterable;
2030
+ }
2031
+ if (Array.isArray(value)) {
2032
+ const next = value.slice();
2033
+ state.seen.set(value, next);
2034
+ return new Frame(ARRAY, value, next, value, null);
2035
+ }
2036
+ if (value instanceof Map) {
2037
+ const next = new Map();
2038
+ state.seen.set(value, next);
2039
+ const items = [];
2040
+ for (const entry of value) items.push(entry[0], entry[1]);
2041
+ return new Frame(MAP, value, next, items, null);
2042
+ }
2043
+ if (value instanceof Set) {
2044
+ const next = new Set();
2045
+ state.seen.set(value, next);
2046
+ return new Frame(SET, value, next, [...value], null);
2047
+ }
2048
+ const prototype = Object.getPrototypeOf(value);
2049
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
2050
+ state.seen.set(value, value);
2051
+ return value;
2052
+ }
2053
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2054
+ for (const key of Object.keys(descriptors)) {
2055
+ descriptors[key].configurable = true;
2056
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
2057
+ }
2058
+ const next = Object.create(prototype, descriptors);
2059
+ state.seen.set(value, next);
2060
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
2061
+ const descriptor = descriptors[key];
2062
+ return descriptor.enumerable || "value" in descriptor;
2063
+ });
2064
+ return new Frame(OBJECT, value, next, children, descriptors);
2065
+ }
2066
+ function keepGuarded(value, next, changed, state) {
2067
+ if (changed || state.cyclic.has(value)) return next;
2068
+ state.seen.set(value, value);
2069
+ return value;
2070
+ }
2071
+ function serializeResponseStream(value, codecOptions, signal, scope) {
2072
+ let closed = false;
2073
+ let streamController = null;
2074
+ let demandWaiters = null;
2075
+ const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
2076
+ const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
2077
+ const supplyDemand = () => {
2078
+ const resolvers = demandWaiters;
2079
+ demandWaiters = null;
2080
+ if (resolvers) for (const resolve of resolvers) resolve();
2081
+ };
2082
+ const sourceClosers = new Set();
2083
+ const gate = {
2084
+ wantsMore,
2085
+ awaitDemand,
2086
+ onOpen(close) {
2087
+ if (closed) close();else sourceClosers.add(close);
2088
+ }
2089
+ };
2090
+ const guardState = {
2091
+ seen: new WeakMap(),
2092
+ cyclic: new WeakSet(),
2093
+ gate,
2094
+ scope
2095
+ };
2096
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
2097
+ let cancelSerialize = null;
2098
+ let onAbort = null;
2099
+ const finishSource = () => {
2100
+ for (const close of sourceClosers) close();
2101
+ sourceClosers.clear();
2102
+ supplyDemand();
2103
+ };
2104
+ const teardown = () => {
2105
+ if (closed) return;
2106
+ closed = true;
2107
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2108
+ if (cancelSerialize) cancelSerialize();
2109
+ finishSource();
2110
+ };
2111
+ return new ReadableStream({
2112
+ async start(controller) {
2113
+ streamController = controller;
2114
+ if (signal) {
2115
+ if (signal.aborted) {
2116
+ teardown();
2117
+ controller.close();
2118
+ return;
2119
+ }
2120
+ onAbort = () => {
2121
+ const alreadyClosed = closed;
2122
+ teardown();
2123
+ if (!alreadyClosed) {
2124
+ try {
2125
+ controller.error(signal.reason || new Error("The operation was aborted."));
2126
+ } catch {}
2127
+ }
2128
+ };
2129
+ signal.addEventListener("abort", onAbort);
2130
+ }
2131
+ const {
2132
+ serializeJSON
2133
+ } = await import('@solidjs/web/serialization');
2134
+ if (closed) {
2135
+ try {
2136
+ controller.close();
2137
+ } catch {}
2138
+ return;
2139
+ }
2140
+ cancelSerialize = serializeJSON(value, {
2141
+ ...codecOptions,
2142
+ onParse(node) {
2143
+ if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
2144
+ },
2145
+ onDone() {
2146
+ if (closed) return;
2147
+ closed = true;
2148
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2149
+ finishSource();
2150
+ controller.close();
2151
+ },
2152
+ onError(error) {
2153
+ if (closed) return;
2154
+ closed = true;
2155
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2156
+ finishSource();
2157
+ try {
2158
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
2159
+ controller.enqueue(createChunk(encodeErrorTrailer(delivered)));
2160
+ controller.close();
2161
+ } catch {
2162
+ try {
2163
+ controller.error(error);
2164
+ } catch {}
2165
+ }
2166
+ }
2167
+ });
2168
+ },
2169
+ pull() {
2170
+ supplyDemand();
2171
+ },
2172
+ cancel() {
2173
+ teardown();
2174
+ }
2175
+ });
2176
+ }
2177
+ function serializedResponse(value, headers, codec, signal, scope) {
2178
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2179
+ headers.set("Content-Type", "text/plain");
2180
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
2181
+ headers
2182
+ });
2183
+ }
2184
+ function encodeResult(value, headers, status, codec, signal, scope) {
2185
+ if (NULL_BODY_STATUSES.has(status)) {
2186
+ if (value === undefined || value === null) {
2187
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
2188
+ return new Response(null, {
2189
+ status,
2190
+ headers
2191
+ });
2192
+ }
2193
+ const error = new Error(`Server function answered status ${status}, which forbids a response body, with a value. ` + `Return respond(undefined, { status: ${status} }) for a bodiless answer, or drop the ` + `status to send the value.`);
2194
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
2195
+ return encodeResult(error, headers, 500, codec, signal, scope);
2196
+ }
2197
+ const direct = getHeadersAndBody(value);
2198
+ if (direct) {
2199
+ for (const [key, val] of Object.entries(direct.headers || {})) {
2200
+ headers.set(key, val);
2201
+ }
2202
+ return new Response(direct.body, {
2203
+ status,
2204
+ headers
2205
+ });
2206
+ }
2207
+ if (value === undefined) {
2208
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
2209
+ return new Response(null, {
2210
+ status,
2211
+ headers
2212
+ });
2213
+ }
2214
+ try {
2215
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
2216
+ if (jsonSafe) {
2217
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
2218
+ headers.set("Content-Type", "application/json");
2219
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
2220
+ return new Response(body, {
2221
+ status,
2222
+ headers
2223
+ });
2224
+ }
2225
+ } catch {
2226
+ }
2227
+ try {
2228
+ const response = serializedResponse(value, headers, codec, signal, scope);
2229
+ return status === 200 ? response : new Response(response.body, {
2230
+ status,
2231
+ headers
2232
+ });
2233
+ } catch (error) {
2234
+ throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2235
+ }
2236
+ }
2237
+ const ERROR_HEADER_VALUE_LIMIT = 1024;
2238
+ function boundedErrorHeaderValue(message) {
2239
+ let label = message.length > 256 ? message.slice(0, 256) : message;
2240
+ let encoded = encodeErrorHeaderValue(label);
2241
+ while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
2242
+ label = label.slice(0, Math.ceil(label.length / 2));
2243
+ encoded = encodeErrorHeaderValue(label);
2244
+ }
2245
+ return encoded;
2246
+ }
2247
+ const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
2248
+ let DEV = false === true;
2249
+ function setServerFunctionsDev(dev) {
2250
+ DEV = !!dev;
2251
+ }
2252
+ const REQUEST_ERROR_HOOKS = new WeakMap();
2253
+ function siteFor(handling, event, direct) {
2254
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
2255
+ const site = {
2256
+ kind: "server-function",
2257
+ handling,
2258
+ direct
2259
+ };
2260
+ if (invocation) site.functionId = invocation.id;
2261
+ if (event) site.event = event;
2262
+ return site;
2263
+ }
2264
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
2265
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
2266
+ return report.mapped ? report.value : sanitizeServerError(value);
2267
+ }
2268
+ function currentEvent() {
2269
+ const store = globalThis[RequestContext];
2270
+ return store ? store.getStore() : undefined;
2271
+ }
2272
+ function reportDirectFailure(run, id) {
2273
+ const report = error => {
2274
+ reportServerError(error, {
2275
+ kind: "server-function",
2276
+ handling: "thrown",
2277
+ functionId: id,
2278
+ direct: true
2279
+ }, null);
2280
+ throw error;
2281
+ };
2282
+ let result;
2283
+ try {
2284
+ result = run();
2285
+ } catch (error) {
2286
+ report(error);
2287
+ }
2288
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
2289
+ }
2290
+ function sanitizeServerError(value) {
2291
+ if (DEV) return value;
2292
+ if (isSafeError(value)) return value;
2293
+ emitFinding({
2294
+ code: "SERVER_FN_ERROR_SANITIZED",
2295
+ kind: "ssr",
2296
+ severity: "error",
2297
+ message: `[SERVER_FN_ERROR_SANITIZED] Server function error replaced with a generic Error before serialization: ${errorText(value)}`,
2298
+ data: {
2299
+ error: value
2300
+ }
2301
+ }, null);
2302
+ return new Error(GENERIC_SERVER_ERROR_MESSAGE);
2303
+ }
2304
+ function serverFunctionUrl(fn, ...args) {
2305
+ return serverFunctionUrlFor(config.endpoint, fn, args);
2306
+ }
2307
+ function serverFunctionActionUrl(fn, ...boundArgs) {
2308
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
2309
+ }
2310
+ function parseServerFunctionActionUrl(url) {
2311
+ const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
2312
+ return parsed && parsed.id;
2313
+ }
2314
+ async function matchesOrigin(origin, request, matcher) {
2315
+ if (matcher === undefined) return origin === new URL(request.url).origin;
2316
+ if (typeof matcher === "function") return (await matcher(origin, request)) === true;
2317
+ return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
2318
+ }
2319
+ async function allowsServerFunctionRequest(request, options) {
2320
+ const fetchSite = request.headers.get("Sec-Fetch-Site");
2321
+ if (fetchSite === "same-origin") return true;
2322
+ if (fetchSite === "same-site" || fetchSite === "cross-site" || fetchSite === "none") {
2323
+ return false;
2324
+ }
2325
+ const origin = request.headers.get("Origin");
2326
+ if (origin !== null) return matchesOrigin(origin, request, options.origin);
2327
+ const referer = request.headers.get("Referer");
2328
+ if (referer !== null) {
2329
+ try {
2330
+ return matchesOrigin(new URL(referer).origin, request, options.origin);
2331
+ } catch {
2332
+ return false;
2333
+ }
2334
+ }
2335
+ return options.allowRequestsWithoutOriginCheck === true;
2336
+ }
2337
+ const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
2338
+ function withCSRFVary(response) {
2339
+ const current = response.headers.get("Vary");
2340
+ if (current === "*") return response;
2341
+ const values = current ? current.split(",").map(value => value.trim()) : [];
2342
+ const names = new Set(values.map(value => value.toLowerCase()));
2343
+ for (const value of CSRF_VARY) {
2344
+ if (!names.has(value.toLowerCase())) values.push(value);
2345
+ }
2346
+ const vary = values.join(", ");
2347
+ try {
2348
+ response.headers.set("Vary", vary);
2349
+ return response;
2350
+ } catch {
2351
+ const headers = new Headers(response.headers);
2352
+ headers.set("Vary", vary);
2353
+ return new Response(response.body, {
2354
+ status: response.status,
2355
+ statusText: response.statusText,
2356
+ headers
2357
+ });
2358
+ }
2359
+ }
2360
+ function forbiddenResponse() {
2361
+ return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
2362
+ status: 403,
2363
+ headers: {
2364
+ "Cache-Control": "no-store"
2365
+ }
2366
+ }));
2367
+ }
2368
+ function nativePromise(value) {
2369
+ if (value instanceof Promise) return value;
2370
+ try {
2371
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
2372
+ } catch {}
2373
+ }
2374
+ async function handleServerFunctionRequest(request, options = {}) {
2375
+ const codec = {
2376
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
2377
+ };
2378
+ codec.serializeErrorStacks ??= DEV;
2379
+ const url = new URL(request.url);
2380
+ const method = request.method;
2381
+ const address = resolveAddress(url);
2382
+ const functionId = address && address.id;
2383
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
2384
+ const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
2385
+ const protectsRequest = csrf !== false && (!declaredRead || typeof csrf === "object" && csrf.protectDeclaredReads === true);
2386
+ let serverFunction;
2387
+ if (functionId) {
2388
+ try {
2389
+ serverFunction = getServerFunction(functionId);
2390
+ } catch {
2391
+ return finalizeTransportResponse(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
2392
+ status: 404,
2393
+ headers: {
2394
+ [UNKNOWN_HEADER]: "true"
2395
+ }
2396
+ }), method);
2397
+ }
2398
+ }
2399
+ if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
2400
+ return finalizeTransportResponse(forbiddenResponse(), method);
2401
+ }
2402
+ if (!functionId) {
2403
+ const response = new Response(DEV ? "Server function not found" : null, {
2404
+ status: 404
2405
+ });
2406
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2407
+ }
2408
+ const scripted = address.data;
2409
+ if (method !== "POST" && !declaredRead) {
2410
+ const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
2411
+ status: 405,
2412
+ headers: {
2413
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
2414
+ }
2415
+ });
2416
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2417
+ }
2418
+ const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
2419
+ const argsEncoding = url.searchParams.get("args");
2420
+ if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
2421
+ const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
2422
+ status: 413
2423
+ });
2424
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2425
+ }
2426
+ if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
2427
+ const raw = request.headers.get("content-length");
2428
+ const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
2429
+ if (declared > bodySizeLimit) {
2430
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2431
+ status: 413
2432
+ });
2433
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2434
+ }
2435
+ let buffered;
2436
+ try {
2437
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
2438
+ } catch {
2439
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
2440
+ status: 400
2441
+ });
2442
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2443
+ }
2444
+ if (buffered === null) {
2445
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
2446
+ status: 413
2447
+ });
2448
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2449
+ }
2450
+ request = withBufferedBody(request, buffered);
2451
+ }
2452
+ let event;
2453
+ try {
2454
+ event = options.createEvent ? options.createEvent(request) : {
2455
+ request,
2456
+ locals: {}
2457
+ };
2458
+ const promised = nativePromise(event);
2459
+ if (promised) event = await promised;
2460
+ } catch (error) {
2461
+ const safe = sanitizeServerError(error);
2462
+ const message = safe instanceof Error ? safe.message : String(safe);
2463
+ const headers = new Headers();
2464
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
2465
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
2466
+ status: 500
2467
+ });
2468
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2469
+ }
2470
+ const refuseCommitted = raw => {
2471
+ const response = commitEventResponse(raw, event);
2472
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2473
+ };
2474
+ const provide = options.provideEvent || provideEvent;
2475
+ const scope = run => provide(event, run);
2476
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
2477
+ const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
2478
+ const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
2479
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
2480
+ const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
2481
+ let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
2482
+ if (handleNoJS === undefined && !scripted && isFormPost(request)) {
2483
+ const fetchMode = request.headers.get("Sec-Fetch-Mode");
2484
+ if (fetchMode === null || fetchMode === "navigate") {
2485
+ handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
2486
+ } else {
2487
+ const response = new Response(DEV ? "The bare server-function address answers form navigations with the " + "no-JS redirect convention. Scripted callers use the data address " + `(…/data/${functionId}) or send the ${BODY_FORMAT_HEADER} tag.` : null, {
2488
+ status: 400
2489
+ });
2490
+ return refuseCommitted(response);
2491
+ }
2492
+ }
2493
+ const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
2494
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
2495
+ const hook = source === "true" ? flightHook : flightSources.get(source);
2496
+ return hook ? [[source, hook]] : [];
2497
+ }) : [];
2498
+ const collectsFlight = flightHooks.length > 0;
2499
+ let parsed;
2500
+ try {
2501
+ parsed = await parseArguments(request, url, scripted, codec);
2502
+ } catch (error) {
2503
+ const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2504
+ const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
2505
+ status: 400
2506
+ });
2507
+ return refuseCommitted(response);
2508
+ }
2509
+ const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
2510
+ if (parsed.length > maxArguments) {
2511
+ const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
2512
+ status: 400
2513
+ });
2514
+ return refuseCommitted(response);
2515
+ }
2516
+ const flightContext = {
2517
+ id: functionId,
2518
+ args: parsed,
2519
+ request,
2520
+ collectsFlight,
2521
+ codec,
2522
+ transformFlightResult
2523
+ };
2524
+ const headers = new Headers();
2525
+ const dispatch = async () => {
2526
+ try {
2527
+ const invokeOnce = async () => {
2528
+ INVOCATIONS.set(event, {
2529
+ id: functionId
2530
+ });
2531
+ const run = () => serverFunction(...parsed);
2532
+ return observeInvocation({
2533
+ id: functionId,
2534
+ direct: false,
2535
+ event,
2536
+ request,
2537
+ args: parsed
2538
+ }, () => wrapInvocation ? wrapInvocation(run, {
2539
+ id: functionId,
2540
+ args: parsed,
2541
+ event,
2542
+ request,
2543
+ direct: false
2544
+ }) : run());
2545
+ };
2546
+ let result = await provideEventOnce(provide, event, invokeOnce);
2547
+ if (transformResult) {
2548
+ result = await transformResult(event, result, flightContext);
2549
+ }
2550
+ let status = 200;
2551
+ let metadata;
2552
+ if (isResponseEnvelope(result)) {
2553
+ const {
2554
+ response,
2555
+ value
2556
+ } = result;
2557
+ if (!scripted && !handleNoJS && response && response.body) {
2558
+ return response;
2559
+ }
2560
+ if (response && response.headers) {
2561
+ mergeResponseHeaders(headers, response.headers);
2562
+ }
2563
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
2564
+ status = response.status;
2565
+ } else if (response && response.status) {
2566
+ maskRedirect(headers, response, request.url);
2567
+ }
2568
+ metadata = response;
2569
+ result = value;
2570
+ } else if (result instanceof Response) {
2571
+ if (result.headers && result.headers.has("X-Content-Raw")) return result;
2572
+ if (scripted) {
2573
+ if (result.headers) {
2574
+ mergeResponseHeaders(headers, result.headers);
2575
+ }
2576
+ if (result.status && !validRedirectStatuses.has(result.status)) {
2577
+ status = result.status;
2578
+ } else if (result.status) {
2579
+ maskRedirect(headers, result, request.url);
2580
+ }
2581
+ metadata = result;
2582
+ if (result.body == null) {
2583
+ result = null;
2584
+ }
2585
+ }
2586
+ }
2587
+ if (collectsFlight) {
2588
+ result = await foldFlightData(flightHooks, event, headers, {
2589
+ id: functionId,
2590
+ value: result,
2591
+ response: metadata,
2592
+ request,
2593
+ thrown: false
2594
+ }, flightContext);
2595
+ if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
2596
+ }
2597
+ if (!scripted) {
2598
+ if (handleNoJS) {
2599
+ return handleNoJS(result == null && metadata !== undefined ? metadata : result, request, parsed);
2600
+ }
2601
+ if (result instanceof Response) return result;
2602
+ return encodeResult(result, headers, status, codec, request.signal, scope);
2603
+ }
2604
+ if (status === 304) warnScripted304(functionId);
2605
+ return encodeResult(result, headers, status, codec, request.signal, scope);
2606
+ } catch (x) {
2607
+ const respondThrown = value => {
2608
+ const safe = wireServerFunctionError(value, "thrown", event);
2609
+ if (!scripted) {
2610
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
2611
+ const message = safe instanceof Error ? safe.message : String(safe);
2612
+ return new Response(DEV ? message : null, {
2613
+ status: 500
2614
+ });
2615
+ }
2616
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
2617
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
2618
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
2619
+ };
2620
+ if (transformResult) {
2621
+ try {
2622
+ x = await transformResult(event, x, {
2623
+ ...flightContext,
2624
+ thrown: true
2625
+ });
2626
+ } catch (hookError) {
2627
+ return respondThrown(hookError);
2628
+ }
2629
+ }
2630
+ if (x instanceof Response || isResponseEnvelope(x)) {
2631
+ let status = 200;
2632
+ let metadata;
2633
+ if (isResponseEnvelope(x)) {
2634
+ const {
2635
+ response,
2636
+ value
2637
+ } = x;
2638
+ if (response && response.headers) {
2639
+ mergeResponseHeaders(headers, response.headers);
2640
+ }
2641
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
2642
+ status = response.status;
2643
+ } else if (response && response.status) {
2644
+ maskRedirect(headers, response, request.url);
2645
+ }
2646
+ metadata = response;
2647
+ x = value;
2648
+ } else if (x instanceof Response) {
2649
+ if (x.headers) {
2650
+ mergeResponseHeaders(headers, x.headers);
2651
+ }
2652
+ if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
2653
+ status = x.status;
2654
+ } else if (x.status) {
2655
+ maskRedirect(headers, x, request.url);
2656
+ }
2657
+ metadata = x;
2658
+ if (x.body == null) {
2659
+ x = null;
2660
+ }
2661
+ }
2662
+ if (collectsFlight) {
2663
+ x = await foldFlightData(flightHooks, event, headers, {
2664
+ id: functionId,
2665
+ value: x,
2666
+ response: metadata,
2667
+ request,
2668
+ thrown: true
2669
+ }, flightContext);
2670
+ if (x instanceof Response && x.headers.has("X-Content-Raw")) {
2671
+ x = ownResponse(x);
2672
+ x.headers.set(ERROR_HEADER, "true");
2673
+ return x;
2674
+ }
2675
+ }
2676
+ headers.set(ERROR_HEADER, "true");
2677
+ if (!scripted) {
2678
+ if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
2679
+ if (x instanceof Response) return x;
2680
+ }
2681
+ if (scripted && status === 304) warnScripted304(functionId);
2682
+ return encodeResult(x, headers, status, codec, request.signal, scope);
2683
+ }
2684
+ return respondThrown(x);
2685
+ }
2686
+ };
2687
+ const response = commitEventResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())), event);
2688
+ return finalizeTransportResponse(protectsRequest ? withCSRFVary(response) : response, method);
2689
+ }
2690
+ function ownResponse(response) {
2691
+ try {
2692
+ return new Response(response.body, response);
2693
+ } catch {
2694
+ return response;
2695
+ }
2696
+ }
2697
+ function finalizeTransportResponse(response, method) {
2698
+ const stripBody = method === "HEAD" && response.body !== null;
2699
+ const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
2700
+ if (stripBody || defaultsCache) {
2701
+ try {
2702
+ if (defaultsCache) {
2703
+ response.headers.set("Cache-Control", "no-store");
2704
+ }
2705
+ if (!stripBody) return response;
2706
+ response.body.cancel().catch(() => {});
2707
+ return new Response(null, {
2708
+ status: response.status,
2709
+ statusText: response.statusText,
2710
+ headers: response.headers
2711
+ });
2712
+ } catch {
2713
+ const headers = new Headers(response.headers);
2714
+ if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
2715
+ if (stripBody) response.body.cancel().catch(() => {});
2716
+ return new Response(stripBody ? null : response.body, {
2717
+ status: response.status,
2718
+ statusText: response.statusText,
2719
+ headers
2720
+ });
2721
+ }
2722
+ }
2723
+ return response;
2724
+ }
2725
+
2726
+ export { ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, withMeta };