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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +5165 -0
  3. package/dist/server.js +1876 -374
  4. package/dist/{server.cjs → server.observe.js} +2070 -577
  5. package/dist/{dev.cjs → web.dev.js} +955 -567
  6. package/dist/web.js +646 -350
  7. package/dist/{dev.js → web.observe.js} +699 -421
  8. package/frames/dist/assets.js +92 -0
  9. package/frames/dist/client.dev.js +1296 -1198
  10. package/frames/dist/client.js +1128 -1191
  11. package/frames/dist/client.observe.js +2041 -0
  12. package/frames/dist/regions.js +171 -0
  13. package/frames/dist/server.dev.js +2545 -0
  14. package/frames/dist/server.js +1683 -3004
  15. package/frames/dist/server.observe.js +2544 -0
  16. package/frames/dist/trace.js +45 -0
  17. package/frames/dist/wire.js +594 -0
  18. package/frames/package.json +2 -25
  19. package/package.json +244 -256
  20. package/performance-tracks/dist/performance-tracks.dev.js +679 -0
  21. package/performance-tracks/dist/performance-tracks.js +6 -0
  22. package/performance-tracks/dist/performance-tracks.observe.js +667 -0
  23. package/performance-tracks/package.json +7 -0
  24. package/performance-tracks/types/index.d.ts +69 -0
  25. package/serialization/decode/package.json +2 -15
  26. package/serialization/dist/decode.js +121 -25
  27. package/serialization/dist/serialization.js +282 -88
  28. package/serialization/package.json +2 -15
  29. package/serialization/types/index.d.ts +115 -153
  30. package/serialization/types/serializer-decode.d.ts +173 -114
  31. package/serialization/types/serializer.d.ts +144 -0
  32. package/server-functions/dist/client.dev.js +1462 -0
  33. package/server-functions/dist/client.js +667 -165
  34. package/server-functions/dist/client.observe.js +1441 -0
  35. package/server-functions/dist/rich-args.js +102 -1
  36. package/server-functions/dist/server.dev.js +2802 -299
  37. package/server-functions/dist/server.js +2724 -314
  38. package/server-functions/dist/server.observe.js +3680 -0
  39. package/server-functions/package.json +2 -35
  40. package/server-functions/rich-args/package.json +2 -15
  41. package/skills/server-components/SKILL.md +117 -0
  42. package/storage/package.json +2 -15
  43. package/types/client.d.ts +342 -288
  44. package/types/constants.d.ts +22 -0
  45. package/types/cookies.d.ts +32 -84
  46. package/types/diagnostics.d.ts +80 -0
  47. package/types/frames/assets-tier.d.ts +78 -0
  48. package/types/frames/client.d.ts +40 -1
  49. package/types/frames/frame-client.d.ts +443 -280
  50. package/types/frames/frame-container-plugin.d.ts +64 -0
  51. package/types/frames/frame-morph.d.ts +29 -0
  52. package/types/frames/frame-sink.d.ts +141 -161
  53. package/types/frames/frame-transport.d.ts +263 -184
  54. package/types/frames/regions-tier.d.ts +60 -0
  55. package/types/frames/serializer-decode.d.ts +241 -0
  56. package/types/frames/serializer.d.ts +115 -153
  57. package/types/frames/server.d.ts +2 -2
  58. package/types/frames/trace-tier.d.ts +2 -0
  59. package/types/frames/tree-rewrite.d.ts +39 -0
  60. package/types/frames/wire-tier.d.ts +169 -0
  61. package/types/head.d.ts +20 -0
  62. package/types/index.d.ts +98 -81
  63. package/types/index.server.d.ts +159 -0
  64. package/types/jsx.d.ts +49 -44
  65. package/types/observe.d.ts +535 -0
  66. package/types/reconcile.d.ts +1 -0
  67. package/types/render.d.ts +11 -0
  68. package/types/request-error-hook.d.ts +5 -0
  69. package/types/response.d.ts +95 -147
  70. package/types/serializer-decode.d.ts +173 -114
  71. package/types/serializer.d.ts +115 -153
  72. package/types/server-functions/argument-codec.d.ts +30 -0
  73. package/types/server-functions/client.d.ts +237 -223
  74. package/types/server-functions/flash.d.ts +28 -30
  75. package/types/server-functions/registry.d.ts +105 -0
  76. package/types/server-functions/rich-args.d.ts +1 -10
  77. package/types/server-functions/server.d.ts +538 -531
  78. package/types/server-functions/shared.d.ts +398 -425
  79. package/types/server-functions/uploads.d.ts +53 -0
  80. package/types/server-mock.d.ts +154 -20
  81. package/types/server-observe.d.ts +86 -0
  82. package/types/server.d.ts +601 -422
  83. package/types/trace.d.ts +127 -0
  84. package/LICENSE +0 -21
  85. package/dist/web.cjs +0 -2033
  86. package/frames/dist/client.cjs +0 -2002
  87. package/frames/dist/client.dev.cjs +0 -2022
  88. package/frames/dist/server.cjs +0 -3877
  89. package/serialization/dist/decode.cjs +0 -139
  90. package/serialization/dist/serialization.cjs +0 -261
  91. package/serialization/types-cjs/index.d.cts +0 -182
  92. package/serialization/types-cjs/package.json +0 -3
  93. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  94. package/server-functions/dist/client.cjs +0 -834
  95. package/server-functions/dist/rich-args.cjs +0 -11
  96. package/server-functions/dist/server.cjs +0 -1242
  97. package/server-functions/dist/server.dev.cjs +0 -1242
  98. package/storage/dist/storage.cjs +0 -12
  99. package/storage/types-cjs/index.d.cts +0 -28
  100. package/storage/types-cjs/package.json +0 -3
  101. package/types/core.d.ts +0 -9
  102. package/types-cjs/client.d.cts +0 -337
  103. package/types-cjs/cookies.d.cts +0 -93
  104. package/types-cjs/core.d.cts +0 -9
  105. package/types-cjs/frames/client.d.cts +0 -36
  106. package/types-cjs/frames/frame-client.d.cts +0 -356
  107. package/types-cjs/frames/frame-sink.d.cts +0 -194
  108. package/types-cjs/frames/frame-transport.d.cts +0 -222
  109. package/types-cjs/frames/serializer.d.cts +0 -182
  110. package/types-cjs/frames/server.d.cts +0 -52
  111. package/types-cjs/index.d.cts +0 -244
  112. package/types-cjs/jsx-properties.d.cts +0 -93
  113. package/types-cjs/jsx.d.cts +0 -4159
  114. package/types-cjs/package.json +0 -3
  115. package/types-cjs/response.d.cts +0 -174
  116. package/types-cjs/serializer-decode.d.cts +0 -182
  117. package/types-cjs/serializer.d.cts +0 -182
  118. package/types-cjs/server-functions/client.d.cts +0 -262
  119. package/types-cjs/server-functions/flash.d.cts +0 -38
  120. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  121. package/types-cjs/server-functions/server.d.cts +0 -681
  122. package/types-cjs/server-functions/shared.d.cts +0 -523
  123. package/types-cjs/server-mock.d.cts +0 -286
  124. package/types-cjs/server.d.cts +0 -544
@@ -1,4 +1,15 @@
1
- import { sharedConfig } from 'solid-js';
1
+ import { OBSERVE, getOwner, DEV as DEV$1 } from 'solid-js';
2
+ import { sharedConfig, 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
+ }
2
13
 
3
14
  const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
4
15
  function isResponseEnvelope(value) {
@@ -9,6 +20,270 @@ function isSafeError(value) {
9
20
  return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
10
21
  }
11
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 REQUEST_ERROR_HOOK = Symbol.for("solid-js/server/request-error-hook");
27
+ function hooks() {
28
+ const g = globalThis;
29
+ return g[REQUEST_ERROR_HOOK] || (g[REQUEST_ERROR_HOOK] = new WeakMap());
30
+ }
31
+ function requestErrorHook(event) {
32
+ return event === undefined ? undefined : hooks().get(event);
33
+ }
34
+
35
+ const PROVIDER = Symbol.for("solid-js/observe/server/provider");
36
+ function currentProvider() {
37
+ if (OBSERVE === undefined) return undefined;
38
+ const slot = OBSERVE.server.trace;
39
+ return slot && slot[PROVIDER];
40
+ }
41
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
42
+ const ZERO_TRACE = "00000000000000000000000000000000";
43
+ const ZERO_SPAN = "0000000000000000";
44
+ function parseTraceparent(value) {
45
+ if (!value) return undefined;
46
+ const m = TRACEPARENT.exec(value.trim());
47
+ if (!m) return undefined;
48
+ const [, version, traceId, parentId, flags, rest] = m;
49
+ if (version === "ff") return undefined;
50
+ if (version === "00" && rest !== undefined) return undefined;
51
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
52
+ return {
53
+ traceId,
54
+ parentId,
55
+ sampled: (parseInt(flags, 16) & 1) === 1
56
+ };
57
+ }
58
+ function randomHex(bytes) {
59
+ let out = "";
60
+ for (let i = 0; i < bytes; i += 4) out += (Math.random() * 0x100000000 >>> 0).toString(16).padStart(8, "0");
61
+ return out.length === bytes * 2 ? out : out.slice(0, bytes * 2);
62
+ }
63
+ function randomTraceId() {
64
+ let id = randomHex(16);
65
+ while (id === ZERO_TRACE) id = randomHex(16);
66
+ return id;
67
+ }
68
+ function randomSpanId() {
69
+ let id = randomHex(8);
70
+ while (id === ZERO_SPAN) id = randomHex(8);
71
+ return id;
72
+ }
73
+ function formatTraceparent(context) {
74
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
75
+ }
76
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
77
+ function records$1() {
78
+ const g = globalThis;
79
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
80
+ }
81
+ function traceFor(key, request) {
82
+ const store = records$1();
83
+ let record = store.get(key);
84
+ if (record) return record;
85
+ const headers = request ? request.headers : undefined;
86
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
87
+ const context = {
88
+ traceId: incoming ? incoming.traceId : randomTraceId(),
89
+ spanId: randomSpanId(),
90
+ entries: {}
91
+ };
92
+ if (incoming) {
93
+ context.parentId = incoming.parentId;
94
+ context.sampled = incoming.sampled;
95
+ }
96
+ if (headers) {
97
+ const state = headers.get("tracestate");
98
+ if (state) context.state = state;
99
+ const baggage = headers.get("baggage");
100
+ if (baggage) context.baggage = baggage;
101
+ }
102
+ let answered = false;
103
+ let providedEntries;
104
+ {
105
+ const provider = currentProvider();
106
+ if (provider) {
107
+ let answer;
108
+ try {
109
+ answer = provider(request);
110
+ } catch (error) {
111
+ console.error(error);
112
+ }
113
+ if (answer !== undefined && answer !== null) {
114
+ answered = true;
115
+ if (answer.traceId !== undefined) context.traceId = answer.traceId;
116
+ if (answer.spanId !== undefined) context.spanId = answer.spanId;
117
+ if (answer.parentId !== undefined) context.parentId = answer.parentId;
118
+ if (answer.sampled !== undefined) context.sampled = answer.sampled;
119
+ if (answer.state !== undefined) context.state = answer.state;
120
+ if (answer.baggage !== undefined) context.baggage = answer.baggage;
121
+ providedEntries = answer.entries;
122
+ }
123
+ }
124
+ }
125
+ context.entries.traceparent = formatTraceparent(context);
126
+ if (providedEntries) Object.assign(context.entries, providedEntries);
127
+ record = {
128
+ context,
129
+ emit: incoming !== undefined && incoming.sampled || answered,
130
+ timing: []
131
+ };
132
+ store.set(key, record);
133
+ return record;
134
+ }
135
+ function traceForEvent(event) {
136
+ return traceFor(event.request || event, event.request);
137
+ }
138
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
139
+ function splitServerTiming(value) {
140
+ const entries = [];
141
+ let start = 0;
142
+ let quoted = false;
143
+ for (let i = 0; i < value.length; i++) {
144
+ const c = value[i];
145
+ if (quoted) {
146
+ if (c === "\\") i++;else if (c === '"') quoted = false;
147
+ } else if (c === '"') quoted = true;else if (c === ",") {
148
+ entries.push(value.slice(start, i));
149
+ start = i + 1;
150
+ }
151
+ }
152
+ entries.push(value.slice(start));
153
+ return entries;
154
+ }
155
+ function metricName(entry) {
156
+ return entry.split(";")[0].trim().toLowerCase();
157
+ }
158
+ function namesOnServerTiming(headers) {
159
+ const names = new Set();
160
+ const existing = headers.get("server-timing");
161
+ if (existing) {
162
+ for (const entry of splitServerTiming(existing)) {
163
+ const name = metricName(entry);
164
+ if (name) names.add(name);
165
+ }
166
+ }
167
+ return names;
168
+ }
169
+ function quoteDesc(value) {
170
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
171
+ }
172
+ function shellMs(record) {
173
+ return record.render !== undefined ? record.render.shellMs : undefined;
174
+ }
175
+ function hasServerTiming(record) {
176
+ return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
177
+ }
178
+ function appendTraceServerTiming(headers, record) {
179
+ if (record.emit) {
180
+ const entries = record.context.entries;
181
+ let present;
182
+ for (const name in entries) {
183
+ if (!TOKEN.test(name)) continue;
184
+ if (!present) present = namesOnServerTiming(headers);
185
+ if (present.has(name.toLowerCase())) continue;
186
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
187
+ present.add(name.toLowerCase());
188
+ }
189
+ }
190
+ const shell = shellMs(record);
191
+ if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
192
+ for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
193
+ }
194
+ function metricOf(work) {
195
+ if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
196
+ const boundary = work.event;
197
+ return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
198
+ }
199
+ function formatMetric(name, dur, desc) {
200
+ let out = `${name};dur=${Math.round(dur * 10) / 10}`;
201
+ if (desc) out += `;desc="${quoteDesc(desc)}"`;
202
+ return out;
203
+ }
204
+ function mergeServerTiming(target, value) {
205
+ const present = namesOnServerTiming(target);
206
+ for (const entry of splitServerTiming(value)) {
207
+ const trimmed = entry.trim();
208
+ const name = metricName(trimmed);
209
+ if (!name || present.has(name)) continue;
210
+ target.append("Server-Timing", trimmed);
211
+ }
212
+ }
213
+
214
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
215
+ function records() {
216
+ return globalThis[RECORDS];
217
+ }
218
+ function settledPromise(value) {
219
+ if (value instanceof Promise) return value;
220
+ try {
221
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, v => v);
222
+ } catch {}
223
+ return undefined;
224
+ }
225
+ function isDeferredBody(value) {
226
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
227
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
228
+ const v = value;
229
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
230
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
231
+ }
232
+
233
+ const IS_DEV = true;
234
+ function timesServerWork(type) {
235
+ const channel = records();
236
+ if (channel === undefined) return false;
237
+ return IS_DEV;
238
+ }
239
+ function deliver(context, at, boundary, outcome, value) {
240
+ const record = {
241
+ id: context.id,
242
+ direct: context.direct,
243
+ at,
244
+ durationMs: performance.now() - at,
245
+ outcome
246
+ };
247
+ if (boundary !== undefined) record.boundary = boundary;
248
+ if (outcome === "ok" && isDeferredBody(value)) record.deferred = true;
249
+ traceForEvent(context.event).timing.push({
250
+ type: "invocation",
251
+ event: record
252
+ });
253
+ const channel = records();
254
+ if (!channel.observed("invocation")) return;
255
+ const live = {
256
+ event: context.event,
257
+ args: context.args
258
+ };
259
+ if (context.request !== undefined) live.request = context.request;
260
+ if (outcome === "ok") live.result = value;else live.error = value;
261
+ channel.emit("invocation", record, live);
262
+ }
263
+ function observeInvocation(context, execute) {
264
+ if (!timesServerWork()) return execute();
265
+ const at = performance.now();
266
+ const boundary = context.direct ? sharedConfig.context?._currentBoundaryId ?? undefined : undefined;
267
+ let result;
268
+ try {
269
+ result = execute();
270
+ } catch (error) {
271
+ deliver(context, at, boundary, "error", error);
272
+ throw error;
273
+ }
274
+ const promised = settledPromise(result);
275
+ if (promised !== undefined) {
276
+ return promised.then(value => {
277
+ deliver(context, at, boundary, "ok", value);
278
+ return value;
279
+ }, error => {
280
+ deliver(context, at, boundary, "error", error);
281
+ throw error;
282
+ });
283
+ }
284
+ deliver(context, at, boundary, "ok", result);
285
+ return result;
286
+ }
12
287
 
13
288
  const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
14
289
  function getServerFunctionMetadata(fn) {
@@ -26,6 +301,32 @@ function withMeta(fn, meta) {
26
301
  Object.assign(metadata, meta);
27
302
  return fn;
28
303
  }
304
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
305
+ const INVOKE_OPTION_REDIRECTS = {
306
+ 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.",
307
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
308
+ body: "The arguments are the body: pass them in the args array.",
309
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
310
+ };
311
+ function invoke(fn, options, ...args) {
312
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
313
+ if (!channel) {
314
+ 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.");
315
+ }
316
+ if (options === null || typeof options !== "object") {
317
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
318
+ }
319
+ const picked = {};
320
+ for (const key in options) {
321
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
322
+ 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."));
323
+ }
324
+ }
325
+ if (options.signal !== undefined) picked.signal = options.signal;
326
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
327
+ if (options.priority !== undefined) picked.priority = options.priority;
328
+ return channel(args, picked);
329
+ }
29
330
  const LIVE_SOURCE = Symbol.for("solid.LiveSource");
30
331
  const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
31
332
  function provideServerFunctionRPC(rpc) {
@@ -55,6 +356,7 @@ function decodeSafe(text) {
55
356
  }
56
357
  }
57
358
  function serializeCookie(name, value, options = {}) {
359
+ assertServableCookie(name, options);
58
360
  let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
59
361
  cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
60
362
  if (options.domain) cookie += `; Domain=${options.domain}`;
@@ -62,14 +364,34 @@ function serializeCookie(name, value, options = {}) {
62
364
  if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
63
365
  if (options.httpOnly) cookie += "; HttpOnly";
64
366
  if (options.secure) cookie += "; Secure";
367
+ if (options.partitioned) cookie += "; Partitioned";
65
368
  if (options.sameSite) {
66
369
  const sameSite = options.sameSite.toLowerCase();
67
370
  cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
68
371
  }
69
372
  return cookie;
70
373
  }
374
+ function assertServableCookie(name, options) {
375
+ const reject = reason => {
376
+ throw new Error(`serializeCookie: every browser silently rejects this cookie — ${reason}. ` + `It would never come back on a request, with no error anywhere.`);
377
+ };
378
+ const lower = name.toLowerCase();
379
+ if (lower.startsWith("__host-")) {
380
+ if (!options.secure) reject(`the __Host- prefix on \`${name}\` requires \`secure: true\``);
381
+ if (options.path !== undefined && options.path !== "/") reject(`the __Host- prefix on \`${name}\` requires \`Path=/\` (got \`${options.path}\`) — ` + `host-locking is the prefix's whole contract, so it cannot be path-scoped`);
382
+ if (options.domain) reject(`the __Host- prefix on \`${name}\` forbids \`Domain\` (got \`${options.domain}\`)`);
383
+ } else if (lower.startsWith("__secure-") && !options.secure) {
384
+ reject(`the __Secure- prefix on \`${name}\` requires \`secure: true\``);
385
+ }
386
+ if (options.sameSite && options.sameSite.toLowerCase() === "none" && !options.secure) {
387
+ reject("`SameSite=None` requires `secure: true`");
388
+ }
389
+ if (options.partitioned && !options.secure) {
390
+ reject("`Partitioned` requires `secure: true`");
391
+ }
392
+ }
71
393
  const FLASH_COOKIE = "flash";
72
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
394
+ const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
73
395
  function hasFlashCookie(cookieHeader) {
74
396
  return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
75
397
  }
@@ -86,11 +408,141 @@ function configureServerFunctionsCodec(codec) {
86
408
  function getServerFunctionsCodec() {
87
409
  return codecConfig.codec;
88
410
  }
89
- function subscribeFlightData(consumer) {
411
+ const UNNAMED_FLIGHT_SOURCE = "true";
412
+ const flightConfig = {
413
+ consumers: new Map()
414
+ };
415
+ function assertFlightSource(source) {
416
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
417
+ 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).`);
418
+ }
419
+ }
420
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
421
+ const named = typeof sourceOrConsumer === "string";
422
+ if (named) assertFlightSource(sourceOrConsumer);
423
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
424
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
425
+ flightConfig.consumers.set(source, consumer);
90
426
  return () => {
427
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
91
428
  };
92
429
  }
93
- const FUNCTION_HEADER = "X-Server-Function-Id";
430
+ function frameAddress(id, args) {
431
+ return args && args.length ? id + ":" + hashArguments(args) : id;
432
+ }
433
+ function hashArguments(args) {
434
+ let hash = 0;
435
+ const text = stableString(args);
436
+ for (let i = 0; i < text.length; i++) {
437
+ hash = (hash << 5) - hash + text.charCodeAt(i);
438
+ hash |= 0;
439
+ }
440
+ return (hash >>> 0).toString(36);
441
+ }
442
+ function stableString(value, seen) {
443
+ if (value === null || typeof value !== "object") {
444
+ return typeof value === "bigint" ? value + "n" : String(value);
445
+ }
446
+ if (value instanceof Date) return "Date:" + value.getTime();
447
+ seen || (seen = new Set());
448
+ if (seen.has(value)) return "~";
449
+ seen.add(value);
450
+ if (value instanceof Map) {
451
+ const entries = [];
452
+ for (const [k, v] of value) {
453
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
454
+ }
455
+ return "Map{" + entries.sort().join(",") + "}";
456
+ }
457
+ if (value instanceof Set) {
458
+ const members = [];
459
+ for (const v of value) members.push(stableString(v, seen));
460
+ return "Set{" + members.sort().join(",") + "}";
461
+ }
462
+ if (Array.isArray(value)) {
463
+ let out = "[";
464
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
465
+ return out + "]";
466
+ }
467
+ const keys = Object.keys(value).sort();
468
+ let out = "{";
469
+ for (let i = 0; i < keys.length; i++) {
470
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
471
+ }
472
+ return out + "}";
473
+ }
474
+ function serverFunctionAddress(endpoint, id) {
475
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
476
+ return `${mount}/${encodeURIComponent(id)}`;
477
+ }
478
+ function serverFunctionDataAddress(endpoint, id) {
479
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
480
+ return `${mount}/data/${encodeURIComponent(id)}`;
481
+ }
482
+ function serverFunctionLiveAddress(endpoint, id) {
483
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
484
+ return `${mount}/live/${encodeURIComponent(id)}`;
485
+ }
486
+ function parseServerFunctionAddress(pathname, endpoint) {
487
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
488
+ if (!pathname.startsWith(mount)) return null;
489
+ const rest = pathname.slice(mount.length);
490
+ if (!rest.startsWith("/")) return null;
491
+ let segment = rest.slice(1);
492
+ let data = false;
493
+ let live = false;
494
+ if (segment.startsWith("data/")) {
495
+ segment = segment.slice(5);
496
+ data = true;
497
+ } else if (segment.startsWith("live/")) {
498
+ segment = segment.slice(5);
499
+ live = true;
500
+ }
501
+ if (!segment || segment.includes("/")) return null;
502
+ try {
503
+ return {
504
+ id: decodeURIComponent(segment),
505
+ data,
506
+ live
507
+ };
508
+ } catch {
509
+ return null;
510
+ }
511
+ }
512
+ const MAX_GET_URL_LENGTH = 2000;
513
+ function urlTargetId(target, helper) {
514
+ if (typeof target === "string") return target;
515
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
516
+ throw new Error(`${helper} expects a server function reference (or its id).`);
517
+ }
518
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
519
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
520
+ if (!boundArgs.length) return address;
521
+ if (!isJSONSafe(boundArgs)) {
522
+ 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.");
523
+ }
524
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
525
+ }
526
+ function serverFunctionUrlFor(endpoint, fn, args) {
527
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
528
+ throw new Error("serverFunctionUrl expects a server function reference.");
529
+ }
530
+ const metadata = getServerFunctionMetadata(fn);
531
+ if (!metadata || metadata.method !== "GET") {
532
+ 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).');
533
+ }
534
+ const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
535
+ if (!args.length) return address;
536
+ if (!isJSONSafe(args)) {
537
+ 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.");
538
+ }
539
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
540
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
541
+ if (length > MAX_GET_URL_LENGTH) {
542
+ 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.");
543
+ }
544
+ return url;
545
+ }
94
546
  const ERROR_HEADER = "X-Server-Function-Error";
95
547
  const ERROR_HEADER_MARKER = "=?1?";
96
548
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -116,8 +568,31 @@ function decodeErrorHeaderValue(value) {
116
568
  return value;
117
569
  }
118
570
  }
119
- const INSTANCE_HEADER = "X-Server-Function-Instance";
120
571
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
572
+ const LAST_EVENT_ID_HEADER = "Last-Event-ID";
573
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
574
+ const BUILD_HEADER = "X-Server-Function-Build";
575
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
576
+ function decodeRedirectHeaderValue(value) {
577
+ if (typeof value !== "string") return undefined;
578
+ const at = value.indexOf(" ");
579
+ if (at < 0) return undefined;
580
+ const status = Number(value.slice(0, at));
581
+ const url = value.slice(at + 1);
582
+ if (!Number.isInteger(status) || !url) return undefined;
583
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
584
+ let parsed;
585
+ try {
586
+ parsed = new URL(url);
587
+ } catch {
588
+ return undefined;
589
+ }
590
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
591
+ return {
592
+ status,
593
+ url
594
+ };
595
+ }
121
596
  const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
122
597
  const FILE_FORM_KEY = "__server_function_file__";
123
598
  const BodyFormat = {
@@ -129,7 +604,8 @@ const BodyFormat = {
129
604
  File: "5",
130
605
  ArrayBuffer: "6",
131
606
  Uint8Array: "7",
132
- Json: "8"
607
+ Json: "8",
608
+ Void: "9"
133
609
  };
134
610
  const JSON_SAFE_DEPTH_LIMIT = 4096;
135
611
  const EXIT = {};
@@ -146,7 +622,7 @@ function isJSONSafe(value) {
146
622
  const t = typeof v;
147
623
  if (t === "string" || t === "boolean") continue;
148
624
  if (t === "number") {
149
- if (!Number.isFinite(v)) return false;
625
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
150
626
  continue;
151
627
  }
152
628
  if (t !== "object") return false;
@@ -159,7 +635,11 @@ function isJSONSafe(value) {
159
635
  const proto = Object.getPrototypeOf(v);
160
636
  if (proto !== Object.prototype && proto !== null) return false;
161
637
  if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
162
- for (const k in v) stack.push(v[k]);
638
+ for (const k in v) {
639
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
640
+ if (descriptor === undefined || !("value" in descriptor)) return false;
641
+ stack.push(descriptor.value);
642
+ }
163
643
  }
164
644
  }
165
645
  return true;
@@ -225,127 +705,262 @@ function getHeadersAndBody(body) {
225
705
  return undefined;
226
706
  }
227
707
  }
228
- async function extractBody(source, codecOptions) {
708
+ async function extractBody(source, codecOptions, wire) {
229
709
  const contentType = source.headers.get("content-type");
230
710
  const format = source.headers.get(BODY_FORMAT_HEADER);
231
- const clone = source.clone();
232
711
  switch (true) {
233
712
  case format === BodyFormat.Serialized:
234
- return await deserializeStream(clone, codecOptions);
713
+ return await deserializeStream(source, codecOptions, wire);
235
714
  case format === BodyFormat.Json:
236
- return JSON.parse(await clone.text());
715
+ return JSON.parse(await source.text());
237
716
  case format === BodyFormat.String:
238
- return await clone.text();
717
+ return await source.text();
239
718
  case format === BodyFormat.File:
240
719
  {
241
- const formData = await clone.formData();
720
+ const formData = await source.formData();
242
721
  return formData.get(FILE_FORM_KEY);
243
722
  }
244
723
  case format === BodyFormat.FormData:
245
724
  case contentType && contentType.startsWith("multipart/form-data"):
246
- return await clone.formData();
725
+ return await source.formData();
247
726
  case format === BodyFormat.URLSearchParams:
248
727
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
249
- return new URLSearchParams(await clone.text());
728
+ return new URLSearchParams(await source.text());
250
729
  case format === BodyFormat.Blob:
251
- return await clone.blob();
730
+ return await source.blob();
252
731
  case format === BodyFormat.ArrayBuffer:
253
- return await clone.arrayBuffer();
732
+ return await source.arrayBuffer();
254
733
  case format === BodyFormat.Uint8Array:
255
- return new Uint8Array(await clone.arrayBuffer());
734
+ return new Uint8Array(await source.arrayBuffer());
256
735
  }
257
736
  return undefined;
258
737
  }
259
738
  function createChunk(data) {
260
- const encoder = new TextEncoder();
261
- const encodeData = encoder.encode(data);
739
+ const encodeData = CHUNK_ENCODER.encode(data);
262
740
  const bytes = encodeData.length;
741
+ if (bytes > MAX_CHUNK_BYTES) {
742
+ throw new RangeError("Server function chunk is too large to frame.");
743
+ }
263
744
  const chunk = new Uint8Array(12 + bytes);
264
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
745
+ chunk.set(CHUNK_ENCODER.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
265
746
  chunk.set(encodeData, 12);
266
747
  return chunk;
267
748
  }
749
+ const CHUNK_ENCODER = /* @__PURE__ */new TextEncoder();
750
+ const CHUNK_DECODER = /* @__PURE__ */new TextDecoder("utf-8", {
751
+ fatal: true
752
+ });
753
+ const MAX_CHUNK_BYTES = 0xffffffff;
754
+ const RETAINED_STORE_BYTES = 64 * 1024;
755
+ const DONE = {
756
+ done: true,
757
+ value: undefined
758
+ };
759
+ function malformedStream() {
760
+ return new Error("Malformed server function stream.");
761
+ }
268
762
  class ChunkReader {
269
763
  constructor(stream) {
270
764
  this.reader = stream.getReader();
271
- this.buffer = new Uint8Array(0);
765
+ this.store = new Uint8Array(0);
766
+ this.buffer = this.store;
272
767
  this.done = false;
768
+ this.cancelled = false;
273
769
  }
274
770
  async readChunk() {
275
771
  const chunk = await this.reader.read();
276
- if (!chunk.done) {
277
- const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
278
- newBuffer.set(this.buffer);
279
- newBuffer.set(chunk.value, this.buffer.length);
280
- this.buffer = newBuffer;
281
- } else {
772
+ if (chunk.done) {
282
773
  this.done = true;
774
+ return this.cancelled;
283
775
  }
776
+ const incoming = chunk.value;
777
+ const store = this.store;
778
+ const start = this.buffer.byteOffset;
779
+ const end = start + this.buffer.length;
780
+ const needed = this.buffer.length + incoming.length;
781
+ if (end + incoming.length <= store.length) {
782
+ store.set(incoming, end);
783
+ this.buffer = store.subarray(start, end + incoming.length);
784
+ } else if (needed <= store.length) {
785
+ store.copyWithin(0, start, end);
786
+ store.set(incoming, this.buffer.length);
787
+ this.buffer = store.subarray(0, needed);
788
+ } else {
789
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
790
+ grown.set(this.buffer);
791
+ grown.set(incoming, this.buffer.length);
792
+ this.store = grown;
793
+ this.buffer = grown.subarray(0, needed);
794
+ }
795
+ return this.cancelled;
284
796
  }
285
797
  async next() {
798
+ if (this.cancelled) return DONE;
286
799
  while (this.buffer.length < 12) {
287
800
  if (this.done) {
288
- if (this.buffer.length === 0) return {
289
- done: true,
290
- value: undefined
291
- };
292
- throw new Error("Malformed server function stream.");
801
+ if (this.buffer.length === 0) return DONE;
802
+ throw malformedStream();
293
803
  }
294
- await this.readChunk();
295
- }
296
- const decoder = new TextDecoder();
297
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
298
- if (Number.isNaN(bytes)) {
299
- throw new Error("Malformed server function stream.");
804
+ if (await this.readChunk()) return DONE;
300
805
  }
806
+ const header = String.fromCharCode(...this.buffer.subarray(0, 12));
807
+ if (!/^;0x[\dA-Fa-f]{8};$/.test(header)) throw malformedStream();
808
+ const bytes = parseInt(header.slice(3, 11), 16);
301
809
  while (bytes > this.buffer.length - 12) {
302
810
  if (this.done) {
303
- throw new Error("Malformed server function stream.");
811
+ throw malformedStream();
304
812
  }
305
- await this.readChunk();
813
+ if (await this.readChunk()) return DONE;
814
+ }
815
+ let partial;
816
+ try {
817
+ partial = CHUNK_DECODER.decode(this.buffer.subarray(12, 12 + bytes));
818
+ } catch {
819
+ throw malformedStream();
306
820
  }
307
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
308
821
  this.buffer = this.buffer.subarray(12 + bytes);
822
+ if (this.store.length > RETAINED_STORE_BYTES && this.buffer.length <= RETAINED_STORE_BYTES) {
823
+ this.store = this.buffer = this.buffer.slice();
824
+ }
309
825
  return {
310
826
  done: false,
311
827
  value: partial
312
828
  };
313
829
  }
314
830
  async drain(interpret) {
315
- while (true) {
316
- const result = await this.next();
317
- if (result.done) {
318
- break;
831
+ try {
832
+ while (true) {
833
+ const result = await this.next();
834
+ if (result.done) {
835
+ break;
836
+ }
837
+ interpret(result.value);
319
838
  }
320
- interpret(result.value);
839
+ } catch (error) {
840
+ this.cancel(error).catch(() => {});
841
+ throw error;
321
842
  }
322
843
  }
844
+ cancel(reason) {
845
+ this.cancelled = true;
846
+ return this.reader.cancel(reason);
847
+ }
848
+ }
849
+ function createEventChunk(data, id) {
850
+ let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
851
+ for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
852
+ return CHUNK_ENCODER.encode(event + "\n");
853
+ }
854
+ const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
855
+ function isEventStream(source) {
856
+ const contentType = source.headers.get("content-type");
857
+ return !!contentType && contentType.startsWith("text/event-stream");
858
+ }
859
+ function positionDigest(value) {
860
+ if (value === undefined || !isJSONSafe(value)) return undefined;
861
+ const text = JSON.stringify(value);
862
+ if (typeof text !== "string") return undefined;
863
+ return textDigest(text);
864
+ }
865
+ function textDigest(text) {
866
+ let a = 0x811c9dc5;
867
+ let b = 0x050c5d1f;
868
+ for (let i = 0; i < text.length; i++) {
869
+ const code = text.charCodeAt(i);
870
+ a = Math.imul(a ^ code, 0x01000193);
871
+ b = Math.imul(b ^ code, 0x01000193);
872
+ }
873
+ return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
874
+ }
875
+ const ERROR_TRAILER_PREFIX = "!";
876
+ function encodeErrorTrailer(error) {
877
+ const shaped = error instanceof Error ? error : new Error(String(error));
878
+ return ERROR_TRAILER_PREFIX + JSON.stringify(shaped.name && shaped.name !== "Error" ? {
879
+ name: shaped.name,
880
+ message: shaped.message
881
+ } : {
882
+ message: shaped.message
883
+ });
884
+ }
885
+ function errorFromTrailer(payload) {
886
+ let shape;
887
+ try {
888
+ shape = JSON.parse(payload.slice(1));
889
+ } catch {
890
+ shape = null;
891
+ }
892
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
893
+ if (shape && typeof shape.name === "string") error.name = shape.name;
894
+ return error;
895
+ }
896
+ function serializeStream(value, codecOptions) {
897
+ return new ReadableStream({
898
+ async start(controller) {
899
+ const {
900
+ serializeJSON
901
+ } = await import('@solidjs/web/serialization');
902
+ serializeJSON(value, {
903
+ ...codecOptions,
904
+ onParse(node) {
905
+ controller.enqueue(createChunk(JSON.stringify(node)));
906
+ },
907
+ onDone() {
908
+ controller.close();
909
+ },
910
+ onError(error) {
911
+ controller.error(error);
912
+ }
913
+ });
914
+ }
915
+ });
323
916
  }
324
- async function deserializeStream(source, codecOptions) {
917
+ async function deserializeStream(source, codecOptions, wire) {
325
918
  if (!source.body) {
326
919
  throw new Error("missing body");
327
920
  }
328
- const reader = new ChunkReader(source.body);
329
- const result = await reader.next();
330
- if (!result.done) {
331
- const {
332
- createJSONDeserializer
333
- } = await import('@solidjs/web/serialization/decode');
334
- const deserializeChunk = createJSONDeserializer(codecOptions);
335
- function interpretChunk(chunk) {
336
- return deserializeChunk(JSON.parse(chunk));
921
+ const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
922
+ try {
923
+ const result = await reader.next();
924
+ if (!result.done) {
925
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
926
+ throw errorFromTrailer(result.value);
927
+ }
928
+ const {
929
+ createJSONDeserializer
930
+ } = await import('@solidjs/web/serialization/decode');
931
+ const deserializeChunk = createJSONDeserializer(codecOptions);
932
+ function interpretChunk(chunk) {
933
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
934
+ throw errorFromTrailer(chunk);
935
+ }
936
+ return deserializeChunk(JSON.parse(chunk));
937
+ }
938
+ const connection = wire && wire.connection;
939
+ let endConnection;
940
+ if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
941
+ const end = error => {
942
+ const sweep = () => deserializeChunk.abort(error);
943
+ if (connection) {
944
+ const close = () => deserializeChunk.close();
945
+ endConnection({
946
+ open: deserializeChunk.open(),
947
+ error,
948
+ sweep,
949
+ close
950
+ });
951
+ } else sweep();
952
+ };
953
+ reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
954
+ return interpretChunk(result.value);
337
955
  }
338
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
339
- return interpretChunk(result.value);
956
+ } catch (error) {
957
+ reader.cancel(error).catch(() => {});
958
+ throw error;
340
959
  }
341
- return undefined;
342
- }
343
- async function deserializeString(text, codecOptions) {
344
- return await deserializeStream(new Response(text), codecOptions);
345
960
  }
346
961
  async function decodeResponse(response, codecOptions) {
347
962
  if (!response.body) return undefined;
348
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
963
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
349
964
  }
350
965
  async function decodeResponsePayload(response, codecOptions) {
351
966
  const decoded = await decodeResponse(response, codecOptions);
@@ -360,21 +975,74 @@ async function decodeResponsePayload(response, codecOptions) {
360
975
  };
361
976
  }
362
977
 
978
+ function emitFinding(finding, subject = getOwner()) {
979
+ if (OBSERVE === undefined) return;
980
+ const entry = OBSERVE.diagnostics.emit(finding, subject);
981
+ if (DEV$1 !== undefined) DEV$1.report(entry);
982
+ }
983
+ function recordFinding(finding, subject = getOwner()) {
984
+ if (OBSERVE !== undefined) OBSERVE.diagnostics.emit(finding, subject);
985
+ }
986
+ function errorText(error) {
987
+ if (error instanceof Error) return error.message ? `${error.name}: ${error.message}` : error.name;
988
+ return String(error);
989
+ }
990
+
363
991
  typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
364
992
  const RequestContext = Symbol.for("solid.RequestContext");
365
993
  function getRequestEvent() {
366
- 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;
994
+ const store = globalThis[RequestContext];
995
+ if (!store) return undefined;
996
+ const event = store.getStore();
997
+ if (event) return event;
998
+ const ctx = renderContextOf(getOwner());
999
+ return ctx && ctx.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.");
1000
+ }
1001
+ const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
1002
+ function renderContextOf(owner) {
1003
+ const roots = globalThis[RENDER_ROOTS];
1004
+ if (!roots) return undefined;
1005
+ for (; owner; owner = owner._parent) {
1006
+ const context = roots.get(owner);
1007
+ if (context) return context;
1008
+ }
1009
+ }
1010
+ function peekRequestEvent() {
1011
+ const store = globalThis[RequestContext];
1012
+ return store ? store.getStore() : undefined;
1013
+ }
1014
+ function traceForStub(stub, event) {
1015
+ if (!event) {
1016
+ event = peekRequestEvent();
1017
+ if (!event || event.response !== stub) return undefined;
1018
+ }
1019
+ return traceForEvent(event);
367
1020
  }
368
1021
  function reportLostHeaderWrite(method, name) {
369
- const message = `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).";
1022
+ 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).";
1023
+ recordFinding({
1024
+ code: "LATE_HEADER_WRITE",
1025
+ kind: "head",
1026
+ severity: "error",
1027
+ message,
1028
+ data: {
1029
+ method,
1030
+ name: String(name)
1031
+ }
1032
+ });
370
1033
  throw new Error(message);
371
1034
  }
372
1035
  function commitResponseStub(stub, {
373
- allowLateLocation = false
1036
+ allowLateLocation = false,
1037
+ event
374
1038
  } = {}) {
375
1039
  if (!stub || stub.committed) return stub;
376
- stub.committed = true;
377
1040
  const headers = stub.headers;
1041
+ if (headers && typeof headers.append === "function") {
1042
+ const trace = traceForStub(stub, event);
1043
+ if (trace) appendTraceServerTiming(headers, trace);
1044
+ }
1045
+ stub.committed = true;
378
1046
  if (!headers || typeof headers.set !== "function") return stub;
379
1047
  for (const method of ["set", "append", "delete"]) {
380
1048
  const original = headers[method].bind(headers);
@@ -396,42 +1064,124 @@ function copyInitHeaders(init) {
396
1064
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
397
1065
  return headers;
398
1066
  }
399
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
1067
+ let stubGapFillExcluded;
1068
+ function isStubGapFillExcluded(key) {
1069
+ return (stubGapFillExcluded ||= new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
1070
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()))).has(key);
1071
+ }
400
1072
  function fillsStubGap(key, headers, response) {
401
- if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
1073
+ if (key === "set-cookie" || isStubGapFillExcluded(key)) return false;
402
1074
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
403
1075
  return !headers.has(key);
404
1076
  }
405
1077
  function commitEventResponse(response, event = getRequestEvent()) {
406
1078
  const stub = event && event.response;
407
- if (!stub || !stub.headers || stub.committed) return response;
408
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
409
- commitResponseStub(stub);
410
- let hasGaps = false;
411
- stub.headers.forEach((value, key) => {
412
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
413
- });
414
- if (!cookies.length && !hasGaps) return response;
415
- try {
416
- for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
417
- stub.headers.forEach((value, key) => {
418
- if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
419
- });
420
- return response;
421
- } catch {
1079
+ if (!stub || !stub.headers || stub.committed) {
1080
+ if (!event || stub) return response;
1081
+ const trace = traceForEvent(event);
1082
+ if (!hasServerTiming(trace)) return response;
422
1083
  const headers = copyInitHeaders(response.headers);
423
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
424
- stub.headers.forEach((value, key) => {
425
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
426
- });
1084
+ appendTraceServerTiming(headers, trace);
427
1085
  return new Response(response.body, {
428
1086
  status: response.status,
429
1087
  statusText: response.statusText,
430
1088
  headers
431
1089
  });
432
1090
  }
1091
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
1092
+ commitResponseStub(stub, {
1093
+ event
1094
+ });
1095
+ let hasGaps = false;
1096
+ stub.headers.forEach((value, key) => {
1097
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
1098
+ });
1099
+ const timing = stub.headers.get("server-timing");
1100
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
1101
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
1102
+ const headers = copyInitHeaders(response.headers);
1103
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
1104
+ stub.headers.forEach((value, key) => {
1105
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
1106
+ });
1107
+ if (mergesTiming) mergeServerTiming(headers, timing);
1108
+ return new Response(response.body, {
1109
+ status: response.status,
1110
+ statusText: response.statusText,
1111
+ headers
1112
+ });
433
1113
  }
434
1114
 
1115
+ let configuredSecret;
1116
+ function setFlashSecret(secret) {
1117
+ configuredSecret = secret;
1118
+ }
1119
+ function resolveSecret() {
1120
+ return configuredSecret !== undefined ? configuredSecret : globalThis.__SOLID_SECRET__;
1121
+ }
1122
+ const FLASH_KEY_DOMAIN = "solid.flash.v1\0";
1123
+ const FLASH_KEY_ITERATIONS = 100_000;
1124
+ let cachedSecret;
1125
+ let cachedKey;
1126
+ function resolveFlashKey() {
1127
+ const secret = resolveSecret();
1128
+ if (typeof secret !== "string" || secret.length === 0) return null;
1129
+ if (secret !== cachedSecret) {
1130
+ cachedSecret = secret;
1131
+ const encoder = new TextEncoder();
1132
+ cachedKey = crypto.subtle.importKey("raw", encoder.encode(secret), "PBKDF2", false, ["deriveKey"]).then(material => crypto.subtle.deriveKey({
1133
+ name: "PBKDF2",
1134
+ salt: encoder.encode(FLASH_KEY_DOMAIN),
1135
+ iterations: FLASH_KEY_ITERATIONS,
1136
+ hash: "SHA-256"
1137
+ }, material, {
1138
+ name: "AES-GCM",
1139
+ length: 256
1140
+ }, false, ["encrypt", "decrypt"]));
1141
+ }
1142
+ return cachedKey;
1143
+ }
1144
+ let warnedMissingKey = false;
1145
+ function warnMissingKey() {
1146
+ if (warnedMissingKey) return;
1147
+ warnedMissingKey = true;
1148
+ console.warn("[solid] A no-JS form outcome was not flashed: the flash cookie is encrypted and no key " + "is configured. Set configureServerFunctionsServer({ secret }) — or build with the Solid " + "bundler plugin, which provides a per-deployment key automatically. The submission " + "committed and the redirect was served; only the outcome echo was withheld.");
1149
+ }
1150
+ const FLASH_FORMAT_VERSION = "1.";
1151
+ const IV_BYTES = 12;
1152
+ const GCM_TAG_BYTES = 16;
1153
+ function toBase64url(bytes) {
1154
+ let binary = "";
1155
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1156
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1157
+ }
1158
+ function fromBase64url(text) {
1159
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
1160
+ const bytes = new Uint8Array(binary.length);
1161
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1162
+ return bytes;
1163
+ }
1164
+ async function encryptFlashValue(key, json) {
1165
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
1166
+ const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
1167
+ name: "AES-GCM",
1168
+ iv
1169
+ }, key, new TextEncoder().encode(json)));
1170
+ const packed = new Uint8Array(IV_BYTES + ciphertext.length);
1171
+ packed.set(iv);
1172
+ packed.set(ciphertext, IV_BYTES);
1173
+ return FLASH_FORMAT_VERSION + toBase64url(packed);
1174
+ }
1175
+ async function decryptFlashValue(key, value) {
1176
+ if (!value.startsWith(FLASH_FORMAT_VERSION)) return;
1177
+ const packed = fromBase64url(value.slice(FLASH_FORMAT_VERSION.length));
1178
+ if (packed.length <= IV_BYTES + GCM_TAG_BYTES) return;
1179
+ const plain = await crypto.subtle.decrypt({
1180
+ name: "AES-GCM",
1181
+ iv: packed.subarray(0, IV_BYTES)
1182
+ }, key, packed.subarray(IV_BYTES));
1183
+ return new TextDecoder().decode(plain);
1184
+ }
435
1185
  function encodeInputValue(value) {
436
1186
  if (value instanceof FormData) return {
437
1187
  $f: [...value.entries()].filter(([, v]) => typeof v === "string")
@@ -452,7 +1202,12 @@ function decodeInputValue(value) {
452
1202
  }
453
1203
  return value;
454
1204
  }
455
- function encodeFlashCookie(url, result, input, thrown) {
1205
+ async function encodeFlashCookie(url, result, input, thrown) {
1206
+ const key = resolveFlashKey();
1207
+ if (!key) {
1208
+ warnMissingKey();
1209
+ return null;
1210
+ }
456
1211
  const isError = result instanceof Error;
457
1212
  const payload = {
458
1213
  url,
@@ -461,29 +1216,168 @@ function encodeFlashCookie(url, result, input, thrown) {
461
1216
  thrown: !!thrown,
462
1217
  input: input.map(encodeInputValue)
463
1218
  };
464
- return serializeCookie(FLASH_COOKIE, JSON.stringify(payload), {
1219
+ if (fitsCookie(payload)) return flashCookie(payload, await key);
1220
+ payload.truncated = true;
1221
+ payload.input = [];
1222
+ if (!fitsCookie(payload)) {
1223
+ if (typeof payload.result === "string") {
1224
+ let prefix = payload.result;
1225
+ while (prefix.length > 0 && !fitsCookie({
1226
+ ...payload,
1227
+ result: prefix
1228
+ })) {
1229
+ prefix = prefix.slice(0, prefix.length >> 1);
1230
+ }
1231
+ payload.result = prefix.length > 0 ? prefix : true;
1232
+ } else {
1233
+ payload.result = true;
1234
+ }
1235
+ }
1236
+ if (!fitsCookie(payload)) return null;
1237
+ return flashCookie(payload, await key);
1238
+ }
1239
+ const FLASH_MAX_AGE_SECONDS = 60;
1240
+ async function flashCookie(payload, key) {
1241
+ return serializeCookie(FLASH_COOKIE, await encryptFlashValue(key, JSON.stringify(payload)), {
465
1242
  secure: true,
466
- httpOnly: true
1243
+ httpOnly: true,
1244
+ sameSite: "lax",
1245
+ maxAge: FLASH_MAX_AGE_SECONDS
467
1246
  });
468
1247
  }
469
- function decodeFlashCookie(cookieHeader) {
1248
+ const COOKIE_PAIR_BUDGET = 4000;
1249
+ function fitsCookie(payload) {
1250
+ const plaintextBytes = new TextEncoder().encode(JSON.stringify(payload)).length;
1251
+ const packedBytes = IV_BYTES + plaintextBytes + GCM_TAG_BYTES;
1252
+ const valueLength = FLASH_FORMAT_VERSION.length + Math.ceil(packedBytes * 4 / 3);
1253
+ return FLASH_COOKIE.length + 1 + valueLength <= COOKIE_PAIR_BUDGET;
1254
+ }
1255
+ async function decodeFlashCookie(cookieHeader) {
470
1256
  const match = parseCookieHeader(cookieHeader)[FLASH_COOKIE];
471
1257
  if (!match) return;
472
1258
  try {
473
- const payload = JSON.parse(match);
474
- if (!payload || !payload.result) return;
1259
+ const key = resolveFlashKey();
1260
+ if (!key) return;
1261
+ const json = await decryptFlashValue(await key, match);
1262
+ if (json === undefined) return;
1263
+ const payload = JSON.parse(json);
1264
+ if (!payload || typeof payload !== "object" || !("result" in payload)) return;
475
1265
  const result = payload.error ? new Error(payload.result) : payload.result;
476
- return {
1266
+ const submission = {
477
1267
  input: Array.isArray(payload.input) ? payload.input.map(decodeInputValue) : [],
478
1268
  url: payload.url,
479
1269
  result: payload.thrown ? undefined : result,
480
1270
  error: payload.thrown ? result : undefined
481
1271
  };
1272
+ if (payload.truncated) submission.truncated = true;
1273
+ return submission;
482
1274
  } catch (error) {
483
1275
  console.error(error);
484
1276
  }
485
1277
  }
486
1278
 
1279
+ const RESPONSE_TAG = "seroval-plugins/web/Response";
1280
+ const REQUEST_TAG = "seroval-plugins/web/Request";
1281
+ const REFUSED_TAGS = [RESPONSE_TAG, REQUEST_TAG];
1282
+ const RESOLVED_PLUGINS = Symbol.for("solid.codec.resolvedPlugins");
1283
+ const REFUSED_ARGUMENT = Symbol("solid.serverFunction.refusedArgument");
1284
+ function refusedArgumentError(name = "Response or Request") {
1285
+ const error = new TypeError(`Server function arguments cannot carry Response or Request values (got a ${name}). ` + "Pass the data it holds — its body, headers or url — instead.");
1286
+ error[REFUSED_ARGUMENT] = true;
1287
+ return error;
1288
+ }
1289
+ function refusedArgument(error) {
1290
+ for (let depth = 0; depth < 4 && error !== null && typeof error === "object"; depth++) {
1291
+ if (error[REFUSED_ARGUMENT] === true) return error;
1292
+ error = error.cause;
1293
+ }
1294
+ }
1295
+ const refused = plugin => REFUSED_TAGS.includes(plugin.tag);
1296
+ const reachesRefused = plugin => refused(plugin) || !!plugin.extends && plugin.extends.some(reachesRefused);
1297
+ function filterPlugins(plugins, out, seen) {
1298
+ for (const plugin of plugins) {
1299
+ if (seen.has(plugin)) continue;
1300
+ seen.add(plugin);
1301
+ if (refused(plugin)) continue;
1302
+ const severs = !!plugin.extends && plugin.extends.some(reachesRefused);
1303
+ out.push(severs ? {
1304
+ ...plugin,
1305
+ extends: undefined
1306
+ } : plugin);
1307
+ if (plugin.extends) filterPlugins(plugin.extends, out, seen);
1308
+ }
1309
+ return out;
1310
+ }
1311
+ let defaultArgumentPlugins;
1312
+ const customArgumentPlugins = new WeakMap();
1313
+ function argumentDecodeCodec(codec, defaults) {
1314
+ const custom = codec && codec.plugins;
1315
+ let plugins = custom ? customArgumentPlugins.get(custom) : defaultArgumentPlugins;
1316
+ if (!plugins) {
1317
+ plugins = filterPlugins(custom ? [...custom, ...defaults] : defaults, [], new Set());
1318
+ if (custom) customArgumentPlugins.set(custom, plugins);else defaultArgumentPlugins = plugins;
1319
+ }
1320
+ return {
1321
+ ...codec,
1322
+ [RESOLVED_PLUGINS]: plugins
1323
+ };
1324
+ }
1325
+ function namesRefusedType(payload) {
1326
+ for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
1327
+ return false;
1328
+ }
1329
+ function withArgumentPlugins(argumentCodec, extra) {
1330
+ return {
1331
+ ...argumentCodec,
1332
+ [RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
1333
+ };
1334
+ }
1335
+
1336
+ const UPLOAD_ARGS_PART = "args";
1337
+ const UPLOAD_FILE_PART = "file";
1338
+ const UPLOAD_TAG = "solid/server-function-upload";
1339
+ function isBlob(value) {
1340
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
1341
+ return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
1342
+ }
1343
+ function malformed() {
1344
+ return new TypeError("Malformed server function upload");
1345
+ }
1346
+ function createUploadDeserializer(form) {
1347
+ const refuse = () => {
1348
+ throw malformed();
1349
+ };
1350
+ return {
1351
+ tag: UPLOAD_TAG,
1352
+ test: () => false,
1353
+ parse: {
1354
+ sync: refuse,
1355
+ async: refuse,
1356
+ stream: refuse
1357
+ },
1358
+ serialize: refuse,
1359
+ deserialize: (node, ctx) => {
1360
+ const index = ctx.deserialize(node.i);
1361
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
1362
+ const part = form.get(UPLOAD_FILE_PART + index);
1363
+ if (!isBlob(part)) refuse();
1364
+ if (node.t === undefined) return part;
1365
+ const type = ctx.deserialize(node.t);
1366
+ if (typeof type !== "string") refuse();
1367
+ if (node.n === undefined) return new Blob([part], {
1368
+ type
1369
+ });
1370
+ const name = ctx.deserialize(node.n);
1371
+ const lastModified = node.l === undefined ? undefined : ctx.deserialize(node.l);
1372
+ if (typeof name !== "string" || typeof lastModified !== "number") refuse();
1373
+ return new File([part], name, {
1374
+ type,
1375
+ lastModified
1376
+ });
1377
+ }
1378
+ };
1379
+ }
1380
+
487
1381
  const config = {
488
1382
  provideEvent: undefined,
489
1383
  wrapInvocation: undefined,
@@ -493,7 +1387,11 @@ const config = {
493
1387
  transformDirectResult: undefined,
494
1388
  handleNoJS: undefined,
495
1389
  endpoint: "/_server",
496
- csrf: true
1390
+ csrf: true,
1391
+ bodySizeLimit: 1_048_576,
1392
+ maxArguments: 1000,
1393
+ chaosReconnectEvery: 0,
1394
+ buildId: undefined
497
1395
  };
498
1396
  function configureServerFunctionsServer({
499
1397
  provideEvent,
@@ -505,7 +1403,12 @@ function configureServerFunctionsServer({
505
1403
  handleNoJS,
506
1404
  endpoint,
507
1405
  csrf,
508
- codec
1406
+ codec,
1407
+ bodySizeLimit,
1408
+ maxArguments,
1409
+ secret,
1410
+ chaosReconnectEvery,
1411
+ buildId
509
1412
  } = {}) {
510
1413
  if (provideEvent !== undefined) config.provideEvent = provideEvent;
511
1414
  if (wrapInvocation !== undefined) config.wrapInvocation = wrapInvocation;
@@ -517,6 +1420,23 @@ function configureServerFunctionsServer({
517
1420
  if (endpoint !== undefined) config.endpoint = endpoint;
518
1421
  if (csrf !== undefined) config.csrf = csrf;
519
1422
  if (codec !== undefined) configureServerFunctionsCodec(codec);
1423
+ if (bodySizeLimit !== undefined) config.bodySizeLimit = bodySizeLimit;
1424
+ if (maxArguments !== undefined) config.maxArguments = maxArguments;
1425
+ if (secret !== undefined) setFlashSecret(secret);
1426
+ if (chaosReconnectEvery !== undefined) config.chaosReconnectEvery = chaosReconnectEvery;
1427
+ if (buildId !== undefined) config.buildId = buildId;
1428
+ }
1429
+ const flightSources = new Map();
1430
+ function registerFlightDataSource(source, hook) {
1431
+ assertFlightSource(source);
1432
+ flightSources.set(source, hook);
1433
+ return () => {
1434
+ if (flightSources.get(source) === hook) flightSources.delete(source);
1435
+ };
1436
+ }
1437
+ function resolveWrapInvocation(hook) {
1438
+ if (hook === undefined || typeof hook === "function") return hook;
1439
+ 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.`);
520
1440
  }
521
1441
  function provideEvent(event, fn) {
522
1442
  if (config.provideEvent) return config.provideEvent(event, fn);
@@ -524,117 +1444,456 @@ function provideEvent(event, fn) {
524
1444
  if (ctx) return ctx.run(event, fn);
525
1445
  throw new Error("No request event provider. Configure one with configureServerFunctionsServer({ provideEvent }).");
526
1446
  }
527
- const REGISTRATIONS = new Map();
528
- const METHODS = new Map();
529
- const INVOCATIONS = new WeakMap();
530
- let rpcProvided = false;
531
- function provideRPC() {
532
- if (rpcProvided) return;
533
- rpcProvided = true;
534
- provideServerFunctionRPC({
535
- GET,
536
- decodeResponse
1447
+ 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.";
1448
+ 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.";
1449
+ function provideEventOnce(provide, event, run) {
1450
+ let invocations = 0;
1451
+ const settle = () => {
1452
+ if (invocations !== 1) throw new Error(invocations === 0 ? PROVIDE_EVENT_NEVER : PROVIDE_EVENT_TWICE);
1453
+ };
1454
+ const result = provide(event, () => {
1455
+ if (++invocations > 1) throw new Error(PROVIDE_EVENT_TWICE);
1456
+ return run();
537
1457
  });
1458
+ const promised = nativePromise(result);
1459
+ if (promised) {
1460
+ return promised.then(value => {
1461
+ settle();
1462
+ return value;
1463
+ });
1464
+ }
1465
+ settle();
1466
+ return result;
1467
+ }
1468
+ function scopeDeferredResult(value, scope) {
1469
+ const bound = bindDeferredBody(value, scope);
1470
+ if (bound !== value || value === null || typeof value !== "object") return bound;
1471
+ return scopeDeferredContents(value, scope);
1472
+ }
1473
+ class ScopeFrame {
1474
+ constructor(value, prototype, keys, i, first) {
1475
+ this.value = value;
1476
+ this.prototype = prototype;
1477
+ this.next = null;
1478
+ this.keys = keys;
1479
+ this.i = i;
1480
+ this.first = first;
1481
+ this.descriptors = null;
1482
+ this.snapshotted = false;
1483
+ this.changed = false;
1484
+ }
538
1485
  }
539
- function registerServerFunction(id, callback) {
540
- provideRPC();
541
- REGISTRATIONS.set(id, callback);
542
- return callback;
1486
+ function frameShell(frame) {
1487
+ return frame.next ??= frame.keys ? Object.create(frame.prototype, frame.descriptors ?? Object.getOwnPropertyDescriptors(frame.value)) : frame.value.slice();
543
1488
  }
544
- function getServerFunction(id) {
545
- const fn = REGISTRATIONS.get(id);
546
- if (fn) {
547
- return fn;
1489
+ function writableValue(descriptor) {
1490
+ return descriptor !== undefined && "value" in descriptor && descriptor.writable === true ? descriptor.value : undefined;
1491
+ }
1492
+ function carrierSlot(frame, key) {
1493
+ return writableValue(frame.descriptors ? frame.descriptors[key] : Object.getOwnPropertyDescriptor(frame.value, key));
1494
+ }
1495
+ function snapshotFrames(stack) {
1496
+ for (let k = stack.length - 1; k >= 0 && !stack[k].snapshotted; k--) {
1497
+ const frame = stack[k];
1498
+ frame.snapshotted = true;
1499
+ if (frame.keys) frame.descriptors = Object.getOwnPropertyDescriptors(frame.value);
548
1500
  }
549
- throw new Error("invalid server function: " + id);
550
1501
  }
551
- function registerServerReference(id, fn, name) {
552
- registerServerFunction(id, fn);
553
- return {
554
- id,
555
- fn,
556
- name
557
- };
1502
+ function isLeaf(value) {
1503
+ return value === null || typeof value !== "object" && typeof value !== "function";
558
1504
  }
559
- function createServerReference({
560
- id,
561
- fn,
562
- name
563
- }) {
564
- if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
565
- provideRPC();
566
- const metadata = name === undefined ? {} : {
567
- name
1505
+ function sharedPrototypesInert() {
1506
+ const {
1507
+ toStringTag,
1508
+ asyncIterator,
1509
+ iterator,
1510
+ hasInstance
1511
+ } = Symbol;
1512
+ return !(Object.hasOwn(Promise, hasInstance) || typeof ReadableStream !== "undefined" && Object.hasOwn(ReadableStream, hasInstance) || Object.hasOwn(Object.prototype, toStringTag) || Object.hasOwn(Object.prototype, asyncIterator) || Object.hasOwn(Object.prototype, iterator) || Object.hasOwn(Array.prototype, toStringTag) || Object.hasOwn(Array.prototype, asyncIterator));
1513
+ }
1514
+ function isInertCarrier(value, prototype, isArray) {
1515
+ const {
1516
+ toStringTag,
1517
+ asyncIterator,
1518
+ iterator
1519
+ } = Symbol;
1520
+ return (isArray ? prototype === Array.prototype : prototype === Object.prototype || prototype === null) && !Object.hasOwn(value, toStringTag) && !Object.hasOwn(value, asyncIterator) && (isArray || !Object.hasOwn(value, iterator)) && typeof value[asyncIterator] !== "function" && (isArray || typeof value[iterator] !== "function");
1521
+ }
1522
+ function enterScopeCarrier(value, state) {
1523
+ if (isLeaf(value)) return value;
1524
+ const seen = state.seen.get(value);
1525
+ if (seen !== undefined) {
1526
+ state.cyclic.add(value);
1527
+ return seen instanceof ScopeFrame ? frameShell(seen) : seen;
1528
+ }
1529
+ let isArray = false;
1530
+ let prototype;
1531
+ if (typeof value === "object") {
1532
+ isArray = Array.isArray(value);
1533
+ prototype = Object.getPrototypeOf(value);
1534
+ }
1535
+ if (!state.inert || prototype === undefined || !isInertCarrier(value, prototype, isArray)) {
1536
+ snapshotFrames(state.stack);
1537
+ const bound = bindDeferredBody(value, state.scope);
1538
+ if (bound !== value) {
1539
+ state.seen.set(value, bound);
1540
+ return bound;
1541
+ }
1542
+ if (typeof value !== "object") return value;
1543
+ }
1544
+ if (isArray) {
1545
+ if (Object.isFrozen(value)) {
1546
+ state.seen.set(value, value);
1547
+ return value;
1548
+ }
1549
+ let i = 0;
1550
+ let first;
1551
+ while (i < value.length && isLeaf(first = value[i])) i++;
1552
+ if (i === value.length) {
1553
+ state.seen.set(value, value);
1554
+ return value;
1555
+ }
1556
+ const frame = new ScopeFrame(value, null, null, i, first);
1557
+ state.seen.set(value, frame);
1558
+ return frame;
1559
+ }
1560
+ if (prototype !== Object.prototype && prototype !== null) {
1561
+ state.seen.set(value, value);
1562
+ return value;
1563
+ }
1564
+ const keys = Object.keys(value);
1565
+ let i = 0;
1566
+ let first;
1567
+ while (i < keys.length && isLeaf(first = writableValue(Object.getOwnPropertyDescriptor(value, keys[i])))) i++;
1568
+ if (i === keys.length) {
1569
+ state.seen.set(value, value);
1570
+ return value;
1571
+ }
1572
+ if (Object.isFrozen(value)) {
1573
+ state.seen.set(value, value);
1574
+ return value;
1575
+ }
1576
+ const frame = new ScopeFrame(value, prototype, keys, i, first);
1577
+ state.seen.set(value, frame);
1578
+ return frame;
1579
+ }
1580
+ function scopeDeferredContents(root, scope) {
1581
+ const stack = [];
1582
+ const state = {
1583
+ seen: new Map(),
1584
+ cyclic: new Set(),
1585
+ scope,
1586
+ inert: sharedPrototypesInert(),
1587
+ stack
1588
+ };
1589
+ const entered = enterScopeCarrier(root, state);
1590
+ if (!(entered instanceof ScopeFrame)) return entered;
1591
+ stack.push(entered);
1592
+ let delivered = NOTHING;
1593
+ for (;;) {
1594
+ const top = stack[stack.length - 1];
1595
+ const length = top.keys ? top.keys.length : top.value.length;
1596
+ let pushed = null;
1597
+ while (top.i < length) {
1598
+ const i = top.i;
1599
+ let original;
1600
+ if (top.first !== NOTHING) {
1601
+ original = top.first;
1602
+ top.first = NOTHING;
1603
+ } else {
1604
+ original = top.keys ? carrierSlot(top, top.keys[i]) : top.value[i];
1605
+ }
1606
+ let bound;
1607
+ if (delivered !== NOTHING) {
1608
+ bound = delivered;
1609
+ delivered = NOTHING;
1610
+ } else {
1611
+ bound = enterScopeCarrier(original, state);
1612
+ if (bound instanceof ScopeFrame) {
1613
+ pushed = bound;
1614
+ break;
1615
+ }
1616
+ }
1617
+ if (bound !== original) {
1618
+ if (top.keys) frameShell(top)[top.keys[i]] = bound;else frameShell(top)[i] = bound;
1619
+ top.changed = true;
1620
+ }
1621
+ top.i++;
1622
+ }
1623
+ if (pushed !== null) {
1624
+ stack.push(pushed);
1625
+ continue;
1626
+ }
1627
+ stack.pop();
1628
+ let out;
1629
+ if (top.changed || state.cyclic.has(top.value)) {
1630
+ out = frameShell(top);
1631
+ state.seen.set(top.value, out);
1632
+ } else {
1633
+ state.seen.set(top.value, top.value);
1634
+ out = top.value;
1635
+ }
1636
+ if (stack.length === 0) return out;
1637
+ delivered = out;
1638
+ }
1639
+ }
1640
+ function bindDeferredBody(value, scope) {
1641
+ if (isLeaf(value)) return value;
1642
+ const promised = scope(() => nativePromise(value));
1643
+ if (promised) {
1644
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
1645
+ }
1646
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
1647
+ let reader;
1648
+ return new ReadableStream({
1649
+ async pull(controller) {
1650
+ try {
1651
+ const step = await scope(() => {
1652
+ if (!reader) reader = value.getReader();
1653
+ return reader.read();
1654
+ });
1655
+ if (step.done) controller.close();else controller.enqueue(step.value);
1656
+ } catch (error) {
1657
+ controller.error(error);
1658
+ }
1659
+ },
1660
+ cancel(reason) {
1661
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
1662
+ }
1663
+ }, {
1664
+ highWaterMark: 0
1665
+ });
1666
+ }
1667
+ const scopedIterator = symbol => ({
1668
+ [symbol]() {
1669
+ const iterator = scope(() => value[symbol]());
1670
+ return new Proxy(iterator, {
1671
+ get(target, property) {
1672
+ const member = Reflect.get(target, property, target);
1673
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
1674
+ }
1675
+ });
1676
+ }
1677
+ });
1678
+ if (typeof value[Symbol.asyncIterator] === "function") {
1679
+ return scopedIterator(Symbol.asyncIterator);
1680
+ }
1681
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
1682
+ return scopedIterator(Symbol.iterator);
1683
+ }
1684
+ return value;
1685
+ }
1686
+ function processState(key, create) {
1687
+ const slot = Symbol.for(key);
1688
+ return globalThis[slot] || (globalThis[slot] = create());
1689
+ }
1690
+ const REGISTRATIONS = processState("solid.ServerFunctionRegistrations", () => new Map());
1691
+ const METHODS = processState("solid.ServerFunctionMethods", () => new Map());
1692
+ const REFERENCE_BINDINGS = processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
1693
+ const CARRIED = processState("solid.ServerFunctionCarriedGrants", () => new Set());
1694
+ function declaresRead(id) {
1695
+ const granted = METHODS.get(id);
1696
+ return granted !== undefined && granted === REGISTRATIONS.get(id);
1697
+ }
1698
+ const INVOCATIONS = new WeakMap();
1699
+ let rpcProvided = false;
1700
+ function provideRPC() {
1701
+ if (rpcProvided) return;
1702
+ rpcProvided = true;
1703
+ provideServerFunctionRPC({
1704
+ GET,
1705
+ decodeResponse
1706
+ });
1707
+ }
1708
+ function registerServerFunction(id, callback) {
1709
+ provideRPC();
1710
+ if (REGISTRATIONS.get(id) !== callback) {
1711
+ if (DEV && declaresRead(id)) {
1712
+ METHODS.set(id, callback);
1713
+ CARRIED.add(id);
1714
+ } else {
1715
+ METHODS.delete(id);
1716
+ CARRIED.delete(id);
1717
+ }
1718
+ }
1719
+ REGISTRATIONS.set(id, callback);
1720
+ return callback;
1721
+ }
1722
+ function getServerFunction(id) {
1723
+ const fn = REGISTRATIONS.get(id);
1724
+ if (fn) {
1725
+ return fn;
1726
+ }
1727
+ throw new Error("invalid server function: " + id);
1728
+ }
1729
+ function registerServerReference(id, fn, name) {
1730
+ if (typeof fn !== "function") {
1731
+ 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.`);
1732
+ }
1733
+ registerServerFunction(id, fn);
1734
+ return {
1735
+ id,
1736
+ fn,
1737
+ name
568
1738
  };
569
- return new Proxy(fn, {
1739
+ }
1740
+ function inProcessInvoker(call) {
1741
+ return (args, options) => {
1742
+ const signal = options && options.signal;
1743
+ if (!signal) return call(...args);
1744
+ if (signal.aborted) return Promise.reject(signal.reason);
1745
+ return new Promise((resolve, reject) => {
1746
+ const onAbort = () => reject(signal.reason);
1747
+ signal.addEventListener("abort", onAbort, {
1748
+ once: true
1749
+ });
1750
+ let result;
1751
+ try {
1752
+ result = call(...args);
1753
+ } catch (error) {
1754
+ signal.removeEventListener("abort", onAbort);
1755
+ return reject(error);
1756
+ }
1757
+ Promise.resolve(result).then(value => {
1758
+ signal.removeEventListener("abort", onAbort);
1759
+ resolve(value);
1760
+ }, error => {
1761
+ signal.removeEventListener("abort", onAbort);
1762
+ reject(error);
1763
+ });
1764
+ });
1765
+ };
1766
+ }
1767
+ function createServerReference({
1768
+ id,
1769
+ fn,
1770
+ name
1771
+ }) {
1772
+ if (typeof fn !== "function") throw new Error("Export from a 'use server' module must be a function");
1773
+ provideRPC();
1774
+ const metadata = name === undefined ? {} : {
1775
+ name
1776
+ };
1777
+ const invokeChannel = inProcessInvoker((...args) => proxy(...args));
1778
+ const proxy = new Proxy(fn, {
570
1779
  get(target, prop) {
571
1780
  if (prop === "id") return id;
572
1781
  if (prop === "url") {
573
- return `${config.endpoint}?id=${encodeURIComponent(id)}`;
1782
+ return serverFunctionAddress(config.endpoint, id);
574
1783
  }
575
1784
  if (prop === SERVER_FUNCTION_METADATA) return metadata;
1785
+ if (prop === SERVER_FUNCTION_INVOKE) return invokeChannel;
576
1786
  return target[prop];
577
1787
  },
578
1788
  apply(target, thisArg, args) {
579
1789
  const ogEvt = getRequestEvent();
580
1790
  if (!ogEvt) throw new Error("Cannot call server function outside of a request");
581
1791
  const evt = {
582
- ...ogEvt
1792
+ ...ogEvt,
1793
+ locals: {
1794
+ ...ogEvt.locals
1795
+ }
583
1796
  };
584
1797
  INVOCATIONS.set(evt, {
585
- id
1798
+ id,
1799
+ live: false
586
1800
  });
587
1801
  evt.serverOnly = true;
588
- const result = provideEvent(evt, () => {
589
- const run = () => fn.apply(thisArg, args);
590
- return config.wrapInvocation ? config.wrapInvocation(run, {
591
- id,
592
- args,
593
- event: evt,
594
- direct: true
595
- }) : run();
596
- });
1802
+ const scope = run => provideEvent(evt, run);
1803
+ const wrap = resolveWrapInvocation(config.wrapInvocation);
1804
+ const hook = requestErrorHook(ogEvt);
1805
+ let result;
1806
+ try {
1807
+ result = provideEventOnce(provideEvent, evt, () => {
1808
+ const run = () => fn.apply(thisArg, args);
1809
+ return observeInvocation({
1810
+ id,
1811
+ direct: true,
1812
+ event: evt,
1813
+ args
1814
+ }, () => reportDirectFailure(() => wrap ? wrap(run, {
1815
+ id,
1816
+ args,
1817
+ event: evt,
1818
+ direct: true
1819
+ }) : run(), id, hook));
1820
+ });
1821
+ } catch (error) {
1822
+ throw directEnvelopeValue(error, evt);
1823
+ }
1824
+ result = result && typeof result.then === "function" ? result.then(value => directEnvelopeValue(value, evt), error => {
1825
+ throw directEnvelopeValue(error, evt);
1826
+ }) : directEnvelopeValue(result, evt);
1827
+ result = scopeDeferredResult(result, scope);
597
1828
  const transform = config.transformDirectResult;
598
1829
  if (transform && result && typeof result.then === "function") {
599
- return result.then(value => transform(value, {
1830
+ return result.then(value => scopeDeferredResult(transform(value, {
600
1831
  id,
601
1832
  args,
602
1833
  event: evt
603
- }));
1834
+ }), scope));
604
1835
  }
605
- return transform ? transform(result, {
1836
+ return transform ? scopeDeferredResult(transform(result, {
606
1837
  id,
607
1838
  args,
608
1839
  event: evt
609
- }) : result;
1840
+ }), scope) : result;
610
1841
  }
611
1842
  });
1843
+ REFERENCE_BINDINGS.set(proxy, fn);
1844
+ return proxy;
612
1845
  }
613
1846
  function GET(fn) {
614
1847
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
615
1848
  throw new Error("GET expects a server function reference");
616
1849
  }
617
- METHODS.set(fn.id, "GET");
618
- return withMeta(fn, {
1850
+ const id = fn.id;
1851
+ const binding = REFERENCE_BINDINGS.has(fn) ? REFERENCE_BINDINGS.get(fn) : REGISTRATIONS.get(id);
1852
+ const existing = METHODS.get(id);
1853
+ if (existing !== undefined && existing !== binding) {
1854
+ if (CARRIED.has(id)) return fn;
1855
+ if (DEV) {
1856
+ 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.`);
1857
+ }
1858
+ METHODS.delete(id);
1859
+ return fn;
1860
+ }
1861
+ METHODS.set(id, binding);
1862
+ CARRIED.delete(id);
1863
+ const reference = withMeta(fn, {
619
1864
  method: "GET"
620
1865
  });
1866
+ guardDeclaredMethod(getServerFunctionMetadata(reference), id);
1867
+ return reference;
1868
+ }
1869
+ function guardDeclaredMethod(metadata, id) {
1870
+ let declared = metadata.method;
1871
+ Object.defineProperty(metadata, "method", {
1872
+ configurable: true,
1873
+ enumerable: true,
1874
+ get: () => declared,
1875
+ set(next) {
1876
+ if (next === declared) return;
1877
+ if (DEV) {
1878
+ 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.`);
1879
+ }
1880
+ METHODS.delete(id);
1881
+ declared = next;
1882
+ }
1883
+ });
621
1884
  }
622
1885
  function live(fn) {
623
1886
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
624
1887
  throw new Error("live expects a server function reference");
625
1888
  }
1889
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
626
1890
  const metadata = {
627
1891
  ...getServerFunctionMetadata(fn),
628
1892
  live: true
629
1893
  };
630
- const wrapped = async (...args) => {
631
- const result = await fn(...args);
632
- if (result !== null && typeof result === "object" && result[Symbol.asyncIterator]) {
633
- result[LIVE_SOURCE] = true;
634
- }
635
- return result;
636
- };
1894
+ const wrapped = async (...args) => brandLive(await fn(...args));
637
1895
  wrapped[SERVER_FUNCTION_METADATA] = metadata;
1896
+ wrapped[SERVER_FUNCTION_INVOKE] = inProcessInvoker(wrapped);
638
1897
  wrapped.id = fn.id;
639
1898
  Object.defineProperty(wrapped, "url", {
640
1899
  get: () => fn.url,
@@ -642,59 +1901,255 @@ function live(fn) {
642
1901
  });
643
1902
  return wrapped;
644
1903
  }
1904
+ function broadcast(fn) {
1905
+ const ref = live(fn);
1906
+ ref[SERVER_FUNCTION_METADATA].broadcast = true;
1907
+ BROADCASTS.add(fn.id);
1908
+ return ref;
1909
+ }
1910
+ function encodedArguments(request, url, argsEncoding, argumentBytes) {
1911
+ if (request.method !== "POST") return argsEncoding || url.search;
1912
+ if (!argumentBytes) return undefined;
1913
+ return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
1914
+ }
1915
+ const BROADCASTS = new Set();
1916
+ function brandLive(answer) {
1917
+ if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
1918
+ answer[LIVE_SOURCE] = true;
1919
+ }
1920
+ return answer;
1921
+ }
645
1922
  function getServerFunctionInvocation() {
646
1923
  return getEventServerFunctionInvocation(getRequestEvent());
647
1924
  }
648
1925
  function getEventServerFunctionInvocation(event) {
649
1926
  return event && INVOCATIONS.get(event);
650
1927
  }
651
- function resolveFunctionId(request, url) {
652
- const reference = request.headers.get(FUNCTION_HEADER);
653
- if (reference) {
654
- return reference.split("#")[0];
1928
+ function resolveAddress(url) {
1929
+ return parseServerFunctionAddress(url.pathname, config.endpoint);
1930
+ }
1931
+ const DECODE_DEPTH_LIMIT = 64;
1932
+ function assertDecodeDepth(value) {
1933
+ let level = [value];
1934
+ for (let depth = 0; level.length > 0; depth++) {
1935
+ if (depth > DECODE_DEPTH_LIMIT) {
1936
+ throw new TypeError("Server function arguments exceed the decode depth limit");
1937
+ }
1938
+ const next = [];
1939
+ for (const node of level) {
1940
+ if (node === null || typeof node !== "object") continue;
1941
+ if (Array.isArray(node)) {
1942
+ for (const child of node) next.push(child);
1943
+ } else {
1944
+ for (const key of Object.keys(node)) next.push(node[key]);
1945
+ }
1946
+ }
1947
+ level = next;
1948
+ }
1949
+ }
1950
+ const UNSAFE_ARGUMENT_KEYS = ["__proto__", "constructor", "prototype"];
1951
+ function stripUnsafeArgumentKeys(value) {
1952
+ const stack = [value];
1953
+ const seen = new Set();
1954
+ while (stack.length) {
1955
+ const v = stack.pop();
1956
+ if (v === null || typeof v !== "object" || seen.has(v)) continue;
1957
+ seen.add(v);
1958
+ for (const key of UNSAFE_ARGUMENT_KEYS) {
1959
+ delete v[key];
1960
+ }
1961
+ for (const key of Object.keys(v)) stack.push(v[key]);
1962
+ if (v instanceof Map) {
1963
+ for (const [k, entry] of v) stack.push(k, entry);
1964
+ } else if (v instanceof Set) {
1965
+ for (const member of v) stack.push(member);
1966
+ }
1967
+ }
1968
+ return value;
1969
+ }
1970
+ async function bufferBodyWithin(request, limit) {
1971
+ const reader = request.body.getReader();
1972
+ const signal = request.signal;
1973
+ const chunks = [];
1974
+ let total = 0;
1975
+ const onAbort = () => {
1976
+ reader.cancel(signal.reason).catch(() => {});
1977
+ };
1978
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
1979
+ once: true
1980
+ });
1981
+ try {
1982
+ for (;;) {
1983
+ const {
1984
+ done,
1985
+ value
1986
+ } = await reader.read();
1987
+ if (signal.aborted) throw signal.reason;
1988
+ if (done) break;
1989
+ total += value.byteLength;
1990
+ if (total > limit) {
1991
+ reader.cancel().catch(() => {});
1992
+ return null;
1993
+ }
1994
+ chunks.push(value);
1995
+ }
1996
+ } catch (error) {
1997
+ reader.cancel(error).catch(() => {});
1998
+ throw error;
1999
+ } finally {
2000
+ signal.removeEventListener("abort", onAbort);
2001
+ reader.releaseLock();
2002
+ }
2003
+ const body = new Uint8Array(total);
2004
+ let offset = 0;
2005
+ for (const chunk of chunks) {
2006
+ body.set(chunk, offset);
2007
+ offset += chunk.byteLength;
2008
+ }
2009
+ return body;
2010
+ }
2011
+ function withBufferedBody(request, body) {
2012
+ return new Request(request.url, {
2013
+ method: request.method,
2014
+ headers: request.headers,
2015
+ signal: request.signal,
2016
+ body
2017
+ });
2018
+ }
2019
+ const KNOWN_BODY_FORMATS = new Set(Object.values(BodyFormat));
2020
+ const FORMAT_SKEW = Symbol("solid.serverFunction.formatSkew");
2021
+ function unknownFormatError(tag) {
2022
+ 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.");
2023
+ error[FORMAT_SKEW] = true;
2024
+ return error;
2025
+ }
2026
+ async function decodeArguments(decode, payload) {
2027
+ if (payload === null) return await decode(undefined);
2028
+ const refuseNamed = () => {
2029
+ const text = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
2030
+ if (namesRefusedType(text)) throw refusedArgumentError();
2031
+ };
2032
+ const connection = {};
2033
+ let value;
2034
+ try {
2035
+ value = await decode({
2036
+ connection
2037
+ });
2038
+ } catch (error) {
2039
+ if (connection.ended) connection.ended.then(end => end.sweep());
2040
+ refuseNamed();
2041
+ throw error;
2042
+ }
2043
+ if (connection.ended) {
2044
+ const {
2045
+ open,
2046
+ sweep
2047
+ } = await connection.ended;
2048
+ sweep();
2049
+ if (open) refuseNamed();
655
2050
  }
656
- return url.searchParams.get("id");
2051
+ return value;
2052
+ }
2053
+ let decodeModule;
2054
+ async function loadArgumentCodec(codec) {
2055
+ decodeModule = await import('@solidjs/web/serialization/decode');
2056
+ return argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS);
657
2057
  }
658
- async function parseArguments(request, url, instance, codec) {
2058
+ const argumentCodecFor = codec => decodeModule ? argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS) : loadArgumentCodec(codec);
2059
+ async function parseArguments(request, url, scripted, codec, buffered) {
659
2060
  const parsed = [];
660
2061
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
661
- if (!instance || request.method === "GET" || bodyFormat !== BodyFormat.Serialized) {
662
- const args = url.searchParams.get("args");
663
- if (args) {
664
- const result = args.startsWith(";0x") ? await deserializeString(args, codec) : JSON.parse(args);
665
- for (const arg of result) {
666
- parsed.push(arg);
667
- }
2062
+ const args = url.searchParams.get("args");
2063
+ if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
2064
+ let result;
2065
+ if (args.startsWith(";0x")) {
2066
+ let argumentCodec = argumentCodecFor(codec);
2067
+ if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
2068
+ result = await decodeArguments(wire => deserializeStream(new Response(args), argumentCodec, wire), args);
2069
+ } else {
2070
+ result = JSON.parse(args);
2071
+ assertDecodeDepth(result);
2072
+ }
2073
+ if (!Array.isArray(result)) {
2074
+ throw new TypeError("Server function arguments must encode an array");
668
2075
  }
2076
+ stripUnsafeArgumentKeys(result);
2077
+ for (const arg of result) {
2078
+ parsed.push(arg);
2079
+ }
2080
+ } else if (!args && url.search && (request.method === "GET" || request.method === "HEAD")) {
2081
+ parsed.push(url.searchParams);
669
2082
  }
670
2083
  if (request.method === "POST" && request.body !== null) {
671
- const decoded = await extractBody(request.clone(), codec);
2084
+ if (bodyFormat !== null && !KNOWN_BODY_FORMATS.has(bodyFormat)) {
2085
+ throw unknownFormatError(bodyFormat);
2086
+ }
2087
+ const body = request.clone();
2088
+ let decoded;
2089
+ if (bodyFormat === BodyFormat.Serialized) {
2090
+ let argumentCodec = argumentCodecFor(codec);
2091
+ if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
2092
+ if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
2093
+ const form = await body.formData();
2094
+ const encoded = form.get(UPLOAD_ARGS_PART);
2095
+ if (typeof encoded !== "string") {
2096
+ throw new TypeError("Malformed server function upload");
2097
+ }
2098
+ const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
2099
+ decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
2100
+ } else {
2101
+ decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
2102
+ }
2103
+ } else {
2104
+ decoded = await extractBody(body, codec);
2105
+ }
672
2106
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
673
- return decoded;
2107
+ if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
2108
+ if (!Array.isArray(decoded)) {
2109
+ throw new TypeError("Server function arguments must encode an array");
2110
+ }
2111
+ return stripUnsafeArgumentKeys(decoded);
2112
+ }
2113
+ if (decoded === undefined) {
2114
+ if (bodyFormat === null && (await body.arrayBuffer()).byteLength === 0) {
2115
+ return parsed;
2116
+ }
2117
+ throw new TypeError("Server function body carries no usable encoding");
674
2118
  }
675
2119
  parsed.push(decoded);
676
2120
  }
677
2121
  return parsed;
678
2122
  }
679
- async function foldFlightData(hook, event, headers, outcome, context = {}) {
2123
+ async function foldFlightData(hooks, event, headers, outcome, context = {}) {
680
2124
  if (outcome.value instanceof Response && outcome.value.body) return outcome.value;
681
2125
  digestOutcome(event, outcome);
682
- const data = await hook(event, outcome);
683
- if (data === undefined) return outcome.value;
684
- headers.set(SINGLE_FLIGHT_HEADER, "true");
2126
+ const folded = [];
2127
+ for (const [source, hook] of hooks) {
2128
+ try {
2129
+ const slice = await hook(event, outcome);
2130
+ if (slice !== undefined) folded.push([source, slice]);
2131
+ } catch (error) {
2132
+ console.error(`Error collecting flight data for source "${source}"`, error);
2133
+ }
2134
+ }
2135
+ if (folded.length === 0) return outcome.value;
2136
+ const data = Object.fromEntries(folded);
2137
+ headers.set(SINGLE_FLIGHT_HEADER, folded.map(([source]) => source).join(","));
685
2138
  if (context.transformFlightResult) {
686
2139
  const transformed = await context.transformFlightResult(event, {
687
2140
  value: outcome.value,
688
2141
  data
689
2142
  }, context);
690
2143
  if (transformed !== undefined) {
691
- for (const cookie of headers.getSetCookie()) transformed.headers.append("Set-Cookie", cookie);
2144
+ const owned = ownResponse(transformed);
2145
+ for (const cookie of headers.getSetCookie()) owned.headers.append("Set-Cookie", cookie);
692
2146
  headers.forEach((value, key) => {
693
- if (key !== "set-cookie" && !transformed.headers.has(key)) {
694
- transformed.headers.set(key, value);
2147
+ if (key !== "set-cookie" && !owned.headers.has(key)) {
2148
+ owned.headers.set(key, value);
695
2149
  }
696
2150
  });
697
- return transformed;
2151
+ owned.headers.set(SINGLE_FLIGHT_HEADER, headers.get(SINGLE_FLIGHT_HEADER));
2152
+ return owned;
698
2153
  }
699
2154
  }
700
2155
  return outcome.value === undefined ? {
@@ -761,7 +2216,7 @@ function foldSetCookies(headers, setCookies) {
761
2216
  }
762
2217
  function mergeResponseHeaders(target, source) {
763
2218
  source.forEach((value, key) => {
764
- if (key !== "set-cookie") target.append(key, value);
2219
+ if (key !== "set-cookie" && !COMPOSED_BODY_FRAMING.has(key)) target.append(key, value);
765
2220
  });
766
2221
  if (source.getSetCookie) {
767
2222
  for (const cookie of source.getSetCookie()) target.append("Set-Cookie", cookie);
@@ -770,10 +2225,52 @@ function mergeResponseHeaders(target, source) {
770
2225
  }
771
2226
  }
772
2227
  const validRedirectStatuses = new Set([301, 302, 303, 307, 308]);
2228
+ function maskRedirect(headers, response, requestUrl) {
2229
+ const target = response.headers && response.headers.get("Location");
2230
+ if (target) {
2231
+ headers.set(REDIRECT_HEADER, `${response.status} ${new URL(target, requestUrl)}`);
2232
+ }
2233
+ headers.delete("Location");
2234
+ }
2235
+ const BOUNDED_COMPOSED_HEADERS = [REDIRECT_HEADER, "Location", REVALIDATE_HEADER];
2236
+ function enforceComposedHeaderInvariants(response) {
2237
+ for (const name of BOUNDED_COMPOSED_HEADERS) {
2238
+ const value = response.headers.get(name);
2239
+ if (value === null) continue;
2240
+ if (value.length > RESPONSE_HEADER_VALUE_LIMIT) {
2241
+ 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);
2242
+ }
2243
+ if (name === REVALIDATE_HEADER) continue;
2244
+ const target = name === REDIRECT_HEADER ? value.slice(value.indexOf(" ") + 1) : value;
2245
+ if (!isHttpNavigationTarget(target)) {
2246
+ 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);
2247
+ }
2248
+ }
2249
+ return response;
2250
+ }
2251
+ function refuseComposedHeader(response, name, headerMessage, body) {
2252
+ if (response.body) {
2253
+ try {
2254
+ const cancelled = response.body.cancel();
2255
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
2256
+ } catch {}
2257
+ }
2258
+ const headers = new Headers();
2259
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(DEV ? headerMessage : GENERIC_SERVER_ERROR_MESSAGE));
2260
+ return new Response(body, {
2261
+ status: 500,
2262
+ headers
2263
+ });
2264
+ }
2265
+ function warnScripted304(functionId) {
2266
+ if (DEV) {
2267
+ 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.`);
2268
+ }
2269
+ }
773
2270
  function createNoJSHandler({
774
2271
  base = ""
775
2272
  } = {}) {
776
- return function handleNoJS(result, request, args, thrown) {
2273
+ return async function handleNoJS(result, request, args, thrown) {
777
2274
  const url = new URL(request.url);
778
2275
  let back = new URL(base || "/", url.origin).toString();
779
2276
  try {
@@ -798,8 +2295,9 @@ function createNoJSHandler({
798
2295
  Location: back
799
2296
  });
800
2297
  }
801
- if (result && !(result instanceof Response)) {
802
- headers.append("Set-Cookie", encodeFlashCookie(url.pathname + url.search, result, args, thrown));
2298
+ if (result !== undefined && !(result instanceof Response)) {
2299
+ const flash = await encodeFlashCookie(url.pathname, result, args, thrown);
2300
+ if (flash !== null) headers.append("Set-Cookie", flash);
803
2301
  }
804
2302
  return new Response(null, {
805
2303
  status,
@@ -813,44 +2311,309 @@ function isFormPost(request) {
813
2311
  const type = request.headers.get("content-type") || "";
814
2312
  return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
815
2313
  }
816
- function serializeResponseStream(value, codecOptions, signal) {
817
- let closeIterator = null;
818
- let closed = false;
819
- let cancelSerialize = null;
820
- let onAbort = null;
821
- const teardown = () => {
822
- if (closed) return;
823
- closed = true;
824
- if (onAbort) signal.removeEventListener("abort", onAbort);
825
- if (cancelSerialize) cancelSerialize();
826
- if (closeIterator) closeIterator();
2314
+ function guardFailures(value, state) {
2315
+ if (!state) state = {
2316
+ seen: new WeakMap(),
2317
+ cyclic: new WeakSet()
827
2318
  };
828
- if (value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
2319
+ const entered = enterGuard(value, state);
2320
+ if (!(entered instanceof Frame)) return entered;
2321
+ const stack = [entered];
2322
+ let delivered = NOTHING;
2323
+ for (;;) {
2324
+ const top = stack[stack.length - 1];
2325
+ const items = top.items;
2326
+ let pushed = null;
2327
+ while (top.i < items.length) {
2328
+ const i = top.i;
2329
+ let original;
2330
+ if (top.kind === OBJECT) {
2331
+ const descriptor = top.descriptors[items[i]];
2332
+ if ("value" in descriptor) {
2333
+ original = descriptor.value;
2334
+ } else if (typeof descriptor.get === "function") {
2335
+ if (top.accessorRead !== i) {
2336
+ try {
2337
+ top.accessorValue = descriptor.get.call(top.value);
2338
+ } catch (error) {
2339
+ throw wireServerFunctionError(error, "channel");
2340
+ }
2341
+ top.accessorRead = i;
2342
+ }
2343
+ original = top.accessorValue;
2344
+ } else {
2345
+ top.i++;
2346
+ continue;
2347
+ }
2348
+ } else {
2349
+ original = items[i];
2350
+ }
2351
+ let guarded;
2352
+ if (delivered !== NOTHING) {
2353
+ guarded = delivered;
2354
+ delivered = NOTHING;
2355
+ } else {
2356
+ guarded = enterGuard(original, state);
2357
+ if (guarded instanceof Frame) {
2358
+ pushed = guarded;
2359
+ break;
2360
+ }
2361
+ }
2362
+ if (top.kind === ARRAY) {
2363
+ if (guarded !== original) {
2364
+ top.next[i] = guarded;
2365
+ top.changed = true;
2366
+ }
2367
+ } else if (top.kind === MAP) {
2368
+ if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
2369
+ if (guarded !== original) top.changed = true;
2370
+ } else if (top.kind === SET) {
2371
+ top.next.add(guarded);
2372
+ if (guarded !== original) top.changed = true;
2373
+ } else if (guarded !== original || top.accessorRead === i) {
2374
+ Object.defineProperty(top.next, items[i], {
2375
+ value: guarded,
2376
+ writable: true,
2377
+ configurable: true,
2378
+ enumerable: top.descriptors[items[i]].enumerable
2379
+ });
2380
+ top.changed = true;
2381
+ }
2382
+ top.i++;
2383
+ }
2384
+ if (pushed !== null) {
2385
+ stack.push(pushed);
2386
+ continue;
2387
+ }
2388
+ stack.pop();
2389
+ const out = keepGuarded(top.value, top.next, top.changed, state);
2390
+ if (stack.length === 0) return out;
2391
+ delivered = out;
2392
+ }
2393
+ }
2394
+ const NOTHING = Symbol();
2395
+ const ARRAY = 0;
2396
+ const MAP = 1;
2397
+ const SET = 2;
2398
+ const OBJECT = 3;
2399
+ class Frame {
2400
+ constructor(kind, value, next, items, descriptors) {
2401
+ this.kind = kind;
2402
+ this.value = value;
2403
+ this.next = next;
2404
+ this.items = items;
2405
+ this.descriptors = descriptors;
2406
+ this.i = 0;
2407
+ this.changed = false;
2408
+ this.accessorRead = -1;
2409
+ this.accessorValue = undefined;
2410
+ this.pendingKey = undefined;
2411
+ }
2412
+ }
2413
+ function guardOperation(state, run) {
2414
+ return state.scope ? state.scope(run) : run();
2415
+ }
2416
+ function enterGuard(value, state) {
2417
+ if (value === null || typeof value !== "object") return value;
2418
+ if (state.seen.has(value)) {
2419
+ state.cyclic.add(value);
2420
+ return state.seen.get(value);
2421
+ }
2422
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
2423
+ let reader;
2424
+ const gate = state.gate;
2425
+ let finished = false;
2426
+ const close = () => {
2427
+ if (finished) return;
2428
+ finished = true;
2429
+ try {
2430
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
2431
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
2432
+ } catch {}
2433
+ };
2434
+ const guardedStream = new ReadableStream({
2435
+ async pull(controller) {
2436
+ try {
2437
+ if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
2438
+ if (finished) {
2439
+ controller.close();
2440
+ return;
2441
+ }
2442
+ if (!reader) reader = guardOperation(state, () => value.getReader());
2443
+ const {
2444
+ done,
2445
+ value: chunk
2446
+ } = await guardOperation(state, () => reader.read());
2447
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
2448
+ } catch (error) {
2449
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
2450
+ }
2451
+ },
2452
+ cancel(reason) {
2453
+ finished = true;
2454
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
2455
+ }
2456
+ });
2457
+ if (gate) gate.onOpen(close);
2458
+ state.seen.set(value, guardedStream);
2459
+ return guardedStream;
2460
+ }
2461
+ if (typeof value.then === "function") {
2462
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
2463
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
2464
+ });
2465
+ guardedPromise.catch(() => {});
2466
+ state.seen.set(value, guardedPromise);
2467
+ return guardedPromise;
2468
+ }
2469
+ if (typeof value[Symbol.asyncIterator] === "function") {
829
2470
  const source = value;
830
- value = {
2471
+ const gate = state.gate;
2472
+ const guardedIterable = {
831
2473
  [Symbol.asyncIterator]() {
832
- const it = source[Symbol.asyncIterator]();
2474
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
833
2475
  let finished = false;
834
- closeIterator = () => {
2476
+ const close = () => {
835
2477
  if (finished) return;
836
2478
  finished = true;
837
2479
  try {
838
- const returned = it.return && it.return();
2480
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
839
2481
  if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
840
2482
  } catch {}
841
2483
  };
842
- if (closed) closeIterator();
2484
+ if (gate) gate.onOpen(close);
2485
+ const step = () => finished ? Promise.resolve({
2486
+ done: true,
2487
+ value: undefined
2488
+ }) : guardOperation(state, () => iterator.next()).then(step => {
2489
+ if (step.done) {
2490
+ finished = true;
2491
+ return step;
2492
+ }
2493
+ return {
2494
+ done: false,
2495
+ value: guardOperation(state, () => guardFailures(step.value, state))
2496
+ };
2497
+ }, error => {
2498
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
2499
+ });
843
2500
  return {
844
- next: () => finished ? Promise.resolve({
845
- done: true,
846
- value: undefined
847
- }) : it.next()
2501
+ next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
2502
+ return: () => {
2503
+ close();
2504
+ return Promise.resolve({
2505
+ done: true,
2506
+ value: undefined
2507
+ });
2508
+ }
848
2509
  };
849
2510
  }
850
2511
  };
2512
+ state.seen.set(value, guardedIterable);
2513
+ return guardedIterable;
2514
+ }
2515
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
2516
+ const scopedIterable = scopeDeferredResult(value, state.scope);
2517
+ state.seen.set(value, scopedIterable);
2518
+ return scopedIterable;
2519
+ }
2520
+ if (Array.isArray(value)) {
2521
+ const next = value.slice();
2522
+ state.seen.set(value, next);
2523
+ return new Frame(ARRAY, value, next, value, null);
851
2524
  }
2525
+ if (value instanceof Map) {
2526
+ const next = new Map();
2527
+ state.seen.set(value, next);
2528
+ const items = [];
2529
+ for (const entry of value) items.push(entry[0], entry[1]);
2530
+ return new Frame(MAP, value, next, items, null);
2531
+ }
2532
+ if (value instanceof Set) {
2533
+ const next = new Set();
2534
+ state.seen.set(value, next);
2535
+ return new Frame(SET, value, next, [...value], null);
2536
+ }
2537
+ const prototype = Object.getPrototypeOf(value);
2538
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
2539
+ state.seen.set(value, value);
2540
+ return value;
2541
+ }
2542
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2543
+ for (const key of Object.keys(descriptors)) {
2544
+ descriptors[key].configurable = true;
2545
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
2546
+ }
2547
+ const next = Object.create(prototype, descriptors);
2548
+ state.seen.set(value, next);
2549
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
2550
+ const descriptor = descriptors[key];
2551
+ return descriptor.enumerable || "value" in descriptor;
2552
+ });
2553
+ return new Frame(OBJECT, value, next, children, descriptors);
2554
+ }
2555
+ function keepGuarded(value, next, changed, state) {
2556
+ if (changed || state.cyclic.has(value)) return next;
2557
+ state.seen.set(value, value);
2558
+ return value;
2559
+ }
2560
+ function serializeResponseStream(value, codecOptions, signal, scope, live) {
2561
+ let closed = false;
2562
+ const frame = live ? payload => {
2563
+ const id = live.pending;
2564
+ live.pending = undefined;
2565
+ return createEventChunk(payload, id);
2566
+ } : createChunk;
2567
+ let stopLive = null;
2568
+ const stopHeartbeat = () => {
2569
+ if (stopLive !== null) {
2570
+ stopLive();
2571
+ stopLive = null;
2572
+ }
2573
+ };
2574
+ let streamController = null;
2575
+ let demandWaiters = null;
2576
+ const wantsMore = () => streamController !== null && streamController.desiredSize > 0;
2577
+ const awaitDemand = () => new Promise(resolve => (demandWaiters ??= []).push(resolve));
2578
+ const supplyDemand = () => {
2579
+ const resolvers = demandWaiters;
2580
+ demandWaiters = null;
2581
+ if (resolvers) for (const resolve of resolvers) resolve();
2582
+ };
2583
+ const sourceClosers = new Set();
2584
+ const gate = {
2585
+ wantsMore,
2586
+ awaitDemand,
2587
+ onOpen(close) {
2588
+ if (closed) close();else sourceClosers.add(close);
2589
+ }
2590
+ };
2591
+ const guardState = {
2592
+ seen: new WeakMap(),
2593
+ cyclic: new WeakSet(),
2594
+ gate,
2595
+ scope
2596
+ };
2597
+ value = guardOperation(guardState, () => guardFailures(value, guardState));
2598
+ let cancelSerialize = null;
2599
+ let onAbort = null;
2600
+ const finishSource = () => {
2601
+ for (const close of sourceClosers) close();
2602
+ sourceClosers.clear();
2603
+ supplyDemand();
2604
+ };
2605
+ const teardown = () => {
2606
+ if (closed) return;
2607
+ closed = true;
2608
+ stopHeartbeat();
2609
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2610
+ if (cancelSerialize) cancelSerialize();
2611
+ finishSource();
2612
+ };
852
2613
  return new ReadableStream({
853
2614
  async start(controller) {
2615
+ streamController = controller;
2616
+ if (live && !live.nodes) stopLive = armLiveBody(controller, teardown);
854
2617
  if (signal) {
855
2618
  if (signal.aborted) {
856
2619
  teardown();
@@ -880,35 +2643,364 @@ function serializeResponseStream(value, codecOptions, signal) {
880
2643
  cancelSerialize = serializeJSON(value, {
881
2644
  ...codecOptions,
882
2645
  onParse(node) {
883
- if (!closed) controller.enqueue(createChunk(JSON.stringify(node)));
2646
+ if (closed) return;
2647
+ const chunk = frame(JSON.stringify(node));
2648
+ if (live && live.nodes) live.nodes.set(chunk, node);
2649
+ controller.enqueue(chunk);
884
2650
  },
885
2651
  onDone() {
886
2652
  if (closed) return;
887
2653
  closed = true;
2654
+ stopHeartbeat();
888
2655
  if (onAbort) signal.removeEventListener("abort", onAbort);
2656
+ finishSource();
889
2657
  controller.close();
890
2658
  },
891
2659
  onError(error) {
892
2660
  if (closed) return;
893
2661
  closed = true;
2662
+ stopHeartbeat();
894
2663
  if (onAbort) signal.removeEventListener("abort", onAbort);
895
- controller.error(error);
2664
+ finishSource();
2665
+ try {
2666
+ const delivered = wireServerFunctionError(DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error, "channel");
2667
+ controller.enqueue(frame(encodeErrorTrailer(delivered)));
2668
+ controller.close();
2669
+ } catch {
2670
+ try {
2671
+ controller.error(error);
2672
+ } catch {}
2673
+ }
896
2674
  }
897
2675
  });
898
2676
  },
2677
+ pull() {
2678
+ supplyDemand();
2679
+ },
899
2680
  cancel() {
900
2681
  teardown();
901
2682
  }
902
2683
  });
903
2684
  }
904
- function serializedResponse(value, headers, codec, signal) {
2685
+ function serializedResponse(value, headers, codec, signal, scope) {
905
2686
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
906
2687
  headers.set("Content-Type", "text/plain");
907
- return new Response(serializeResponseStream(value, codec, signal), {
2688
+ return new Response(serializeResponseStream(value, codec, signal, scope), {
2689
+ headers
2690
+ });
2691
+ }
2692
+ const LIVE_HEARTBEAT_INTERVAL = 20000;
2693
+ function armLiveBody(controller, teardown) {
2694
+ let stopped = false;
2695
+ const heartbeat = setInterval(() => {
2696
+ if (stopped) return;
2697
+ try {
2698
+ controller.enqueue(EVENT_STREAM_HEARTBEAT);
2699
+ } catch {}
2700
+ }, LIVE_HEARTBEAT_INTERVAL);
2701
+ if (typeof heartbeat === "object" && heartbeat && typeof heartbeat.unref === "function") heartbeat.unref();
2702
+ let chaos = null;
2703
+ if (DEV && config.chaosReconnectEvery > 0) {
2704
+ chaos = setTimeout(() => {
2705
+ if (stopped) return;
2706
+ teardown();
2707
+ try {
2708
+ controller.error(new Error("Live response ended by the chaos knob."));
2709
+ } catch {}
2710
+ }, config.chaosReconnectEvery);
2711
+ if (typeof chaos === "object" && chaos && typeof chaos.unref === "function") chaos.unref();
2712
+ }
2713
+ return () => {
2714
+ if (stopped) return;
2715
+ stopped = true;
2716
+ clearInterval(heartbeat);
2717
+ if (chaos !== null) clearTimeout(chaos);
2718
+ };
2719
+ }
2720
+ function liveSource(value, lastEventId, position, scope, refs) {
2721
+ const digestOf = v => scope ? scope(() => positionDigest(v)) : positionDigest(v);
2722
+ if (value === null || typeof value !== "object" || typeof value[Symbol.asyncIterator] !== "function") {
2723
+ const digest = digestOf(value);
2724
+ if (digest !== undefined && digest === lastEventId) return async function* () {}();
2725
+ position.pending = digest;
2726
+ return value;
2727
+ }
2728
+ const source = value;
2729
+ return {
2730
+ [Symbol.asyncIterator]() {
2731
+ const iterator = source[Symbol.asyncIterator]();
2732
+ let first = true;
2733
+ const step = () => iterator.next().then(result => {
2734
+ if (result.done) return result;
2735
+ if (refs) refs.turn();
2736
+ const digest = digestOf(result.value);
2737
+ if (refs) position.yields.push({
2738
+ value: result.value,
2739
+ digest
2740
+ });
2741
+ if (first) {
2742
+ first = false;
2743
+ if (digest !== undefined && digest === lastEventId) return step();
2744
+ }
2745
+ position.pending = digest;
2746
+ return result;
2747
+ });
2748
+ return {
2749
+ next: step,
2750
+ return: v => iterator.return ? iterator.return(v) : Promise.resolve({
2751
+ done: true,
2752
+ value: v
2753
+ }),
2754
+ throw: e => iterator.throw ? iterator.throw(e) : Promise.reject(e)
2755
+ };
2756
+ }
2757
+ };
2758
+ }
2759
+ function encodeLiveResult(value, headers, status, codec, request, scope, shareKey) {
2760
+ if (NULL_BODY_STATUSES.has(status) || value === undefined || getHeadersAndBody(value)) {
2761
+ return encodeResult(value, headers, status, codec, request.signal, scope);
2762
+ }
2763
+ if (shareKey !== undefined && value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function") {
2764
+ const shared = sharedSourceResponse(shareKey, value, headers, status, codec, request);
2765
+ if (shared) return shared;
2766
+ }
2767
+ const position = {
2768
+ pending: undefined
2769
+ };
2770
+ const source = liveSource(value, request.headers.get(LAST_EVENT_ID_HEADER), position, scope);
2771
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2772
+ headers.set("Content-Type", "text/event-stream");
2773
+ headers.set("Cache-Control", "no-store");
2774
+ headers.set("X-Accel-Buffering", "no");
2775
+ try {
2776
+ return new Response(serializeResponseStream(source, codec, request.signal, scope, position), {
2777
+ status,
2778
+ headers
2779
+ });
2780
+ } catch (error) {
2781
+ throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
2782
+ }
2783
+ }
2784
+ const SHARED_SOURCES = new Map();
2785
+ class GenerationalRefs extends Map {
2786
+ count = 0;
2787
+ touched = new Set();
2788
+ get size() {
2789
+ return this.count;
2790
+ }
2791
+ get(key) {
2792
+ const id = super.get(key);
2793
+ if (id !== undefined) this.touched.add(key);
2794
+ return id;
2795
+ }
2796
+ set(key, value) {
2797
+ if (!super.has(key)) this.count++;
2798
+ this.touched.add(key);
2799
+ return super.set(key, value);
2800
+ }
2801
+ turn() {
2802
+ for (const key of [...super.keys()]) if (!this.touched.has(key)) super.delete(key);
2803
+ this.touched = new Set();
2804
+ }
2805
+ idOf(key) {
2806
+ return super.get(key);
2807
+ }
2808
+ reserve() {
2809
+ return this.count++;
2810
+ }
2811
+ }
2812
+ function sharedSourceResponse(key, value, headers, status, codec, request) {
2813
+ let shared = SHARED_SOURCES.get(key);
2814
+ let snapshot;
2815
+ if (shared && !shared.ended) {
2816
+ snapshot = sharedSnapshot(shared);
2817
+ if (snapshot === null) return undefined;
2818
+ if (value !== shared.source) closeUnread(value);
2819
+ } else shared = startSharedSource(key, value, codec);
2820
+ return tapSharedSource(shared, request, headers, status, snapshot);
2821
+ }
2822
+ function closeUnread(value) {
2823
+ try {
2824
+ const closing = typeof value.return === "function" ? value.return() : typeof value.cancel === "function" ? value.cancel() : undefined;
2825
+ if (closing && typeof closing.then === "function") closing.then(undefined, () => {});
2826
+ } catch {}
2827
+ }
2828
+ function startSharedSource(key, value, codec) {
2829
+ const refs = new GenerationalRefs();
2830
+ const shared = {
2831
+ key,
2832
+ codec,
2833
+ refs,
2834
+ encode: null,
2835
+ head: null,
2836
+ node: null,
2837
+ value: undefined,
2838
+ position: undefined,
2839
+ stream: undefined,
2840
+ source: value,
2841
+ taps: new Set(),
2842
+ ended: false,
2843
+ teardown: new AbortController()
2844
+ };
2845
+ SHARED_SOURCES.set(key, shared);
2846
+ const event = broadcastEvent();
2847
+ const store = globalThis[RequestContext];
2848
+ const scope = run => store ? store.run(event, run) : run();
2849
+ const live = {
2850
+ pending: undefined,
2851
+ yields: [],
2852
+ nodes: new WeakMap()
2853
+ };
2854
+ const body = serializeResponseStream(liveSource(value, undefined, live, scope, refs), {
2855
+ ...codec,
2856
+ refs
2857
+ }, shared.teardown.signal, scope, live);
2858
+ pumpSharedSource(shared, body.getReader(), live);
2859
+ return shared;
2860
+ }
2861
+ async function pumpSharedSource(shared, reader, {
2862
+ nodes,
2863
+ yields
2864
+ }) {
2865
+ try {
2866
+ shared.encode = (await import('@solidjs/web/serialization')).serializeJSON;
2867
+ while (true) {
2868
+ const {
2869
+ done,
2870
+ value: chunk
2871
+ } = await reader.read();
2872
+ if (done) break;
2873
+ const node = nodes.get(chunk);
2874
+ if (shared.head === null) shared.head = chunk;else if (node && node.t === 32 && (shared.stream ??= node.i) === node.i) {
2875
+ const {
2876
+ value,
2877
+ digest
2878
+ } = yields.shift();
2879
+ shared.node = node;
2880
+ shared.value = value;
2881
+ shared.position = digest;
2882
+ }
2883
+ for (const tap of shared.taps) tap.write(chunk);
2884
+ }
2885
+ } catch {}
2886
+ shared.ended = true;
2887
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2888
+ for (const tap of [...shared.taps]) tap.end();
2889
+ }
2890
+ function sharedSnapshot(shared) {
2891
+ if (shared.node === null) return undefined;
2892
+ const own = new Map();
2893
+ let root;
2894
+ let done = false;
2895
+ const cancel = shared.encode(shared.value, {
2896
+ ...shared.codec,
2897
+ refs: own,
2898
+ onParse(node) {
2899
+ root ??= node;
2900
+ },
2901
+ onDone() {
2902
+ done = true;
2903
+ },
2904
+ onError() {}
2905
+ });
2906
+ if (!done || root === undefined) {
2907
+ cancel();
2908
+ return null;
2909
+ }
2910
+ const ids = new Map();
2911
+ for (const [value, id] of own) ids.set(id, shared.refs.idOf(value) ?? shared.refs.reserve());
2912
+ return createEventChunk(JSON.stringify({
2913
+ ...shared.node,
2914
+ f: renumberNode(root, ids)
2915
+ }), shared.position);
2916
+ }
2917
+ function renumberNode(node, ids) {
2918
+ if (Array.isArray(node)) return node.map(item => renumberNode(item, ids));
2919
+ if (node === null || typeof node !== "object") return node;
2920
+ const out = {};
2921
+ for (const key in node) out[key] = key === "i" && typeof node[key] === "number" ? ids.get(node[key]) ?? node[key] : renumberNode(node[key], ids);
2922
+ return out;
2923
+ }
2924
+ function tapSharedSource(shared, request, headers, status, snapshot) {
2925
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Serialized);
2926
+ headers.set("Content-Type", "text/event-stream");
2927
+ headers.set("Cache-Control", "no-store");
2928
+ headers.set("X-Accel-Buffering", "no");
2929
+ const signal = request.signal;
2930
+ let closed = false;
2931
+ let stopLive = null;
2932
+ let tap = null;
2933
+ const leave = () => {
2934
+ if (closed) return;
2935
+ closed = true;
2936
+ if (stopLive) stopLive();
2937
+ if (signal) signal.removeEventListener("abort", leave);
2938
+ shared.taps.delete(tap);
2939
+ if (!shared.taps.size && !shared.ended) {
2940
+ shared.ended = true;
2941
+ if (SHARED_SOURCES.get(shared.key) === shared) SHARED_SOURCES.delete(shared.key);
2942
+ shared.teardown.abort();
2943
+ }
2944
+ };
2945
+ const body = new ReadableStream({
2946
+ start(controller) {
2947
+ tap = {
2948
+ write(chunk) {
2949
+ if (closed) return;
2950
+ try {
2951
+ controller.enqueue(chunk);
2952
+ } catch {
2953
+ leave();
2954
+ }
2955
+ },
2956
+ end() {
2957
+ leave();
2958
+ try {
2959
+ controller.close();
2960
+ } catch {}
2961
+ }
2962
+ };
2963
+ stopLive = armLiveBody(controller, leave);
2964
+ if (shared.head) controller.enqueue(shared.head);
2965
+ if (snapshot) controller.enqueue(snapshot);
2966
+ if (shared.ended || signal && signal.aborted) return tap.end();
2967
+ shared.taps.add(tap);
2968
+ if (signal) signal.addEventListener("abort", leave);
2969
+ },
2970
+ cancel() {
2971
+ leave();
2972
+ }
2973
+ });
2974
+ return new Response(body, {
2975
+ status,
908
2976
  headers
909
2977
  });
910
2978
  }
911
- function encodeResult(value, headers, status, codec, signal) {
2979
+ function broadcastEvent() {
2980
+ const event = {
2981
+ broadcast: true
2982
+ };
2983
+ for (const name of ["request", "locals", "clientAddress", "nativeEvent"]) Object.defineProperty(event, name, {
2984
+ get() {
2985
+ if (DEV) console.warn(`A broadcast server function read the request (\`event.${name}\`) while producing ` + "its answer, which every viewer shares; read per-viewer state before returning it.");
2986
+ return undefined;
2987
+ }
2988
+ });
2989
+ return event;
2990
+ }
2991
+ function encodeResult(value, headers, status, codec, signal, scope) {
2992
+ if (NULL_BODY_STATUSES.has(status)) {
2993
+ if (value === undefined || value === null) {
2994
+ if (status !== 304) headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
2995
+ return new Response(null, {
2996
+ status,
2997
+ headers
2998
+ });
2999
+ }
3000
+ 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.`);
3001
+ headers.set(ERROR_HEADER, encodeErrorHeaderValue(error.message));
3002
+ return encodeResult(error, headers, 500, codec, signal, scope);
3003
+ }
912
3004
  const direct = getHeadersAndBody(value);
913
3005
  if (direct) {
914
3006
  for (const [key, val] of Object.entries(direct.headers || {})) {
@@ -920,54 +3012,148 @@ function encodeResult(value, headers, status, codec, signal) {
920
3012
  });
921
3013
  }
922
3014
  if (value === undefined) {
3015
+ headers.set(BODY_FORMAT_HEADER, BodyFormat.Void);
923
3016
  return new Response(null, {
924
3017
  status,
925
3018
  headers
926
3019
  });
927
3020
  }
928
3021
  try {
929
- if (isJSONSafe(value)) {
3022
+ const jsonSafe = scope ? scope(() => isJSONSafe(value)) : isJSONSafe(value);
3023
+ if (jsonSafe) {
930
3024
  headers.set(BODY_FORMAT_HEADER, BodyFormat.Json);
931
3025
  headers.set("Content-Type", "application/json");
932
- return new Response(JSON.stringify(value), {
3026
+ const body = scope ? scope(() => JSON.stringify(value)) : JSON.stringify(value);
3027
+ return new Response(body, {
933
3028
  status,
934
3029
  headers
935
3030
  });
936
3031
  }
937
3032
  } catch {
938
3033
  }
939
- const response = serializedResponse(value, headers, codec, signal);
940
- return status === 200 ? response : new Response(response.body, {
941
- status,
942
- headers
943
- });
3034
+ try {
3035
+ const response = serializedResponse(value, headers, codec, signal, scope);
3036
+ return status === 200 ? response : new Response(response.body, {
3037
+ status,
3038
+ headers
3039
+ });
3040
+ } catch (error) {
3041
+ throw DEV && error instanceof Error ? new Error(`Server function result could not be encoded: ${error.message}`) : error;
3042
+ }
3043
+ }
3044
+ const ERROR_HEADER_VALUE_LIMIT = 1024;
3045
+ function boundedErrorHeaderValue(message) {
3046
+ let label = message.length > 256 ? message.slice(0, 256) : message;
3047
+ let encoded = encodeErrorHeaderValue(label);
3048
+ while (encoded.length > ERROR_HEADER_VALUE_LIMIT && label.length > 1) {
3049
+ label = label.slice(0, Math.ceil(label.length / 2));
3050
+ encoded = encodeErrorHeaderValue(label);
3051
+ }
3052
+ return encoded;
944
3053
  }
945
3054
  const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
946
3055
  let DEV = true === true;
947
3056
  function setServerFunctionsDev(dev) {
948
3057
  DEV = !!dev;
949
3058
  }
3059
+ const REQUEST_ERROR_HOOKS = new WeakMap();
3060
+ function siteFor(handling, event, direct) {
3061
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
3062
+ const site = {
3063
+ kind: "server-function",
3064
+ handling,
3065
+ direct
3066
+ };
3067
+ if (invocation) site.functionId = invocation.id;
3068
+ if (event) site.event = event;
3069
+ return site;
3070
+ }
3071
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
3072
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
3073
+ return report.mapped ? report.value : sanitizeServerError(value);
3074
+ }
3075
+ function currentEvent() {
3076
+ const store = globalThis[RequestContext];
3077
+ return store ? store.getStore() : undefined;
3078
+ }
3079
+ function reportDirectFailure(run, id, hook) {
3080
+ const report = error => {
3081
+ if (error instanceof Response || isResponseEnvelope(error)) throw error;
3082
+ reportServerError(error, {
3083
+ kind: "server-function",
3084
+ handling: "thrown",
3085
+ functionId: id,
3086
+ direct: true
3087
+ }, null, hook);
3088
+ throw error;
3089
+ };
3090
+ let result;
3091
+ try {
3092
+ result = run();
3093
+ } catch (error) {
3094
+ report(error);
3095
+ }
3096
+ return result && typeof result.then === "function" ? result.then(undefined, report) : result;
3097
+ }
3098
+ function directEnvelopeValue(result, event) {
3099
+ if (!isResponseEnvelope(result)) return result;
3100
+ const {
3101
+ response,
3102
+ value
3103
+ } = result;
3104
+ const stub = event.response;
3105
+ if (response && stub && stub.headers && response.headers.getSetCookie) {
3106
+ for (const cookie of response.headers.getSetCookie()) {
3107
+ stub.headers.append("Set-Cookie", cookie);
3108
+ }
3109
+ }
3110
+ return value;
3111
+ }
950
3112
  function sanitizeServerError(value) {
951
3113
  if (DEV) return value;
952
3114
  if (isSafeError(value)) return value;
953
- return new Error(GENERIC_SERVER_ERROR_MESSAGE);
3115
+ const wire = new Error(GENERIC_SERVER_ERROR_MESSAGE);
3116
+ emitFinding({
3117
+ code: "SERVER_ERROR_SANITIZED",
3118
+ kind: "ssr",
3119
+ severity: "error",
3120
+ message: `[SERVER_ERROR_SANITIZED] Server function error replaced with a generic Error before serialization: ${errorText(value)}`,
3121
+ data: {
3122
+ source: "server-function",
3123
+ error: value,
3124
+ wire
3125
+ }
3126
+ }, null);
3127
+ return wire;
3128
+ }
3129
+ function serverFunctionUrl(fn, ...args) {
3130
+ return serverFunctionUrlFor(config.endpoint, fn, args);
954
3131
  }
955
- function observeServerFunctionCalls() {
956
- return () => {};
3132
+ function serverFunctionActionUrl(fn, ...boundArgs) {
3133
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
3134
+ }
3135
+ function parseServerFunctionActionUrl(url) {
3136
+ const parsed = parseServerFunctionAddress(new URL(url, "http://localhost").pathname, config.endpoint);
3137
+ return parsed && parsed.id;
957
3138
  }
958
3139
  async function matchesOrigin(origin, request, matcher) {
959
3140
  if (matcher === undefined) return origin === new URL(request.url).origin;
960
- if (typeof matcher === "function") return !!(await matcher(origin, request));
3141
+ if (typeof matcher === "function") return (await matcher(origin, request)) === true;
961
3142
  return Array.isArray(matcher) ? matcher.includes(origin) : origin === matcher;
962
3143
  }
963
3144
  async function allowsServerFunctionRequest(request, options) {
964
3145
  const fetchSite = request.headers.get("Sec-Fetch-Site");
965
3146
  if (fetchSite === "same-origin") return true;
966
- if (fetchSite === "same-site" || fetchSite === "cross-site" || fetchSite === "none") {
967
- return false;
968
- }
3147
+ if (fetchSite === "none") return false;
969
3148
  const origin = request.headers.get("Origin");
970
- if (origin !== null) return matchesOrigin(origin, request, options.origin);
3149
+ if (fetchSite === "same-site" || fetchSite === "cross-site") {
3150
+ if (origin === null || options.origin === undefined) return false;
3151
+ return (await matchesOrigin(origin, request, options.origin)) ? origin : false;
3152
+ }
3153
+ if (origin !== null) {
3154
+ if (!(await matchesOrigin(origin, request, options.origin))) return false;
3155
+ return origin === new URL(request.url).origin ? true : origin;
3156
+ }
971
3157
  const referer = request.headers.get("Referer");
972
3158
  if (referer !== null) {
973
3159
  try {
@@ -979,21 +3165,23 @@ async function allowsServerFunctionRequest(request, options) {
979
3165
  return options.allowRequestsWithoutOriginCheck === true;
980
3166
  }
981
3167
  const CSRF_VARY = ["Sec-Fetch-Site", "Origin", "Referer"];
982
- function withCSRFVary(response) {
983
- const current = response.headers.get("Vary");
984
- if (current === "*") return response;
3168
+ function appendVary(headers, names) {
3169
+ const current = headers.get("Vary");
3170
+ if (current === "*") return;
985
3171
  const values = current ? current.split(",").map(value => value.trim()) : [];
986
- const names = new Set(values.map(value => value.toLowerCase()));
987
- for (const value of CSRF_VARY) {
988
- if (!names.has(value.toLowerCase())) values.push(value);
3172
+ const seen = new Set(values.map(value => value.toLowerCase()));
3173
+ for (const name of names) {
3174
+ if (!seen.has(name.toLowerCase())) values.push(name);
989
3175
  }
990
- const vary = values.join(", ");
3176
+ headers.set("Vary", values.join(", "));
3177
+ }
3178
+ function withHeaders(response, write) {
991
3179
  try {
992
- response.headers.set("Vary", vary);
3180
+ write(response.headers);
993
3181
  return response;
994
3182
  } catch {
995
3183
  const headers = new Headers(response.headers);
996
- headers.set("Vary", vary);
3184
+ write(headers);
997
3185
  return new Response(response.body, {
998
3186
  status: response.status,
999
3187
  statusText: response.statusText,
@@ -1001,6 +3189,42 @@ function withCSRFVary(response) {
1001
3189
  });
1002
3190
  }
1003
3191
  }
3192
+ function withCSRFVary(response) {
3193
+ return withHeaders(response, headers => appendVary(headers, CSRF_VARY));
3194
+ }
3195
+ const TRANSPORT_REQUEST_HEADERS = ["Content-Type", BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, BUILD_HEADER].join(", ");
3196
+ const PREFLIGHT_MAX_AGE = "600";
3197
+ const CORS_SAFELISTED_RESPONSE_HEADERS = new Set(["cache-control", "content-language", "content-length", "content-type", "expires", "last-modified", "pragma"]);
3198
+ function withCORS(response, cors) {
3199
+ if (cors === null) return response;
3200
+ return withHeaders(response, headers => {
3201
+ headers.set("Access-Control-Allow-Origin", cors.origin);
3202
+ if (cors.credentials) headers.set("Access-Control-Allow-Credentials", "true");
3203
+ const exposed = [];
3204
+ for (const name of headers.keys()) {
3205
+ if (CORS_SAFELISTED_RESPONSE_HEADERS.has(name) || name === "set-cookie" || name === "vary" || name.startsWith("access-control-")) {
3206
+ continue;
3207
+ }
3208
+ exposed.push(name);
3209
+ }
3210
+ if (exposed.length > 0) headers.set("Access-Control-Expose-Headers", exposed.join(", "));
3211
+ appendVary(headers, ["Origin"]);
3212
+ });
3213
+ }
3214
+ function preflightResponse(request) {
3215
+ const requested = request.headers.get("Access-Control-Request-Headers");
3216
+ const response = new Response(null, {
3217
+ status: 204,
3218
+ headers: {
3219
+ "Access-Control-Allow-Methods": "POST, GET, HEAD",
3220
+ "Access-Control-Allow-Headers": requested !== null && requested.trim() !== "" ? requested : TRANSPORT_REQUEST_HEADERS,
3221
+ "Access-Control-Max-Age": PREFLIGHT_MAX_AGE,
3222
+ "Cache-Control": "no-store"
3223
+ }
3224
+ });
3225
+ appendVary(response.headers, ["Access-Control-Request-Method", "Access-Control-Request-Headers"]);
3226
+ return response;
3227
+ }
1004
3228
  function forbiddenResponse() {
1005
3229
  return withCSRFVary(new Response(DEV ? "Forbidden" : null, {
1006
3230
  status: 403,
@@ -1009,56 +3233,198 @@ function forbiddenResponse() {
1009
3233
  }
1010
3234
  }));
1011
3235
  }
3236
+ function nativePromise(value) {
3237
+ if (value instanceof Promise) return value;
3238
+ try {
3239
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
3240
+ } catch {}
3241
+ }
1012
3242
  async function handleServerFunctionRequest(request, options = {}) {
1013
- const codec = options.codec !== undefined ? options.codec : getServerFunctionsCodec();
3243
+ const codec = {
3244
+ ...(options.codec !== undefined ? options.codec : getServerFunctionsCodec())
3245
+ };
3246
+ codec.serializeErrorStacks ??= DEV;
1014
3247
  const url = new URL(request.url);
3248
+ const method = request.method;
3249
+ const address = resolveAddress(url);
3250
+ const functionId = address && address.id;
3251
+ const declaredRead = (method === "GET" || method === "HEAD") && functionId !== null && declaresRead(functionId);
1015
3252
  const csrf = options.csrf !== undefined ? options.csrf : config.csrf;
1016
- const protectsRequest = csrf !== false;
1017
- if (protectsRequest && !(await allowsServerFunctionRequest(request, csrf === true ? {} : csrf))) {
1018
- return forbiddenResponse();
3253
+ const protectsRequest = csrf !== false && (!declaredRead || CARRIED.has(functionId) || typeof csrf === "object" && csrf.protectDeclaredReads === true);
3254
+ const csrfOptions = csrf === true ? {} : csrf;
3255
+ let verdict = true;
3256
+ let readVariesByOrigin = false;
3257
+ if (protectsRequest) {
3258
+ verdict = await allowsServerFunctionRequest(request, csrfOptions);
3259
+ } else if (csrfOptions !== false && csrfOptions.origin !== undefined) {
3260
+ readVariesByOrigin = true;
3261
+ const admitted = await allowsServerFunctionRequest(request, csrfOptions);
3262
+ if (typeof admitted === "string") verdict = admitted;
3263
+ }
3264
+ const cors = typeof verdict === "string" ? {
3265
+ origin: verdict,
3266
+ credentials: csrfOptions.allowCredentials === true
3267
+ } : null;
3268
+ const finish = response => {
3269
+ const finalized = withCORS(finalizeTransportResponse(response, method), cors);
3270
+ return readVariesByOrigin && cors === null ? withHeaders(finalized, headers => appendVary(headers, ["Origin"])) : finalized;
3271
+ };
3272
+ if (cors !== null && method === "OPTIONS" && request.headers.has("Access-Control-Request-Method")) {
3273
+ return finish(preflightResponse(request));
3274
+ }
3275
+ let serverFunction;
3276
+ if (functionId) {
3277
+ try {
3278
+ serverFunction = getServerFunction(functionId);
3279
+ } catch {
3280
+ return finish(new Response(DEV ? `Unknown server function: ${functionId}` : null, {
3281
+ status: 404,
3282
+ headers: {
3283
+ [UNKNOWN_HEADER]: "true"
3284
+ }
3285
+ }));
3286
+ }
3287
+ }
3288
+ if (verdict === false) {
3289
+ return finish(forbiddenResponse());
1019
3290
  }
1020
- const instance = request.headers.get(INSTANCE_HEADER);
1021
- const functionId = resolveFunctionId(request, url);
1022
3291
  if (!functionId) {
1023
3292
  const response = new Response(DEV ? "Server function not found" : null, {
1024
3293
  status: 404
1025
3294
  });
1026
- return protectsRequest ? withCSRFVary(response) : response;
3295
+ return finish(protectsRequest ? withCSRFVary(response) : response);
1027
3296
  }
1028
- let serverFunction;
1029
- try {
1030
- serverFunction = getServerFunction(functionId);
1031
- } catch {
1032
- const response = new Response(DEV ? `Unknown server function: ${functionId}` : null, {
1033
- status: 404
1034
- });
1035
- return protectsRequest ? withCSRFVary(response) : response;
3297
+ const callerBuild = request.headers.get(BUILD_HEADER);
3298
+ if (config.buildId && callerBuild !== null && callerBuild !== config.buildId) {
3299
+ return finish(new Response(DEV ? `Server function call from build "${callerBuild}" refused by build "${config.buildId}"` : null, {
3300
+ status: 409,
3301
+ headers: {
3302
+ [UNKNOWN_HEADER]: "true",
3303
+ [BUILD_HEADER]: config.buildId,
3304
+ "Cache-Control": "no-store"
3305
+ }
3306
+ }));
1036
3307
  }
1037
- if (request.method === "GET" && METHODS.get(functionId) !== "GET") {
3308
+ const scripted = address.data || address.live;
3309
+ const live = address.live;
3310
+ if (method !== "POST" && !declaredRead) {
1038
3311
  const response = new Response(DEV ? `Method not allowed for server function: ${functionId}` : null, {
1039
3312
  status: 405,
1040
3313
  headers: {
1041
- Allow: "POST"
3314
+ Allow: declaresRead(functionId) ? "POST, GET, HEAD" : "POST"
1042
3315
  }
1043
3316
  });
1044
- return protectsRequest ? withCSRFVary(response) : response;
3317
+ return finish(protectsRequest ? withCSRFVary(response) : response);
1045
3318
  }
1046
- const event = options.createEvent ? options.createEvent(request) : {
1047
- request,
1048
- locals: {}
3319
+ const bodySizeLimit = options.bodySizeLimit !== undefined ? options.bodySizeLimit : config.bodySizeLimit;
3320
+ const argsEncoding = url.searchParams.get("args");
3321
+ if (argsEncoding !== null && argsEncoding.length > bodySizeLimit) {
3322
+ const response = new Response(DEV ? "Server function arguments exceed the configured bodySizeLimit" : null, {
3323
+ status: 413
3324
+ });
3325
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3326
+ }
3327
+ let argumentBytes = null;
3328
+ if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
3329
+ const raw = request.headers.get("content-length");
3330
+ const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
3331
+ if (declared > bodySizeLimit) {
3332
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
3333
+ status: 413
3334
+ });
3335
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3336
+ }
3337
+ let buffered;
3338
+ try {
3339
+ buffered = await bufferBodyWithin(request, bodySizeLimit);
3340
+ } catch {
3341
+ const response = new Response(DEV ? "Malformed server function arguments" : null, {
3342
+ status: 400
3343
+ });
3344
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3345
+ }
3346
+ if (buffered === null) {
3347
+ const response = new Response(DEV ? "Server function request body exceeds the configured bodySizeLimit" : null, {
3348
+ status: 413
3349
+ });
3350
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3351
+ }
3352
+ request = withBufferedBody(request, buffered);
3353
+ argumentBytes = buffered;
3354
+ }
3355
+ let event;
3356
+ try {
3357
+ event = options.createEvent ? options.createEvent(request) : {
3358
+ request,
3359
+ locals: {}
3360
+ };
3361
+ const promised = nativePromise(event);
3362
+ if (promised) event = await promised;
3363
+ } catch (error) {
3364
+ const safe = sanitizeServerError(error);
3365
+ const message = safe instanceof Error ? safe.message : String(safe);
3366
+ const headers = new Headers();
3367
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(message));
3368
+ const response = scripted ? encodeResult(safe, headers, 500, codec, request.signal) : new Response(DEV ? message : null, {
3369
+ status: 500
3370
+ });
3371
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3372
+ }
3373
+ const commitResponse = raw => {
3374
+ if ((method === "GET" || method === "HEAD") && (sharedCacheMayStore(departingHeader(raw, event, "Cache-Control")) || cdnMayStore(departingHeader(raw, event, "CDN-Cache-Control")))) {
3375
+ withholdTrace(event);
3376
+ }
3377
+ return commitEventResponse(raw, event);
3378
+ };
3379
+ const refuseCommitted = raw => {
3380
+ const response = commitResponse(raw);
3381
+ return finish(protectsRequest ? withCSRFVary(response) : response);
1049
3382
  };
1050
3383
  const provide = options.provideEvent || provideEvent;
3384
+ const scope = run => provide(event, run);
3385
+ if (options.onError !== undefined) REQUEST_ERROR_HOOKS.set(event, options.onError);
1051
3386
  const flightHook = options.collectFlightData !== undefined ? options.collectFlightData : config.collectFlightData;
1052
3387
  const transformResult = options.transformResult !== undefined ? options.transformResult : config.transformResult;
1053
- const wrapInvocation = options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation;
3388
+ const wrapInvocation = resolveWrapInvocation(options.wrapInvocation !== undefined ? options.wrapInvocation : config.wrapInvocation);
1054
3389
  const transformFlightResult = options.transformFlightResult !== undefined ? options.transformFlightResult : config.transformFlightResult;
1055
- const handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS !== undefined ? config.handleNoJS : isFormPost(request) ? defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler()) : undefined;
1056
- const collectsFlight = !!(flightHook && instance && request.headers.has(SINGLE_FLIGHT_HEADER));
1057
- const parsed = await parseArguments(request, url, instance, codec);
3390
+ let handleNoJS = options.handleNoJS !== undefined ? options.handleNoJS : config.handleNoJS;
3391
+ if (handleNoJS === undefined && !scripted && isFormPost(request)) {
3392
+ const fetchMode = request.headers.get("Sec-Fetch-Mode");
3393
+ if (fetchMode === null || fetchMode === "navigate") {
3394
+ handleNoJS = defaultNoJSHandler || (defaultNoJSHandler = createNoJSHandler());
3395
+ } else {
3396
+ 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, {
3397
+ status: 400
3398
+ });
3399
+ return refuseCommitted(response);
3400
+ }
3401
+ }
3402
+ const flightHeader = scripted && method === "POST" ? request.headers.get(SINGLE_FLIGHT_HEADER) : null;
3403
+ const flightHooks = flightHeader ? [...new Set(flightHeader.split(","))].flatMap(source => {
3404
+ const hook = source === "true" ? flightHook : flightSources.get(source);
3405
+ return hook ? [[source, hook]] : [];
3406
+ }) : [];
3407
+ const collectsFlight = flightHooks.length > 0;
3408
+ let parsed;
3409
+ try {
3410
+ parsed = await parseArguments(request, url, scripted, codec, argumentBytes);
3411
+ } catch (error) {
3412
+ const named = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true ? error : refusedArgument(error);
3413
+ const response = new Response(DEV ? named ? named.message : "Malformed server function arguments" : null, {
3414
+ status: 400
3415
+ });
3416
+ return refuseCommitted(response);
3417
+ }
3418
+ const maxArguments = options.maxArguments !== undefined ? options.maxArguments : config.maxArguments;
3419
+ if (parsed.length > maxArguments) {
3420
+ const response = new Response(DEV ? "Server function call exceeds the configured maxArguments" : null, {
3421
+ status: 400
3422
+ });
3423
+ return refuseCommitted(response);
3424
+ }
1058
3425
  const flightContext = {
1059
3426
  id: functionId,
1060
3427
  args: parsed,
1061
- instance,
1062
3428
  request,
1063
3429
  collectsFlight,
1064
3430
  codec,
@@ -1067,19 +3433,30 @@ async function handleServerFunctionRequest(request, options = {}) {
1067
3433
  const headers = new Headers();
1068
3434
  const dispatch = async () => {
1069
3435
  try {
1070
- let result = await provide(event, async () => {
3436
+ const invokeOnce = async () => {
3437
+ const shared = !!live && BROADCASTS.has(functionId);
1071
3438
  INVOCATIONS.set(event, {
1072
- id: functionId
3439
+ id: functionId,
3440
+ live: !!live,
3441
+ broadcast: shared || undefined,
3442
+ shareKey: shared ? encodedArguments(request, url, argsEncoding, argumentBytes) : undefined
1073
3443
  });
1074
3444
  const run = () => serverFunction(...parsed);
1075
- return wrapInvocation ? wrapInvocation(run, {
3445
+ return observeInvocation({
3446
+ id: functionId,
3447
+ direct: false,
3448
+ event,
3449
+ request,
3450
+ args: parsed
3451
+ }, () => wrapInvocation ? wrapInvocation(run, {
1076
3452
  id: functionId,
1077
3453
  args: parsed,
1078
3454
  event,
1079
3455
  request,
1080
3456
  direct: false
1081
- }) : run();
1082
- });
3457
+ }) : run());
3458
+ };
3459
+ let result = await provideEventOnce(provide, event, invokeOnce);
1083
3460
  if (transformResult) {
1084
3461
  result = await transformResult(event, result, flightContext);
1085
3462
  }
@@ -1090,25 +3467,29 @@ async function handleServerFunctionRequest(request, options = {}) {
1090
3467
  response,
1091
3468
  value
1092
3469
  } = result;
1093
- if (!instance && !handleNoJS && response && response.body) {
3470
+ if (!scripted && !handleNoJS && response && response.body && isJSONSafe(value)) {
1094
3471
  return response;
1095
3472
  }
1096
3473
  if (response && response.headers) {
1097
3474
  mergeResponseHeaders(headers, response.headers);
1098
3475
  }
1099
- if (response && response.status && (response.status < 300 || response.status >= 400)) {
3476
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
1100
3477
  status = response.status;
3478
+ } else if (response && response.status) {
3479
+ maskRedirect(headers, response, request.url);
1101
3480
  }
1102
3481
  metadata = response;
1103
3482
  result = value;
1104
3483
  } else if (result instanceof Response) {
1105
3484
  if (result.headers && result.headers.has("X-Content-Raw")) return result;
1106
- if (instance) {
3485
+ if (scripted) {
1107
3486
  if (result.headers) {
1108
3487
  mergeResponseHeaders(headers, result.headers);
1109
3488
  }
1110
- if (result.status && (result.status < 300 || result.status >= 400)) {
3489
+ if (result.status && !validRedirectStatuses.has(result.status)) {
1111
3490
  status = result.status;
3491
+ } else if (result.status) {
3492
+ maskRedirect(headers, result, request.url);
1112
3493
  }
1113
3494
  metadata = result;
1114
3495
  if (result.body == null) {
@@ -1117,7 +3498,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1117
3498
  }
1118
3499
  }
1119
3500
  if (collectsFlight) {
1120
- result = await foldFlightData(flightHook, event, headers, {
3501
+ result = await foldFlightData(flightHooks, event, headers, {
1121
3502
  id: functionId,
1122
3503
  value: result,
1123
3504
  response: metadata,
@@ -1126,20 +3507,45 @@ async function handleServerFunctionRequest(request, options = {}) {
1126
3507
  }, flightContext);
1127
3508
  if (result instanceof Response && result.headers.has("X-Content-Raw")) return result;
1128
3509
  }
1129
- if (!instance) {
1130
- if (handleNoJS) return handleNoJS(result, request, parsed);
3510
+ if (!scripted) {
3511
+ if (handleNoJS) {
3512
+ const outcome = result == null && metadata !== undefined ? metadata : result;
3513
+ return withEnvelopeCookies(await handleNoJS(outcome, request, parsed), outcome, metadata);
3514
+ }
1131
3515
  if (result instanceof Response) return result;
1132
- return encodeResult(result, headers, 200, codec, request.signal);
3516
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1133
3517
  }
1134
- return encodeResult(result, headers, status, codec, request.signal);
3518
+ if (status === 304) warnScripted304(functionId);
3519
+ if (live) {
3520
+ const invocation = INVOCATIONS.get(event);
3521
+ return encodeLiveResult(result, headers, status, codec, request, scope, invocation && invocation.broadcast && invocation.shareKey !== undefined ? invocation.id + "\0" + invocation.shareKey : undefined);
3522
+ }
3523
+ return encodeResult(result, headers, status, codec, request.signal, scope);
1135
3524
  } catch (x) {
1136
- if (x instanceof Response || isResponseEnvelope(x)) {
1137
- if (transformResult) {
3525
+ const respondThrown = value => {
3526
+ const safe = wireServerFunctionError(value, "thrown", event);
3527
+ if (!scripted) {
3528
+ if (handleNoJS) return handleNoJS(safe, request, parsed, true);
3529
+ const message = safe instanceof Error ? safe.message : String(safe);
3530
+ return new Response(DEV ? message : null, {
3531
+ status: 500
3532
+ });
3533
+ }
3534
+ const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
3535
+ headers.set(ERROR_HEADER, boundedErrorHeaderValue(error));
3536
+ return encodeResult(safe, headers, 500, codec, request.signal, scope);
3537
+ };
3538
+ if (transformResult) {
3539
+ try {
1138
3540
  x = await transformResult(event, x, {
1139
3541
  ...flightContext,
1140
3542
  thrown: true
1141
3543
  });
3544
+ } catch (hookError) {
3545
+ return respondThrown(hookError);
1142
3546
  }
3547
+ }
3548
+ if (x instanceof Response || isResponseEnvelope(x)) {
1143
3549
  let status = 200;
1144
3550
  let metadata;
1145
3551
  if (isResponseEnvelope(x)) {
@@ -1150,8 +3556,10 @@ async function handleServerFunctionRequest(request, options = {}) {
1150
3556
  if (response && response.headers) {
1151
3557
  mergeResponseHeaders(headers, response.headers);
1152
3558
  }
1153
- if (response && response.status && (!instance || response.status < 300 || response.status >= 400)) {
3559
+ if (response && response.status && (!scripted || !validRedirectStatuses.has(response.status))) {
1154
3560
  status = response.status;
3561
+ } else if (response && response.status) {
3562
+ maskRedirect(headers, response, request.url);
1155
3563
  }
1156
3564
  metadata = response;
1157
3565
  x = value;
@@ -1159,8 +3567,10 @@ async function handleServerFunctionRequest(request, options = {}) {
1159
3567
  if (x.headers) {
1160
3568
  mergeResponseHeaders(headers, x.headers);
1161
3569
  }
1162
- if (x.status && (!instance || x.status < 300 || x.status >= 400)) {
3570
+ if (x.status && (!scripted || !validRedirectStatuses.has(x.status))) {
1163
3571
  status = x.status;
3572
+ } else if (x.status) {
3573
+ maskRedirect(headers, x, request.url);
1164
3574
  }
1165
3575
  metadata = x;
1166
3576
  if (x.body == null) {
@@ -1168,7 +3578,7 @@ async function handleServerFunctionRequest(request, options = {}) {
1168
3578
  }
1169
3579
  }
1170
3580
  if (collectsFlight) {
1171
- x = await foldFlightData(flightHook, event, headers, {
3581
+ x = await foldFlightData(flightHooks, event, headers, {
1172
3582
  id: functionId,
1173
3583
  value: x,
1174
3584
  response: metadata,
@@ -1176,32 +3586,125 @@ async function handleServerFunctionRequest(request, options = {}) {
1176
3586
  thrown: true
1177
3587
  }, flightContext);
1178
3588
  if (x instanceof Response && x.headers.has("X-Content-Raw")) {
3589
+ x = ownResponse(x);
1179
3590
  x.headers.set(ERROR_HEADER, "true");
1180
3591
  return x;
1181
3592
  }
1182
3593
  }
1183
3594
  headers.set(ERROR_HEADER, "true");
1184
- if (!instance) {
1185
- if (handleNoJS) return handleNoJS(x ?? metadata, request, parsed, true);
3595
+ if (!scripted) {
3596
+ if (handleNoJS) {
3597
+ const outcome = x ?? metadata;
3598
+ return withEnvelopeCookies(await handleNoJS(outcome, request, parsed, true), outcome, metadata);
3599
+ }
1186
3600
  if (x instanceof Response) return x;
1187
3601
  }
1188
- return encodeResult(x, headers, status, codec, request.signal);
1189
- }
1190
- const safe = sanitizeServerError(x);
1191
- if (!instance) {
1192
- if (handleNoJS) return handleNoJS(safe, request, parsed, true);
1193
- const message = safe instanceof Error ? safe.message : String(safe);
1194
- return new Response(DEV ? message : null, {
1195
- status: 500
1196
- });
3602
+ if (scripted && status === 304) warnScripted304(functionId);
3603
+ return encodeResult(x, headers, status, codec, request.signal, scope);
1197
3604
  }
1198
- const error = safe instanceof Error ? safe.message : typeof safe === "string" ? safe : "true";
1199
- headers.set(ERROR_HEADER, encodeErrorHeaderValue(error));
1200
- return encodeResult(safe, headers, 200, codec, request.signal);
3605
+ return respondThrown(x);
1201
3606
  }
1202
3607
  };
1203
- const response = commitEventResponse(await dispatch(), event);
1204
- return protectsRequest ? withCSRFVary(response) : response;
3608
+ const response = commitResponse(enforceComposedHeaderInvariants(ownResponse(await dispatch())));
3609
+ return finish(protectsRequest ? withCSRFVary(response) : response);
3610
+ }
3611
+ function departingHeader(response, event, name) {
3612
+ const own = response.headers.get(name);
3613
+ if (own !== null) return own;
3614
+ const stub = event.response;
3615
+ return stub && stub.headers && !stub.committed ? stub.headers.get(name) : null;
3616
+ }
3617
+ function cdnMayStore(cdnCacheControl) {
3618
+ return cdnCacheControl !== null && !forbidsStoring(cdnCacheControl);
3619
+ }
3620
+ function sharedCacheMayStore(cacheControl) {
3621
+ let shared = false;
3622
+ return !!cacheControl && !eachDirective(cacheControl, name => {
3623
+ if (name === "public" || name === "s-maxage") shared = true;
3624
+ }) && shared;
3625
+ }
3626
+ function forbidsStoring(value) {
3627
+ return eachDirective(value, () => {});
3628
+ }
3629
+ function eachDirective(value, visit) {
3630
+ let start = 0;
3631
+ let quoted = false;
3632
+ for (let i = 0; i <= value.length; i++) {
3633
+ const c = value[i];
3634
+ if (quoted) {
3635
+ if (c === "\\") i++;else if (c === '"') quoted = false;
3636
+ continue;
3637
+ }
3638
+ if (c === '"') {
3639
+ quoted = true;
3640
+ continue;
3641
+ }
3642
+ if (c !== "," && i < value.length) continue;
3643
+ const directive = value.slice(start, i);
3644
+ start = i + 1;
3645
+ const eq = directive.indexOf("=");
3646
+ const name = (eq === -1 ? directive : directive.slice(0, eq)).trim().toLowerCase();
3647
+ if (name === "no-store" || name === "private" && eq === -1) return true;
3648
+ visit(name);
3649
+ }
3650
+ return false;
3651
+ }
3652
+ function withholdTrace(event) {
3653
+ if (event.response && event.response.committed) return;
3654
+ traceForEvent(event).emit = false;
3655
+ }
3656
+ function withEnvelopeCookies(response, outcome, metadata) {
3657
+ if (outcome === metadata || !metadata || !metadata.headers || !(response instanceof Response)) {
3658
+ return response;
3659
+ }
3660
+ const cookies = metadata.headers.getSetCookie ? metadata.headers.getSetCookie() : [];
3661
+ if (!cookies.length) return response;
3662
+ const owned = ownResponse(response);
3663
+ if (owned === response) return response;
3664
+ for (const cookie of cookies) owned.headers.append("Set-Cookie", cookie);
3665
+ return owned;
3666
+ }
3667
+ function ownResponse(response) {
3668
+ try {
3669
+ return new Response(response.body, response);
3670
+ } catch {
3671
+ return response;
3672
+ }
3673
+ }
3674
+ function finalizeTransportResponse(response, method) {
3675
+ const stripBody = method === "HEAD" && response.body !== null;
3676
+ const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
3677
+ const defaultsSniff = !response.headers.has("X-Content-Type-Options");
3678
+ if (stripBody || defaultsCache || defaultsSniff) {
3679
+ try {
3680
+ if (defaultsCache) {
3681
+ response.headers.set("Cache-Control", "no-store");
3682
+ }
3683
+ if (defaultsSniff) {
3684
+ response.headers.set("X-Content-Type-Options", "nosniff");
3685
+ }
3686
+ if (!stripBody) return response;
3687
+ response.body.cancel().catch(() => {});
3688
+ return new Response(null, {
3689
+ status: response.status,
3690
+ statusText: response.statusText,
3691
+ headers: response.headers
3692
+ });
3693
+ } catch {
3694
+ const headers = new Headers(response.headers);
3695
+ if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
3696
+ if (defaultsSniff && !headers.has("X-Content-Type-Options")) {
3697
+ headers.set("X-Content-Type-Options", "nosniff");
3698
+ }
3699
+ if (stripBody) response.body.cancel().catch(() => {});
3700
+ return new Response(stripBody ? null : response.body, {
3701
+ status: response.status,
3702
+ statusText: response.statusText,
3703
+ headers
3704
+ });
3705
+ }
3706
+ }
3707
+ return response;
1205
3708
  }
1206
3709
 
1207
- export { ERROR_HEADER, FLASH_COOKIE, FUNCTION_HEADER, GENERIC_SERVER_ERROR_MESSAGE, GET, INSTANCE_HEADER, SINGLE_FLIGHT_HEADER, clearFlashCookie, configureServerFunctionsServer, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, handleServerFunctionRequest, hasFlashCookie, isServerFunction, live, observeServerFunctionCalls, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, setServerFunctionsDev, subscribeFlightData, withMeta };
3710
+ export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, broadcast, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };