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

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