@statewalker/webrun-http-browser 0.3.3 → 0.4.2

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 (93) hide show
  1. package/README.md +406 -51
  2. package/demo/demo-1.html +109 -194
  3. package/demo/demo-2.html +118 -299
  4. package/dist/core/data-calls.d.ts +5 -0
  5. package/dist/core/data-calls.d.ts.map +1 -0
  6. package/dist/core/data-channels.d.ts +17 -0
  7. package/dist/core/data-channels.d.ts.map +1 -0
  8. package/dist/core/index.d.ts +6 -0
  9. package/dist/core/index.d.ts.map +1 -0
  10. package/dist/core/message-target.d.ts +2 -0
  11. package/dist/core/message-target.d.ts.map +1 -0
  12. package/dist/core/registry.d.ts +18 -0
  13. package/dist/core/registry.d.ts.map +1 -0
  14. package/dist/http/http-send-recieve.d.ts +36 -0
  15. package/dist/http/http-send-recieve.d.ts.map +1 -0
  16. package/dist/http/index.d.ts +4 -0
  17. package/dist/http/index.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +2670 -807
  21. package/dist/relay/index-sw.d.ts +7 -0
  22. package/dist/relay/index-sw.d.ts.map +1 -0
  23. package/dist/relay/index.d.ts +69 -0
  24. package/dist/relay/index.d.ts.map +1 -0
  25. package/dist/relay/split-service-url.d.ts +13 -0
  26. package/dist/relay/split-service-url.d.ts.map +1 -0
  27. package/dist/relay-sw.d.ts +2 -0
  28. package/dist/relay-sw.d.ts.map +1 -0
  29. package/dist/relay-sw.js +1660 -0
  30. package/dist/sw/http-sw-dispatcher.d.ts +28 -0
  31. package/dist/sw/http-sw-dispatcher.d.ts.map +1 -0
  32. package/dist/sw/index.d.ts +3 -0
  33. package/dist/sw/index.d.ts.map +1 -0
  34. package/dist/sw/sw-dispatcher.d.ts +74 -0
  35. package/dist/sw/sw-dispatcher.d.ts.map +1 -0
  36. package/dist/sw-worker.d.ts +2 -0
  37. package/dist/sw-worker.d.ts.map +1 -0
  38. package/dist/sw-worker.js +1597 -0
  39. package/dist/sw.d.ts +2 -0
  40. package/dist/sw.d.ts.map +1 -0
  41. package/dist/sw.js +1883 -0
  42. package/package.json +51 -37
  43. package/public/index.html +61 -97
  44. package/public/index.js +7 -4
  45. package/public/sw-worker.js +4 -0
  46. package/public-relay/heartbeat.js +4 -3
  47. package/public-relay/relay-sw.js +4 -6
  48. package/public-relay/relay.html +16 -11
  49. package/src/core/data-calls.ts +46 -0
  50. package/src/core/data-channels.ts +262 -0
  51. package/src/core/index.ts +9 -0
  52. package/src/core/message-target.ts +8 -0
  53. package/src/core/registry.ts +54 -0
  54. package/src/http/http-send-recieve.ts +94 -0
  55. package/src/http/index.ts +7 -0
  56. package/src/index.ts +3 -0
  57. package/src/relay/index-sw.ts +145 -0
  58. package/src/relay/index.ts +261 -0
  59. package/src/relay/split-service-url.ts +30 -0
  60. package/src/relay-sw.ts +7 -0
  61. package/src/sw/http-sw-dispatcher.ts +122 -0
  62. package/src/sw/index.ts +2 -0
  63. package/src/sw/sw-dispatcher.ts +332 -0
  64. package/src/sw-worker.ts +7 -0
  65. package/src/sw.ts +1 -0
  66. package/CHANGELOG.md +0 -1
  67. package/LICENSE +0 -21
  68. package/demo/demo-2 copy.html +0 -598
  69. package/demo/demo-3.html +0 -167
  70. package/dist/index-sw-umd.js +0 -798
  71. package/dist/index-sw-umd.min.js +0 -2
  72. package/dist/index-sw.js +0 -791
  73. package/dist/index-sw.min.js +0 -2
  74. package/dist/index-umd.js +0 -853
  75. package/dist/index-umd.min.js +0 -2
  76. package/dist/index.min.js +0 -2
  77. package/index.js +0 -1
  78. package/src/core/data-calls.js +0 -36
  79. package/src/core/data-channels.js +0 -192
  80. package/src/core/data-send-recieve.js +0 -28
  81. package/src/core/errors.js +0 -13
  82. package/src/core/index.js +0 -4
  83. package/src/http/HttpError.js +0 -59
  84. package/src/http/http-send-recieve.js +0 -40
  85. package/src/http/http-stubs.js +0 -135
  86. package/src/http/index.js +0 -3
  87. package/src/http/readable-streams.js +0 -33
  88. package/src/index.js +0 -7
  89. package/src/relay/index-sw.js +0 -216
  90. package/src/relay/index.js +0 -263
  91. package/src/relay/splitServiceUrl.js +0 -24
  92. package/src/sw/http-sw-dispatcher.js +0 -128
  93. package/src/sw/sw-dispatcher.js +0 -264
package/dist/sw.js ADDED
@@ -0,0 +1,1883 @@
1
+ //#region ../webrun-streams/dist/index.js
2
+ function serializeError(error) {
3
+ if (error instanceof Error) {
4
+ const out = {
5
+ message: error.message,
6
+ stack: error.stack
7
+ };
8
+ const bag = error;
9
+ for (const key of Object.keys(bag)) out[key] = bag[key];
10
+ return out;
11
+ }
12
+ if (typeof error === "object" && error !== null) {
13
+ const bag = error;
14
+ return {
15
+ message: String(bag.message ?? error),
16
+ ...bag
17
+ };
18
+ }
19
+ return { message: String(error) };
20
+ }
21
+ function deserializeError(error) {
22
+ const payload = typeof error === "string" ? { message: error } : error;
23
+ return Object.assign(new Error(payload.message), payload);
24
+ }
25
+ new TextEncoder();
26
+ new TextDecoder();
27
+ /**
28
+ * The newAsyncGenerator function creates async generators from callback-based initialization
29
+ * functions, providing a bridge between imperative event handling and declarative async
30
+ * iteration patterns.
31
+ *
32
+ * The initialization function receives two callback functions that control the generator's
33
+ * behavior. The `next` function yields values to consumers, while the `done` function
34
+ * signals completion or error conditions. The initialization function can return a cleanup
35
+ * function that will be called when the generator is closed or an error occurs.
36
+ *
37
+ * The generator manages an internal queue of values and completion signals, ensuring that
38
+ * producers can yield values without overwhelming consumers. Proper backpressure is implemented
39
+ * by having the `next` and `done` functions return promises that resolve only after the
40
+ * consumer has processed the values. This prevents memory leaks and ensures that producers
41
+ * are aware of whether their values were successfully handled.
42
+ * The generator also handles cleanup by draining any remaining items in the queue and notifying
43
+ * producers that their values were not processed if the generator is closed early. This ensures
44
+ * that resources are properly managed and that no memory leaks occur.
45
+ *
46
+ * Example usage:
47
+ * ```typescript
48
+ * const asyncGen = newAsyncGenerator<number>((next, done) => {
49
+ * let count = 0;
50
+ * const interval = setInterval(() => {
51
+ * if (count < 5) {
52
+ * next(count++);
53
+ * } else {
54
+ * done();
55
+ * clearInterval(interval);
56
+ * }
57
+ * }, 1000);
58
+ * return () => clearInterval(interval); // Cleanup function
59
+ * });
60
+ * (async () => {
61
+ * for await (const num of asyncGen) {
62
+ * console.log(num); // Logs numbers 0 to 4 at 1 second intervals
63
+ * }
64
+ * console.log("Completed");
65
+ * })();
66
+ * ```
67
+ * @template T The type of values yielded by the generator
68
+ * @template E The type of errors that can be thrown; defaults to Error
69
+ * @param init Initialization function that sets up the generator behavior with next/done callbacks;
70
+ * The first parameter - `next` function - is used to yield values to consumers;
71
+ * It returns a Promise<boolean> indicating whether the value was successfully handled;
72
+ * The second parameter - `done` function - is used to signal completion or error;
73
+ * It returns a Promise<boolean> indicating whether the completion was successfully handled;
74
+ * The initialization function can optionally return a cleanup function that will be called
75
+ * when the generator is closed or an error occurs;
76
+ * @param skipValues If true, only the most recent value is kept in the queue,
77
+ * skipping intermediate values (not consumed values are considered skipped);
78
+ * This is useful for scenarios where only the latest value matters, such as UI updates.
79
+ * Defaults to false, meaning all values are queued and processed in order.
80
+ * @returns AsyncGenerator that properly manages backpressure and resource cleanup
81
+ */
82
+ async function* newAsyncGenerator(init, skipValues = false) {
83
+ let head;
84
+ let tail;
85
+ /** Flag to prevent new values from being queued after generator closes */
86
+ let closed = false;
87
+ /** Wake-up function to notify the generator loop of new items */
88
+ let wakeUp;
89
+ /**
90
+ * Drains the internal queue, notifying all pending producers that their values
91
+ * were not processed due to generator closure. This prevents memory leaks and
92
+ * ensures proper backpressure signaling.
93
+ */
94
+ const drainQueue = () => {
95
+ for (; head; head = head.next) {
96
+ closed = closed || head.done;
97
+ head.resolve(false);
98
+ }
99
+ tail = void 0;
100
+ };
101
+ /**
102
+ * Enqueues a value or completion signal with a promise that resolves when the item
103
+ * is processed. This enables backpressure by allowing producers to know when their
104
+ * values have been consumed.
105
+ */
106
+ const enqueue = (params) => {
107
+ if (skipValues) drainQueue();
108
+ return !closed ? new Promise((resolve) => {
109
+ const next = {
110
+ ...params,
111
+ next: void 0,
112
+ resolve
113
+ };
114
+ if (tail) tail.next = next;
115
+ tail = next;
116
+ if (!head) head = tail;
117
+ wakeUp?.();
118
+ }) : Promise.resolve(false);
119
+ };
120
+ /**
121
+ * Producer function to yield a value to consumers. Returns a promise that resolves
122
+ * to true if the value was successfully processed, false if the generator is closed
123
+ * or the value was skipped due to backpressure.
124
+ */
125
+ const next = (value) => enqueue({
126
+ done: false,
127
+ value
128
+ });
129
+ /**
130
+ * Producer function to signal completion or error. Optional error parameter will
131
+ * cause the generator to throw that error to consumers.
132
+ */
133
+ const done = (error) => enqueue({
134
+ done: true,
135
+ error
136
+ });
137
+ const unsubscribe = init(next, done);
138
+ try {
139
+ while (!closed) {
140
+ if (!head) {
141
+ await new Promise((resolve) => {
142
+ wakeUp = resolve;
143
+ }).then(() => {
144
+ wakeUp = void 0;
145
+ });
146
+ continue;
147
+ }
148
+ const slot = head;
149
+ head = head.next;
150
+ if (tail === slot) tail = head;
151
+ try {
152
+ if (slot.done) {
153
+ closed = true;
154
+ if (slot.error !== void 0) throw slot.error;
155
+ break;
156
+ }
157
+ yield slot.value;
158
+ } finally {
159
+ slot.resolve(true);
160
+ }
161
+ }
162
+ } finally {
163
+ /**
164
+ * Cleanup phase - ensures proper resource management and notification of any
165
+ * remaining producers. This runs whether the generator completes normally,
166
+ * encounters an error, or is closed early by the consumer.
167
+ */
168
+ closed = true;
169
+ wakeUp?.();
170
+ if (typeof unsubscribe === "function") await unsubscribe();
171
+ /**
172
+ * Drain any remaining items in the queue and notify their producers that
173
+ * the values were not processed. This prevents memory leaks and ensures
174
+ * proper backpressure signaling.
175
+ */
176
+ drainQueue();
177
+ }
178
+ }
179
+ new TextEncoder();
180
+ /**
181
+ * The iterator ↔ `ReadableStream` boundary.
182
+ *
183
+ * Both adapters must carry CANCELLATION, not just data: a response body leaves
184
+ * a handler as a `ReadableStream`, crosses a transport as an iterator, and
185
+ * becomes a `ReadableStream` again at the caller — so when the caller walks
186
+ * away, the only path back to the handler's producer runs through both of
187
+ * these functions. Teardown that stops at an adapter leaves a producer running
188
+ * for ever.
189
+ */
190
+ function toReadableStream(it) {
191
+ return new ReadableStream({
192
+ /**
193
+ * One chunk per pull. An earlier version drained the whole iterator inside
194
+ * a single `pull`, which defeated the stream's own backpressure (every
195
+ * chunk was enqueued as fast as the producer could make them, however slow
196
+ * the reader was) and left no point between chunks at which a cancellation
197
+ * could take effect.
198
+ */
199
+ async pull(controller) {
200
+ try {
201
+ const slot = await it.next();
202
+ if (!slot || slot.done) {
203
+ controller.close();
204
+ return;
205
+ }
206
+ controller.enqueue(await slot.value);
207
+ } catch (error) {
208
+ controller.error(error);
209
+ }
210
+ },
211
+ /**
212
+ * Release the source. NOT awaited: `.return()` on an async generator that
213
+ * is parked awaiting its own source is queued behind that pending
214
+ * `next()`, so awaiting it here would hang `reader.cancel()` on exactly
215
+ * the producers that most need cancelling.
216
+ */
217
+ cancel(reason) {
218
+ Promise.resolve(it.return?.(reason)).catch(() => {});
219
+ }
220
+ });
221
+ }
222
+ async function* fromReadableStream(stream) {
223
+ const reader = stream.getReader();
224
+ let drained = false;
225
+ try {
226
+ while (true) {
227
+ const { done, value } = await reader.read();
228
+ if (done) {
229
+ drained = true;
230
+ break;
231
+ }
232
+ if (value !== void 0) yield value;
233
+ }
234
+ } finally {
235
+ if (drained) reader.releaseLock();
236
+ else await reader.cancel().catch(() => {});
237
+ }
238
+ }
239
+ /**
240
+ * Inverse of {@link sendIterator}: turns a sequence of `{done, value, error}`
241
+ * chunks (delivered to the supplied callback by `installer`) into an async
242
+ * generator.
243
+ *
244
+ * The `installer` is given a `deliver` function. It should call `deliver`
245
+ * once for each incoming chunk and may return a cleanup callback that
246
+ * runs when the consumer stops iterating.
247
+ */
248
+ function recieveIterator(installer) {
249
+ return newAsyncGenerator((next, done) => {
250
+ const cleanup = installer(async (chunk = { done: true }) => {
251
+ const { done: isDone = true, value, error } = chunk;
252
+ if (error) return await done(error);
253
+ if (isDone) return await done();
254
+ return await next(value);
255
+ });
256
+ if (cleanup) return async () => {
257
+ await cleanup();
258
+ };
259
+ });
260
+ }
261
+ /**
262
+ * Drain an async iterator into a sink that consumes one chunk at a time.
263
+ *
264
+ * Each yielded value becomes `{ done: false, value }`. Completion emits
265
+ * `{ done: true }`. If the iterator throws, the error is caught and the
266
+ * final `done` chunk carries it so the peer can rethrow on its side.
267
+ */
268
+ async function sendIterator(send, it) {
269
+ let error;
270
+ try {
271
+ for await (const value of it) await send({
272
+ done: false,
273
+ value
274
+ });
275
+ } catch (err) {
276
+ error = err;
277
+ } finally {
278
+ await send({
279
+ done: true,
280
+ error
281
+ });
282
+ }
283
+ }
284
+ //#endregion
285
+ //#region ../webrun-http-streams/dist/index.js
286
+ const CR = 13;
287
+ const LF = 10;
288
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
289
+ var ByteStreamError = class extends Error {
290
+ name = "ByteStreamError";
291
+ };
292
+ function toAsyncIterator(input) {
293
+ const asyncIter = input[Symbol.asyncIterator];
294
+ if (asyncIter) return asyncIter.call(input);
295
+ const syncIter = input[Symbol.iterator]();
296
+ return { next() {
297
+ return Promise.resolve(syncIter.next());
298
+ } };
299
+ }
300
+ /**
301
+ * Discard an iterable we are contractually forbidden from consuming — a body
302
+ * skipped for HEAD/204, or one abandoned because the peer reported an error.
303
+ *
304
+ * The `.next()` is not optional: `.return()` on a generator still in suspended
305
+ * start is a no-op, so the body never runs and its `try/finally` never unwinds.
306
+ * Without it a wrapped ReadableStream or socket is never cancelled.
307
+ */
308
+ async function discard(source) {
309
+ if (source === void 0) return;
310
+ const it = toAsyncIterator(source);
311
+ try {
312
+ await it.next();
313
+ await it.return?.();
314
+ } catch {}
315
+ }
316
+ function concatChunks(parts, totalLen) {
317
+ if (parts.length === 1) {
318
+ const only = parts[0];
319
+ if (only !== void 0) return only;
320
+ }
321
+ const out = new Uint8Array(totalLen);
322
+ let off = 0;
323
+ for (const p of parts) {
324
+ out.set(p, off);
325
+ off += p.byteLength;
326
+ }
327
+ return out;
328
+ }
329
+ /**
330
+ * Pull-based reader over a byte source. Holds at most one pending buffer, and
331
+ * hands out `subarray` views rather than copies — a body never passes through
332
+ * an allocation here.
333
+ */
334
+ var ByteReader = class {
335
+ #iter;
336
+ #buf = EMPTY;
337
+ #done = false;
338
+ constructor(input) {
339
+ this.#iter = toAsyncIterator(input);
340
+ }
341
+ /** Bytes already pulled from the source but not yet consumed. */
342
+ bufferedLength() {
343
+ return this.#buf.byteLength;
344
+ }
345
+ /** Pull one more non-empty chunk. Returns false at end of stream. */
346
+ async #pull() {
347
+ if (this.#done) return false;
348
+ while (true) {
349
+ const next = await this.#iter.next();
350
+ if (next.done) {
351
+ this.#done = true;
352
+ return false;
353
+ }
354
+ const chunk = next.value;
355
+ if (chunk.byteLength === 0) continue;
356
+ this.#buf = this.#buf.byteLength === 0 ? chunk : concatChunks([this.#buf, chunk], this.#buf.byteLength + chunk.byteLength);
357
+ return true;
358
+ }
359
+ }
360
+ async peekByte() {
361
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
362
+ return this.#buf[0];
363
+ }
364
+ /** Up to `max` bytes. `undefined` means end of stream. */
365
+ async readSome(max) {
366
+ while (this.#buf.byteLength === 0) if (!await this.#pull()) return void 0;
367
+ const take = Math.min(max, this.#buf.byteLength);
368
+ const out = this.#buf.subarray(0, take);
369
+ this.#buf = this.#buf.subarray(take);
370
+ return out;
371
+ }
372
+ /**
373
+ * One CRLF-terminated line, without the CRLF. A bare LF is rejected: real
374
+ * peers always send CRLF, and tolerating a bare LF is precisely the lenience
375
+ * that lets request smuggling through a proxy pair.
376
+ *
377
+ * The `maxBytes` bound is best-effort: it only rejects a line if the check
378
+ * happens to run before the line is fully buffered. A line already sitting in
379
+ * the buffer bypasses the check. Callers needing a hard per-line limit or
380
+ * aggregate bounds must keep their own running total.
381
+ */
382
+ async readLine(maxBytes) {
383
+ let searched = 0;
384
+ while (true) {
385
+ const idx = this.#buf.indexOf(LF, searched);
386
+ if (idx !== -1) {
387
+ if (idx === 0 || this.#buf[idx - 1] !== CR) throw new ByteStreamError("bare LF line terminator; CRLF required");
388
+ const line = this.#buf.subarray(0, idx - 1);
389
+ this.#buf = this.#buf.subarray(idx + 1);
390
+ return line;
391
+ }
392
+ searched = this.#buf.byteLength;
393
+ if (searched > maxBytes) throw new ByteStreamError(`line exceeds ${maxBytes} bytes without CRLF`);
394
+ if (!await this.#pull()) throw new ByteStreamError(`stream ended after ${searched} bytes without CRLF`);
395
+ }
396
+ }
397
+ /** Everything not yet consumed, lazily. */
398
+ async *rest() {
399
+ while (true) {
400
+ if (this.#buf.byteLength > 0) {
401
+ const out = this.#buf;
402
+ this.#buf = EMPTY;
403
+ yield out;
404
+ continue;
405
+ }
406
+ if (!await this.#pull()) return;
407
+ }
408
+ }
409
+ };
410
+ /**
411
+ * Raised for any byte sequence this codec refuses to interpret. Every case is
412
+ * a refusal to guess: HTTP/1.1 parsers that guess are how request smuggling
413
+ * works.
414
+ */
415
+ var HttpParseError = class extends Error {
416
+ name = "HttpParseError";
417
+ };
418
+ const NEWLINE = 10;
419
+ /** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
420
+ const MAX_ENVELOPE_BYTES = 65536;
421
+ const encoder$1 = new TextEncoder();
422
+ const decoder = new TextDecoder();
423
+ /**
424
+ * Encode an HTTP envelope plus optional body as one continuous byte stream:
425
+ *
426
+ * <JSON.stringify(envelope)>\n<body bytes...>
427
+ *
428
+ * `JSON.stringify` with default whitespace never emits a literal `\n`, so the
429
+ * first `0x0a` byte unambiguously terminates the envelope.
430
+ *
431
+ * This is the same wire shape used by the legacy `webrun-http-port` package.
432
+ */
433
+ async function* encodeMessage(envelope, body) {
434
+ yield encoder$1.encode(`${JSON.stringify(envelope)}\n`);
435
+ if (!body) return;
436
+ for await (const chunk of body) if (chunk.byteLength > 0) yield chunk;
437
+ }
438
+ /**
439
+ * Consume an envelope-then-body byte stream. Returns the parsed envelope and
440
+ * an async iterable over the remaining body bytes.
441
+ */
442
+ async function decodeMessage(input) {
443
+ const iter = toAsyncIterator(input);
444
+ const accum = [];
445
+ let accumLen = 0;
446
+ let before;
447
+ let tail;
448
+ while (true) {
449
+ const next = await iter.next();
450
+ if (next.done) throw new HttpParseError(`decodeMessage: stream ended after ${accumLen} bytes without delimiter (\\n)`);
451
+ const chunk = next.value;
452
+ if (chunk.byteLength === 0) continue;
453
+ const nl = chunk.indexOf(NEWLINE);
454
+ if (nl === -1) {
455
+ accum.push(chunk);
456
+ accumLen += chunk.byteLength;
457
+ if (accumLen > MAX_ENVELOPE_BYTES) throw new HttpParseError(`decodeMessage: envelope exceeds ${MAX_ENVELOPE_BYTES} bytes without delimiter (\\n)`);
458
+ continue;
459
+ }
460
+ accum.push(chunk.subarray(0, nl));
461
+ accumLen += nl;
462
+ before = concatChunks(accum, accumLen);
463
+ tail = chunk.subarray(nl + 1);
464
+ break;
465
+ }
466
+ let envelope;
467
+ try {
468
+ envelope = JSON.parse(decoder.decode(before));
469
+ } catch (err) {
470
+ throw new HttpParseError(`decodeMessage: malformed envelope JSON at bytes 0..${before.byteLength}: ${err.message}`);
471
+ }
472
+ async function* body() {
473
+ if (tail.byteLength > 0) yield tail;
474
+ while (true) {
475
+ const next = await iter.next();
476
+ if (next.done) return;
477
+ if (next.value.byteLength > 0) yield next.value;
478
+ }
479
+ }
480
+ return {
481
+ envelope,
482
+ body: body()
483
+ };
484
+ }
485
+ const OPEN_BRACE = 123;
486
+ /**
487
+ * The original wire format — `<JSON.stringify(envelope)>\n<body bytes…>` —
488
+ * expressed as a `MessageCodec`. Direction-agnostic: requests and responses
489
+ * serialise identically.
490
+ *
491
+ * Retained so a peer pair can be upgraded in either order; see ADR-0006.
492
+ */
493
+ const jsonEnvelopeCodec = {
494
+ name: "json-envelope",
495
+ sniff: (byte) => byte === OPEN_BRACE,
496
+ encodeRequest: (env, body) => encodeMessage(env, body),
497
+ encodeResponse: (env, body) => encodeMessage(env, body),
498
+ decodeRequest: (input) => decodeMessage(input),
499
+ decodeResponse: (input) => decodeMessage(input)
500
+ };
501
+ const TCHAR = /* @__PURE__ */ new Set("!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
502
+ const SP = 32;
503
+ const HTAB = 9;
504
+ function isTokenChar(byte) {
505
+ return byte > SP && byte < 127 && TCHAR.has(String.fromCharCode(byte));
506
+ }
507
+ function isToken(value) {
508
+ if (value.length === 0) return false;
509
+ for (const ch of value) if (!TCHAR.has(ch)) return false;
510
+ return true;
511
+ }
512
+ /**
513
+ * Header bytes are latin-1: byte-preserving, matching Node, and lossless
514
+ * across a decode/encode round-trip. Control characters are rejected
515
+ * separately by `assertValidHeaderValue`.
516
+ */
517
+ function decodeLatin1(bytes) {
518
+ let out = "";
519
+ for (const byte of bytes) out += String.fromCharCode(byte);
520
+ return out;
521
+ }
522
+ function encodeLatin1(text) {
523
+ const out = new Uint8Array(text.length);
524
+ for (let i = 0; i < text.length; i++) {
525
+ const code = text.charCodeAt(i);
526
+ if (code > 255) throw new HttpParseError(`not latin-1 encodable: ${JSON.stringify(text)}`);
527
+ out[i] = code;
528
+ }
529
+ return out;
530
+ }
531
+ const HOST_IP_LITERAL = /^\[[0-9A-Fa-f:.]+\](:\d{1,5})?$/;
532
+ const HOST_REG_NAME = /^[A-Za-z0-9._~-]+(:\d{1,5})?$/;
533
+ /**
534
+ * Validates a value that is about to become (or was read as) a `Host`
535
+ * header: untrusted input either way, so an unrecognised shape is a refusal,
536
+ * not a guess. Rejects a present-but-empty value, one carrying userinfo
537
+ * (`evil.com@good.com`), and — the reason this also runs on encode — one
538
+ * smuggling a CRLF-terminated line into the authority of a caller-supplied
539
+ * url. Never applied to trusted configuration (a codec's `opts.host`).
540
+ */
541
+ function assertValidHost(host) {
542
+ if (!HOST_IP_LITERAL.test(host) && !HOST_REG_NAME.test(host)) throw new HttpParseError(`invalid Host header: ${JSON.stringify(host)}`);
543
+ }
544
+ /**
545
+ * A request-target must be entirely visible ASCII (RFC 9110 VCHAR) — nothing
546
+ * `<= 0x20` (space and every control character, CR/LF included) and nothing
547
+ * `>= 0x7F` (DEL and beyond). Applied on encode (`splitTarget`, so a
548
+ * caller-supplied url can never inject a second request line) and on decode
549
+ * (so a relay that decodes then re-encodes can never put an embedded control
550
+ * character back on the wire).
551
+ */
552
+ function assertValidTarget(target) {
553
+ for (let i = 0; i < target.length; i++) {
554
+ const code = target.charCodeAt(i);
555
+ if (code <= SP || code >= 127) throw new HttpParseError(`invalid request-target: ${JSON.stringify(target)}`);
556
+ }
557
+ }
558
+ /**
559
+ * Shared control-character check behind both `assertValidHeaderValue` and
560
+ * `assertValidStatusText` — the two were previously checked by different,
561
+ * looser rules (statusText only rejected CR/LF), which is exactly the
562
+ * asymmetry class C1 and M5 are both instances of. `label` is prepended
563
+ * verbatim to each message, so callers keep their own wording.
564
+ */
565
+ function assertNoControlChars(label, value) {
566
+ for (let i = 0; i < value.length; i++) {
567
+ const code = value.charCodeAt(i);
568
+ if (code === 13 || code === 10) throw new HttpParseError(`${label} contains CR or LF`);
569
+ if (code < SP && code !== HTAB || code === 127) throw new HttpParseError(`${label} contains a control character`);
570
+ if (code > 255) throw new HttpParseError(`${label} is not latin-1 encodable`);
571
+ }
572
+ }
573
+ function assertValidHeaderValue(name, value) {
574
+ assertNoControlChars(`header "${name}" value`, value);
575
+ }
576
+ /** Same character class as a header value (M5) — CR/LF, every C0 control, and DEL. */
577
+ function assertValidStatusText(value) {
578
+ assertNoControlChars("statusText", value);
579
+ }
580
+ function encodeHeaderLines(headers) {
581
+ let out = "";
582
+ for (const [name, value] of headers) {
583
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
584
+ assertValidHeaderValue(name, value);
585
+ out += `${name}: ${value}\r\n`;
586
+ }
587
+ return out;
588
+ }
589
+ /**
590
+ * Read to the blank line. `alreadyUsed` is the byte count of the start line,
591
+ * so the bound covers the whole head section rather than the headers alone.
592
+ */
593
+ async function readHeaderSection(reader, maxHeaderBytes, alreadyUsed) {
594
+ const headers = [];
595
+ let used = alreadyUsed;
596
+ while (true) {
597
+ const remaining = maxHeaderBytes - used;
598
+ if (remaining <= 0) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
599
+ const lineBytes = await reader.readLine(remaining);
600
+ used += lineBytes.byteLength + 2;
601
+ if (used > maxHeaderBytes) throw new HttpParseError(`head section exceeds ${maxHeaderBytes} bytes`);
602
+ if (lineBytes.byteLength === 0) return headers;
603
+ if (lineBytes[0] === SP || lineBytes[0] === HTAB) throw new HttpParseError("obs-fold header continuation is not accepted");
604
+ const line = decodeLatin1(lineBytes);
605
+ const colon = line.indexOf(":");
606
+ if (colon <= 0) throw new HttpParseError(`malformed header line: ${JSON.stringify(line)}`);
607
+ const name = line.slice(0, colon);
608
+ if (!isToken(name)) throw new HttpParseError(`invalid header name: ${JSON.stringify(name)}`);
609
+ const value = line.slice(colon + 1).replace(/^[ \t]+/, "").replace(/[ \t]+$/, "");
610
+ assertValidHeaderValue(name, value);
611
+ headers.push([name, value]);
612
+ }
613
+ }
614
+ function getAll(headers, name) {
615
+ const lower = name.toLowerCase();
616
+ return headers.filter(([k]) => k.toLowerCase() === lower).map(([, v]) => v);
617
+ }
618
+ function withoutHeaders(headers, names) {
619
+ const drop = new Set(names.map((n) => n.toLowerCase()));
620
+ return headers.filter(([k]) => !drop.has(k.toLowerCase()));
621
+ }
622
+ /**
623
+ * Parse a `Content-Length` field into a single validated value.
624
+ *
625
+ * RFC 9110 §8.6 permits the value to be a comma-separated list of identical
626
+ * numbers (a relay may have appended one), so the list is folded; differing
627
+ * values are a refusal, not a choice. Shared by `resolveFraming` on decode and
628
+ * by the encoder's declared-length check, which previously carried its own
629
+ * copy that did NOT split on commas — so decode accepted `5, 5` while encode
630
+ * rejected it, and a relay that decoded then re-encoded threw.
631
+ *
632
+ * Returns undefined when the field is absent.
633
+ */
634
+ function parseContentLength(values) {
635
+ if (values.length === 0) return void 0;
636
+ const unique = new Set(values.flatMap((v) => v.split(",").map((s) => s.trim())));
637
+ if (unique.size !== 1) throw new HttpParseError(`conflicting Content-Length values: ${[...unique].join(", ")}`);
638
+ const raw = [...unique][0];
639
+ if (!/^\d{1,15}$/.test(raw)) throw new HttpParseError(`invalid Content-Length: ${JSON.stringify(raw)}`);
640
+ return Number(raw);
641
+ }
642
+ /**
643
+ * Statuses that carry no body whatever the headers say (RFC 9110 §8.6): 1xx,
644
+ * 204 and 304. Defined once because the encoder must not frame a body for
645
+ * them and the decoder must not try to read one — two lists that agreed today
646
+ * and were free to drift tomorrow.
647
+ *
648
+ * A response to HEAD is also bodyless, but that depends on the request rather
649
+ * than the status, so callers test it separately.
650
+ */
651
+ function isBodylessStatus(status) {
652
+ return status < 200 || status === 204 || status === 304;
653
+ }
654
+ /**
655
+ * RFC 9112 §6.3, with every ambiguity turned into a refusal. In particular a
656
+ * message declaring both Content-Length and Transfer-Encoding is rejected
657
+ * rather than resolved — disagreeing on which one wins is request smuggling.
658
+ */
659
+ function resolveFraming(headers, version) {
660
+ const te = getAll(headers, "transfer-encoding");
661
+ const cl = getAll(headers, "content-length");
662
+ if (te.length > 0 && cl.length > 0) throw new HttpParseError("message declares both Content-Length and Transfer-Encoding; refusing (request smuggling)");
663
+ if (te.length > 0) {
664
+ const encodings = te.join(",").split(",").map((s) => s.trim().toLowerCase()).filter((s) => s !== "");
665
+ if (encodings.length !== 1 || encodings[0] !== "chunked") throw new HttpParseError(`unsupported Transfer-Encoding: ${JSON.stringify(te.join(", "))}`);
666
+ if (version === "HTTP/1.0") throw new HttpParseError("Transfer-Encoding is not valid in HTTP/1.0");
667
+ return { kind: "chunked" };
668
+ }
669
+ const length = parseContentLength(cl);
670
+ if (length !== void 0) return {
671
+ kind: "length",
672
+ length
673
+ };
674
+ return { kind: "none" };
675
+ }
676
+ const CRLF = new Uint8Array([13, 10]);
677
+ const LAST_CHUNK = new Uint8Array([
678
+ 48,
679
+ 13,
680
+ 10,
681
+ 13,
682
+ 10
683
+ ]);
684
+ const encoder = new TextEncoder();
685
+ /**
686
+ * Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
687
+ * them in decimal is the defect note 15 found in @libp2p/http, and it is the
688
+ * one that cannot be caught downstream: decimal digits are also valid hex, so
689
+ * a conforming parser silently reads the wrong length.
690
+ *
691
+ * Zero-length source chunks are skipped; a zero-sized chunk on the wire is the
692
+ * body terminator.
693
+ */
694
+ async function* encodeChunked(body) {
695
+ for await (const chunk of body) {
696
+ if (chunk.byteLength === 0) continue;
697
+ yield encoder.encode(`${chunk.byteLength.toString(16)}\r\n`);
698
+ yield chunk;
699
+ yield CRLF;
700
+ }
701
+ yield LAST_CHUNK;
702
+ }
703
+ /**
704
+ * Decode a chunked body, yielding data chunks as they arrive. Nothing is
705
+ * accumulated: a chunk larger than the transport's frame is yielded in pieces.
706
+ */
707
+ async function* decodeChunked(reader, maxLineBytes) {
708
+ while (true) {
709
+ const sizeLine = decodeLatin1(await reader.readLine(maxLineBytes));
710
+ const semicolon = sizeLine.indexOf(";");
711
+ const sizeText = semicolon === -1 ? sizeLine : sizeLine.slice(0, semicolon);
712
+ if (!/^[0-9a-fA-F]{1,32}$/.test(sizeText)) throw new HttpParseError(`invalid chunk size: ${JSON.stringify(sizeLine)}`);
713
+ const size = Number.parseInt(sizeText, 16);
714
+ if (!Number.isSafeInteger(size)) throw new HttpParseError(`chunk size is too large: ${JSON.stringify(sizeLine)}`);
715
+ if (size === 0) {
716
+ let used = 0;
717
+ while (true) {
718
+ const remaining = maxLineBytes - used;
719
+ if (remaining <= 0) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
720
+ const lineBytes = await reader.readLine(remaining);
721
+ used += lineBytes.byteLength + 2;
722
+ if (used > maxLineBytes) throw new HttpParseError(`trailer section exceeds ${maxLineBytes} bytes`);
723
+ if (lineBytes.byteLength === 0) break;
724
+ }
725
+ return;
726
+ }
727
+ let remaining = size;
728
+ while (remaining > 0) {
729
+ const part = await reader.readSome(remaining);
730
+ if (part === void 0) throw new HttpParseError(`chunk truncated: ${remaining} of ${size} bytes missing`);
731
+ remaining -= part.byteLength;
732
+ yield part;
733
+ }
734
+ try {
735
+ if ((await reader.readLine(2)).byteLength !== 0) throw new HttpParseError("chunk data not terminated by CRLF");
736
+ } catch (err) {
737
+ if (err instanceof ByteStreamError) throw new HttpParseError("chunk data not terminated by CRLF");
738
+ throw err;
739
+ }
740
+ }
741
+ }
742
+ const VERSIONS = /* @__PURE__ */ new Set(["HTTP/1.1", "HTTP/1.0"]);
743
+ const ABSOLUTE_FORM = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
744
+ /**
745
+ * One message per Duplex call (ADR-0006), so bytes after a complete message
746
+ * are an error. Checked against what is ALREADY BUFFERED rather than by
747
+ * awaiting end-of-stream: a live socket from a keep-alive peer never reaches
748
+ * EOF, so awaiting one would hang instead of failing.
749
+ */
750
+ function assertNoBufferedBytes(reader) {
751
+ const extra = reader.bufferedLength();
752
+ if (extra > 0) throw new HttpParseError(`${extra} trailing bytes after a complete message`);
753
+ }
754
+ /**
755
+ * The public error contract (I2): everything leaving `decodeRequest` /
756
+ * `decodeResponse` is an `HttpParseError`, whether the refusal happened
757
+ * synchronously (a malformed start line or header) or lazily while the body
758
+ * is later drained. `ByteStreamError` — the `ByteReader`'s own class, never
759
+ * exported — is the one thing converted here, message and all preserved via
760
+ * `cause`. Anything else is a genuine failure of the underlying source (a
761
+ * dropped socket, say) and must reach the caller unchanged: blanket-catching
762
+ * would hide that distinction.
763
+ */
764
+ function toHttpParseError(err) {
765
+ if (err instanceof ByteStreamError) throw new HttpParseError(err.message, { cause: err });
766
+ throw err;
767
+ }
768
+ /** Applies `toHttpParseError` across the whole lifetime of a body generator. */
769
+ async function* convertBodyErrors(source) {
770
+ try {
771
+ yield* source;
772
+ } catch (err) {
773
+ toHttpParseError(err);
774
+ }
775
+ }
776
+ async function* readBody(reader, framing, opts, noneMeansEof) {
777
+ if (framing.kind === "chunked") {
778
+ yield* decodeChunked(reader, opts.maxHeaderBytes);
779
+ assertNoBufferedBytes(reader);
780
+ return;
781
+ }
782
+ if (framing.kind === "length") {
783
+ let remaining = framing.length;
784
+ while (remaining > 0) {
785
+ const part = await reader.readSome(remaining);
786
+ if (part === void 0) throw new HttpParseError(`body truncated: ${remaining} of ${framing.length} bytes missing`);
787
+ remaining -= part.byteLength;
788
+ yield part;
789
+ }
790
+ assertNoBufferedBytes(reader);
791
+ return;
792
+ }
793
+ if (noneMeansEof) {
794
+ yield* reader.rest();
795
+ return;
796
+ }
797
+ assertNoBufferedBytes(reader);
798
+ }
799
+ /**
800
+ * `readLine`'s bound is best-effort — it is skipped when the line is already
801
+ * buffered — so a very long start line can reach these messages intact. Since
802
+ * a refusal is now echoed back to the sender in a 400 body, quote only enough
803
+ * to diagnose rather than reflecting the whole thing.
804
+ */
805
+ function quoteLine(line) {
806
+ const MAX = 120;
807
+ return line.length <= MAX ? JSON.stringify(line) : `${JSON.stringify(line.slice(0, MAX))} (truncated from ${line.length} chars)`;
808
+ }
809
+ async function decodeRequest(input, opts) {
810
+ const reader = new ByteReader(input);
811
+ try {
812
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
813
+ const startLine = decodeLatin1(startBytes);
814
+ const parts = startLine.split(" ");
815
+ if (parts.length !== 3) throw new HttpParseError(`malformed request line: ${quoteLine(startLine)}`);
816
+ const [method, target, version] = parts;
817
+ if (!isToken(method)) throw new HttpParseError(`invalid method: ${JSON.stringify(method)}`);
818
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
819
+ if (target === "*") throw new HttpParseError("asterisk-form request target is not supported");
820
+ assertValidTarget(target);
821
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
822
+ const hosts = getAll(headers, "host");
823
+ if (hosts.length > 1) throw new HttpParseError("multiple Host headers");
824
+ const host = hosts[0];
825
+ let url;
826
+ if (target.startsWith("/")) {
827
+ if (version === "HTTP/1.1" && host === void 0) throw new HttpParseError("HTTP/1.1 request has no Host header");
828
+ if (host !== void 0) assertValidHost(host);
829
+ url = `${opts.scheme}://${host ?? opts.host}${target}`;
830
+ } else if (ABSOLUTE_FORM.test(target)) url = target;
831
+ else throw new HttpParseError(`unsupported request target: ${JSON.stringify(target)}`);
832
+ try {
833
+ new URL(url);
834
+ } catch {
835
+ throw new HttpParseError(`decoded url is not a valid URL: ${JSON.stringify(url)}`);
836
+ }
837
+ return {
838
+ envelope: {
839
+ url,
840
+ method,
841
+ headers
842
+ },
843
+ body: convertBodyErrors(readBody(reader, resolveFraming(headers, version), opts, false))
844
+ };
845
+ } catch (err) {
846
+ toHttpParseError(err);
847
+ }
848
+ }
849
+ async function decodeResponse(input, opts, method) {
850
+ const reader = new ByteReader(input);
851
+ try {
852
+ const startBytes = await reader.readLine(opts.maxHeaderBytes);
853
+ const startLine = decodeLatin1(startBytes);
854
+ const firstSp = startLine.indexOf(" ");
855
+ if (firstSp === -1) throw new HttpParseError(`malformed status line: ${quoteLine(startLine)}`);
856
+ const version = startLine.slice(0, firstSp);
857
+ if (!VERSIONS.has(version)) throw new HttpParseError(`unsupported HTTP version: ${JSON.stringify(version)}`);
858
+ const afterVersion = startLine.slice(firstSp + 1);
859
+ const secondSp = afterVersion.indexOf(" ");
860
+ const codeText = secondSp === -1 ? afterVersion : afterVersion.slice(0, secondSp);
861
+ if (!/^\d{3}$/.test(codeText)) throw new HttpParseError(`invalid status code: ${JSON.stringify(codeText)}`);
862
+ const status = Number(codeText);
863
+ const statusText = secondSp === -1 ? "" : afterVersion.slice(secondSp + 1);
864
+ const headers = await readHeaderSection(reader, opts.maxHeaderBytes, startBytes.byteLength + 2);
865
+ const bodyless = isBodylessStatus(status) || method.toUpperCase() === "HEAD";
866
+ const framing = bodyless ? { kind: "none" } : resolveFraming(headers, version);
867
+ return {
868
+ envelope: {
869
+ status,
870
+ statusText,
871
+ headers
872
+ },
873
+ body: convertBodyErrors(readBody(reader, framing, opts, !bodyless))
874
+ };
875
+ } catch (err) {
876
+ toHttpParseError(err);
877
+ }
878
+ }
879
+ /** Headers the codec owns: a caller-supplied copy is dropped and re-derived. */
880
+ const REQUEST_OWNED = [
881
+ "host",
882
+ "connection",
883
+ "transfer-encoding"
884
+ ];
885
+ const RESPONSE_OWNED = ["connection", "transfer-encoding"];
886
+ /**
887
+ * Split a URL into an origin-form request target and an authority *without*
888
+ * going through `new URL()`. `URL` normalises percent-encoding and would
889
+ * re-serialise the target — which is the exact class of defect note 15 found
890
+ * in @libp2p/http, where rebuilding the request line silently dropped
891
+ * `url.search`. Here the target is a verbatim slice of the caller's string.
892
+ */
893
+ function splitTarget(url, opts) {
894
+ if (url.startsWith("/")) {
895
+ assertValidTarget(url);
896
+ return {
897
+ target: url,
898
+ authority: opts.host
899
+ };
900
+ }
901
+ const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/([^/?#]*)([^#]*)/.exec(url);
902
+ if (!match) throw new HttpParseError(`cannot derive a request target from url: ${JSON.stringify(url)}`);
903
+ const rawAuthority = match[1];
904
+ if (rawAuthority === "") throw new HttpParseError(`url has no authority: ${JSON.stringify(url)}`);
905
+ const at = rawAuthority.lastIndexOf("@");
906
+ const authority = at === -1 ? rawAuthority : rawAuthority.slice(at + 1);
907
+ assertValidHost(authority);
908
+ const rawTarget = match[2];
909
+ const target = rawTarget === "" ? "/" : rawTarget.startsWith("/") ? rawTarget : `/${rawTarget}`;
910
+ assertValidTarget(target);
911
+ return {
912
+ target,
913
+ authority
914
+ };
915
+ }
916
+ async function* emitBody(body, declared) {
917
+ if (declared === void 0) {
918
+ yield* encodeChunked(body);
919
+ return;
920
+ }
921
+ let sent = 0;
922
+ for await (const chunk of body) {
923
+ if (chunk.byteLength === 0) continue;
924
+ sent += chunk.byteLength;
925
+ if (sent > declared) throw new HttpParseError(`body exceeds declared Content-Length ${declared} (${sent} bytes so far)`);
926
+ yield chunk;
927
+ }
928
+ if (sent !== declared) throw new HttpParseError(`body is ${sent} bytes but Content-Length declares ${declared}`);
929
+ }
930
+ async function* encodeRequest(env, body, opts) {
931
+ if (!isToken(env.method)) throw new HttpParseError(`invalid method: ${JSON.stringify(env.method)}`);
932
+ const { target, authority } = splitTarget(env.url, opts);
933
+ if (authority === "") throw new HttpParseError("no Host available: url has no authority and no host is configured");
934
+ const carried = withoutHeaders(env.headers, REQUEST_OWNED);
935
+ const declared = parseContentLength(getAll(carried, "content-length"));
936
+ let head = `${env.method} ${target} HTTP/1.1\r\n`;
937
+ head += `Host: ${authority}\r\n`;
938
+ head += encodeHeaderLines(carried);
939
+ head += "Connection: close\r\n";
940
+ if (body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
941
+ head += "\r\n";
942
+ yield encodeLatin1(head);
943
+ if (body === void 0) {
944
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
945
+ return;
946
+ }
947
+ yield* emitBody(body, declared);
948
+ }
949
+ async function* encodeResponse(env, body, _opts, requestMethod) {
950
+ if (!Number.isInteger(env.status) || env.status < 100 || env.status > 599) throw new HttpParseError(`invalid status: ${env.status}`);
951
+ const reason = env.statusText ?? "";
952
+ assertValidStatusText(reason);
953
+ const bodylessStatus = isBodylessStatus(env.status);
954
+ const bodyless = bodylessStatus || requestMethod?.toUpperCase() === "HEAD";
955
+ const owned = bodylessStatus ? [...RESPONSE_OWNED, "content-length"] : RESPONSE_OWNED;
956
+ const carried = withoutHeaders(env.headers, owned);
957
+ const declared = parseContentLength(getAll(carried, "content-length"));
958
+ let head = `HTTP/1.1 ${env.status} ${reason}\r\n`;
959
+ head += encodeHeaderLines(carried);
960
+ head += "Connection: close\r\n";
961
+ if (!bodyless && body !== void 0 && declared === void 0) head += "Transfer-Encoding: chunked\r\n";
962
+ head += "\r\n";
963
+ yield encodeLatin1(head);
964
+ if (bodyless) {
965
+ await discard(body);
966
+ return;
967
+ }
968
+ if (body === void 0) {
969
+ if (declared !== void 0 && declared !== 0) throw new HttpParseError(`body is 0 bytes but Content-Length declares ${declared}`);
970
+ return;
971
+ }
972
+ yield* emitBody(body, declared);
973
+ }
974
+ function newHttpCodec(options = {}) {
975
+ const opts = {
976
+ scheme: options.scheme ?? "http",
977
+ host: options.host ?? "localhost",
978
+ maxHeaderBytes: options.maxHeaderBytes ?? 65536
979
+ };
980
+ return {
981
+ name: "http/1.1",
982
+ sniff: (byte) => isTokenChar(byte),
983
+ encodeRequest: (env, body) => encodeRequest(env, body, opts),
984
+ encodeResponse: (env, body, o) => encodeResponse(env, body, opts, o?.method),
985
+ decodeRequest: (input) => decodeRequest(input, opts),
986
+ decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
987
+ };
988
+ }
989
+ const httpCodec = newHttpCodec();
990
+ /**
991
+ * Dispatches on byte 0. The formats are self-identifying — a JSON envelope
992
+ * always begins `{`, which is not a token character and so can never begin an
993
+ * HTTP start-line — so no negotiation handshake, magic prefix, or version byte
994
+ * is needed.
995
+ *
996
+ * This is what makes a mixed-version peer pair safe: readers accept either
997
+ * format, so the two ends can be upgraded in any order.
998
+ */
999
+ function newSniffingCodec(options) {
1000
+ const { write, accept } = options;
1001
+ async function pick(input) {
1002
+ const reader = new ByteReader(input);
1003
+ const first = await reader.peekByte();
1004
+ if (first === void 0) throw new HttpParseError("sniff: stream ended before any bytes arrived");
1005
+ const codec = accept.find((c) => c.sniff(first));
1006
+ if (!codec) throw new HttpParseError(`sniff: no accepted codec recognises a message starting with byte 0x${first.toString(16).padStart(2, "0")}`);
1007
+ return {
1008
+ codec,
1009
+ input: reader.rest()
1010
+ };
1011
+ }
1012
+ return {
1013
+ name: `sniff(write=${write.name}; accept=${accept.map((c) => c.name).join(",")})`,
1014
+ sniff: (byte) => accept.some((c) => c.sniff(byte)),
1015
+ encodeRequest: (env, body) => write.encodeRequest(env, body),
1016
+ encodeResponse: (env, body, o) => write.encodeResponse(env, body, o),
1017
+ decodeRequest: async (input) => {
1018
+ const picked = await pick(input);
1019
+ try {
1020
+ return {
1021
+ ...await picked.codec.decodeRequest(picked.input),
1022
+ codec: picked.codec
1023
+ };
1024
+ } catch (error) {
1025
+ if (error !== null && typeof error === "object") error.codec = picked.codec;
1026
+ throw error;
1027
+ }
1028
+ },
1029
+ decodeResponse: async (input, o) => {
1030
+ const picked = await pick(input);
1031
+ return picked.codec.decodeResponse(picked.input, o);
1032
+ }
1033
+ };
1034
+ }
1035
+ newSniffingCodec({
1036
+ write: httpCodec,
1037
+ accept: [httpCodec, jsonEnvelopeCodec]
1038
+ });
1039
+ /**
1040
+ * The one place that knows a runtime may not implement request body streams,
1041
+ * and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
1042
+ * carry a client and a server direction that must agree on the answer, so the
1043
+ * predicate lives here rather than being written out four times.
1044
+ */
1045
+ /**
1046
+ * Whether `Request.prototype` exposes a `body` accessor. Two call sites read
1047
+ * that property, and two more depend on the constructor accepting a
1048
+ * `ReadableStream` as `init.body`; this predicate answers for all four.
1049
+ *
1050
+ * What was verified, and all that is claimed here: Firefox (146 at the time of
1051
+ * writing) has *neither*, and Chromium and Node have *both*. On Firefox it is
1052
+ * not that `body` is `undefined` on the instance —
1053
+ * `Object.getOwnPropertyDescriptor(Request.prototype, "body")` is `null`, the
1054
+ * accessor is genuinely absent — and because a `ReadableStream` is then not a
1055
+ * recognised `BodyInit`, the constructor falls through to the string branch and
1056
+ * stores the literal text `[object ReadableStream]`.
1057
+ *
1058
+ * The two halves are NOT guaranteed to ship together, so do not read this as a
1059
+ * test for "request streams" in general. Safari is the counterexample: it has
1060
+ * had `Request.body` since 11.1 but only accepts a stream as `init.body` from
1061
+ * Technology Preview 250, so a shipping Safari has the reader half without the
1062
+ * upload half and this returns `true` there. That looks benign — WebKit appears
1063
+ * to store the stream on the `Request` rather than stringify it, and its error
1064
+ * comes from `fetch()`, which this package never calls on the objects it builds
1065
+ * — but it is untested, and it is the case to look at first if a Safari report
1066
+ * arrives. The sharper probe, if one is ever needed, is whether
1067
+ * `new Request(url, {method:"POST", body:new ReadableStream(), duplex:"half"})`
1068
+ * has a `content-type` of `text/plain;charset=UTF-8` (stringified) or `null`
1069
+ * (stored); it is not used here because it costs a `Request` and a
1070
+ * `ReadableStream` per call and agrees with the descriptor check on every
1071
+ * runtime measured.
1072
+ *
1073
+ * A capability check, never a user-agent test: the question is what this
1074
+ * runtime does, and the answer flips on its own the day Firefox ships request
1075
+ * streams. Evaluated per call rather than cached at module load so that a test
1076
+ * can install a `Request` without the capability and exercise the real branch
1077
+ * under Node.
1078
+ */
1079
+ function supportsRequestStreams() {
1080
+ return typeof Request === "function" && Object.getOwnPropertyDescriptor(Request.prototype, "body") != null;
1081
+ }
1082
+ /**
1083
+ * Drain a body iterable into one contiguous buffer. Only the fallbacks need it.
1084
+ * Allocates its own buffer rather than reusing `bytes.ts`'s `concatChunks`,
1085
+ * which passes a single chunk straight through: that chunk is a view onto the
1086
+ * decoder's own read buffer, and the result here is handed to `new Request` and
1087
+ * outlives the decode. The allocation is also what makes it a
1088
+ * `Uint8Array<ArrayBuffer>`, which `BodyInit` accepts and the looser
1089
+ * `Uint8Array<ArrayBufferLike>` does not.
1090
+ */
1091
+ async function collectBytes(source) {
1092
+ const parts = [];
1093
+ let total = 0;
1094
+ for await (const chunk of source) {
1095
+ if (chunk.byteLength === 0) continue;
1096
+ parts.push(chunk);
1097
+ total += chunk.byteLength;
1098
+ }
1099
+ const out = new Uint8Array(total);
1100
+ let offset = 0;
1101
+ for (const part of parts) {
1102
+ out.set(part, offset);
1103
+ offset += part.byteLength;
1104
+ }
1105
+ return out;
1106
+ }
1107
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
1108
+ 101,
1109
+ 103,
1110
+ 204,
1111
+ 205,
1112
+ 304
1113
+ ]);
1114
+ const REQUEST_FIELDS = [
1115
+ "url",
1116
+ "method",
1117
+ "mode",
1118
+ "credentials",
1119
+ "cache",
1120
+ "redirect",
1121
+ "referrer",
1122
+ "referrerPolicy",
1123
+ "integrity",
1124
+ "keepalive"
1125
+ ];
1126
+ /** `SerializedHttpEnvelope.content` is never absent, only empty. */
1127
+ async function* noBytes() {}
1128
+ async function* oneChunk(chunk) {
1129
+ yield chunk;
1130
+ }
1131
+ /**
1132
+ * Returns an HTTP handler that serializes a Request, hands the envelope to
1133
+ * `send` for transport, and deserializes the reply into a Response. Used on
1134
+ * the caller side.
1135
+ */
1136
+ function newHttpClientStub(send) {
1137
+ return async (requestOrPromise) => {
1138
+ const request = await requestOrPromise;
1139
+ const headers = [...request.headers].map(([k, v]) => [k, v]);
1140
+ const options = {
1141
+ url: request.url,
1142
+ headers
1143
+ };
1144
+ for (const field of REQUEST_FIELDS) {
1145
+ const val = request[field];
1146
+ if (val !== void 0 && field !== "url") options[field] = val;
1147
+ }
1148
+ let content;
1149
+ if (request.body != null) content = fromReadableStream(request.body);
1150
+ else if (!supportsRequestStreams()) content = oneChunk(new Uint8Array(await request.arrayBuffer()));
1151
+ else content = noBytes();
1152
+ const result = await send({
1153
+ options,
1154
+ content
1155
+ });
1156
+ if (!result) return new Response(null, {
1157
+ status: 404,
1158
+ statusText: "Error 404: Not Found"
1159
+ });
1160
+ const responseOptions = result.options;
1161
+ const method = options.method;
1162
+ if (method === "HEAD" || method === "OPTIONS" || NULL_BODY_STATUSES.has(responseOptions.status)) {
1163
+ await discard(result.content);
1164
+ return new Response(null, responseOptions);
1165
+ }
1166
+ return new Response(toReadableStream(result.content[Symbol.asyncIterator]()), responseOptions);
1167
+ };
1168
+ }
1169
+ /**
1170
+ * Returns a server-side transport handler. It deserializes the incoming
1171
+ * request envelope, delegates to `handler`, and serializes the response.
1172
+ */
1173
+ function newHttpServerStub(handler) {
1174
+ return async (envelopeOrPromise) => {
1175
+ const { options, content } = await envelopeOrPromise;
1176
+ const { url, method, headers = [], ...rest } = options;
1177
+ const { mode: _mode, ...forwardable } = rest;
1178
+ const requestHeaders = new Headers();
1179
+ for (const [key, value] of headers) requestHeaders.append(key, value);
1180
+ const hasBody = method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
1181
+ const requestInit = {
1182
+ ...forwardable,
1183
+ method,
1184
+ headers: requestHeaders
1185
+ };
1186
+ if (!hasBody) await discard(content);
1187
+ else if (supportsRequestStreams()) {
1188
+ requestInit.body = toReadableStream(content[Symbol.asyncIterator]());
1189
+ requestInit.duplex = "half";
1190
+ } else requestInit.body = await collectBytes(content);
1191
+ const response = await handler(new Request(url, requestInit));
1192
+ return {
1193
+ options: {
1194
+ status: response.status,
1195
+ statusText: response.statusText,
1196
+ headers: Object.fromEntries([...response.headers])
1197
+ },
1198
+ content: response.body ? fromReadableStream(response.body) : (async function* () {})()
1199
+ };
1200
+ };
1201
+ }
1202
+ //#endregion
1203
+ //#region src/core/data-channels.ts
1204
+ const MESSAGE_TYPE_REQUEST = "REQUEST";
1205
+ const MESSAGE_TYPE_RESPONSE = "RESPONSE";
1206
+ let __invocationCounter = 0;
1207
+ function newInvokationChannel({ port, handler = () => {
1208
+ throw new Error("Handler not implemented");
1209
+ }, onError = console.error, newCallId = () => ++__invocationCounter }) {
1210
+ const requests = {};
1211
+ const listener = async (event) => {
1212
+ const data = event.data ?? {};
1213
+ if (data.type === MESSAGE_TYPE_REQUEST) try {
1214
+ const result = await handler(data.request, ...event.ports);
1215
+ const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
1216
+ port.postMessage({
1217
+ type: MESSAGE_TYPE_RESPONSE,
1218
+ callId: data.callId,
1219
+ response
1220
+ }, transfers);
1221
+ } catch (error) {
1222
+ port.postMessage({
1223
+ type: MESSAGE_TYPE_RESPONSE,
1224
+ callId: data.callId,
1225
+ error: serializeError(error)
1226
+ });
1227
+ }
1228
+ else if (data.type === MESSAGE_TYPE_RESPONSE) {
1229
+ const pending = requests[data.callId];
1230
+ delete requests[data.callId];
1231
+ if (!pending) return;
1232
+ if (data.error) pending.reject(deserializeError(data.error));
1233
+ else pending.resolve(data.response);
1234
+ }
1235
+ };
1236
+ const start = async () => {
1237
+ try {
1238
+ port.addEventListener("message", listener);
1239
+ await port.start?.();
1240
+ } catch (e) {
1241
+ onError(e);
1242
+ }
1243
+ };
1244
+ const close = async () => {
1245
+ try {
1246
+ port.removeEventListener("message", listener);
1247
+ await port.close?.();
1248
+ } catch (e) {
1249
+ onError(e);
1250
+ }
1251
+ };
1252
+ const invoke = (request = {}, ...transfers) => {
1253
+ const callId = newCallId();
1254
+ return new Promise((resolve, reject) => {
1255
+ try {
1256
+ requests[callId] = {
1257
+ resolve,
1258
+ reject
1259
+ };
1260
+ port.postMessage({
1261
+ type: MESSAGE_TYPE_REQUEST,
1262
+ callId,
1263
+ request
1264
+ }, transfers);
1265
+ } catch (error) {
1266
+ delete requests[callId];
1267
+ reject(error);
1268
+ }
1269
+ });
1270
+ };
1271
+ return {
1272
+ start,
1273
+ close,
1274
+ invoke
1275
+ };
1276
+ }
1277
+ async function* sendStream(communicationPort, input, params = {}) {
1278
+ const messageChannel = new MessageChannel();
1279
+ communicationPort.postMessage({
1280
+ type: "START_CALL",
1281
+ params
1282
+ }, [messageChannel.port2]);
1283
+ const channel = newStreamChannel(messageChannel.port1);
1284
+ let drained = false;
1285
+ try {
1286
+ await channel.start();
1287
+ channel.sendAll(input);
1288
+ yield* channel.recieveAll();
1289
+ drained = true;
1290
+ } finally {
1291
+ if (!drained) channel.cancel();
1292
+ await channel.close();
1293
+ }
1294
+ }
1295
+ function handleStreams(communicationPort, handler) {
1296
+ const listener = async (event) => {
1297
+ const { type, params } = event.data ?? {};
1298
+ if (type !== "START_CALL") return;
1299
+ const port = event.ports[0];
1300
+ const channel = newStreamChannel(port);
1301
+ try {
1302
+ await channel.start();
1303
+ const response = await handler(channel.recieveAll(), params ?? {});
1304
+ await channel.sendAll(response);
1305
+ } finally {
1306
+ await channel.close();
1307
+ }
1308
+ };
1309
+ communicationPort.addEventListener("message", listener);
1310
+ communicationPort.start?.();
1311
+ return () => communicationPort.removeEventListener("message", listener);
1312
+ }
1313
+ function newStreamChannel(port) {
1314
+ let listeners = [];
1315
+ let iterators = [];
1316
+ const notifyAll = async (data) => {
1317
+ for (const listener of listeners) await listener(data);
1318
+ };
1319
+ /**
1320
+ * Release whatever we are sending. NOT awaited: `.return()` on an async
1321
+ * generator parked awaiting its own source is queued behind that pending
1322
+ * `next()`, so awaiting it here would block the message handler — and the
1323
+ * chunk that would unblock it can only arrive through that same handler.
1324
+ */
1325
+ const cancelOutgoing = () => {
1326
+ for (const it of [...iterators]) {
1327
+ const iterable = it;
1328
+ Promise.resolve(iterable.return?.()).catch(() => {});
1329
+ }
1330
+ };
1331
+ const channel = newInvokationChannel({
1332
+ port,
1333
+ handler: (data) => {
1334
+ const message = data;
1335
+ if (message?.cancel) {
1336
+ cancelOutgoing();
1337
+ return;
1338
+ }
1339
+ return notifyAll(message);
1340
+ }
1341
+ });
1342
+ const start = () => channel.start();
1343
+ const cancel = () => {
1344
+ channel.invoke({ cancel: true }).catch(() => {});
1345
+ };
1346
+ const close = async () => {
1347
+ await notifyAll({ done: true });
1348
+ for (const it of [...iterators]) await it.return?.();
1349
+ await channel.close();
1350
+ };
1351
+ async function* recieveAll() {
1352
+ yield* recieveIterator((deliver) => {
1353
+ listeners.push(deliver);
1354
+ return () => {
1355
+ listeners = listeners.filter((l) => l !== deliver);
1356
+ };
1357
+ });
1358
+ }
1359
+ async function sendAll(it) {
1360
+ await sendIterator((chunk) => void channel.invoke(chunk), (async function* () {
1361
+ try {
1362
+ iterators.push(it);
1363
+ yield* it;
1364
+ } finally {
1365
+ iterators = iterators.filter((i) => i !== it);
1366
+ }
1367
+ })());
1368
+ }
1369
+ return {
1370
+ start,
1371
+ close,
1372
+ cancel,
1373
+ recieveAll,
1374
+ sendAll
1375
+ };
1376
+ }
1377
+ //#endregion
1378
+ //#region src/http/http-send-recieve.ts
1379
+ async function* httpToIterator(envelopeOrPromise) {
1380
+ const { options, content } = await envelopeOrPromise;
1381
+ yield new TextEncoder().encode(JSON.stringify(options));
1382
+ yield* content;
1383
+ }
1384
+ async function httpFromIterator(iterable) {
1385
+ const it = (await iterable)[Symbol.asyncIterator]();
1386
+ const { done, value } = await it.next();
1387
+ let options = {};
1388
+ if (!done && value) {
1389
+ const str = new TextDecoder().decode(value);
1390
+ options = JSON.parse(str);
1391
+ }
1392
+ return {
1393
+ options,
1394
+ content: { [Symbol.asyncIterator]() {
1395
+ return it;
1396
+ } }
1397
+ };
1398
+ }
1399
+ /**
1400
+ * Serve an `HttpHandler` over a `MessageTarget`, using this package's own
1401
+ * `handleStreams` transport.
1402
+ *
1403
+ * @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
1404
+ * (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
1405
+ * transfer a real `MessagePort`), turn it into a `Duplex` with
1406
+ * `serveDuplexOverPort`, and serve HTTP on that with
1407
+ * `httpServe(handler, options)` from `@statewalker/webrun-http-streams`.
1408
+ *
1409
+ * That path has backpressure; **this one does not.** `sendStream`'s chunk
1410
+ * sender discards the promise it is given, so a fast producer over a slow
1411
+ * consumer accumulates without bound. It also has no per-stream timeout and no
1412
+ * chunking to a transport's message ceiling.
1413
+ *
1414
+ * Kept for existing ServiceWorker setups built on the `MessageTarget` surface.
1415
+ */
1416
+ function handleHttpRequests(communicationPort, handler) {
1417
+ const serverStub = newHttpServerStub(handler);
1418
+ return handleStreams(communicationPort, async (it) => {
1419
+ const envelope = await httpFromIterator(it);
1420
+ return httpToIterator(await serverStub(envelope));
1421
+ });
1422
+ }
1423
+ /**
1424
+ * Ship a `Request` over a `MessageTarget` and await the `Response`, using this
1425
+ * package's own `sendStream` transport.
1426
+ *
1427
+ * @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
1428
+ * (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
1429
+ * transfer a real `MessagePort`), turn it into a `Duplex` with
1430
+ * `duplexOverPort`, and drive HTTP over it with `httpFetch` from
1431
+ * `@statewalker/webrun-http-streams`.
1432
+ *
1433
+ * Same caveat as {@link handleHttpRequests}: the transport underneath this
1434
+ * helper has no backpressure, no per-stream timeout, and no chunking to a
1435
+ * transport's message ceiling. Kept for existing ServiceWorker setups.
1436
+ */
1437
+ async function sendHttpRequest(communicationPort, request) {
1438
+ return await newHttpClientStub(async (req) => {
1439
+ return await httpFromIterator(sendStream(communicationPort, httpToIterator(req)));
1440
+ })(request);
1441
+ }
1442
+ //#endregion
1443
+ //#region ../../../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
1444
+ function promisifyRequest(request) {
1445
+ return new Promise((resolve, reject) => {
1446
+ request.oncomplete = request.onsuccess = () => resolve(request.result);
1447
+ request.onabort = request.onerror = () => reject(request.error);
1448
+ });
1449
+ }
1450
+ function createStore(dbName, storeName) {
1451
+ let dbp;
1452
+ const getDB = () => {
1453
+ if (dbp) return dbp;
1454
+ const request = indexedDB.open(dbName);
1455
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName);
1456
+ dbp = promisifyRequest(request);
1457
+ dbp.then((db) => {
1458
+ db.onclose = () => dbp = void 0;
1459
+ }, () => {
1460
+ dbp = void 0;
1461
+ });
1462
+ return dbp;
1463
+ };
1464
+ return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
1465
+ }
1466
+ let defaultGetStoreFunc;
1467
+ function defaultGetStore() {
1468
+ if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
1469
+ return defaultGetStoreFunc;
1470
+ }
1471
+ /**
1472
+ * Get a value by its key.
1473
+ *
1474
+ * @param key
1475
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
1476
+ */
1477
+ function get(key, customStore = defaultGetStore()) {
1478
+ return customStore("readonly", (store) => promisifyRequest(store.get(key)));
1479
+ }
1480
+ /**
1481
+ * Set a value with a key.
1482
+ *
1483
+ * @param key
1484
+ * @param value
1485
+ * @param customStore Method to get a custom store. Use with caution (see the docs).
1486
+ */
1487
+ function set(key, value, customStore = defaultGetStore()) {
1488
+ return customStore("readwrite", (store) => {
1489
+ store.put(value, key);
1490
+ return promisifyRequest(store.transaction);
1491
+ });
1492
+ }
1493
+ //#endregion
1494
+ //#region src/core/data-calls.ts
1495
+ function callChannel(target, callType, params, ...transfers) {
1496
+ return new Promise((resolve, reject) => {
1497
+ const channel = new MessageChannel();
1498
+ channel.port1.onmessage = (ev) => {
1499
+ const { result, error } = ev.data;
1500
+ if (error) reject(deserializeError(error));
1501
+ else resolve(result);
1502
+ };
1503
+ target.postMessage({
1504
+ type: callType,
1505
+ params
1506
+ }, [channel.port2, ...transfers]);
1507
+ });
1508
+ }
1509
+ function handleChannelCalls(target, callType, handler) {
1510
+ const listener = async (event) => {
1511
+ if (!event.data || event.data.type !== callType) return;
1512
+ const [port, ...transfers] = event.ports ?? [];
1513
+ const response = {};
1514
+ try {
1515
+ response.result = await handler(event, event.data.params, ...transfers);
1516
+ } catch (error) {
1517
+ response.error = serializeError(error);
1518
+ }
1519
+ port?.postMessage(response);
1520
+ };
1521
+ target.addEventListener("message", listener);
1522
+ target.start?.();
1523
+ return () => target.removeEventListener("message", listener);
1524
+ }
1525
+ //#endregion
1526
+ //#region src/core/registry.ts
1527
+ function newRegistry(onError = console.error) {
1528
+ let counter = 0;
1529
+ const registrations = {};
1530
+ const register = (action) => {
1531
+ const id = counter++;
1532
+ const fn = Object.assign((skip) => {
1533
+ try {
1534
+ delete registrations[id];
1535
+ return skip ? void 0 : action();
1536
+ } catch (error) {
1537
+ onError(error);
1538
+ }
1539
+ }, { action });
1540
+ registrations[id] = fn;
1541
+ return fn;
1542
+ };
1543
+ const unregister = (action) => {
1544
+ for (const r of Object.values(registrations)) if (r.action === action) r(true);
1545
+ };
1546
+ const clear = () => {
1547
+ for (const r of Object.values(registrations)) r();
1548
+ };
1549
+ return Object.assign([
1550
+ register,
1551
+ clear,
1552
+ unregister
1553
+ ], {
1554
+ register,
1555
+ clear,
1556
+ unregister
1557
+ });
1558
+ }
1559
+ //#endregion
1560
+ //#region src/sw/sw-dispatcher.ts
1561
+ /**
1562
+ * Page-side counterpart: registers a ServiceWorker and sets up a
1563
+ * MessageChannel with it, re-establishing the connection after SW wake-ups.
1564
+ */
1565
+ var SwPortHandler = class {
1566
+ options;
1567
+ _serviceWorkerUrl;
1568
+ _serviceWorker;
1569
+ _registrationPromise;
1570
+ _cleanupRegistrations;
1571
+ constructor(options) {
1572
+ this.options = options;
1573
+ if (!this.key) throw new Error("Key is not defined.");
1574
+ if (!this.scope) throw new Error("Scope is not defined");
1575
+ }
1576
+ get key() {
1577
+ return this.options.key;
1578
+ }
1579
+ get scope() {
1580
+ return this.options.scope ?? new URL("./", this.serviceWorkerUrl).pathname;
1581
+ }
1582
+ get rootUrl() {
1583
+ return new URL(this.scope, import.meta.url);
1584
+ }
1585
+ get serviceWorkerUrl() {
1586
+ if (!this._serviceWorkerUrl) {
1587
+ const url = this.options.serviceWorkerUrl ? resolveWorkerUrl(this.options.serviceWorkerUrl) : new URL("./index-sw.js", this.rootUrl);
1588
+ this._serviceWorkerUrl = `${url}`;
1589
+ }
1590
+ return this._serviceWorkerUrl;
1591
+ }
1592
+ async _newCommunicationChannel() {
1593
+ const messageChannel = new MessageChannel();
1594
+ return [messageChannel.port1, messageChannel.port2];
1595
+ }
1596
+ async _setCommunicationPort(port) {
1597
+ await this.options.bindPort(port);
1598
+ }
1599
+ async _updateCommunicationChannel() {
1600
+ if (!this._serviceWorker) return;
1601
+ const [port1, port2] = await this._newCommunicationChannel();
1602
+ await this._setCommunicationPort(port1);
1603
+ await callChannel(this._serviceWorker, "UPDATE_COMMUNICATION_PORT", this._getRegistrationInfo(), port2);
1604
+ }
1605
+ _getRegistrationInfo() {
1606
+ return { key: this.key };
1607
+ }
1608
+ async start() {
1609
+ if (!this._registrationPromise) this._registrationPromise = (async () => {
1610
+ const [register, cleanup] = newRegistry();
1611
+ this._cleanupRegistrations = cleanup;
1612
+ register(() => {
1613
+ this._cleanupRegistrations = void 0;
1614
+ });
1615
+ const registration = await navigator.serviceWorker.register(this.serviceWorkerUrl, { scope: this.scope });
1616
+ register(() => registration.unregister());
1617
+ register(handleChannelCalls(navigator.serviceWorker, "UPDATE_COMMUNICATION_PORT", async (_event, _params, port) => {
1618
+ await this._setCommunicationPort(port);
1619
+ return this._getRegistrationInfo();
1620
+ }));
1621
+ this._serviceWorker = await getServiceWorkerController();
1622
+ await awaitServiceWorkerActivation(this._serviceWorker);
1623
+ await this._updateCommunicationChannel();
1624
+ })();
1625
+ return this._registrationPromise;
1626
+ }
1627
+ async stop() {
1628
+ this._cleanupRegistrations?.();
1629
+ const registrations = await navigator.serviceWorker.getRegistrations();
1630
+ for (const registration of registrations) try {
1631
+ await registration.unregister();
1632
+ } catch (error) {
1633
+ console.log("Service Worker registration failed: ", error);
1634
+ }
1635
+ }
1636
+ };
1637
+ function getServiceWorkerController() {
1638
+ return new Promise((resolve) => {
1639
+ const container = navigator.serviceWorker;
1640
+ if (container.controller) {
1641
+ resolve(container.controller);
1642
+ return;
1643
+ }
1644
+ const onChange = () => {
1645
+ if (!container.controller) return;
1646
+ resolve(container.controller);
1647
+ container.removeEventListener("controllerchange", onChange);
1648
+ };
1649
+ container.addEventListener("controllerchange", onChange);
1650
+ });
1651
+ }
1652
+ function awaitServiceWorkerActivation(worker) {
1653
+ return new Promise((resolve) => {
1654
+ if (worker.state === "activated") {
1655
+ resolve();
1656
+ return;
1657
+ }
1658
+ const onStateChange = () => {
1659
+ if (worker.state !== "activated") return;
1660
+ worker.removeEventListener("statechange", onStateChange);
1661
+ resolve();
1662
+ };
1663
+ worker.addEventListener("statechange", onStateChange);
1664
+ });
1665
+ }
1666
+ /**
1667
+ * ServiceWorker-side counterpart: maintains an index of connected clients keyed by
1668
+ * clientId, persisted in IndexedDB so it can reclaim ports across SW restarts.
1669
+ */
1670
+ var SwPortDispatcher = class {
1671
+ self;
1672
+ log;
1673
+ handlersIndex = /* @__PURE__ */ new Map();
1674
+ /**
1675
+ * Set of keys that were registered at some point on this SW (sticky —
1676
+ * survives client closures + SW wake-ups via IndexedDB). Lets the fetch
1677
+ * handler distinguish "site URL whose owner is gone → 404" from
1678
+ * "unknown URL under scope → pass through to the network".
1679
+ */
1680
+ claimedKeys = /* @__PURE__ */ new Set();
1681
+ _cleanup;
1682
+ _activationPromise;
1683
+ constructor({ self, log = () => {} }) {
1684
+ this.self = self;
1685
+ this.log = log;
1686
+ }
1687
+ get scope() {
1688
+ return `${new URL("./", this.self.location.href)}`;
1689
+ }
1690
+ /**
1691
+ * Look up the active channel for a key. Returns `undefined` when there
1692
+ * is no registration (or the registering client has gone away — stale
1693
+ * entries are pruned in place).
1694
+ */
1695
+ async loadChannelInfo(key) {
1696
+ await this._checkActivation();
1697
+ for (const channelInfo of this.handlersIndex.values()) {
1698
+ if (channelInfo.key !== key) continue;
1699
+ const clientId = channelInfo.clientId;
1700
+ if (!clientId) continue;
1701
+ if (!await this.self.clients.get(clientId)) {
1702
+ this.handlersIndex.delete(clientId);
1703
+ continue;
1704
+ }
1705
+ return channelInfo;
1706
+ }
1707
+ }
1708
+ /** Whether `key` has ever been registered on this SW. */
1709
+ isClaimedKey(key) {
1710
+ return this.claimedKeys.has(key);
1711
+ }
1712
+ start() {
1713
+ this._cleanup = handleChannelCalls(this.self, "UPDATE_COMMUNICATION_PORT", async (event, channelInfo, port) => {
1714
+ const clientId = event.source?.id;
1715
+ this.log("[UPDATE_COMMUNICATION_PORT]", clientId, channelInfo);
1716
+ await this._updateChannelInfo({
1717
+ ...channelInfo,
1718
+ port,
1719
+ clientId
1720
+ });
1721
+ return { ...channelInfo };
1722
+ });
1723
+ this.self.addEventListener("install", (event) => {
1724
+ this.log("Skip waiting on install.", event);
1725
+ this.self.skipWaiting();
1726
+ });
1727
+ this.self.addEventListener("activate", (event) => {
1728
+ this.log("Claim control over all clients.", event);
1729
+ event.waitUntil((async () => {
1730
+ await this.self.clients.claim();
1731
+ await this._checkActivation();
1732
+ })());
1733
+ });
1734
+ }
1735
+ async stop() {
1736
+ if (this._cleanup) {
1737
+ this._cleanup();
1738
+ this._cleanup = void 0;
1739
+ }
1740
+ }
1741
+ _checkActivation() {
1742
+ if (!this._activationPromise) this._activationPromise = this._activate();
1743
+ return this._activationPromise;
1744
+ }
1745
+ async _activate() {
1746
+ this.log("[checkActivation]");
1747
+ const clientsIndex = await this._loadClientIds();
1748
+ for (const [clientId, client] of clientsIndex.entries()) {
1749
+ const messageChannel = new MessageChannel();
1750
+ const port = messageChannel.port1;
1751
+ const channelInfo = await callChannel(client, "UPDATE_COMMUNICATION_PORT", {}, messageChannel.port2);
1752
+ await this._updateChannelInfo({
1753
+ ...channelInfo,
1754
+ port,
1755
+ clientId
1756
+ });
1757
+ }
1758
+ }
1759
+ async _updateChannelInfo(channelInfo) {
1760
+ this.log("[updateClientInfo]", channelInfo);
1761
+ if (!channelInfo.clientId) return;
1762
+ this.handlersIndex.set(channelInfo.clientId, channelInfo);
1763
+ if (channelInfo.key && !this.claimedKeys.has(channelInfo.key)) {
1764
+ this.claimedKeys.add(channelInfo.key);
1765
+ await set("claimedKeys", [...this.claimedKeys].sort());
1766
+ }
1767
+ await this._updateClientIds([]);
1768
+ }
1769
+ async _loadClientIds() {
1770
+ const storedKeys = await get("claimedKeys") ?? [];
1771
+ for (const key of storedKeys) this.claimedKeys.add(key);
1772
+ const stored = await get("clientIds") ?? [];
1773
+ return await this._updateClientIds(new Set(stored));
1774
+ }
1775
+ async _updateClientIds(clientIds) {
1776
+ const ids = new Set(clientIds);
1777
+ for (const clientId of this.handlersIndex.keys()) ids.add(clientId);
1778
+ const index = /* @__PURE__ */ new Map();
1779
+ for (const clientId of ids) {
1780
+ const client = await this.self.clients.get(clientId);
1781
+ if (client) index.set(clientId, client);
1782
+ else this.handlersIndex.delete(clientId);
1783
+ }
1784
+ await set("clientIds", [...index.keys()].sort());
1785
+ return index;
1786
+ }
1787
+ };
1788
+ /**
1789
+ * Resolve a `serviceWorkerUrl` option the way a page would: relative to the
1790
+ * current document. Absolute urls pass through untouched. A url that cannot
1791
+ * be resolved is reported with the option name and the offending value,
1792
+ * because the raw `TypeError: Failed to construct 'URL': Invalid URL` says
1793
+ * neither.
1794
+ */
1795
+ function resolveWorkerUrl(serviceWorkerUrl) {
1796
+ const base = globalThis.location?.href;
1797
+ try {
1798
+ return new URL(serviceWorkerUrl, base);
1799
+ } catch (error) {
1800
+ throw new Error(`Invalid serviceWorkerUrl: ${JSON.stringify(serviceWorkerUrl)}` + (base ? ` (relative to ${base})` : " (no document to resolve it against)"), { cause: error });
1801
+ }
1802
+ }
1803
+ //#endregion
1804
+ //#region src/sw/http-sw-dispatcher.ts
1805
+ var SwHttpAdapter = class extends SwPortHandler {
1806
+ _handlers = /* @__PURE__ */ new Map();
1807
+ _cleanupRequestChannel;
1808
+ constructor(options) {
1809
+ super({
1810
+ bindPort: () => {},
1811
+ ...options
1812
+ });
1813
+ }
1814
+ async _setCommunicationPort(port) {
1815
+ this._cleanupRequestChannel?.();
1816
+ this._cleanupRequestChannel = handleHttpRequests(port, this._handleHttpRequest.bind(this));
1817
+ }
1818
+ async _handleHttpRequest(request) {
1819
+ const requestUrl = request.url;
1820
+ for (const [urlPrefix, handler] of this._handlers) if (requestUrl.indexOf(urlPrefix) === 0) return handler(request);
1821
+ return new Response(null, {
1822
+ status: 404,
1823
+ statusText: "Error 404: Not found"
1824
+ });
1825
+ }
1826
+ /**
1827
+ * Registers an HTTP handler on a prefix. Returns the resulting base URL and a
1828
+ * disposer.
1829
+ */
1830
+ async register(prefix, handler) {
1831
+ const cleanPrefix = `./${(prefix ?? "").replace(/^[./]+/, "")}`;
1832
+ const baseUrl = `${new URL(cleanPrefix, this.rootUrl)}`;
1833
+ this._handlers.set(baseUrl, handler);
1834
+ const handlers = this._handlers;
1835
+ return {
1836
+ baseUrl,
1837
+ prefix: cleanPrefix,
1838
+ async remove() {
1839
+ handlers.delete(baseUrl);
1840
+ }
1841
+ };
1842
+ }
1843
+ };
1844
+ var SwHttpDispatcher = class extends SwPortDispatcher {
1845
+ start() {
1846
+ super.start();
1847
+ this.self.addEventListener("fetch", this._handleFetchEvent.bind(this));
1848
+ }
1849
+ _handleFetchEvent(event) {
1850
+ event.respondWith((async () => {
1851
+ const request = event.request;
1852
+ try {
1853
+ const requestUrl = request.url;
1854
+ const rootUrl = this.scope;
1855
+ if (requestUrl.indexOf(rootUrl) === 0) {
1856
+ const key = requestUrl.substring(rootUrl.length).replace(/^\/?([^/]+).*$/, "$1");
1857
+ const channelInfo = await this.loadChannelInfo(key);
1858
+ if (channelInfo?.port) return await sendHttpRequest(channelInfo.port, request);
1859
+ if (this.isClaimedKey(key)) return new Response(null, {
1860
+ status: 404,
1861
+ statusText: "Not Found (no active handler)"
1862
+ });
1863
+ }
1864
+ return await fetch(request);
1865
+ } catch (error) {
1866
+ console.error(error);
1867
+ return new Response(null, {
1868
+ status: 500,
1869
+ statusText: "Error 500: Internal error"
1870
+ });
1871
+ }
1872
+ })());
1873
+ }
1874
+ };
1875
+ function startHttpDispatcher(options) {
1876
+ const dispatcher = new SwHttpDispatcher(options);
1877
+ dispatcher.start();
1878
+ return () => {
1879
+ dispatcher.stop();
1880
+ };
1881
+ }
1882
+ //#endregion
1883
+ export { SwHttpAdapter, SwHttpDispatcher, SwPortDispatcher, SwPortHandler, startHttpDispatcher };