@statewalker/webrun-http-browser 0.6.5 → 0.7.1
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.
- package/README.md +302 -52
- package/dist/core/data-calls.d.ts +17 -0
- package/dist/core/data-calls.d.ts.map +1 -1
- package/dist/core/service-worker-control.d.ts +3 -1
- package/dist/core/service-worker-control.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4218 -301
- package/dist/link/async-dispose.d.ts +10 -0
- package/dist/link/async-dispose.d.ts.map +1 -0
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.d.ts.map +1 -0
- package/dist/link/http-link.d.ts +72 -0
- package/dist/link/http-link.d.ts.map +1 -0
- package/dist/link/index.d.ts +4 -0
- package/dist/link/index.d.ts.map +1 -0
- package/dist/link/locks.d.ts +39 -0
- package/dist/link/locks.d.ts.map +1 -0
- package/dist/link/rendezvous.d.ts +21 -0
- package/dist/link/rendezvous.d.ts.map +1 -0
- package/dist/relay/index-sw.d.ts +12 -2
- package/dist/relay/index-sw.d.ts.map +1 -1
- package/dist/relay/index.d.ts +66 -8
- package/dist/relay/index.d.ts.map +1 -1
- package/dist/relay-sw.js +1328 -64
- package/dist/relay-worker.js +1329 -64
- package/dist/sw/handler-endpoint.d.ts +81 -0
- package/dist/sw/handler-endpoint.d.ts.map +1 -0
- package/dist/sw/handler-table.d.ts +53 -0
- package/dist/sw/handler-table.d.ts.map +1 -0
- package/dist/sw/http-sw-dispatcher.d.ts +162 -21
- package/dist/sw/http-sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/index.d.ts +5 -0
- package/dist/sw/index.d.ts.map +1 -1
- package/dist/sw/protocol.d.ts +115 -0
- package/dist/sw/protocol.d.ts.map +1 -0
- package/dist/sw/sw-dispatcher.d.ts.map +1 -1
- package/dist/sw/sw-http-adapter.d.ts +199 -0
- package/dist/sw/sw-http-adapter.d.ts.map +1 -0
- package/dist/sw/sw-websocket.d.ts +16 -0
- package/dist/sw/sw-websocket.d.ts.map +1 -0
- package/dist/sw/worker-service.d.ts +45 -0
- package/dist/sw/worker-service.d.ts.map +1 -0
- package/dist/sw/worker-url.d.ts +9 -0
- package/dist/sw/worker-url.d.ts.map +1 -0
- package/dist/sw-worker.js +2403 -265
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -1
- package/dist/sw.js +4189 -546
- package/dist/worker.d.ts +10 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +3780 -0
- package/dist/ws/client.d.ts +73 -0
- package/dist/ws/client.d.ts.map +1 -0
- package/dist/ws/frames.d.ts +68 -0
- package/dist/ws/frames.d.ts.map +1 -0
- package/dist/ws/index.d.ts +6 -0
- package/dist/ws/index.d.ts.map +1 -0
- package/dist/ws/server.d.ts +53 -0
- package/dist/ws/server.d.ts.map +1 -0
- package/dist/ws/socket-core.d.ts +91 -0
- package/dist/ws/socket-core.d.ts.map +1 -0
- package/dist/ws/upgrade.d.ts +93 -0
- package/dist/ws/upgrade.d.ts.map +1 -0
- package/package.json +10 -5
- package/src/core/data-calls.ts +52 -2
- package/src/core/service-worker-control.ts +7 -1
- package/src/index.ts +3 -0
- package/src/link/async-dispose.ts +22 -0
- package/src/link/errors.ts +3 -0
- package/src/link/http-link.ts +238 -0
- package/src/link/index.ts +3 -0
- package/src/link/locks.ts +97 -0
- package/src/link/rendezvous.ts +60 -0
- package/src/relay/index-sw.ts +84 -12
- package/src/relay/index.ts +203 -27
- package/src/sw/handler-endpoint.ts +278 -0
- package/src/sw/handler-table.ts +130 -0
- package/src/sw/http-sw-dispatcher.ts +649 -90
- package/src/sw/index.ts +5 -0
- package/src/sw/protocol.ts +103 -0
- package/src/sw/sw-dispatcher.ts +1 -20
- package/src/sw/sw-http-adapter.ts +613 -0
- package/src/sw/sw-websocket.ts +43 -0
- package/src/sw/worker-service.ts +133 -0
- package/src/sw/worker-url.ts +19 -0
- package/src/sw-worker.ts +8 -3
- package/src/sw.ts +2 -0
- package/src/worker.ts +9 -0
- package/src/ws/client.ts +346 -0
- package/src/ws/frames.ts +119 -0
- package/src/ws/index.ts +11 -0
- package/src/ws/server.ts +132 -0
- package/src/ws/socket-core.ts +251 -0
- package/src/ws/upgrade.ts +200 -0
package/dist/sw.js
CHANGED
|
@@ -22,8 +22,6 @@ function deserializeError(error) {
|
|
|
22
22
|
const payload = typeof error === "string" ? { message: error } : error;
|
|
23
23
|
return Object.assign(new Error(payload.message), payload);
|
|
24
24
|
}
|
|
25
|
-
new TextEncoder();
|
|
26
|
-
new TextDecoder();
|
|
27
25
|
/**
|
|
28
26
|
* The newAsyncGenerator function creates async generators from callback-based initialization
|
|
29
27
|
* functions, providing a bridge between imperative event handling and declarative async
|
|
@@ -176,7 +174,6 @@ async function* newAsyncGenerator(init, skipValues = false) {
|
|
|
176
174
|
drainQueue();
|
|
177
175
|
}
|
|
178
176
|
}
|
|
179
|
-
new TextEncoder();
|
|
180
177
|
/**
|
|
181
178
|
* The iterator ↔ `ReadableStream` boundary.
|
|
182
179
|
*
|
|
@@ -281,6 +278,34 @@ async function sendIterator(send, it) {
|
|
|
281
278
|
});
|
|
282
279
|
}
|
|
283
280
|
}
|
|
281
|
+
const DEFAULT_CHUNK_SIZE = 16384;
|
|
282
|
+
/**
|
|
283
|
+
* Curried `Duplex`-shaped transformer that splits incoming `Uint8Array`s into
|
|
284
|
+
* chunks no larger than `size` bytes. Empty input chunks are skipped; small
|
|
285
|
+
* input chunks pass through unchanged (zero-copy `subarray` views are used
|
|
286
|
+
* when splitting, so no allocation per chunk).
|
|
287
|
+
*
|
|
288
|
+
* Use to respect transport MTUs before reaching `channel.send`. Reassembly on
|
|
289
|
+
* the receive side is not needed — consumers iterate a continuous byte stream.
|
|
290
|
+
*/
|
|
291
|
+
function toChunks(size = DEFAULT_CHUNK_SIZE) {
|
|
292
|
+
if (!(Number.isInteger(size) && size > 0)) throw new RangeError(`toChunks: size must be a positive integer, got ${size}`);
|
|
293
|
+
return async function* (input) {
|
|
294
|
+
for await (const block of input) {
|
|
295
|
+
if (block.byteLength === 0) continue;
|
|
296
|
+
if (block.byteLength <= size) {
|
|
297
|
+
yield block;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
let offset = 0;
|
|
301
|
+
while (offset < block.byteLength) {
|
|
302
|
+
const end = Math.min(offset + size, block.byteLength);
|
|
303
|
+
yield block.subarray(offset, end);
|
|
304
|
+
offset = end;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
}
|
|
284
309
|
//#endregion
|
|
285
310
|
//#region ../webrun-http-streams/dist/index.js
|
|
286
311
|
const CR = 13;
|
|
@@ -418,8 +443,8 @@ var HttpParseError = class extends Error {
|
|
|
418
443
|
const NEWLINE = 10;
|
|
419
444
|
/** Mirrors the HTTP/1.1 codec's default `maxHeaderBytes`. */
|
|
420
445
|
const MAX_ENVELOPE_BYTES = 65536;
|
|
421
|
-
const encoder$1 = new TextEncoder();
|
|
422
|
-
const decoder = new TextDecoder();
|
|
446
|
+
const encoder$1 = /* @__PURE__ */ new TextEncoder();
|
|
447
|
+
const decoder = /* @__PURE__ */ new TextDecoder();
|
|
423
448
|
/**
|
|
424
449
|
* Encode an HTTP envelope plus optional body as one continuous byte stream:
|
|
425
450
|
*
|
|
@@ -673,15 +698,15 @@ function resolveFraming(headers, version) {
|
|
|
673
698
|
};
|
|
674
699
|
return { kind: "none" };
|
|
675
700
|
}
|
|
676
|
-
const CRLF = new Uint8Array([13, 10]);
|
|
677
|
-
const LAST_CHUNK = new Uint8Array([
|
|
701
|
+
const CRLF = /* @__PURE__ */ new Uint8Array([13, 10]);
|
|
702
|
+
const LAST_CHUNK = /* @__PURE__ */ new Uint8Array([
|
|
678
703
|
48,
|
|
679
704
|
13,
|
|
680
705
|
10,
|
|
681
706
|
13,
|
|
682
707
|
10
|
|
683
708
|
]);
|
|
684
|
-
const encoder = new TextEncoder();
|
|
709
|
+
const encoder = /* @__PURE__ */ new TextEncoder();
|
|
685
710
|
/**
|
|
686
711
|
* Chunk sizes are written in HEXADECIMAL — a 21-byte chunk is `15`. Writing
|
|
687
712
|
* them in decimal is the defect note 15 found in @libp2p/http, and it is the
|
|
@@ -986,7 +1011,7 @@ function newHttpCodec(options = {}) {
|
|
|
986
1011
|
decodeResponse: (input, o) => decodeResponse(input, opts, o.method)
|
|
987
1012
|
};
|
|
988
1013
|
}
|
|
989
|
-
const httpCodec = newHttpCodec();
|
|
1014
|
+
const httpCodec = /* @__PURE__ */ newHttpCodec();
|
|
990
1015
|
/**
|
|
991
1016
|
* Dispatches on byte 0. The formats are self-identifying — a JSON envelope
|
|
992
1017
|
* always begins `{`, which is not a token character and so can never begin an
|
|
@@ -1032,11 +1057,245 @@ function newSniffingCodec(options) {
|
|
|
1032
1057
|
}
|
|
1033
1058
|
};
|
|
1034
1059
|
}
|
|
1035
|
-
|
|
1060
|
+
/**
|
|
1061
|
+
* Writes HTTP/1.1; accepts HTTP/1.1 or the legacy JSON envelope. Used whenever
|
|
1062
|
+
* no `codec` option is supplied.
|
|
1063
|
+
*/
|
|
1064
|
+
const defaultCodec = /* @__PURE__ */ newSniffingCodec({
|
|
1036
1065
|
write: httpCodec,
|
|
1037
1066
|
accept: [httpCodec, jsonEnvelopeCodec]
|
|
1038
1067
|
});
|
|
1039
1068
|
/**
|
|
1069
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
1070
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
1071
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
1072
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
1073
|
+
* declared types, which would require consumers to compile with the
|
|
1074
|
+
* `esnext.disposable` lib.
|
|
1075
|
+
*/
|
|
1076
|
+
function asyncDisposable$2(target, dispose) {
|
|
1077
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
1078
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
1079
|
+
value: async () => {
|
|
1080
|
+
await dispose();
|
|
1081
|
+
},
|
|
1082
|
+
configurable: true,
|
|
1083
|
+
writable: true
|
|
1084
|
+
});
|
|
1085
|
+
return target;
|
|
1086
|
+
}
|
|
1087
|
+
/** Carries the serialized JS error between two webrun peers. */
|
|
1088
|
+
const PEER_ERROR_HEADER = "x-webrun-error";
|
|
1089
|
+
/** Hard cap on the peer-error header (M3): see `encodeErrorResponse`. */
|
|
1090
|
+
const MAX_DETAIL_CHARS = 4096;
|
|
1091
|
+
/**
|
|
1092
|
+
* JSON with every non-printable-ASCII character escaped, so the result is a
|
|
1093
|
+
* legal latin-1 header value whatever the error message contained.
|
|
1094
|
+
*/
|
|
1095
|
+
function asciiJson(value) {
|
|
1096
|
+
return JSON.stringify(value).replace(/[^\x20-\x7E]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Decision 13: a real HTTP peer cannot receive a JavaScript exception, only a
|
|
1100
|
+
* response. So an uncaught handler error becomes a conforming 500 whose body
|
|
1101
|
+
* carries the message, with the serialized error in a namespaced header that
|
|
1102
|
+
* another webrun peer re-throws from.
|
|
1103
|
+
*/
|
|
1104
|
+
function encodeErrorResponse(codec, error, method, status = 500, statusText = "Internal Server Error") {
|
|
1105
|
+
const serialized = serializeError(error);
|
|
1106
|
+
let detail = asciiJson(serialized);
|
|
1107
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = asciiJson({ message: serialized.message });
|
|
1108
|
+
if (detail.length > MAX_DETAIL_CHARS) detail = detail.slice(0, MAX_DETAIL_CHARS);
|
|
1109
|
+
const message = serialized.message ?? statusText;
|
|
1110
|
+
return codec.encodeResponse({
|
|
1111
|
+
status,
|
|
1112
|
+
statusText,
|
|
1113
|
+
headers: [["Content-Type", "text/plain; charset=utf-8"], [PEER_ERROR_HEADER, detail]]
|
|
1114
|
+
}, [new TextEncoder().encode(message)], { method });
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* `output` is the `Duplex` call's own generator — one logical call, per the
|
|
1118
|
+
* `Duplex` contract in `@statewalker/webrun-streams`: "Consumer `.return()`
|
|
1119
|
+
* on the output → producer's `finally` runs." On a mux transport
|
|
1120
|
+
* (`emulateMux`), that `finally` is what frees the stream-table slot; skip it
|
|
1121
|
+
* and every peer-error response leaks one slot, unboundedly, until the mux
|
|
1122
|
+
* itself is exhausted (`maxStreams` reached, every further call rejected).
|
|
1123
|
+
*
|
|
1124
|
+
* Cancelling `output` here — not inside the codec's own decode logic — is
|
|
1125
|
+
* deliberate. `codec.decodeResponse` already pulled from `output` to read the
|
|
1126
|
+
* head before this function runs, so unlike the body case above there's no
|
|
1127
|
+
* suspended-start no-op to worry about. And it's safe specifically *because*
|
|
1128
|
+
* this is the client's own response-only generator: the request was already
|
|
1129
|
+
* fully sent before we got here, so there is nothing left to write on it.
|
|
1130
|
+
* The equivalent is NOT safe inside `src/http1/decode.ts`'s `ByteReader` —
|
|
1131
|
+
* that code also runs when a caller wires `codec.decodeRequest`/
|
|
1132
|
+
* `decodeResponse` directly onto a raw bidirectional socket (see
|
|
1133
|
+
* `tests/http1-node-interop.test.ts`), where the *same* object is read from
|
|
1134
|
+
* and then written back to (a server reads the request, then replies on the
|
|
1135
|
+
* same socket); cancelling the read side there tears down the whole
|
|
1136
|
+
* connection out from under the pending write. That was tried and reverted —
|
|
1137
|
+
* see the Task 11 report for the "socket hang up" failure it caused.
|
|
1138
|
+
*/
|
|
1139
|
+
async function throwIfPeerError(result, output) {
|
|
1140
|
+
const found = result.envelope.headers.find(([k]) => k.toLowerCase() === PEER_ERROR_HEADER);
|
|
1141
|
+
if (!found) return;
|
|
1142
|
+
await discard(result.body);
|
|
1143
|
+
try {
|
|
1144
|
+
await output.return?.(void 0);
|
|
1145
|
+
} catch {}
|
|
1146
|
+
let payload;
|
|
1147
|
+
try {
|
|
1148
|
+
payload = JSON.parse(found[1]);
|
|
1149
|
+
} catch {
|
|
1150
|
+
payload = { message: found[1] };
|
|
1151
|
+
}
|
|
1152
|
+
throw deserializeError(payload);
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* Initiate an HTTP call over a `Duplex`. The caller's `call: Duplex` is
|
|
1156
|
+
* obtained from any `webrun-streams-*` adapter's `connect`. Returns the
|
|
1157
|
+
* response envelope and an async iterable over the response body bytes.
|
|
1158
|
+
*
|
|
1159
|
+
* The call is one logical Duplex invocation; multiplexing of concurrent
|
|
1160
|
+
* calls is the adapter's concern (native or `emulateMux`).
|
|
1161
|
+
*/
|
|
1162
|
+
async function httpFetch(call, env, body, options = {}) {
|
|
1163
|
+
const codec = options.codec ?? defaultCodec;
|
|
1164
|
+
const { signal } = options;
|
|
1165
|
+
if (signal?.aborted) throw abortReason$1(signal);
|
|
1166
|
+
const output = call(codec.encodeRequest(env, body));
|
|
1167
|
+
let released;
|
|
1168
|
+
const release = () => {
|
|
1169
|
+
released ??= (async () => {
|
|
1170
|
+
try {
|
|
1171
|
+
await output.return?.(void 0);
|
|
1172
|
+
} catch {}
|
|
1173
|
+
})();
|
|
1174
|
+
return released;
|
|
1175
|
+
};
|
|
1176
|
+
let finished = false;
|
|
1177
|
+
const finish = () => {
|
|
1178
|
+
if (finished || released) return;
|
|
1179
|
+
finished = true;
|
|
1180
|
+
if (signal?.aborted) {
|
|
1181
|
+
release();
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
const onAbort = () => void release();
|
|
1185
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1186
|
+
drain(output).finally(() => signal?.removeEventListener("abort", onAbort));
|
|
1187
|
+
};
|
|
1188
|
+
let decoded;
|
|
1189
|
+
try {
|
|
1190
|
+
decoded = await untilAborted(codec.decodeResponse(output, { method: env.method }), signal);
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
if (signal?.aborted) release();
|
|
1193
|
+
else await release();
|
|
1194
|
+
throw error;
|
|
1195
|
+
}
|
|
1196
|
+
const result = {
|
|
1197
|
+
envelope: decoded.envelope,
|
|
1198
|
+
body: releasingOnExit(decoded.body, finish, release),
|
|
1199
|
+
release,
|
|
1200
|
+
finish
|
|
1201
|
+
};
|
|
1202
|
+
await throwIfPeerError(result, output);
|
|
1203
|
+
return result;
|
|
1204
|
+
}
|
|
1205
|
+
/** `promise`, rejected with the signal's reason if it aborts first. */
|
|
1206
|
+
function untilAborted(promise, signal) {
|
|
1207
|
+
if (!signal) return promise;
|
|
1208
|
+
return new Promise((resolve, reject) => {
|
|
1209
|
+
const onAbort = () => reject(abortReason$1(signal));
|
|
1210
|
+
if (signal.aborted) return onAbort();
|
|
1211
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1212
|
+
promise.then((value) => {
|
|
1213
|
+
signal.removeEventListener("abort", onAbort);
|
|
1214
|
+
resolve(value);
|
|
1215
|
+
}, (error) => {
|
|
1216
|
+
signal.removeEventListener("abort", onAbort);
|
|
1217
|
+
reject(error);
|
|
1218
|
+
});
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
/** The signal's reason as an `Error` (`AbortError` when it gave none). */
|
|
1222
|
+
function abortReason$1(signal) {
|
|
1223
|
+
const reason = signal.reason;
|
|
1224
|
+
if (reason instanceof Error) return reason;
|
|
1225
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
1226
|
+
err.name = "AbortError";
|
|
1227
|
+
return err;
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* `body`, ending the call however it is left: read to its end, or left early.
|
|
1231
|
+
*
|
|
1232
|
+
* The body the codec hands back is a generator of its own over a `ByteReader`,
|
|
1233
|
+
* and its ending never reaches the call's `output` (see `throwIfPeerError` for
|
|
1234
|
+
* why the codec must not do that itself). A caller that stopped reading — an
|
|
1235
|
+
* aborted `fetch`, a cancelled response stream — left the peer's producer
|
|
1236
|
+
* parked forever; and one that read the body to its end left the call itself
|
|
1237
|
+
* open, which on a multiplexed transport is one port per exchange until the
|
|
1238
|
+
* multiplexer refuses to open more (`maxPorts`).
|
|
1239
|
+
*
|
|
1240
|
+
* Left early, the call is abandoned (`.return()`): the peer's producer is
|
|
1241
|
+
* released. Read to its end, the call is not cut short but read to ITS end, in
|
|
1242
|
+
* the background: the peer ends it once its side of the exchange is over,
|
|
1243
|
+
* which may be later than the response — a handler that answered before it
|
|
1244
|
+
* read the request body is still receiving it (`HttpDataHandlerResult.settled`),
|
|
1245
|
+
* and abandoning the call would abort that upload.
|
|
1246
|
+
*/
|
|
1247
|
+
async function* releasingOnExit(body, finish, release) {
|
|
1248
|
+
let completed = false;
|
|
1249
|
+
try {
|
|
1250
|
+
yield* body;
|
|
1251
|
+
completed = true;
|
|
1252
|
+
} finally {
|
|
1253
|
+
if (completed) finish();
|
|
1254
|
+
else await release();
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
/** Reads `output` to its end, discarding what is left, ignoring a failure. */
|
|
1258
|
+
async function drain(output) {
|
|
1259
|
+
try {
|
|
1260
|
+
for (let r = await output.next(); !r.done; r = await output.next());
|
|
1261
|
+
} catch {}
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Wrap an HTTP handler as a `Duplex` so it can be registered with any
|
|
1265
|
+
* `webrun-streams-*` adapter's `serve`.
|
|
1266
|
+
*/
|
|
1267
|
+
function httpServe(handler, options = {}) {
|
|
1268
|
+
const codec = options.codec ?? defaultCodec;
|
|
1269
|
+
return async function* httpHandlerDuplex(input) {
|
|
1270
|
+
let decoded;
|
|
1271
|
+
try {
|
|
1272
|
+
decoded = await codec.decodeRequest(input);
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
if (!(error instanceof HttpParseError)) throw error;
|
|
1275
|
+
yield* encodeErrorResponse(error.codec ?? codec, error, "GET", 400, "Bad Request");
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
const replyCodec = decoded.codec ?? codec;
|
|
1279
|
+
let result;
|
|
1280
|
+
try {
|
|
1281
|
+
result = await handler(decoded.envelope, decoded.body);
|
|
1282
|
+
} catch (error) {
|
|
1283
|
+
yield* encodeErrorResponse(replyCodec, error, decoded.envelope.method);
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
let completed = false;
|
|
1287
|
+
try {
|
|
1288
|
+
yield* replyCodec.encodeResponse(result.envelope, result.body, { method: decoded.envelope.method });
|
|
1289
|
+
completed = true;
|
|
1290
|
+
await result.settled?.();
|
|
1291
|
+
} finally {
|
|
1292
|
+
if (!completed) try {
|
|
1293
|
+
await result.release?.();
|
|
1294
|
+
} catch {}
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1040
1299
|
* The one place that knows a runtime may not implement request body streams,
|
|
1041
1300
|
* and the buffering both fallbacks need. `fetch.ts` and `http-stubs.ts` each
|
|
1042
1301
|
* carry a client and a server direction that must agree on the answer, so the
|
|
@@ -1167,580 +1426,3297 @@ function newHttpClientStub(send) {
|
|
|
1167
1426
|
};
|
|
1168
1427
|
}
|
|
1169
1428
|
/**
|
|
1170
|
-
*
|
|
1171
|
-
*
|
|
1429
|
+
* Connection-scoped headers. The codec surfaces them verbatim (decision 12),
|
|
1430
|
+
* but they are meaningless to a `Request`/`Response`, and re-emitting them
|
|
1431
|
+
* from a relay would corrupt its framing.
|
|
1172
1432
|
*/
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
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
|
-
};
|
|
1433
|
+
const HOP_BY_HOP = /* @__PURE__ */ new Set([
|
|
1434
|
+
"connection",
|
|
1435
|
+
"host",
|
|
1436
|
+
"keep-alive",
|
|
1437
|
+
"proxy-authenticate",
|
|
1438
|
+
"proxy-authorization",
|
|
1439
|
+
"te",
|
|
1440
|
+
"trailer",
|
|
1441
|
+
"transfer-encoding",
|
|
1442
|
+
"upgrade"
|
|
1443
|
+
]);
|
|
1444
|
+
function forwardableHeaders(headers) {
|
|
1445
|
+
return headers.filter(([name]) => !HOP_BY_HOP.has(name.toLowerCase()));
|
|
1201
1446
|
}
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
const
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
const
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
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);
|
|
1447
|
+
function headersToArray(headers) {
|
|
1448
|
+
const out = [];
|
|
1449
|
+
headers.forEach((value, key) => {
|
|
1450
|
+
out.push([key, value]);
|
|
1451
|
+
});
|
|
1452
|
+
return out;
|
|
1453
|
+
}
|
|
1454
|
+
async function* readableToAsyncIterable(stream) {
|
|
1455
|
+
if (!stream) return;
|
|
1456
|
+
const reader = stream.getReader();
|
|
1457
|
+
let consumed = false;
|
|
1458
|
+
try {
|
|
1459
|
+
while (true) {
|
|
1460
|
+
const { done, value } = await reader.read();
|
|
1461
|
+
if (done) {
|
|
1462
|
+
consumed = true;
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
if (value) yield value;
|
|
1234
1466
|
}
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1467
|
+
} finally {
|
|
1468
|
+
if (!consumed) try {
|
|
1469
|
+
await reader.cancel();
|
|
1470
|
+
} catch {}
|
|
1237
1471
|
try {
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1472
|
+
reader.releaseLock();
|
|
1473
|
+
} catch {}
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
function asyncIterableToReadable(iter) {
|
|
1477
|
+
const it = iter[Symbol.asyncIterator]();
|
|
1478
|
+
return new ReadableStream({
|
|
1479
|
+
async pull(controller) {
|
|
1480
|
+
try {
|
|
1481
|
+
const { done, value } = await it.next();
|
|
1482
|
+
if (done) {
|
|
1483
|
+
controller.close();
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
controller.enqueue(value);
|
|
1487
|
+
} catch (err) {
|
|
1488
|
+
controller.error(err);
|
|
1489
|
+
}
|
|
1490
|
+
},
|
|
1491
|
+
async cancel() {
|
|
1492
|
+
await it.return?.();
|
|
1242
1493
|
}
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Run a `Request` through a `Duplex` call and reconstruct the `Response` on
|
|
1498
|
+
* the other side. The request's `signal` is plumbed into the body iteration —
|
|
1499
|
+
* abort terminates the underlying call.
|
|
1500
|
+
*/
|
|
1501
|
+
async function fetchOverDuplex(call, request, options = {}) {
|
|
1502
|
+
if (request.signal?.aborted) throw abortReason$1(request.signal);
|
|
1503
|
+
const env = {
|
|
1504
|
+
url: request.url,
|
|
1505
|
+
method: request.method,
|
|
1506
|
+
headers: headersToArray(request.headers)
|
|
1243
1507
|
};
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1508
|
+
let body;
|
|
1509
|
+
if (request.body != null) body = readableToAsyncIterable(request.body);
|
|
1510
|
+
else if (!supportsRequestStreams()) {
|
|
1511
|
+
const buffered = new Uint8Array(await request.arrayBuffer());
|
|
1512
|
+
if (buffered.byteLength > 0) body = [buffered];
|
|
1513
|
+
}
|
|
1514
|
+
const { envelope, body: respBody, release, finish } = await httpFetch(call, env, body, {
|
|
1515
|
+
...options,
|
|
1516
|
+
signal: request.signal ?? void 0
|
|
1517
|
+
});
|
|
1518
|
+
const responseInit = {
|
|
1519
|
+
status: envelope.status,
|
|
1520
|
+
statusText: envelope.statusText,
|
|
1521
|
+
headers: forwardableHeaders(envelope.headers)
|
|
1522
|
+
};
|
|
1523
|
+
if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
|
|
1524
|
+
if (finish) finish();
|
|
1525
|
+
else await release?.();
|
|
1526
|
+
return new Response(null, responseInit);
|
|
1527
|
+
}
|
|
1528
|
+
return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
|
|
1529
|
+
}
|
|
1530
|
+
/**
|
|
1531
|
+
* Wrap a `(Request) => Promise<Response>` handler as a `Duplex` so it can be
|
|
1532
|
+
* registered with any `webrun-streams-*` adapter's `serve`.
|
|
1533
|
+
*/
|
|
1534
|
+
function serveFetchOverDuplex(handler, options = {}) {
|
|
1535
|
+
return httpServe(async (env, body) => {
|
|
1536
|
+
const reqInit = {
|
|
1537
|
+
method: env.method,
|
|
1538
|
+
headers: forwardableHeaders(env.headers)
|
|
1539
|
+
};
|
|
1540
|
+
let upload;
|
|
1541
|
+
if (env.method !== "GET" && env.method !== "HEAD") {
|
|
1542
|
+
if (supportsRequestStreams()) {
|
|
1543
|
+
upload = trackingEnd(body);
|
|
1544
|
+
reqInit.body = asyncIterableToReadable(upload.source);
|
|
1545
|
+
reqInit.duplex = "half";
|
|
1546
|
+
} else reqInit.body = await collectBytes(body);
|
|
1547
|
+
}
|
|
1548
|
+
const request = new Request(env.url, reqInit);
|
|
1549
|
+
const response = await handler(request);
|
|
1550
|
+
const settled = async () => {
|
|
1551
|
+
if (!upload) return;
|
|
1552
|
+
if (!request.bodyUsed && !request.body?.locked) request.body?.cancel().catch(() => {});
|
|
1553
|
+
await upload.settle(options.requestIdleMs ?? 3e4);
|
|
1554
|
+
};
|
|
1555
|
+
const respEnv = {
|
|
1556
|
+
status: response.status,
|
|
1557
|
+
statusText: response.statusText,
|
|
1558
|
+
headers: headersToArray(response.headers)
|
|
1559
|
+
};
|
|
1560
|
+
if (env.method === "HEAD" || env.method === "OPTIONS" || NULL_BODY_STATUSES.has(response.status)) {
|
|
1561
|
+
await response.body?.cancel();
|
|
1562
|
+
return {
|
|
1563
|
+
envelope: respEnv,
|
|
1564
|
+
body: void 0,
|
|
1565
|
+
settled
|
|
1566
|
+
};
|
|
1250
1567
|
}
|
|
1568
|
+
return {
|
|
1569
|
+
envelope: respEnv,
|
|
1570
|
+
body: response.body ? readableToAsyncIterable(response.body) : void 0,
|
|
1571
|
+
release: () => response.body?.cancel(),
|
|
1572
|
+
settled
|
|
1573
|
+
};
|
|
1574
|
+
}, options);
|
|
1575
|
+
}
|
|
1576
|
+
/**
|
|
1577
|
+
* `source`, and `settle(idleMs)`: resolves once it is done — read to its end,
|
|
1578
|
+
* failed, or abandoned (`return()` included before the first `next()`, which a
|
|
1579
|
+
* generator's `finally` would not see) — or once nobody has asked it for a
|
|
1580
|
+
* chunk for `idleMs`, in which case it is abandoned: later reads fail.
|
|
1581
|
+
*
|
|
1582
|
+
* Idle counts only while no `next()` is pending: a reader waiting for a slow
|
|
1583
|
+
* sender is still reading.
|
|
1584
|
+
*/
|
|
1585
|
+
function trackingEnd(source) {
|
|
1586
|
+
let end = () => {};
|
|
1587
|
+
let isEnded = false;
|
|
1588
|
+
const ended = new Promise((resolve) => {
|
|
1589
|
+
end = () => {
|
|
1590
|
+
isEnded = true;
|
|
1591
|
+
resolve();
|
|
1592
|
+
};
|
|
1593
|
+
});
|
|
1594
|
+
let abandoned;
|
|
1595
|
+
let pending = 0;
|
|
1596
|
+
let idleSince = Date.now();
|
|
1597
|
+
const it = source[Symbol.asyncIterator]();
|
|
1598
|
+
const abandon = (reason) => {
|
|
1599
|
+
abandoned ??= reason;
|
|
1600
|
+
end();
|
|
1601
|
+
Promise.resolve(it.return?.(void 0)).catch(() => {});
|
|
1251
1602
|
};
|
|
1252
|
-
const
|
|
1253
|
-
|
|
1254
|
-
|
|
1603
|
+
const tracked = {
|
|
1604
|
+
[Symbol.asyncIterator]() {
|
|
1605
|
+
return tracked;
|
|
1606
|
+
},
|
|
1607
|
+
async next() {
|
|
1608
|
+
if (abandoned) throw abandoned;
|
|
1609
|
+
pending++;
|
|
1255
1610
|
try {
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
};
|
|
1260
|
-
port.postMessage({
|
|
1261
|
-
type: MESSAGE_TYPE_REQUEST,
|
|
1262
|
-
callId,
|
|
1263
|
-
request
|
|
1264
|
-
}, transfers);
|
|
1611
|
+
const r = await it.next();
|
|
1612
|
+
if (r.done) end();
|
|
1613
|
+
return r;
|
|
1265
1614
|
} catch (error) {
|
|
1266
|
-
|
|
1267
|
-
|
|
1615
|
+
end();
|
|
1616
|
+
throw error;
|
|
1617
|
+
} finally {
|
|
1618
|
+
if (--pending === 0) idleSince = Date.now();
|
|
1268
1619
|
}
|
|
1620
|
+
},
|
|
1621
|
+
async return(value) {
|
|
1622
|
+
end();
|
|
1623
|
+
try {
|
|
1624
|
+
await it.return?.(value);
|
|
1625
|
+
} catch {}
|
|
1626
|
+
return {
|
|
1627
|
+
done: true,
|
|
1628
|
+
value: void 0
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
asyncDisposable$2(tracked, () => tracked.return?.() ?? Promise.resolve());
|
|
1633
|
+
const settle = (idleMs) => {
|
|
1634
|
+
if (isEnded || !Number.isFinite(idleMs)) return ended;
|
|
1635
|
+
return new Promise((resolve) => {
|
|
1636
|
+
let timer;
|
|
1637
|
+
const check = () => {
|
|
1638
|
+
if (isEnded) return resolve();
|
|
1639
|
+
const idle = pending === 0 ? Date.now() - idleSince : 0;
|
|
1640
|
+
if (idle >= idleMs) {
|
|
1641
|
+
abandon(/* @__PURE__ */ new Error(`webrun-http-streams: the request body was left unread for ${idleMs} ms after the response; abandoned`));
|
|
1642
|
+
return resolve();
|
|
1643
|
+
}
|
|
1644
|
+
timer = setTimeout(check, Math.max(1, Math.min(idleMs - idle, 1e3)));
|
|
1645
|
+
timer.unref?.();
|
|
1646
|
+
};
|
|
1647
|
+
ended.then(() => {
|
|
1648
|
+
clearTimeout(timer);
|
|
1649
|
+
resolve();
|
|
1650
|
+
});
|
|
1651
|
+
check();
|
|
1269
1652
|
});
|
|
1270
1653
|
};
|
|
1271
1654
|
return {
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
invoke
|
|
1655
|
+
source: tracked,
|
|
1656
|
+
settle
|
|
1275
1657
|
};
|
|
1276
1658
|
}
|
|
1277
|
-
async function*
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
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();
|
|
1659
|
+
async function* withAbort(iter, signal) {
|
|
1660
|
+
if (!signal) {
|
|
1661
|
+
yield* iter;
|
|
1662
|
+
return;
|
|
1663
|
+
}
|
|
1664
|
+
for await (const chunk of iter) {
|
|
1665
|
+
if (signal.aborted) throw abortReason$1(signal);
|
|
1666
|
+
yield chunk;
|
|
1293
1667
|
}
|
|
1294
1668
|
}
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1669
|
+
//#endregion
|
|
1670
|
+
//#region ../webrun-rpc/dist/index.js
|
|
1671
|
+
const closeSignals = /* @__PURE__ */ new WeakMap();
|
|
1672
|
+
/**
|
|
1673
|
+
* Internal: register a port's close signal. Called once by `bindBytesToPort`.
|
|
1674
|
+
*
|
|
1675
|
+
* @internal
|
|
1676
|
+
*/
|
|
1677
|
+
function setPortCloseSignal(port, signal) {
|
|
1678
|
+
closeSignals.set(port, signal);
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Return the AbortSignal that fires when `port`'s transport closes, or
|
|
1682
|
+
* `undefined` if `port` is not transport-backed (e.g., a raw
|
|
1683
|
+
* `MessageChannel().port1`).
|
|
1684
|
+
*/
|
|
1685
|
+
function getPortCloseSignal(port) {
|
|
1686
|
+
return closeSignals.get(port);
|
|
1687
|
+
}
|
|
1688
|
+
/**
|
|
1689
|
+
* Pass as `timeout` to install no deadline at all. Used by the stream tier,
|
|
1690
|
+
* where the deadline belongs to the stream rather than to one chunk (spec D8):
|
|
1691
|
+
* a slow consumer is throttled, never failed.
|
|
1692
|
+
*/
|
|
1693
|
+
const NO_TIMEOUT = Number.POSITIVE_INFINITY;
|
|
1694
|
+
/**
|
|
1695
|
+
* Asynchronous request/response over any `MessageTarget`.
|
|
1696
|
+
*
|
|
1697
|
+
* Sends `params` to the peer listening with `listenPort`, waits up to
|
|
1698
|
+
* `timeout` ms for a matching reply, and either resolves with the result or
|
|
1699
|
+
* rejects with the deserialised error.
|
|
1700
|
+
*/
|
|
1701
|
+
function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
|
|
1702
|
+
const callId = newCallId();
|
|
1703
|
+
log("[callPort]", {
|
|
1704
|
+
channelName,
|
|
1705
|
+
callId,
|
|
1706
|
+
params
|
|
1707
|
+
});
|
|
1708
|
+
const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
|
|
1709
|
+
let timerId;
|
|
1710
|
+
let onMessage;
|
|
1711
|
+
let onAbort;
|
|
1712
|
+
const promise = new Promise((resolve, reject) => {
|
|
1713
|
+
if (combinedSignal?.aborted) {
|
|
1714
|
+
reject(abortReason(combinedSignal));
|
|
1715
|
+
return;
|
|
1307
1716
|
}
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1717
|
+
if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
|
|
1718
|
+
onMessage = (event) => {
|
|
1719
|
+
const data = event.data;
|
|
1720
|
+
if (!data) return;
|
|
1721
|
+
if (data.channelName !== channelName) return;
|
|
1722
|
+
if (data.callId !== callId) return;
|
|
1723
|
+
if (data.type === "response:error") reject(deserializeError(data.error));
|
|
1724
|
+
else if (data.type === "response:result") resolve(data.result);
|
|
1725
|
+
};
|
|
1726
|
+
port.addEventListener("message", onMessage);
|
|
1727
|
+
if (combinedSignal) {
|
|
1728
|
+
onAbort = () => reject(abortReason(combinedSignal));
|
|
1729
|
+
combinedSignal.addEventListener("abort", onAbort, { once: true });
|
|
1730
|
+
}
|
|
1731
|
+
});
|
|
1732
|
+
promise.catch(() => {}).finally(() => {
|
|
1733
|
+
if (timerId !== void 0) clearTimeout(timerId);
|
|
1734
|
+
if (onMessage) port.removeEventListener("message", onMessage);
|
|
1735
|
+
if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
|
|
1736
|
+
});
|
|
1737
|
+
port.postMessage({
|
|
1738
|
+
type: "request",
|
|
1739
|
+
channelName,
|
|
1740
|
+
callId,
|
|
1741
|
+
params
|
|
1742
|
+
});
|
|
1743
|
+
return promise;
|
|
1312
1744
|
}
|
|
1313
|
-
function
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
const
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1745
|
+
function abortReason(signal) {
|
|
1746
|
+
const reason = signal.reason;
|
|
1747
|
+
if (reason instanceof Error) return reason;
|
|
1748
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
1749
|
+
err.name = "AbortError";
|
|
1750
|
+
return err;
|
|
1751
|
+
}
|
|
1752
|
+
function combineSignals(...signals) {
|
|
1753
|
+
const live = signals.filter((s) => s !== void 0);
|
|
1754
|
+
if (live.length === 0) return void 0;
|
|
1755
|
+
if (live.length === 1) return live[0];
|
|
1756
|
+
return AbortSignal.any(live);
|
|
1757
|
+
}
|
|
1758
|
+
/**
|
|
1759
|
+
* Installs `handler` as the server side of a `callPort` / `listenPort`
|
|
1760
|
+
* request/response pair on `port`.
|
|
1761
|
+
*
|
|
1762
|
+
* Returns a cleanup function that removes the listener.
|
|
1763
|
+
*/
|
|
1764
|
+
function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
|
|
1765
|
+
const onMessage = async (event) => {
|
|
1766
|
+
const data = event.data;
|
|
1767
|
+
if (!data || data.channelName !== channelName || data.type !== "request") return;
|
|
1768
|
+
const { callId, params } = data;
|
|
1769
|
+
log("[listenPort]", {
|
|
1770
|
+
channelName,
|
|
1771
|
+
callId,
|
|
1772
|
+
params
|
|
1773
|
+
});
|
|
1774
|
+
let result;
|
|
1775
|
+
let error;
|
|
1776
|
+
let type;
|
|
1777
|
+
try {
|
|
1778
|
+
result = await handler(params);
|
|
1779
|
+
type = "response:result";
|
|
1780
|
+
} catch (e) {
|
|
1781
|
+
error = serializeError(e);
|
|
1782
|
+
type = "response:error";
|
|
1340
1783
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1784
|
+
port.postMessage({
|
|
1785
|
+
callId,
|
|
1786
|
+
channelName,
|
|
1787
|
+
type,
|
|
1788
|
+
result,
|
|
1789
|
+
error
|
|
1790
|
+
});
|
|
1345
1791
|
};
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1792
|
+
port.addEventListener("message", onMessage);
|
|
1793
|
+
return () => port.removeEventListener("message", onMessage);
|
|
1794
|
+
}
|
|
1795
|
+
/**
|
|
1796
|
+
* Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
|
|
1797
|
+
* to return cleanly, forwarding `return()` to the underlying iterator so the
|
|
1798
|
+
* producer (e.g., a user-supplied generator) sees its own `finally` blocks
|
|
1799
|
+
* run immediately rather than waiting for the next yield.
|
|
1800
|
+
*/
|
|
1801
|
+
async function* throughAbort(input, signal) {
|
|
1802
|
+
const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
|
|
1803
|
+
const onAbort = () => {
|
|
1804
|
+
iter.return?.(void 0);
|
|
1350
1805
|
};
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
return () => {
|
|
1355
|
-
listeners = listeners.filter((l) => l !== deliver);
|
|
1356
|
-
};
|
|
1357
|
-
});
|
|
1806
|
+
if (signal.aborted) {
|
|
1807
|
+
iter.return?.(void 0);
|
|
1808
|
+
return;
|
|
1358
1809
|
}
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1810
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1811
|
+
try {
|
|
1812
|
+
while (true) {
|
|
1813
|
+
const r = await iter.next();
|
|
1814
|
+
if (r.done) return;
|
|
1815
|
+
if (signal.aborted) return;
|
|
1816
|
+
yield r.value;
|
|
1817
|
+
}
|
|
1818
|
+
} finally {
|
|
1819
|
+
signal.removeEventListener("abort", onAbort);
|
|
1368
1820
|
}
|
|
1369
|
-
return {
|
|
1370
|
-
start,
|
|
1371
|
-
close,
|
|
1372
|
-
cancel,
|
|
1373
|
-
recieveAll,
|
|
1374
|
-
sendAll
|
|
1375
|
-
};
|
|
1376
1821
|
}
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1822
|
+
/**
|
|
1823
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
1824
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
1825
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
1826
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
1827
|
+
* declared types, which would require consumers to compile with the
|
|
1828
|
+
* `esnext.disposable` lib.
|
|
1829
|
+
*/
|
|
1830
|
+
function asyncDisposable$1(target, dispose) {
|
|
1831
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
1832
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
1833
|
+
value: async () => {
|
|
1834
|
+
await dispose();
|
|
1835
|
+
},
|
|
1836
|
+
configurable: true,
|
|
1837
|
+
writable: true
|
|
1838
|
+
});
|
|
1839
|
+
return target;
|
|
1383
1840
|
}
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1841
|
+
/**
|
|
1842
|
+
* `gen`, except that `return()` and `throw()` take effect at once.
|
|
1843
|
+
*
|
|
1844
|
+
* On an async generator both are queued behind a `next()` that is still
|
|
1845
|
+
* pending: a consumer that gives up on a stream while it waits for the peer's
|
|
1846
|
+
* next chunk — an aborted fetch whose response head has not come, say — cannot
|
|
1847
|
+
* end it until that chunk arrives, which for a peer that never answers is
|
|
1848
|
+
* never. The stream's `finally` (which closes its port and tells the peer)
|
|
1849
|
+
* then never runs, and on a multiplexer the port is kept for good.
|
|
1850
|
+
*
|
|
1851
|
+
* So `abandon` runs first, synchronously: it must make the pending `next()`
|
|
1852
|
+
* settle (abort the stream), which then resolves done, after which the
|
|
1853
|
+
* generator's own `return()` / `throw()` proceeds as usual. On a generator
|
|
1854
|
+
* suspended at a `yield` it is the same ending, a step earlier. `abandon` runs once, whichever comes first.
|
|
1855
|
+
*/
|
|
1856
|
+
function returningAtOnce(gen, abandon) {
|
|
1857
|
+
let abandoned = false;
|
|
1858
|
+
const giveUp = (reason) => {
|
|
1859
|
+
if (abandoned) return;
|
|
1860
|
+
abandoned = true;
|
|
1861
|
+
abandon(reason);
|
|
1862
|
+
};
|
|
1863
|
+
const wrapped = {
|
|
1864
|
+
next: (...args) => gen.next(...args).catch((error) => {
|
|
1865
|
+
if (abandoned) return {
|
|
1866
|
+
done: true,
|
|
1867
|
+
value: void 0
|
|
1868
|
+
};
|
|
1869
|
+
throw error;
|
|
1870
|
+
}),
|
|
1871
|
+
return(value) {
|
|
1872
|
+
giveUp();
|
|
1873
|
+
return gen.return(value);
|
|
1874
|
+
},
|
|
1875
|
+
throw(error) {
|
|
1876
|
+
giveUp(error);
|
|
1877
|
+
return gen.throw(error);
|
|
1878
|
+
},
|
|
1879
|
+
[Symbol.asyncIterator]() {
|
|
1880
|
+
return wrapped;
|
|
1881
|
+
}
|
|
1397
1882
|
};
|
|
1883
|
+
return asyncDisposable$1(wrapped, () => wrapped.return(void 0));
|
|
1398
1884
|
}
|
|
1399
1885
|
/**
|
|
1400
|
-
*
|
|
1401
|
-
* `handleStreams` transport.
|
|
1886
|
+
* The `type` of the out-of-band notice a side posts when it abandons a stream.
|
|
1402
1887
|
*
|
|
1403
|
-
*
|
|
1404
|
-
*
|
|
1405
|
-
*
|
|
1406
|
-
*
|
|
1407
|
-
|
|
1888
|
+
* Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
|
|
1889
|
+
* its listeners silently and is indistinguishable from a working port nobody
|
|
1890
|
+
* is answering — so the peer would otherwise wait forever. Exported because
|
|
1891
|
+
* tests and adapters assert on it.
|
|
1892
|
+
*/
|
|
1893
|
+
const STREAM_ABORT = "webrun-rpc:stream-abort";
|
|
1894
|
+
/** Caller's input travels on this channel; the handler listens on it. */
|
|
1895
|
+
const CHANNEL_IN = "in";
|
|
1896
|
+
/** The handler's output travels on this channel; the caller listens on it. */
|
|
1897
|
+
const CHANNEL_OUT = "out";
|
|
1898
|
+
/**
|
|
1899
|
+
* One port in, one `Duplex` out (spec D9).
|
|
1408
1900
|
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1412
|
-
*
|
|
1901
|
+
* The returned `Duplex` runs a single stream on `port`: the caller's `input`
|
|
1902
|
+
* is sent chunk by chunk with `callPort`, and the handler's output arrives the
|
|
1903
|
+
* same way on the other channel. Within each direction the next chunk is never
|
|
1904
|
+
* sent until the previous one has been delivered *and* pulled past by the
|
|
1905
|
+
* consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
|
|
1906
|
+
* `listenPort` withholds it until then.
|
|
1413
1907
|
*
|
|
1414
|
-
*
|
|
1908
|
+
* A stream port carries exactly one invocation. To make several calls, open
|
|
1909
|
+
* several ports: `mux.openPort({ kind: "stream" })` per call.
|
|
1415
1910
|
*/
|
|
1416
|
-
function
|
|
1417
|
-
|
|
1418
|
-
return handleStreams(communicationPort, async (it) => {
|
|
1419
|
-
const envelope = await httpFromIterator(it);
|
|
1420
|
-
return httpToIterator(await serverStub(envelope));
|
|
1421
|
-
});
|
|
1911
|
+
function duplexOverPort(port, options = {}) {
|
|
1912
|
+
return (input) => runCallerSide(port, input, options);
|
|
1422
1913
|
}
|
|
1423
1914
|
/**
|
|
1424
|
-
*
|
|
1425
|
-
*
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1915
|
+
* Installs `handler` as the serving side of one stream on `port`. Returns an
|
|
1916
|
+
* idempotent teardown that abandons the stream and notifies the peer.
|
|
1917
|
+
*/
|
|
1918
|
+
function serveDuplexOverPort(port, handler, options = {}) {
|
|
1919
|
+
const controller = new AbortController();
|
|
1920
|
+
const notice = installAbortNotice(port, controller);
|
|
1921
|
+
abortOnPortClose(port, controller);
|
|
1922
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
1923
|
+
const inbound = receiveChunks(port, CHANNEL_IN, controller, clock.touch);
|
|
1924
|
+
let output;
|
|
1925
|
+
try {
|
|
1926
|
+
output = handler(inbound.stream);
|
|
1927
|
+
} catch (err) {
|
|
1928
|
+
const pump = sendChunks(port, CHANNEL_OUT, failing(err), options, controller.signal, clock.touch);
|
|
1929
|
+
pump.catch(() => {});
|
|
1930
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
1931
|
+
return teardownOnce(controller, notice, clock, inbound, void 0);
|
|
1932
|
+
}
|
|
1933
|
+
const pump = sendChunks(port, CHANNEL_OUT, output, options, controller.signal, clock.touch);
|
|
1934
|
+
pump.catch(() => {});
|
|
1935
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
1936
|
+
return teardownOnce(controller, notice, clock, inbound, output);
|
|
1937
|
+
}
|
|
1938
|
+
/**
|
|
1939
|
+
* A stream that completes normally has nobody left to call the returned
|
|
1940
|
+
* teardown — the caller only knows the stream ended, not that it must also
|
|
1941
|
+
* dispose the serve-side handle. Without this, the last `touch()`'s timer
|
|
1942
|
+
* stays armed for up to `timeout` ms after real completion, doing nothing
|
|
1943
|
+
* but holding the event loop open.
|
|
1432
1944
|
*
|
|
1433
|
-
*
|
|
1434
|
-
*
|
|
1435
|
-
*
|
|
1945
|
+
* Only disarms once BOTH `pump` (our output) and `inboundEnded` (the peer's
|
|
1946
|
+
* declared end of input, or an abort) have settled. Disarming on `pump`
|
|
1947
|
+
* alone is not safe: under half-close the handler can finish producing
|
|
1948
|
+
* output while the caller is still sending input, and a clock stopped then
|
|
1949
|
+
* would leave that still-open half with no deadline at all — worse than the
|
|
1950
|
+
* leak this fixes.
|
|
1436
1951
|
*/
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
})
|
|
1952
|
+
function disarmClockWhenBothSidesSettle(clock, pump, inboundEnded) {
|
|
1953
|
+
Promise.allSettled([pump, inboundEnded]).then(() => {
|
|
1954
|
+
clock.stop();
|
|
1955
|
+
});
|
|
1441
1956
|
}
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1957
|
+
async function* failing(err) {
|
|
1958
|
+
throw err;
|
|
1959
|
+
}
|
|
1960
|
+
function teardownOnce(controller, notice, clock, inbound, output) {
|
|
1961
|
+
let torn = false;
|
|
1962
|
+
return () => {
|
|
1963
|
+
if (torn) return;
|
|
1964
|
+
torn = true;
|
|
1965
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: stream torn down"));
|
|
1966
|
+
notice.post();
|
|
1967
|
+
notice.stop();
|
|
1968
|
+
clock.stop();
|
|
1969
|
+
inbound.stop();
|
|
1970
|
+
output?.return(void 0).catch(() => {});
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
function runCallerSide(port, input, options) {
|
|
1974
|
+
const controller = new AbortController();
|
|
1975
|
+
const notice = installAbortNotice(port, controller);
|
|
1976
|
+
abortOnPortClose(port, controller);
|
|
1977
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
1978
|
+
const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
|
|
1979
|
+
const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
|
|
1980
|
+
pump.catch(() => {});
|
|
1981
|
+
return returningAtOnce((async function* () {
|
|
1982
|
+
try {
|
|
1983
|
+
yield* inbound.stream;
|
|
1984
|
+
} finally {
|
|
1985
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
1986
|
+
notice.post();
|
|
1987
|
+
notice.stop();
|
|
1988
|
+
clock.stop();
|
|
1989
|
+
inbound.stop();
|
|
1990
|
+
await pump.catch(() => {});
|
|
1991
|
+
try {
|
|
1992
|
+
await port.close?.();
|
|
1993
|
+
} catch {}
|
|
1994
|
+
}
|
|
1995
|
+
})(), () => {
|
|
1996
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
1448
1997
|
});
|
|
1449
1998
|
}
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1999
|
+
/**
|
|
2000
|
+
* Listens for the peer's abort notice, and can post our own. The notice is a
|
|
2001
|
+
* plain message with no `channelName` and a `type` that is not `"request"`,
|
|
2002
|
+
* so neither `callPort` nor `listenPort` reacts to it, and it carries no
|
|
2003
|
+
* numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
|
|
2004
|
+
*/
|
|
2005
|
+
function installAbortNotice(port, controller) {
|
|
2006
|
+
const onMessage = (event) => {
|
|
2007
|
+
const data = event.data;
|
|
2008
|
+
if (!data || data.type !== "webrun-rpc:stream-abort") return;
|
|
2009
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
|
|
2010
|
+
};
|
|
2011
|
+
port.addEventListener("message", onMessage);
|
|
2012
|
+
let posted = false;
|
|
2013
|
+
return {
|
|
2014
|
+
post() {
|
|
2015
|
+
if (posted) return;
|
|
2016
|
+
posted = true;
|
|
2017
|
+
try {
|
|
2018
|
+
port.postMessage({ type: STREAM_ABORT });
|
|
2019
|
+
} catch {}
|
|
2020
|
+
},
|
|
2021
|
+
stop() {
|
|
2022
|
+
port.removeEventListener("message", onMessage);
|
|
2023
|
+
}
|
|
1463
2024
|
};
|
|
1464
|
-
return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
|
|
1465
2025
|
}
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
2026
|
+
/**
|
|
2027
|
+
* Aborts the stream when its port closes underneath it — the multiplexer was
|
|
2028
|
+
* closed, or the peer closed the port — for ports that report it (see
|
|
2029
|
+
* `getPortCloseSignal`). Without this a stream waiting for the peer's next
|
|
2030
|
+
* chunk would wait forever on a port that can no longer deliver one: the
|
|
2031
|
+
* outbound half's `callPort` already fails on the close signal, but nothing
|
|
2032
|
+
* failed the inbound half.
|
|
2033
|
+
*/
|
|
2034
|
+
function abortOnPortClose(port, controller) {
|
|
2035
|
+
const closed = getPortCloseSignal(port);
|
|
2036
|
+
if (!closed) return;
|
|
2037
|
+
const onClose = () => {
|
|
2038
|
+
if (!controller.signal.aborted) controller.abort(closed.reason);
|
|
2039
|
+
};
|
|
2040
|
+
if (closed.aborted) {
|
|
2041
|
+
onClose();
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
closed.addEventListener("abort", onClose, { once: true });
|
|
2045
|
+
controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
|
|
1470
2046
|
}
|
|
1471
2047
|
/**
|
|
1472
|
-
*
|
|
1473
|
-
*
|
|
1474
|
-
*
|
|
1475
|
-
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
2048
|
+
* The per-stream inactivity timeout (spec D8). Reset by any chunk in either
|
|
2049
|
+
* direction; elapsing aborts the stream. Unset, zero or non-finite installs no
|
|
2050
|
+
* timer at all, which is the default: a slow consumer is throttled, not failed.
|
|
1476
2051
|
*/
|
|
1477
|
-
function
|
|
1478
|
-
|
|
2052
|
+
function installStreamTimeout(controller, timeout) {
|
|
2053
|
+
if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
|
|
2054
|
+
touch() {},
|
|
2055
|
+
stop() {}
|
|
2056
|
+
};
|
|
2057
|
+
let timer;
|
|
2058
|
+
let stopped = false;
|
|
2059
|
+
const arm = () => {
|
|
2060
|
+
timer = setTimeout(() => {
|
|
2061
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
|
|
2062
|
+
}, timeout);
|
|
2063
|
+
};
|
|
2064
|
+
arm();
|
|
2065
|
+
return {
|
|
2066
|
+
touch() {
|
|
2067
|
+
if (stopped) return;
|
|
2068
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2069
|
+
arm();
|
|
2070
|
+
},
|
|
2071
|
+
stop() {
|
|
2072
|
+
stopped = true;
|
|
2073
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2074
|
+
timer = void 0;
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
1479
2077
|
}
|
|
1480
2078
|
/**
|
|
1481
|
-
*
|
|
2079
|
+
* The receiving half of one direction.
|
|
1482
2080
|
*
|
|
1483
|
-
*
|
|
1484
|
-
*
|
|
1485
|
-
*
|
|
2081
|
+
* The `listenPort` listener is installed **eagerly**, not lazily inside
|
|
2082
|
+
* `recieveIterator`'s installer, because a handler that never drains its input
|
|
2083
|
+
* would otherwise leave the peer's chunk calls with nobody to answer them. If
|
|
2084
|
+
* the local consumer has not started iterating, an inbound chunk waits for it —
|
|
2085
|
+
* which is the correct backpressure, and different from having no listener.
|
|
1486
2086
|
*/
|
|
1487
|
-
function
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
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]);
|
|
2087
|
+
function receiveChunks(port, channelName, controller, touch) {
|
|
2088
|
+
let deliver;
|
|
2089
|
+
const waiting = [];
|
|
2090
|
+
let finished = false;
|
|
2091
|
+
let outstanding = false;
|
|
2092
|
+
let poison;
|
|
2093
|
+
let resolveEnded = () => {};
|
|
2094
|
+
const ended = new Promise((resolve) => {
|
|
2095
|
+
resolveEnded = resolve;
|
|
1507
2096
|
});
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
const
|
|
1511
|
-
|
|
1512
|
-
const
|
|
1513
|
-
|
|
2097
|
+
let aborted = false;
|
|
2098
|
+
let abortReason;
|
|
2099
|
+
const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
|
|
2100
|
+
const wake = () => {
|
|
2101
|
+
for (const r of waiting.splice(0)) r();
|
|
2102
|
+
};
|
|
2103
|
+
const off = listenPort(port, async ({ done, value, error }) => {
|
|
2104
|
+
touch();
|
|
2105
|
+
if (poison) throw poison;
|
|
2106
|
+
if (outstanding) {
|
|
2107
|
+
poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
|
|
2108
|
+
controller.abort(poison);
|
|
2109
|
+
setTimeout(() => {
|
|
2110
|
+
try {
|
|
2111
|
+
port.close?.();
|
|
2112
|
+
} catch {}
|
|
2113
|
+
}, 0);
|
|
2114
|
+
throw poison;
|
|
2115
|
+
}
|
|
2116
|
+
outstanding = true;
|
|
1514
2117
|
try {
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
2118
|
+
await ready();
|
|
2119
|
+
if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
|
|
2120
|
+
await deliver?.({
|
|
2121
|
+
done,
|
|
2122
|
+
value,
|
|
2123
|
+
error: error ? deserializeError(error) : void 0
|
|
2124
|
+
});
|
|
2125
|
+
} finally {
|
|
2126
|
+
outstanding = false;
|
|
1518
2127
|
}
|
|
1519
|
-
|
|
2128
|
+
if (done) resolveEnded();
|
|
2129
|
+
}, { channelName });
|
|
2130
|
+
const detach = () => {
|
|
2131
|
+
finished = true;
|
|
2132
|
+
wake();
|
|
2133
|
+
off();
|
|
2134
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
2135
|
+
resolveEnded();
|
|
2136
|
+
};
|
|
2137
|
+
const onAbort = () => {
|
|
2138
|
+
aborted = true;
|
|
2139
|
+
abortReason = controller.signal.reason;
|
|
2140
|
+
finished = true;
|
|
2141
|
+
wake();
|
|
2142
|
+
deliver?.({
|
|
2143
|
+
done: true,
|
|
2144
|
+
error: abortReason
|
|
2145
|
+
});
|
|
2146
|
+
resolveEnded();
|
|
2147
|
+
};
|
|
2148
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
2149
|
+
return {
|
|
2150
|
+
stream: recieveIterator((d) => {
|
|
2151
|
+
if (aborted) {
|
|
2152
|
+
d({
|
|
2153
|
+
done: true,
|
|
2154
|
+
error: abortReason
|
|
2155
|
+
});
|
|
2156
|
+
return detach;
|
|
2157
|
+
}
|
|
2158
|
+
deliver = d;
|
|
2159
|
+
wake();
|
|
2160
|
+
return detach;
|
|
2161
|
+
}),
|
|
2162
|
+
stop: detach,
|
|
2163
|
+
ended
|
|
1520
2164
|
};
|
|
1521
|
-
target.addEventListener("message", listener);
|
|
1522
|
-
target.start?.();
|
|
1523
|
-
return () => target.removeEventListener("message", listener);
|
|
1524
2165
|
}
|
|
1525
|
-
//#endregion
|
|
1526
|
-
//#region src/core/deadline.ts
|
|
1527
2166
|
/**
|
|
1528
|
-
*
|
|
1529
|
-
*
|
|
1530
|
-
* other value resolves. Internal; not re-exported.
|
|
2167
|
+
* The sending half of one direction: one `callPort` per chunk, one call
|
|
2168
|
+
* outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
|
|
1531
2169
|
*/
|
|
1532
|
-
function
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
if (
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
2170
|
+
async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
|
|
2171
|
+
const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
|
|
2172
|
+
try {
|
|
2173
|
+
await sendIterator(async ({ done, value, error }) => {
|
|
2174
|
+
if (signal.aborted) return;
|
|
2175
|
+
const chunk = {
|
|
2176
|
+
done,
|
|
2177
|
+
value,
|
|
2178
|
+
error: error === void 0 ? void 0 : serializeError(error)
|
|
2179
|
+
};
|
|
2180
|
+
log?.("[duplexOverPort] send", {
|
|
2181
|
+
channelName,
|
|
2182
|
+
done,
|
|
2183
|
+
size: value?.byteLength
|
|
2184
|
+
});
|
|
2185
|
+
await callPort(port, chunk, {
|
|
2186
|
+
channelName,
|
|
2187
|
+
timeout: NO_TIMEOUT,
|
|
2188
|
+
signal
|
|
2189
|
+
});
|
|
2190
|
+
touch();
|
|
2191
|
+
}, stream);
|
|
2192
|
+
} catch (err) {
|
|
2193
|
+
if (signal.aborted) return;
|
|
2194
|
+
throw err;
|
|
2195
|
+
}
|
|
1547
2196
|
}
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
2197
|
+
/**
|
|
2198
|
+
* One virtual port.
|
|
2199
|
+
*
|
|
2200
|
+
* `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
|
|
2201
|
+
* only a `MessageTarget`, so it cannot forge inbound traffic or close the port
|
|
2202
|
+
* out from under the multiplexer's bookkeeping.
|
|
2203
|
+
*/
|
|
2204
|
+
function newVirtualPort(send, requestClose) {
|
|
2205
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2206
|
+
let closed = false;
|
|
2207
|
+
const closing = new AbortController();
|
|
2208
|
+
const abort = (reason) => {
|
|
2209
|
+
if (closing.signal.aborted) return;
|
|
2210
|
+
closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
|
|
2211
|
+
};
|
|
2212
|
+
const port = {
|
|
2213
|
+
addEventListener(_type, listener) {
|
|
2214
|
+
listeners.add(listener);
|
|
2215
|
+
},
|
|
2216
|
+
removeEventListener(_type, listener) {
|
|
2217
|
+
listeners.delete(listener);
|
|
2218
|
+
},
|
|
2219
|
+
postMessage(message, transfer) {
|
|
2220
|
+
if (closed) return;
|
|
2221
|
+
send(message, transfer);
|
|
2222
|
+
},
|
|
2223
|
+
close() {
|
|
2224
|
+
if (closed) return;
|
|
2225
|
+
closed = true;
|
|
2226
|
+
const notify = requestClose;
|
|
2227
|
+
listeners.clear();
|
|
2228
|
+
notify();
|
|
2229
|
+
abort();
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
setPortCloseSignal(port, closing.signal);
|
|
2233
|
+
return {
|
|
2234
|
+
port,
|
|
2235
|
+
deliver(payload) {
|
|
2236
|
+
if (closed) return;
|
|
2237
|
+
const event = new MessageEvent("message", { data: payload });
|
|
2238
|
+
for (const listener of [...listeners]) try {
|
|
2239
|
+
listener(event);
|
|
2240
|
+
} catch {}
|
|
2241
|
+
},
|
|
2242
|
+
markClosed(reason) {
|
|
2243
|
+
closed = true;
|
|
2244
|
+
listeners.clear();
|
|
2245
|
+
abort(reason);
|
|
2246
|
+
},
|
|
2247
|
+
isClosed() {
|
|
2248
|
+
return closed;
|
|
2249
|
+
}
|
|
2250
|
+
};
|
|
2251
|
+
}
|
|
2252
|
+
/**
|
|
2253
|
+
* The message of the error that fails the calls still in flight on a
|
|
2254
|
+
* multiplexer when it is closed (`PortMux.close()`).
|
|
2255
|
+
*/
|
|
2256
|
+
const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
|
|
2257
|
+
/** Ceiling on concurrently open virtual ports. Bounds the id table only. */
|
|
2258
|
+
const DEFAULT_MAX_PORTS = 1024;
|
|
2259
|
+
/**
|
|
2260
|
+
* The default `PortMux`: emulates multiplexing over a single port.
|
|
2261
|
+
*
|
|
2262
|
+
* A transport that already multiplexes natively supplies its own `PortMux`
|
|
2263
|
+
* instead — this implementation is for transports that offer one pipe.
|
|
2264
|
+
*/
|
|
2265
|
+
function multiplexPort(port, options) {
|
|
2266
|
+
const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
|
|
2267
|
+
const open = /* @__PURE__ */ new Map();
|
|
2268
|
+
let nextId = side === "initiator" ? 0 : 1;
|
|
2269
|
+
let muxClosed = false;
|
|
2270
|
+
const post = (envelope, transfer) => {
|
|
2271
|
+
if (muxClosed) return;
|
|
2272
|
+
try {
|
|
2273
|
+
codec.post(port, envelope, transfer);
|
|
2274
|
+
} catch {}
|
|
2275
|
+
};
|
|
2276
|
+
const attach = (id) => {
|
|
2277
|
+
let self;
|
|
2278
|
+
self = newVirtualPort((payload, transfer) => post({
|
|
2279
|
+
type: "message",
|
|
2280
|
+
id,
|
|
2281
|
+
payload
|
|
2282
|
+
}, transfer), (reason) => {
|
|
2283
|
+
post({
|
|
2284
|
+
type: "close",
|
|
2285
|
+
id,
|
|
2286
|
+
reason
|
|
2287
|
+
});
|
|
2288
|
+
open.delete(id);
|
|
2289
|
+
self.markClosed();
|
|
2290
|
+
});
|
|
2291
|
+
open.set(id, self);
|
|
2292
|
+
return self;
|
|
2293
|
+
};
|
|
2294
|
+
const handleEnvelope = (envelope) => {
|
|
2295
|
+
if (muxClosed) return;
|
|
2296
|
+
if (envelope.type === "open") {
|
|
2297
|
+
if (open.has(envelope.id)) return;
|
|
2298
|
+
if (open.size >= maxPorts) {
|
|
2299
|
+
post({
|
|
2300
|
+
type: "close",
|
|
2301
|
+
id: envelope.id,
|
|
2302
|
+
reason: "max-ports"
|
|
2303
|
+
});
|
|
2304
|
+
return;
|
|
1561
2305
|
}
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
2306
|
+
const handle = attach(envelope.id);
|
|
2307
|
+
let accepted = false;
|
|
2308
|
+
if (onPort) try {
|
|
2309
|
+
accepted = onPort(handle.port, envelope.meta) !== false;
|
|
2310
|
+
} catch {
|
|
2311
|
+
accepted = false;
|
|
2312
|
+
}
|
|
2313
|
+
if (!accepted) {
|
|
2314
|
+
open.delete(envelope.id);
|
|
2315
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
|
|
2316
|
+
post({
|
|
2317
|
+
type: "close",
|
|
2318
|
+
id: envelope.id,
|
|
2319
|
+
reason: "rejected"
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
return;
|
|
2323
|
+
}
|
|
2324
|
+
const handle = open.get(envelope.id);
|
|
2325
|
+
if (envelope.type === "message") {
|
|
2326
|
+
if (!handle) return;
|
|
2327
|
+
handle.deliver(envelope.payload);
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2330
|
+
if (!handle) return;
|
|
2331
|
+
open.delete(envelope.id);
|
|
2332
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
|
|
1565
2333
|
};
|
|
1566
|
-
const
|
|
1567
|
-
|
|
2334
|
+
const listener = (event) => {
|
|
2335
|
+
const envelope = codec.read(event);
|
|
2336
|
+
if (envelope) handleEnvelope(envelope);
|
|
1568
2337
|
};
|
|
1569
|
-
|
|
1570
|
-
|
|
2338
|
+
port.addEventListener("message", listener);
|
|
2339
|
+
port.start?.();
|
|
2340
|
+
return {
|
|
2341
|
+
maxMessageSize,
|
|
2342
|
+
async openPort(meta) {
|
|
2343
|
+
if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
|
|
2344
|
+
if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
|
|
2345
|
+
while (open.has(nextId)) nextId += 2;
|
|
2346
|
+
const id = nextId;
|
|
2347
|
+
nextId += 2;
|
|
2348
|
+
const handle = attach(id);
|
|
2349
|
+
post({
|
|
2350
|
+
type: "open",
|
|
2351
|
+
id,
|
|
2352
|
+
meta
|
|
2353
|
+
});
|
|
2354
|
+
return handle.port;
|
|
2355
|
+
},
|
|
2356
|
+
async close() {
|
|
2357
|
+
if (muxClosed) return;
|
|
2358
|
+
for (const [id, handle] of [...open]) {
|
|
2359
|
+
post({
|
|
2360
|
+
type: "close",
|
|
2361
|
+
id
|
|
2362
|
+
});
|
|
2363
|
+
open.delete(id);
|
|
2364
|
+
handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
|
|
2365
|
+
}
|
|
2366
|
+
muxClosed = true;
|
|
2367
|
+
port.removeEventListener("message", listener);
|
|
2368
|
+
await port.close?.();
|
|
2369
|
+
}
|
|
1571
2370
|
};
|
|
1572
|
-
return Object.assign([
|
|
1573
|
-
register,
|
|
1574
|
-
clear,
|
|
1575
|
-
unregister
|
|
1576
|
-
], {
|
|
1577
|
-
register,
|
|
1578
|
-
clear,
|
|
1579
|
-
unregister
|
|
1580
|
-
});
|
|
1581
2371
|
}
|
|
1582
|
-
//#endregion
|
|
1583
|
-
//#region src/core/service-worker-control.ts
|
|
1584
2372
|
/**
|
|
1585
|
-
*
|
|
1586
|
-
*
|
|
1587
|
-
*
|
|
2373
|
+
* Announced with every port this pair opens. Layer 1 never reads `meta` — it is
|
|
2374
|
+
* here so a peer running something else over the same multiplexer can tell a
|
|
2375
|
+
* stream port from whatever else it hands out, and so a packet capture says
|
|
2376
|
+
* what the port is for.
|
|
1588
2377
|
*/
|
|
1589
|
-
const
|
|
2378
|
+
const STREAM_META = { kind: "stream" };
|
|
1590
2379
|
/**
|
|
1591
|
-
*
|
|
1592
|
-
*
|
|
1593
|
-
*
|
|
1594
|
-
*
|
|
2380
|
+
* One port source in, one caller `Duplex` out.
|
|
2381
|
+
*
|
|
2382
|
+
* A call is a port: the mux allocates one, `duplexOverPort` runs the single
|
|
2383
|
+
* invocation on it, and closing the stream closes the port. No stream ids, no
|
|
2384
|
+
* framing and no credit accounting live here — the mux owns the first, and
|
|
2385
|
+
* `duplexOverPort` owns the one-chunk window that makes memory bounded.
|
|
1595
2386
|
*/
|
|
1596
|
-
const
|
|
1597
|
-
|
|
1598
|
-
const
|
|
2387
|
+
const connect = async ({ mux: factory, timeout }) => {
|
|
2388
|
+
const mux = await factory();
|
|
2389
|
+
const streamOptions = {
|
|
2390
|
+
maxMessageSize: mux.maxMessageSize,
|
|
2391
|
+
timeout
|
|
2392
|
+
};
|
|
2393
|
+
const call = (input) => {
|
|
2394
|
+
let stream;
|
|
2395
|
+
let abandoned = false;
|
|
2396
|
+
return returningAtOnce((async function* () {
|
|
2397
|
+
const port = await mux.openPort(STREAM_META);
|
|
2398
|
+
if (abandoned) {
|
|
2399
|
+
await port.close?.();
|
|
2400
|
+
return;
|
|
2401
|
+
}
|
|
2402
|
+
stream = duplexOverPort(port, streamOptions)(input);
|
|
2403
|
+
yield* stream;
|
|
2404
|
+
})(), () => {
|
|
2405
|
+
abandoned = true;
|
|
2406
|
+
stream?.return(void 0).catch(() => {});
|
|
2407
|
+
});
|
|
2408
|
+
};
|
|
2409
|
+
return {
|
|
2410
|
+
call,
|
|
2411
|
+
async close() {
|
|
2412
|
+
await mux.close();
|
|
2413
|
+
}
|
|
2414
|
+
};
|
|
2415
|
+
};
|
|
1599
2416
|
/**
|
|
1600
|
-
*
|
|
1601
|
-
*
|
|
1602
|
-
*
|
|
2417
|
+
* One port source in, `handler` serving every call that arrives on it.
|
|
2418
|
+
*
|
|
2419
|
+
* Each inbound port is one invocation, so the factory's `onPort` is the accept
|
|
2420
|
+
* loop: it installs `handler` on the new port and nothing else. The returned
|
|
2421
|
+
* teardown abandons the streams still running *before* dropping the mux, so
|
|
2422
|
+
* the peer's callers reject with "the peer abandoned the stream" instead of
|
|
2423
|
+
* parking forever on a port that has silently gone inert — layer 1's close is
|
|
2424
|
+
* not observable to layer 2, which is why the notice has to be posted
|
|
2425
|
+
* deliberately.
|
|
1603
2426
|
*/
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
2427
|
+
const serve = async ({ mux: factory, timeout }, handler) => {
|
|
2428
|
+
const live = /* @__PURE__ */ new Set();
|
|
2429
|
+
let streamOptions = { timeout };
|
|
2430
|
+
const mux = await factory((port) => {
|
|
2431
|
+
let off;
|
|
2432
|
+
let finished = false;
|
|
2433
|
+
const tracked = (input) => (async function* () {
|
|
2434
|
+
try {
|
|
2435
|
+
yield* handler(input);
|
|
2436
|
+
} finally {
|
|
2437
|
+
finished = true;
|
|
2438
|
+
if (off) live.delete(off);
|
|
2439
|
+
}
|
|
2440
|
+
})();
|
|
2441
|
+
off = serveDuplexOverPort(port, tracked, streamOptions);
|
|
2442
|
+
if (!finished) live.add(off);
|
|
2443
|
+
});
|
|
2444
|
+
streamOptions = {
|
|
2445
|
+
maxMessageSize: mux.maxMessageSize,
|
|
2446
|
+
timeout
|
|
2447
|
+
};
|
|
2448
|
+
let torn = false;
|
|
2449
|
+
return async () => {
|
|
2450
|
+
if (torn) return;
|
|
2451
|
+
torn = true;
|
|
2452
|
+
for (const off of [...live]) {
|
|
2453
|
+
live.delete(off);
|
|
2454
|
+
try {
|
|
2455
|
+
off();
|
|
2456
|
+
} catch {}
|
|
2457
|
+
}
|
|
2458
|
+
await mux.close();
|
|
2459
|
+
};
|
|
1611
2460
|
};
|
|
1612
2461
|
/**
|
|
1613
|
-
*
|
|
1614
|
-
*
|
|
1615
|
-
*
|
|
1616
|
-
*
|
|
2462
|
+
* Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
|
|
2463
|
+
*
|
|
2464
|
+
* There is no second port to be had, so `multiplexPort`'s id table invents
|
|
2465
|
+
* them. Use this when the transport gives you exactly one channel.
|
|
1617
2466
|
*/
|
|
1618
|
-
|
|
1619
|
-
return
|
|
1620
|
-
|
|
1621
|
-
|
|
2467
|
+
function overPipe(pipe, options) {
|
|
2468
|
+
return (onPort) => multiplexPort(pipe, {
|
|
2469
|
+
...options,
|
|
2470
|
+
onPort
|
|
1622
2471
|
});
|
|
1623
2472
|
}
|
|
2473
|
+
function isEnvelope(value) {
|
|
2474
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2475
|
+
const candidate = value;
|
|
2476
|
+
if (typeof candidate.id !== "number") return false;
|
|
2477
|
+
if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
|
|
2478
|
+
return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
|
|
2479
|
+
}
|
|
1624
2480
|
/**
|
|
1625
|
-
*
|
|
1626
|
-
*
|
|
2481
|
+
* For ports whose messages are structured values — a real `MessagePort`, a
|
|
2482
|
+
* worker, an iframe.
|
|
1627
2483
|
*
|
|
1628
|
-
*
|
|
1629
|
-
*
|
|
1630
|
-
*
|
|
1631
|
-
*
|
|
1632
|
-
* - Firefox can leave a page loaded while the worker is running uncontrolled.
|
|
1633
|
-
*
|
|
1634
|
-
* So when the page is uncontrolled, this asks the active worker to claim it
|
|
1635
|
-
* again (a `CLAIM` channel call — this package's workers answer it) and waits
|
|
1636
|
-
* for `controllerchange`. Every wait is bounded by `timeout`. If control never
|
|
1637
|
-
* comes it reloads once (`reloadIfUncontrolled`) or rejects with a
|
|
1638
|
-
* `ServiceWorkerControlError` (`reason: "uncontrolled"`) that says what
|
|
1639
|
-
* happened and what to do.
|
|
2484
|
+
* Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
|
|
2485
|
+
* zero-copy through the transfer list, and structured clone does the work the
|
|
2486
|
+
* platform already does well. This is a performance choice only: layer 2 may
|
|
2487
|
+
* not send anything a byte codec could not also carry.
|
|
1640
2488
|
*/
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
await Promise.race([callChannel(active, CLAIM_CALL, {}), controlled.promise]);
|
|
1649
|
-
return await Promise.race([controlled.promise, delay(CLAIM_GRACE_MS, null)]);
|
|
1650
|
-
})(), () => null);
|
|
1651
|
-
if (controller) {
|
|
1652
|
-
forgetReload(registration);
|
|
1653
|
-
return controller;
|
|
1654
|
-
}
|
|
1655
|
-
if (reloadIfUncontrolled && markReload(registration)) {
|
|
1656
|
-
location.reload();
|
|
1657
|
-
return await new Promise(() => {});
|
|
1658
|
-
}
|
|
1659
|
-
forgetReload(registration);
|
|
1660
|
-
throw new ServiceWorkerControlError("uncontrolled", `This page is not controlled by its ServiceWorker ${scriptUrl(active)} (scope ${registration.scope}), although the worker is active, and the worker did not take control when asked (clients.claim()) within ${timeout} ms. This happens after a hard reload (Ctrl+Shift+R / Cmd+Shift+R), which bypasses ServiceWorkers for that load, and in Firefox for some pages opened while the worker was already running. Requests from this page would not reach the worker. Reload the page normally, pass \`reloadIfUncontrolled: true\` to do that automatically, check that the page is inside the worker's scope, and that the worker answers the "${CLAIM_CALL}" request (this package's workers do).`);
|
|
1661
|
-
} finally {
|
|
1662
|
-
controlled.cancel();
|
|
2489
|
+
const structuredCodec = {
|
|
2490
|
+
post(port, envelope, transfer) {
|
|
2491
|
+
if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
|
|
2492
|
+
else port.postMessage(envelope);
|
|
2493
|
+
},
|
|
2494
|
+
read(event) {
|
|
2495
|
+
return isEnvelope(event.data) ? event.data : void 0;
|
|
1663
2496
|
}
|
|
2497
|
+
};
|
|
2498
|
+
//#endregion
|
|
2499
|
+
//#region src/link/async-dispose.ts
|
|
2500
|
+
/**
|
|
2501
|
+
* Makes `target` disposable with `await using`: installs `dispose` as its
|
|
2502
|
+
* `[Symbol.asyncDispose]`, where the runtime defines the symbol. Hand-written
|
|
2503
|
+
* iterators lose what a native generator gets from `AsyncIteratorPrototype`;
|
|
2504
|
+
* this gives it back. A no-op where the symbol is missing. Kept off the
|
|
2505
|
+
* declared types, which would require consumers to compile with the
|
|
2506
|
+
* `esnext.disposable` lib.
|
|
2507
|
+
*/
|
|
2508
|
+
function asyncDisposable(target, dispose) {
|
|
2509
|
+
const asyncDispose = Symbol.asyncDispose;
|
|
2510
|
+
if (asyncDispose && !(asyncDispose in target)) Object.defineProperty(target, asyncDispose, {
|
|
2511
|
+
value: async () => {
|
|
2512
|
+
await dispose();
|
|
2513
|
+
},
|
|
2514
|
+
configurable: true,
|
|
2515
|
+
writable: true
|
|
2516
|
+
});
|
|
2517
|
+
return target;
|
|
1664
2518
|
}
|
|
2519
|
+
//#endregion
|
|
2520
|
+
//#region src/link/http-link.ts
|
|
1665
2521
|
/**
|
|
1666
|
-
*
|
|
1667
|
-
*
|
|
1668
|
-
*
|
|
2522
|
+
* The version of the HTTP-over-`MessagePort` protocol this package speaks,
|
|
2523
|
+
* sent in every hand-shake that sets up a link. Version 1 was this package's
|
|
2524
|
+
* own `handleStreams` / `sendStream` (no backpressure); version 2 is
|
|
2525
|
+
* webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
|
|
2526
|
+
* `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
|
|
2527
|
+
* multiplexed on it, each call a stream with a one-chunk window in both
|
|
2528
|
+
* directions, and cancellation that reaches the handler.
|
|
1669
2529
|
*/
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
2530
|
+
const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
|
|
2531
|
+
/**
|
|
2532
|
+
* Why a request failed when its link went away under it: the far side (the
|
|
2533
|
+
* handler, or the ServiceWorker) was lost. The request may or may not have
|
|
2534
|
+
* been applied.
|
|
2535
|
+
*/
|
|
2536
|
+
var LinkLostError = class extends Error {
|
|
2537
|
+
constructor(message = "The link was lost while this request was in flight") {
|
|
2538
|
+
super(`${message}; it may or may not have been applied.`);
|
|
2539
|
+
this.name = "LinkLostError";
|
|
2540
|
+
}
|
|
2541
|
+
};
|
|
2542
|
+
/**
|
|
2543
|
+
* Posted on a link's port by the calling end when it closes the link, so the
|
|
2544
|
+
* answering end can release it: a `MessagePort` never reports that its other
|
|
2545
|
+
* end is gone.
|
|
2546
|
+
*/
|
|
2547
|
+
const LINK_CLOSE = "webrun-http:link-close";
|
|
2548
|
+
/** Opens the calling end of a link on `port` (one port per link). */
|
|
2549
|
+
async function connectHttpLink(port, { streamTimeout, maxPorts } = {}) {
|
|
2550
|
+
const { call, close } = await connect({
|
|
2551
|
+
mux: overPipe(port, {
|
|
2552
|
+
codec: structuredCodec,
|
|
2553
|
+
side: "initiator",
|
|
2554
|
+
maxPorts
|
|
2555
|
+
}),
|
|
2556
|
+
timeout: streamTimeout
|
|
2557
|
+
});
|
|
2558
|
+
return trackedLink((request) => fetchOverDuplex(call, request), async () => {
|
|
2559
|
+
try {
|
|
2560
|
+
port.postMessage({ type: LINK_CLOSE });
|
|
2561
|
+
} catch {}
|
|
2562
|
+
await close();
|
|
1675
2563
|
});
|
|
1676
2564
|
}
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
2565
|
+
/**
|
|
2566
|
+
* Serves `handler` on the answering end of a link. Resolves with a teardown
|
|
2567
|
+
* that abandons the requests still running (their handlers see the
|
|
2568
|
+
* cancellation) and releases the port.
|
|
2569
|
+
*/
|
|
2570
|
+
async function serveHttpLink(port, handler, { streamTimeout, maxPorts, requestIdleMs } = {}) {
|
|
2571
|
+
const teardown = await serve({
|
|
2572
|
+
mux: overPipe(port, {
|
|
2573
|
+
codec: structuredCodec,
|
|
2574
|
+
side: "responder",
|
|
2575
|
+
maxPorts
|
|
2576
|
+
}),
|
|
2577
|
+
timeout: streamTimeout
|
|
2578
|
+
}, serveFetchOverDuplex(async (request) => await handler(request), { requestIdleMs }));
|
|
2579
|
+
const onClose = (event) => {
|
|
2580
|
+
if (event.data?.type === LINK_CLOSE) close();
|
|
2581
|
+
};
|
|
2582
|
+
const close = async () => {
|
|
2583
|
+
port.removeEventListener("message", onClose);
|
|
2584
|
+
await teardown();
|
|
2585
|
+
};
|
|
2586
|
+
port.addEventListener("message", onClose);
|
|
2587
|
+
return close;
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* Wraps a `send` so the link knows its requests in flight (for draining and
|
|
2591
|
+
* load-based routing) and can fail them all at once when it is closed.
|
|
2592
|
+
*/
|
|
2593
|
+
function trackedLink(send, release) {
|
|
2594
|
+
let inflight = 0;
|
|
2595
|
+
let closed = false;
|
|
2596
|
+
let lostReason;
|
|
2597
|
+
const failers = /* @__PURE__ */ new Set();
|
|
2598
|
+
const idleWaiters = [];
|
|
2599
|
+
const done = () => {
|
|
2600
|
+
inflight--;
|
|
2601
|
+
if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
|
|
2602
|
+
};
|
|
2603
|
+
const link = {
|
|
2604
|
+
get inflight() {
|
|
2605
|
+
return inflight;
|
|
2606
|
+
},
|
|
2607
|
+
get closed() {
|
|
2608
|
+
return closed;
|
|
2609
|
+
},
|
|
2610
|
+
whenIdle() {
|
|
2611
|
+
return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
|
|
2612
|
+
},
|
|
2613
|
+
async send(request) {
|
|
2614
|
+
if (closed) throw lostReason ?? new LinkLostError("The link is closed");
|
|
2615
|
+
inflight++;
|
|
2616
|
+
let finished = false;
|
|
2617
|
+
const finish = () => {
|
|
2618
|
+
if (finished) return;
|
|
2619
|
+
finished = true;
|
|
2620
|
+
failers.delete(fail);
|
|
2621
|
+
done();
|
|
2622
|
+
};
|
|
2623
|
+
let fail = () => {};
|
|
2624
|
+
const lost = new Promise((_, reject) => {
|
|
2625
|
+
fail = reject;
|
|
2626
|
+
});
|
|
2627
|
+
failers.add(fail);
|
|
2628
|
+
lost.catch(() => {});
|
|
2629
|
+
let response;
|
|
2630
|
+
try {
|
|
2631
|
+
response = await Promise.race([send(request), lost]);
|
|
2632
|
+
} catch (error) {
|
|
2633
|
+
finish();
|
|
2634
|
+
throw lostReason ?? error;
|
|
1687
2635
|
}
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
for (const worker of [
|
|
1692
|
-
registration.installing,
|
|
1693
|
-
registration.waiting,
|
|
1694
|
-
registration.active
|
|
1695
|
-
]) {
|
|
1696
|
-
if (!worker || watched.has(worker)) continue;
|
|
1697
|
-
watched.add(worker);
|
|
1698
|
-
worker.addEventListener("statechange", check);
|
|
2636
|
+
if (!response.body) {
|
|
2637
|
+
finish();
|
|
2638
|
+
return response;
|
|
1699
2639
|
}
|
|
2640
|
+
return new Response(guardBody(response.body, lost, () => lostReason, finish), {
|
|
2641
|
+
status: response.status,
|
|
2642
|
+
statusText: response.statusText,
|
|
2643
|
+
headers: response.headers
|
|
2644
|
+
});
|
|
2645
|
+
},
|
|
2646
|
+
async close(reason) {
|
|
2647
|
+
if (closed) return;
|
|
2648
|
+
closed = true;
|
|
2649
|
+
lostReason = reason ?? new LinkLostError("The link was closed");
|
|
2650
|
+
for (const fail of [...failers]) fail(lostReason);
|
|
2651
|
+
try {
|
|
2652
|
+
await release();
|
|
2653
|
+
} catch {}
|
|
1700
2654
|
}
|
|
1701
|
-
registration.addEventListener("updatefound", watch);
|
|
1702
|
-
check();
|
|
1703
|
-
});
|
|
1704
|
-
}
|
|
1705
|
-
function waitForController(container) {
|
|
1706
|
-
let cancel = () => {};
|
|
1707
|
-
return {
|
|
1708
|
-
promise: new Promise((resolve) => {
|
|
1709
|
-
const onChange = () => {
|
|
1710
|
-
if (!container.controller) return;
|
|
1711
|
-
cancel();
|
|
1712
|
-
resolve(container.controller);
|
|
1713
|
-
};
|
|
1714
|
-
cancel = () => container.removeEventListener("controllerchange", onChange);
|
|
1715
|
-
container.addEventListener("controllerchange", onChange);
|
|
1716
|
-
}),
|
|
1717
|
-
cancel
|
|
1718
2655
|
};
|
|
2656
|
+
return asyncDisposable(link, () => link.close());
|
|
1719
2657
|
}
|
|
1720
|
-
|
|
1721
|
-
|
|
2658
|
+
/**
|
|
2659
|
+
* A response body that reports its end (done, cancelled or failed) and fails
|
|
2660
|
+
* with the link's reason when the link is lost mid-stream.
|
|
2661
|
+
*/
|
|
2662
|
+
function guardBody(body, lost, reason, finish) {
|
|
2663
|
+
const reader = body.getReader();
|
|
2664
|
+
return new ReadableStream({
|
|
2665
|
+
async pull(controller) {
|
|
2666
|
+
try {
|
|
2667
|
+
const { done, value } = await Promise.race([reader.read(), lost]);
|
|
2668
|
+
if (done) {
|
|
2669
|
+
finish();
|
|
2670
|
+
controller.close();
|
|
2671
|
+
return;
|
|
2672
|
+
}
|
|
2673
|
+
controller.enqueue(value);
|
|
2674
|
+
} catch (error) {
|
|
2675
|
+
finish();
|
|
2676
|
+
reader.cancel().catch(() => {});
|
|
2677
|
+
controller.error(reason() ?? error);
|
|
2678
|
+
}
|
|
2679
|
+
},
|
|
2680
|
+
async cancel(why) {
|
|
2681
|
+
finish();
|
|
2682
|
+
await reader.cancel(why).catch(() => {});
|
|
2683
|
+
}
|
|
2684
|
+
});
|
|
1722
2685
|
}
|
|
1723
|
-
|
|
1724
|
-
|
|
2686
|
+
//#endregion
|
|
2687
|
+
//#region src/link/locks.ts
|
|
2688
|
+
function lockManager() {
|
|
2689
|
+
return globalThis.navigator?.locks;
|
|
1725
2690
|
}
|
|
1726
|
-
function
|
|
1727
|
-
return
|
|
2691
|
+
function locksAvailable() {
|
|
2692
|
+
return lockManager() !== void 0;
|
|
1728
2693
|
}
|
|
1729
|
-
/**
|
|
1730
|
-
function
|
|
2694
|
+
/** A fresh lock name: `<prefix>:<uuid>`. */
|
|
2695
|
+
function newLockName(prefix) {
|
|
2696
|
+
return `${prefix}:${crypto.randomUUID()}`;
|
|
2697
|
+
}
|
|
2698
|
+
/**
|
|
2699
|
+
* Takes the lock `name` and holds it until the returned release is called or
|
|
2700
|
+
* this context dies. Resolves once the lock is held; with no Web Locks,
|
|
2701
|
+
* resolves at once.
|
|
2702
|
+
*/
|
|
2703
|
+
async function holdLock(name) {
|
|
2704
|
+
const locks = lockManager();
|
|
2705
|
+
if (!locks) return () => {};
|
|
2706
|
+
let release = () => {};
|
|
2707
|
+
const released = new Promise((resolve) => {
|
|
2708
|
+
release = resolve;
|
|
2709
|
+
});
|
|
2710
|
+
await new Promise((held) => {
|
|
2711
|
+
locks.request(name, {}, () => {
|
|
2712
|
+
held();
|
|
2713
|
+
return released;
|
|
2714
|
+
}).catch(() => held());
|
|
2715
|
+
});
|
|
2716
|
+
return release;
|
|
2717
|
+
}
|
|
2718
|
+
/**
|
|
2719
|
+
* Calls `onLost` once the lock `name` is granted to this context — that is,
|
|
2720
|
+
* once whoever holds it is gone — and releases it at once. Returns a function
|
|
2721
|
+
* that stops watching. With no Web Locks, never calls `onLost`.
|
|
2722
|
+
*/
|
|
2723
|
+
function watchLock(name, onLost) {
|
|
2724
|
+
const locks = lockManager();
|
|
2725
|
+
if (!locks) return () => {};
|
|
2726
|
+
const controller = new AbortController();
|
|
2727
|
+
locks.request(name, { signal: controller.signal }, () => {
|
|
2728
|
+
if (!controller.signal.aborted) onLost();
|
|
2729
|
+
}).catch(() => {});
|
|
2730
|
+
return () => controller.abort();
|
|
2731
|
+
}
|
|
2732
|
+
/**
|
|
2733
|
+
* The names of the locks held right now in this origin, or `undefined` where
|
|
2734
|
+
* that cannot be asked. A backup for `watchLock`: a grant can be late, a query
|
|
2735
|
+
* cannot.
|
|
2736
|
+
*/
|
|
2737
|
+
async function heldLockNames() {
|
|
2738
|
+
const locks = lockManager();
|
|
2739
|
+
if (!locks?.query) return void 0;
|
|
1731
2740
|
try {
|
|
1732
|
-
const
|
|
1733
|
-
|
|
1734
|
-
sessionStorage.setItem(key, "1");
|
|
1735
|
-
return true;
|
|
2741
|
+
const { held = [] } = await locks.query();
|
|
2742
|
+
return new Set(held.map((lock) => lock.name ?? ""));
|
|
1736
2743
|
} catch {
|
|
1737
|
-
return
|
|
2744
|
+
return;
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
//#endregion
|
|
2748
|
+
//#region src/link/rendezvous.ts
|
|
2749
|
+
/**
|
|
2750
|
+
* Matches replies to requests by id, for the control messages that hand
|
|
2751
|
+
* WebSocket ports across: each waiting request has a deadline, and all of a
|
|
2752
|
+
* peer's waiting requests can be failed at once when the peer is lost.
|
|
2753
|
+
*/
|
|
2754
|
+
var PortRendezvous = class {
|
|
2755
|
+
_prefix;
|
|
2756
|
+
_waiting = /* @__PURE__ */ new Map();
|
|
2757
|
+
_counter = 0;
|
|
2758
|
+
constructor(_prefix = "r") {
|
|
2759
|
+
this._prefix = _prefix;
|
|
2760
|
+
}
|
|
2761
|
+
/** A fresh id for a request. */
|
|
2762
|
+
newId() {
|
|
2763
|
+
return `${this._prefix}:${++this._counter}`;
|
|
2764
|
+
}
|
|
2765
|
+
get size() {
|
|
2766
|
+
return this._waiting.size;
|
|
2767
|
+
}
|
|
2768
|
+
/** Waits for the reply to `id`, failing after `timeoutMs`. */
|
|
2769
|
+
wait(id, timeoutMs, describe = "the reply") {
|
|
2770
|
+
return new Promise((resolve, reject) => {
|
|
2771
|
+
const timer = setTimeout(() => {
|
|
2772
|
+
this._waiting.delete(id);
|
|
2773
|
+
reject(/* @__PURE__ */ new Error(`No answer to ${describe} within ${timeoutMs} ms`));
|
|
2774
|
+
}, timeoutMs);
|
|
2775
|
+
this._waiting.set(id, {
|
|
2776
|
+
resolve,
|
|
2777
|
+
reject,
|
|
2778
|
+
timer
|
|
2779
|
+
});
|
|
2780
|
+
});
|
|
2781
|
+
}
|
|
2782
|
+
/** Delivers the reply to `id`. `false` when nobody waits for it (it timed out). */
|
|
2783
|
+
settle(id, value) {
|
|
2784
|
+
const waiting = this._waiting.get(id);
|
|
2785
|
+
if (!waiting) return false;
|
|
2786
|
+
this._waiting.delete(id);
|
|
2787
|
+
clearTimeout(waiting.timer);
|
|
2788
|
+
waiting.resolve(value);
|
|
2789
|
+
return true;
|
|
2790
|
+
}
|
|
2791
|
+
fail(id, error) {
|
|
2792
|
+
const waiting = this._waiting.get(id);
|
|
2793
|
+
if (!waiting) return;
|
|
2794
|
+
this._waiting.delete(id);
|
|
2795
|
+
clearTimeout(waiting.timer);
|
|
2796
|
+
waiting.reject(error);
|
|
2797
|
+
}
|
|
2798
|
+
failAll(error) {
|
|
2799
|
+
for (const id of [...this._waiting.keys()]) this.fail(id, error);
|
|
2800
|
+
}
|
|
2801
|
+
};
|
|
2802
|
+
//#endregion
|
|
2803
|
+
//#region src/link/errors.ts
|
|
2804
|
+
function errorMessage(error) {
|
|
2805
|
+
return error instanceof Error ? error.message : String(error);
|
|
2806
|
+
}
|
|
2807
|
+
//#endregion
|
|
2808
|
+
//#region src/ws/frames.ts
|
|
2809
|
+
/**
|
|
2810
|
+
* The wire protocol of a WebSocket carried over a `MessagePort`.
|
|
2811
|
+
*
|
|
2812
|
+
* A `MessagePort` is a natural carrier for a WebSocket: messages arrive in
|
|
2813
|
+
* order, and strings and transferable `ArrayBuffer`s cross it as they are. The
|
|
2814
|
+
* protocol on top is these frames, the same in both directions:
|
|
2815
|
+
*
|
|
2816
|
+
* - `m` — one message. An `ArrayBuffer` is transferred, never copied.
|
|
2817
|
+
* - `c` — close. The side that closes first sends it; the other answers with
|
|
2818
|
+
* its own `c` (the echo), and both are then closed cleanly.
|
|
2819
|
+
* - `p` — ping, client to server, carrying the client's heartbeat period.
|
|
2820
|
+
* - `q` — pong, server to client.
|
|
2821
|
+
* - `a` — ack: the receiver consumed `n` more bytes of messages. This is the
|
|
2822
|
+
* flow control: what a side has sent and not yet seen acknowledged is its
|
|
2823
|
+
* `bufferedAmount`, and the server end can wait for it to fall
|
|
2824
|
+
* (`whenDrained`). Added in version 2; version 1 had no backpressure.
|
|
2825
|
+
*
|
|
2826
|
+
* HEARTBEAT. A `MessagePort` never reports that the other side died, so the
|
|
2827
|
+
* client pings every `hb` ms and closes with 1006 when pongs stop for `2·hb`;
|
|
2828
|
+
* the server closes with 1006 when pings stop for `3·hb`. That is how a socket
|
|
2829
|
+
* notices a closed tab or a terminated worker.
|
|
2830
|
+
*
|
|
2831
|
+
* Unknown frames are ignored, so a later version can add frames a peer of
|
|
2832
|
+
* this version skips.
|
|
2833
|
+
*/
|
|
2834
|
+
/** The version of this frame protocol. Sent in the upgrade hand-shake. */
|
|
2835
|
+
const WS_PORT_PROTOCOL_VERSION = 2;
|
|
2836
|
+
/** Default heartbeat period of the client, in ms. */
|
|
2837
|
+
const DEFAULT_HEARTBEAT_MS = 1e4;
|
|
2838
|
+
/** How long a side waits for the echo of its close frame, in ms. */
|
|
2839
|
+
const DEFAULT_CLOSE_TIMEOUT_MS = 5e3;
|
|
2840
|
+
const defaultTimers = {
|
|
2841
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
2842
|
+
clearTimeout: (id) => clearTimeout(id),
|
|
2843
|
+
setInterval: (fn, ms) => setInterval(fn, ms),
|
|
2844
|
+
clearInterval: (id) => clearInterval(id)
|
|
2845
|
+
};
|
|
2846
|
+
/** Recovers a frame from a message's data, or `undefined` for anything else. */
|
|
2847
|
+
function readFrame(data) {
|
|
2848
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
2849
|
+
const frame = data;
|
|
2850
|
+
switch (frame.t) {
|
|
2851
|
+
case "m": return typeof frame.d === "string" || frame.d instanceof ArrayBuffer ? frame : void 0;
|
|
2852
|
+
case "c": return {
|
|
2853
|
+
t: "c",
|
|
2854
|
+
code: typeof frame.code === "number" ? frame.code : 1005,
|
|
2855
|
+
reason: typeof frame.reason === "string" ? frame.reason : ""
|
|
2856
|
+
};
|
|
2857
|
+
case "p": {
|
|
2858
|
+
const hb = frame.hb;
|
|
2859
|
+
return {
|
|
2860
|
+
t: "p",
|
|
2861
|
+
hb: typeof hb === "number" && hb > 0 ? hb : DEFAULT_HEARTBEAT_MS
|
|
2862
|
+
};
|
|
2863
|
+
}
|
|
2864
|
+
case "q": return { t: "q" };
|
|
2865
|
+
case "a": {
|
|
2866
|
+
const n = frame.n;
|
|
2867
|
+
return typeof n === "number" && n >= 0 ? {
|
|
2868
|
+
t: "a",
|
|
2869
|
+
n
|
|
2870
|
+
} : void 0;
|
|
2871
|
+
}
|
|
2872
|
+
default: return;
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
/** Posts `frame`, transferring a message's `ArrayBuffer`. */
|
|
2876
|
+
function postFrame(port, frame) {
|
|
2877
|
+
if (frame.t === "m" && frame.d instanceof ArrayBuffer) port.postMessage(frame, [frame.d]);
|
|
2878
|
+
else port.postMessage(frame);
|
|
2879
|
+
}
|
|
2880
|
+
/** The size a message counts for in `bufferedAmount`: UTF-8 bytes, or the buffer's length. */
|
|
2881
|
+
function messageSize(data) {
|
|
2882
|
+
return typeof data === "string" ? utf8Length(data) : data.byteLength;
|
|
2883
|
+
}
|
|
2884
|
+
/** The UTF-8 length of `text`, without encoding it. */
|
|
2885
|
+
function utf8Length(text) {
|
|
2886
|
+
let length = 0;
|
|
2887
|
+
for (let i = 0; i < text.length; i++) {
|
|
2888
|
+
const code = text.charCodeAt(i);
|
|
2889
|
+
if (code < 128) length += 1;
|
|
2890
|
+
else if (code < 2048) length += 2;
|
|
2891
|
+
else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
|
|
2892
|
+
const next = text.charCodeAt(i + 1);
|
|
2893
|
+
if (next >= 56320 && next <= 57343) {
|
|
2894
|
+
length += 4;
|
|
2895
|
+
i++;
|
|
2896
|
+
} else length += 3;
|
|
2897
|
+
} else length += 3;
|
|
2898
|
+
}
|
|
2899
|
+
return length;
|
|
2900
|
+
}
|
|
2901
|
+
/**
|
|
2902
|
+
* A `CloseEvent` for runtimes that have none: Node 22 has `Event` and
|
|
2903
|
+
* `MessageEvent` as globals, but not `CloseEvent`.
|
|
2904
|
+
*/
|
|
2905
|
+
var WsCloseEvent = class extends Event {
|
|
2906
|
+
code;
|
|
2907
|
+
reason;
|
|
2908
|
+
wasClean;
|
|
2909
|
+
constructor(type, init = {}) {
|
|
2910
|
+
super(type, init);
|
|
2911
|
+
this.code = init.code ?? 0;
|
|
2912
|
+
this.reason = init.reason ?? "";
|
|
2913
|
+
this.wasClean = init.wasClean ?? false;
|
|
2914
|
+
}
|
|
2915
|
+
};
|
|
2916
|
+
/** A `close` event: the platform's `CloseEvent` where there is one. */
|
|
2917
|
+
function newCloseEvent(init) {
|
|
2918
|
+
const Native = globalThis.CloseEvent;
|
|
2919
|
+
return Native ? new Native("close", init) : new WsCloseEvent("close", init);
|
|
2920
|
+
}
|
|
2921
|
+
/**
|
|
2922
|
+
* What both ends of a socket over a `MessagePort` share: the frames, the close
|
|
2923
|
+
* handshake, and the byte accounting behind `bufferedAmount`.
|
|
2924
|
+
*
|
|
2925
|
+
* Not exported from the package: the two ends are `createWebSocketClass`'s
|
|
2926
|
+
* class and `ServerWebSocket`.
|
|
2927
|
+
*/
|
|
2928
|
+
var PortSocketCore = class extends EventTarget {
|
|
2929
|
+
_port;
|
|
2930
|
+
_state = 0;
|
|
2931
|
+
_timers;
|
|
2932
|
+
_closeTimeoutMs;
|
|
2933
|
+
/** Bytes sent and not yet acknowledged by the peer, plus those still being prepared. */
|
|
2934
|
+
_inFlight = 0;
|
|
2935
|
+
/** Bytes of messages "sent" after the socket started closing: counted, never sent. */
|
|
2936
|
+
_discarded = 0;
|
|
2937
|
+
_toAck = 0;
|
|
2938
|
+
_ackScheduled = false;
|
|
2939
|
+
_closeTimer;
|
|
2940
|
+
_drainWaiters = [];
|
|
2941
|
+
constructor(options = {}) {
|
|
2942
|
+
super();
|
|
2943
|
+
this._timers = options.timers ?? defaultTimers;
|
|
2944
|
+
this._closeTimeoutMs = options.closeTimeoutMs ?? 5e3;
|
|
2945
|
+
}
|
|
2946
|
+
get readyState() {
|
|
2947
|
+
return this._state;
|
|
2948
|
+
}
|
|
2949
|
+
/**
|
|
2950
|
+
* Bytes queued by `send()` that the peer has not consumed yet. A peer
|
|
2951
|
+
* acknowledges what it has dispatched, so this falls as the other side reads.
|
|
2952
|
+
*/
|
|
2953
|
+
get bufferedAmount() {
|
|
2954
|
+
return this._inFlight + this._discarded;
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Resolves once `bufferedAmount` is at most `limit` (default 0), or the
|
|
2958
|
+
* socket is closed. The backpressure a producer applies:
|
|
2959
|
+
* `if (socket.bufferedAmount > HIGH) await socket.whenDrained(LOW)`.
|
|
2960
|
+
*/
|
|
2961
|
+
whenDrained(limit = 0) {
|
|
2962
|
+
if (this._state === 3 || this._inFlight <= limit) return Promise.resolve();
|
|
2963
|
+
return new Promise((resolve) => this._drainWaiters.push({
|
|
2964
|
+
limit,
|
|
2965
|
+
resolve
|
|
2966
|
+
}));
|
|
2967
|
+
}
|
|
2968
|
+
_attach(port) {
|
|
2969
|
+
this._port = port;
|
|
2970
|
+
port.onmessage = (event) => {
|
|
2971
|
+
const frame = readFrame(event.data);
|
|
2972
|
+
if (frame) this._onFrame(frame);
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
_onFrame(frame) {
|
|
2976
|
+
switch (frame.t) {
|
|
2977
|
+
case "m":
|
|
2978
|
+
case "c":
|
|
2979
|
+
this._deliver(frame);
|
|
2980
|
+
return;
|
|
2981
|
+
case "a":
|
|
2982
|
+
this._inFlight = Math.max(0, this._inFlight - frame.n);
|
|
2983
|
+
this._wakeDrainWaiters();
|
|
2984
|
+
return;
|
|
2985
|
+
case "p":
|
|
2986
|
+
this._onPing(frame.hb);
|
|
2987
|
+
return;
|
|
2988
|
+
case "q":
|
|
2989
|
+
this._onPong();
|
|
2990
|
+
return;
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
/** A message or close frame the socket is ready to act on. */
|
|
2994
|
+
_deliver(frame) {
|
|
2995
|
+
if (frame.t === "c") {
|
|
2996
|
+
this._onCloseFrame(frame.code, frame.reason);
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
if (this._state !== 1) return;
|
|
3000
|
+
this._dispatchMessage(frame.d);
|
|
3001
|
+
this._consumed(messageSize(frame.d));
|
|
3002
|
+
}
|
|
3003
|
+
_onPing(_hb) {}
|
|
3004
|
+
_onPong() {}
|
|
3005
|
+
_onClosed() {}
|
|
3006
|
+
/** Acknowledge consumed bytes, coalescing the acks of one turn into one frame. */
|
|
3007
|
+
_consumed(bytes) {
|
|
3008
|
+
this._toAck += bytes;
|
|
3009
|
+
if (this._ackScheduled) return;
|
|
3010
|
+
this._ackScheduled = true;
|
|
3011
|
+
queueMicrotask(() => {
|
|
3012
|
+
this._ackScheduled = false;
|
|
3013
|
+
const n = this._toAck;
|
|
3014
|
+
this._toAck = 0;
|
|
3015
|
+
if (n > 0 && this._state !== 3) this._post({
|
|
3016
|
+
t: "a",
|
|
3017
|
+
n
|
|
3018
|
+
});
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
3021
|
+
/** Reserves `bytes` in `bufferedAmount` for a message still being prepared (a Blob). */
|
|
3022
|
+
_reserve(bytes) {
|
|
3023
|
+
this._inFlight += bytes;
|
|
3024
|
+
}
|
|
3025
|
+
/** Sends one message whose bytes were reserved with `_reserve` (or `reserved = false`). */
|
|
3026
|
+
_sendData(data, reserved = false) {
|
|
3027
|
+
const size = messageSize(data);
|
|
3028
|
+
if (this._state !== 1) {
|
|
3029
|
+
if (reserved) this._inFlight = Math.max(0, this._inFlight - size);
|
|
3030
|
+
this._discarded += size;
|
|
3031
|
+
return;
|
|
3032
|
+
}
|
|
3033
|
+
if (!reserved) this._inFlight += size;
|
|
3034
|
+
this._post({
|
|
3035
|
+
t: "m",
|
|
3036
|
+
d: data
|
|
3037
|
+
});
|
|
3038
|
+
}
|
|
3039
|
+
_post(frame) {
|
|
3040
|
+
try {
|
|
3041
|
+
if (this._port) postFrame(this._port, frame);
|
|
3042
|
+
} catch {}
|
|
3043
|
+
}
|
|
3044
|
+
/** Starts the close handshake. */
|
|
3045
|
+
_startClose(code, reason) {
|
|
3046
|
+
if (this._state === 2 || this._state === 3) return;
|
|
3047
|
+
this._state = 2;
|
|
3048
|
+
this._post({
|
|
3049
|
+
t: "c",
|
|
3050
|
+
code,
|
|
3051
|
+
reason
|
|
3052
|
+
});
|
|
3053
|
+
this._closeTimer = this._timers.setTimeout(() => this._finish(1006, "", false), this._closeTimeoutMs);
|
|
3054
|
+
}
|
|
3055
|
+
_onCloseFrame(code, reason) {
|
|
3056
|
+
if (this._state === 3) return;
|
|
3057
|
+
if (this._state === 2) {
|
|
3058
|
+
this._finish(code, reason, true);
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
this._state = 2;
|
|
3062
|
+
this._post({
|
|
3063
|
+
t: "c",
|
|
3064
|
+
code,
|
|
3065
|
+
reason
|
|
3066
|
+
});
|
|
3067
|
+
this._finish(code, reason, true);
|
|
3068
|
+
}
|
|
3069
|
+
/** The socket is closed: release the port and tell the listeners. */
|
|
3070
|
+
_finish(code, reason, wasClean, error = false) {
|
|
3071
|
+
if (this._state === 3) return;
|
|
3072
|
+
this._state = 3;
|
|
3073
|
+
if (this._closeTimer !== void 0) this._timers.clearTimeout(this._closeTimer);
|
|
3074
|
+
this._closeTimer = void 0;
|
|
3075
|
+
this._onClosed();
|
|
3076
|
+
if (this._port) {
|
|
3077
|
+
this._port.onmessage = null;
|
|
3078
|
+
try {
|
|
3079
|
+
this._port.close();
|
|
3080
|
+
} catch {}
|
|
3081
|
+
}
|
|
3082
|
+
this._wakeDrainWaiters();
|
|
3083
|
+
if (error) this.dispatchEvent(new Event("error"));
|
|
3084
|
+
this.dispatchEvent(newCloseEvent({
|
|
3085
|
+
code,
|
|
3086
|
+
reason,
|
|
3087
|
+
wasClean
|
|
3088
|
+
}));
|
|
3089
|
+
}
|
|
3090
|
+
_wakeDrainWaiters() {
|
|
3091
|
+
if (this._drainWaiters.length === 0) return;
|
|
3092
|
+
const closed = this._state === 3;
|
|
3093
|
+
this._drainWaiters = this._drainWaiters.filter(({ limit, resolve }) => {
|
|
3094
|
+
if (!closed && this._inFlight > limit) return true;
|
|
3095
|
+
resolve();
|
|
3096
|
+
return false;
|
|
3097
|
+
});
|
|
3098
|
+
}
|
|
3099
|
+
};
|
|
3100
|
+
/** Copies `data` into a fresh `ArrayBuffer`: `send()` must never detach the caller's buffer. */
|
|
3101
|
+
function toArrayBuffer(data) {
|
|
3102
|
+
if (data instanceof ArrayBuffer) return data.slice(0);
|
|
3103
|
+
const copy = new Uint8Array(data.byteLength);
|
|
3104
|
+
copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
3105
|
+
return copy.buffer;
|
|
3106
|
+
}
|
|
3107
|
+
function isBinary(data) {
|
|
3108
|
+
return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
|
|
3109
|
+
}
|
|
3110
|
+
function isBlob(data) {
|
|
3111
|
+
return typeof Blob !== "undefined" && data instanceof Blob;
|
|
3112
|
+
}
|
|
3113
|
+
/** Valid close codes for an application to send: 1000, or 3000–4999. */
|
|
3114
|
+
function isApplicationCloseCode(code) {
|
|
3115
|
+
return code === 1e3 || code >= 3e3 && code <= 4999;
|
|
3116
|
+
}
|
|
3117
|
+
//#endregion
|
|
3118
|
+
//#region src/ws/server.ts
|
|
3119
|
+
/**
|
|
3120
|
+
* The server end of a socket over a `MessagePort`: what a handler gets from
|
|
3121
|
+
* `upgradeWebSocket` and talks to.
|
|
3122
|
+
*
|
|
3123
|
+
* - Events are delivered only after `accept()`; frames that arrive earlier are
|
|
3124
|
+
* queued. Pings are answered even before `accept()`, so a slow handler does
|
|
3125
|
+
* not look like a dead one.
|
|
3126
|
+
* - Messages arrive as strings or `ArrayBuffer`s.
|
|
3127
|
+
* - `bufferedAmount` counts what the client has not consumed yet, and
|
|
3128
|
+
* `whenDrained(limit)` waits for it to fall: the backpressure a producer
|
|
3129
|
+
* applies.
|
|
3130
|
+
* - When the client's pings stop for three heartbeat periods (a closed tab, a
|
|
3131
|
+
* terminated worker), the socket closes with 1006.
|
|
3132
|
+
*/
|
|
3133
|
+
var ServerWebSocket = class extends PortSocketCore {
|
|
3134
|
+
static CONNECTING = 0;
|
|
3135
|
+
static OPEN = 1;
|
|
3136
|
+
static CLOSING = 2;
|
|
3137
|
+
static CLOSED = 3;
|
|
3138
|
+
url;
|
|
3139
|
+
protocol;
|
|
3140
|
+
_accepted = false;
|
|
3141
|
+
_queue = [];
|
|
3142
|
+
_heartbeatMs = DEFAULT_HEARTBEAT_MS;
|
|
3143
|
+
_lastPing = Date.now();
|
|
3144
|
+
_watch;
|
|
3145
|
+
constructor(port, options = {}) {
|
|
3146
|
+
super({
|
|
3147
|
+
timers: options.timers,
|
|
3148
|
+
closeTimeoutMs: options.closeTimeoutMs
|
|
3149
|
+
});
|
|
3150
|
+
this.url = options.url ?? "";
|
|
3151
|
+
this.protocol = options.protocol ?? "";
|
|
3152
|
+
this._attach(port);
|
|
3153
|
+
this._state = 1;
|
|
3154
|
+
this._watchHeartbeat();
|
|
3155
|
+
}
|
|
3156
|
+
/** Whether `accept()` was called. */
|
|
3157
|
+
get accepted() {
|
|
3158
|
+
return this._accepted;
|
|
3159
|
+
}
|
|
3160
|
+
/** Starts delivering events, the queued ones first. */
|
|
3161
|
+
accept() {
|
|
3162
|
+
if (this._accepted) return;
|
|
3163
|
+
this._accepted = true;
|
|
3164
|
+
for (const frame of this._queue.splice(0)) super._deliver(frame);
|
|
3165
|
+
}
|
|
3166
|
+
send(data) {
|
|
3167
|
+
if (!this._accepted) throw new DOMException("accept() the socket before sending on it.", "InvalidStateError");
|
|
3168
|
+
this._sendData(isBinary(data) ? toArrayBuffer(data) : String(data));
|
|
3169
|
+
}
|
|
3170
|
+
close(code = 1e3, reason = "") {
|
|
3171
|
+
if (!isSendableCloseCode(code)) throw new DOMException(`${code} is not a close code an endpoint may send.`, "InvalidAccessError");
|
|
3172
|
+
if (utf8Length(reason) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
|
|
3173
|
+
this._startClose(code, reason);
|
|
3174
|
+
}
|
|
3175
|
+
_deliver(frame) {
|
|
3176
|
+
if (!this._accepted) {
|
|
3177
|
+
this._queue.push(frame);
|
|
3178
|
+
return;
|
|
3179
|
+
}
|
|
3180
|
+
super._deliver(frame);
|
|
3181
|
+
}
|
|
3182
|
+
_dispatchMessage(data) {
|
|
3183
|
+
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
3184
|
+
}
|
|
3185
|
+
_onPing(hb) {
|
|
3186
|
+
this._post({ t: "q" });
|
|
3187
|
+
this._lastPing = Date.now();
|
|
3188
|
+
if (hb !== this._heartbeatMs) {
|
|
3189
|
+
this._heartbeatMs = hb;
|
|
3190
|
+
this._watchHeartbeat();
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
_onClosed() {
|
|
3194
|
+
if (this._watch !== void 0) this._timers.clearInterval(this._watch);
|
|
3195
|
+
this._watch = void 0;
|
|
3196
|
+
}
|
|
3197
|
+
_watchHeartbeat() {
|
|
3198
|
+
if (this._watch !== void 0) this._timers.clearInterval(this._watch);
|
|
3199
|
+
this._watch = this._timers.setInterval(() => {
|
|
3200
|
+
if (Date.now() - this._lastPing > 3 * this._heartbeatMs) this._finish(1006, "", false, true);
|
|
3201
|
+
}, this._heartbeatMs);
|
|
3202
|
+
}
|
|
3203
|
+
};
|
|
3204
|
+
/** Codes an endpoint may put in a close frame (RFC 6455 §7.4). */
|
|
3205
|
+
function isSendableCloseCode(code) {
|
|
3206
|
+
if (!Number.isInteger(code)) return false;
|
|
3207
|
+
if (code >= 3e3 && code <= 4999) return true;
|
|
3208
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006;
|
|
3209
|
+
}
|
|
3210
|
+
//#endregion
|
|
3211
|
+
//#region src/ws/upgrade.ts
|
|
3212
|
+
/**
|
|
3213
|
+
* The upgrade, as an HTTP exchange: a `GET` with `Upgrade: websocket` goes to
|
|
3214
|
+
* an ordinary `(Request) => Response` handler, and a `101` answer carrying a
|
|
3215
|
+
* server socket means accepted. Anything else is a refusal, with its status.
|
|
3216
|
+
*
|
|
3217
|
+
* FORBIDDEN HEADERS. A browser drops `Upgrade`, `Connection` and every
|
|
3218
|
+
* `Sec-*` header from a `new Request()`. The upgrade request therefore carries
|
|
3219
|
+
* its headers as an own `headers` property, a standalone `Headers` that keeps
|
|
3220
|
+
* them, so handler code reads `request.headers.get("upgrade")` as usual.
|
|
3221
|
+
*
|
|
3222
|
+
* NO 101 IN A `Response`. The constructor refuses statuses below 200, so the
|
|
3223
|
+
* response `upgradeWebSocket` returns reports 101 through an own `status`
|
|
3224
|
+
* property; the port that goes back to the caller is found with `takePort`.
|
|
3225
|
+
*/
|
|
3226
|
+
/** The request header carrying the client's version of the frame protocol. */
|
|
3227
|
+
const WS_VERSION_HEADER = "x-webrun-ws-version";
|
|
3228
|
+
/**
|
|
3229
|
+
* The `GET` a handler sees for `new WebSocket(url, protocols)`. A `ws:` or
|
|
3230
|
+
* `wss:` url is given as `http:` or `https:`, as a server sees it.
|
|
3231
|
+
*/
|
|
3232
|
+
function newWebSocketUpgradeRequest(url, { protocols = [], headers } = {}) {
|
|
3233
|
+
const httpUrl = new URL(`${url}`);
|
|
3234
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
3235
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
3236
|
+
const all = new Headers(headers);
|
|
3237
|
+
all.set("upgrade", "websocket");
|
|
3238
|
+
all.set("connection", "Upgrade");
|
|
3239
|
+
all.set("sec-websocket-version", "13");
|
|
3240
|
+
if (!all.has("sec-websocket-key")) all.set("sec-websocket-key", randomKey());
|
|
3241
|
+
if (protocols.length > 0) all.set("sec-websocket-protocol", protocols.join(", "));
|
|
3242
|
+
if (!all.has("x-webrun-ws-version")) all.set(WS_VERSION_HEADER, `2`);
|
|
3243
|
+
return withHeaders(new Request(httpUrl, {
|
|
3244
|
+
method: "GET",
|
|
3245
|
+
headers: all
|
|
3246
|
+
}), all);
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* Re-attaches `headers` to `request` as its own `headers` property, keeping
|
|
3250
|
+
* the forbidden ones a browser dropped. Returns `request`.
|
|
3251
|
+
*/
|
|
3252
|
+
function withHeaders(request, headers) {
|
|
3253
|
+
Object.defineProperty(request, "headers", {
|
|
3254
|
+
value: headers,
|
|
3255
|
+
configurable: true
|
|
3256
|
+
});
|
|
3257
|
+
return request;
|
|
3258
|
+
}
|
|
3259
|
+
/** Whether `request` asks for a WebSocket. */
|
|
3260
|
+
function isWebSocketUpgrade(request) {
|
|
3261
|
+
return request.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
3262
|
+
}
|
|
3263
|
+
/** The subprotocols `request` asks for, in order of preference. */
|
|
3264
|
+
function requestedProtocols(request) {
|
|
3265
|
+
const header = request.headers.get("sec-websocket-protocol");
|
|
3266
|
+
if (!header) return [];
|
|
3267
|
+
return header.split(",").map((protocol) => protocol.trim()).filter((protocol) => protocol !== "");
|
|
3268
|
+
}
|
|
3269
|
+
/**
|
|
3270
|
+
* Where a response from `upgradeWebSocket` keeps its port. A registered
|
|
3271
|
+
* symbol, not a module-level `WeakMap`: the handler and the host that takes
|
|
3272
|
+
* the port often run different bundles of this package (a page's adapter from
|
|
3273
|
+
* `dist/sw.js`, its handler code importing `dist/worker.js`), and each bundle
|
|
3274
|
+
* has its own copy of every module.
|
|
3275
|
+
*/
|
|
3276
|
+
const UPGRADE = Symbol.for("webrun-http-browser:websocket-upgrade");
|
|
3277
|
+
/**
|
|
3278
|
+
* Accepts a WebSocket upgrade in a handler:
|
|
3279
|
+
*
|
|
3280
|
+
* ```ts
|
|
3281
|
+
* if (isWebSocketUpgrade(request)) {
|
|
3282
|
+
* const { socket, response } = upgradeWebSocket(request, { protocol: "v1" });
|
|
3283
|
+
* socket.accept();
|
|
3284
|
+
* socket.addEventListener("message", (event) => socket.send(event.data));
|
|
3285
|
+
* return response;
|
|
3286
|
+
* }
|
|
3287
|
+
* ```
|
|
3288
|
+
*
|
|
3289
|
+
* The host takes the client's port from the response with `takePort` and
|
|
3290
|
+
* hands it to the caller.
|
|
3291
|
+
*/
|
|
3292
|
+
function upgradeWebSocket(request, options = {}) {
|
|
3293
|
+
const protocol = options.protocol ?? "";
|
|
3294
|
+
const channel = new MessageChannel();
|
|
3295
|
+
const socket = new ServerWebSocket(channel.port1, {
|
|
3296
|
+
...options,
|
|
3297
|
+
url: request.url,
|
|
3298
|
+
protocol
|
|
3299
|
+
});
|
|
3300
|
+
const response = new Response(null, {
|
|
3301
|
+
status: 200,
|
|
3302
|
+
headers: protocol ? { "sec-websocket-protocol": protocol } : {}
|
|
3303
|
+
});
|
|
3304
|
+
Object.defineProperties(response, {
|
|
3305
|
+
status: {
|
|
3306
|
+
value: 101,
|
|
3307
|
+
configurable: true
|
|
3308
|
+
},
|
|
3309
|
+
statusText: {
|
|
3310
|
+
value: "Switching Protocols",
|
|
3311
|
+
configurable: true
|
|
3312
|
+
},
|
|
3313
|
+
webSocket: {
|
|
3314
|
+
value: socket,
|
|
3315
|
+
configurable: true
|
|
3316
|
+
},
|
|
3317
|
+
[UPGRADE]: {
|
|
3318
|
+
value: {
|
|
3319
|
+
port: channel.port2,
|
|
3320
|
+
protocol
|
|
3321
|
+
},
|
|
3322
|
+
configurable: true,
|
|
3323
|
+
writable: true
|
|
3324
|
+
}
|
|
3325
|
+
});
|
|
3326
|
+
return {
|
|
3327
|
+
socket,
|
|
3328
|
+
response
|
|
3329
|
+
};
|
|
3330
|
+
}
|
|
3331
|
+
/**
|
|
3332
|
+
* The port to hand to the caller, for a response from `upgradeWebSocket`.
|
|
3333
|
+
* Taken once: a second call returns `undefined`.
|
|
3334
|
+
*/
|
|
3335
|
+
function takePort(response) {
|
|
3336
|
+
return takeUpgrade(response)?.port;
|
|
3337
|
+
}
|
|
3338
|
+
/** `takePort`, with the subprotocol the server picked. */
|
|
3339
|
+
function takeUpgrade(response) {
|
|
3340
|
+
const holder = response;
|
|
3341
|
+
const upgrade = holder[UPGRADE];
|
|
3342
|
+
if (upgrade) holder[UPGRADE] = void 0;
|
|
3343
|
+
return upgrade;
|
|
3344
|
+
}
|
|
3345
|
+
/**
|
|
3346
|
+
* Runs an upgrade through `handler`, as a host does when a caller asks for a
|
|
3347
|
+
* socket: builds the upgrade request, calls the handler, and either takes the
|
|
3348
|
+
* port of a `101` or reports the refusal. A subprotocol the caller did not ask
|
|
3349
|
+
* for is a refusal, as in the standard.
|
|
3350
|
+
*/
|
|
3351
|
+
async function serveWebSocketUpgrade(handler, { url, protocols = [], headers }) {
|
|
3352
|
+
let response;
|
|
3353
|
+
try {
|
|
3354
|
+
response = await handler(newWebSocketUpgradeRequest(url, {
|
|
3355
|
+
protocols,
|
|
3356
|
+
headers
|
|
3357
|
+
}));
|
|
3358
|
+
} catch (error) {
|
|
3359
|
+
return {
|
|
3360
|
+
ok: false,
|
|
3361
|
+
status: 500,
|
|
3362
|
+
message: errorMessage(error)
|
|
3363
|
+
};
|
|
3364
|
+
}
|
|
3365
|
+
const upgrade = takeUpgrade(response);
|
|
3366
|
+
if (!upgrade || response.status !== 101) {
|
|
3367
|
+
upgrade?.port.close();
|
|
3368
|
+
try {
|
|
3369
|
+
await response.body?.cancel();
|
|
3370
|
+
} catch {}
|
|
3371
|
+
return {
|
|
3372
|
+
ok: false,
|
|
3373
|
+
status: response.status,
|
|
3374
|
+
message: `The server refused the upgrade: ${response.status} ${response.statusText}`.trim()
|
|
3375
|
+
};
|
|
3376
|
+
}
|
|
3377
|
+
if (upgrade.protocol !== "" && !protocols.includes(upgrade.protocol)) {
|
|
3378
|
+
upgrade.port.close();
|
|
3379
|
+
return {
|
|
3380
|
+
ok: false,
|
|
3381
|
+
status: 400,
|
|
3382
|
+
message: `The server picked the subprotocol '${upgrade.protocol}', which was not requested.`
|
|
3383
|
+
};
|
|
3384
|
+
}
|
|
3385
|
+
return {
|
|
3386
|
+
ok: true,
|
|
3387
|
+
port: upgrade.port,
|
|
3388
|
+
protocol: upgrade.protocol
|
|
3389
|
+
};
|
|
3390
|
+
}
|
|
3391
|
+
function randomKey() {
|
|
3392
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
3393
|
+
crypto.getRandomValues(bytes);
|
|
3394
|
+
return btoa(String.fromCharCode(...bytes));
|
|
3395
|
+
}
|
|
3396
|
+
//#endregion
|
|
3397
|
+
//#region src/sw/handler-endpoint.ts
|
|
3398
|
+
/** The message calls through a lost ServiceWorker fail with. */
|
|
3399
|
+
const ROUTER_LOST_MESSAGE = "The ServiceWorker was lost while this call was in flight";
|
|
3400
|
+
/**
|
|
3401
|
+
* The handler's end of its links to the ServiceWorker, the same in a page and
|
|
3402
|
+
* in a Dedicated Worker.
|
|
3403
|
+
*
|
|
3404
|
+
* - Serves `handler` on each link's `down` port, and answers WebSocket
|
|
3405
|
+
* upgrades arriving on its `ctl` port by running them through `handler`.
|
|
3406
|
+
* - Sends requests through the router on `up` (`fetch`) and opens sockets to
|
|
3407
|
+
* other handlers over `ctl` (`connectWebSocket`).
|
|
3408
|
+
* - Watches the ServiceWorker's router lock. When the ServiceWorker dies, the
|
|
3409
|
+
* links made for it are dropped: calls in flight on them fail with
|
|
3410
|
+
* `LinkLostError` ("may or may not have been applied") instead of hanging,
|
|
3411
|
+
* and new calls wait for a link, asking for one (`requestRelink`) every
|
|
3412
|
+
* `relinkRetryMs` until it comes.
|
|
3413
|
+
* - While calls are in flight, calls `keepAlive` every `keepAliveMs`: port
|
|
3414
|
+
* messages are not events, so without it the browser may stop the
|
|
3415
|
+
* ServiceWorker in the middle of a long call.
|
|
3416
|
+
*/
|
|
3417
|
+
var HandlerEndpoint = class {
|
|
3418
|
+
handler;
|
|
3419
|
+
options;
|
|
3420
|
+
_links = /* @__PURE__ */ new Set();
|
|
3421
|
+
_waiters = [];
|
|
3422
|
+
_sockets = new PortRendezvous("o");
|
|
3423
|
+
_keepAliveTimer;
|
|
3424
|
+
_closed = false;
|
|
3425
|
+
constructor(handler, options = {}) {
|
|
3426
|
+
this.handler = handler;
|
|
3427
|
+
this.options = options;
|
|
3428
|
+
}
|
|
3429
|
+
/** Whether any link is live. */
|
|
3430
|
+
get linked() {
|
|
3431
|
+
return this._links.size > 0;
|
|
3432
|
+
}
|
|
3433
|
+
/** Installs a fresh link made for the router holding `routerLock`. */
|
|
3434
|
+
async link(key, ports, routerLock) {
|
|
3435
|
+
if (this._closed) {
|
|
3436
|
+
for (const port of Object.values(ports)) port?.close();
|
|
3437
|
+
return;
|
|
3438
|
+
}
|
|
3439
|
+
const closeDown = await serveHttpLink(ports.down, this.handler, this.options);
|
|
3440
|
+
const up = ports.up ? await connectHttpLink(ports.up, this.options) : void 0;
|
|
3441
|
+
const link = {
|
|
3442
|
+
key,
|
|
3443
|
+
routerLock,
|
|
3444
|
+
ctl: ports.ctl,
|
|
3445
|
+
up,
|
|
3446
|
+
closeDown,
|
|
3447
|
+
stopWatch: () => {}
|
|
3448
|
+
};
|
|
3449
|
+
if (ports.ctl) ports.ctl.onmessage = (event) => this._onControl(link, event.data);
|
|
3450
|
+
if (routerLock) link.stopWatch = watchLock(routerLock, () => this._routerLost(routerLock));
|
|
3451
|
+
for (const old of [...this._links]) {
|
|
3452
|
+
if (old.key !== key) continue;
|
|
3453
|
+
if (old.routerLock !== routerLock) this._drop(old, new LinkLostError(ROUTER_LOST_MESSAGE));
|
|
3454
|
+
else if (!old.superseded) {
|
|
3455
|
+
old.superseded = true;
|
|
3456
|
+
setTimeout(() => void this._drop(old), this.options.supersededLinkMs ?? 3e4);
|
|
3457
|
+
}
|
|
3458
|
+
}
|
|
3459
|
+
this._links.add(link);
|
|
3460
|
+
for (const wake of this._waiters.splice(0)) wake();
|
|
3461
|
+
}
|
|
3462
|
+
/** Drops the links attached under `key` (all of them without a key). */
|
|
3463
|
+
async unlink(key, reason) {
|
|
3464
|
+
const dropped = [...this._links].filter((link) => key === void 0 || link.key === key);
|
|
3465
|
+
await Promise.all(dropped.map((link) => this._drop(link, reason)));
|
|
3466
|
+
}
|
|
3467
|
+
/** The routers this endpoint has live links for. */
|
|
3468
|
+
routerLocks() {
|
|
3469
|
+
return new Set([...this._links].map((link) => link.routerLock));
|
|
3470
|
+
}
|
|
3471
|
+
/**
|
|
3472
|
+
* Sends `request` through the ServiceWorker's router, as if the browser had
|
|
3473
|
+
* fetched it: it reaches the handler its url routes to.
|
|
3474
|
+
*/
|
|
3475
|
+
async fetch(request) {
|
|
3476
|
+
const link = await this._linkWith("up");
|
|
3477
|
+
this._startKeepAlive();
|
|
3478
|
+
return await link.up.send(request);
|
|
3479
|
+
}
|
|
3480
|
+
/** Opens a socket to the handler `url` routes to, through the ServiceWorker. */
|
|
3481
|
+
async connectWebSocket(url, protocols = []) {
|
|
3482
|
+
const link = await this._linkWith("ctl");
|
|
3483
|
+
const id = this._sockets.newId();
|
|
3484
|
+
const answer = this._sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
|
|
3485
|
+
link.ctl?.postMessage({
|
|
3486
|
+
t: "ws-open",
|
|
3487
|
+
id,
|
|
3488
|
+
url,
|
|
3489
|
+
protocols
|
|
3490
|
+
});
|
|
3491
|
+
return await answer;
|
|
3492
|
+
}
|
|
3493
|
+
async close() {
|
|
3494
|
+
this._closed = true;
|
|
3495
|
+
if (this._keepAliveTimer) clearInterval(this._keepAliveTimer);
|
|
3496
|
+
await this.unlink(void 0, new LinkLostError("The handler was closed"));
|
|
3497
|
+
for (const wake of this._waiters.splice(0)) wake();
|
|
3498
|
+
}
|
|
3499
|
+
async _drop(link, reason) {
|
|
3500
|
+
if (!this._links.delete(link)) return;
|
|
3501
|
+
link.stopWatch();
|
|
3502
|
+
await link.up?.close(reason);
|
|
3503
|
+
try {
|
|
3504
|
+
await link.closeDown();
|
|
3505
|
+
} catch {}
|
|
3506
|
+
if (link.ctl) {
|
|
3507
|
+
link.ctl.onmessage = null;
|
|
3508
|
+
link.ctl.close();
|
|
3509
|
+
}
|
|
3510
|
+
}
|
|
3511
|
+
_routerLost(routerLock) {
|
|
3512
|
+
const reason = new LinkLostError(ROUTER_LOST_MESSAGE);
|
|
3513
|
+
for (const link of [...this._links]) if (link.routerLock === routerLock) this._drop(link, reason);
|
|
3514
|
+
this._sockets.failAll(reason);
|
|
3515
|
+
}
|
|
3516
|
+
/** A live link with `port`, waiting (and asking) for one when there is none. */
|
|
3517
|
+
async _linkWith(port) {
|
|
3518
|
+
const find = () => [...this._links].filter((link) => !link.superseded).reverse().find((link) => port === "up" ? link.up && !link.up.closed : link.ctl);
|
|
3519
|
+
const found = find();
|
|
3520
|
+
if (found) return found;
|
|
3521
|
+
const retryMs = this.options.relinkRetryMs ?? 2e3;
|
|
3522
|
+
const deadline = Date.now() + (this.options.relinkTimeoutMs ?? 3e4);
|
|
3523
|
+
while (!this._closed) {
|
|
3524
|
+
this.options.requestRelink?.();
|
|
3525
|
+
await new Promise((resolve) => {
|
|
3526
|
+
const timer = setTimeout(resolve, Math.max(0, Math.min(retryMs, deadline - Date.now())));
|
|
3527
|
+
this._waiters.push(() => {
|
|
3528
|
+
clearTimeout(timer);
|
|
3529
|
+
resolve();
|
|
3530
|
+
});
|
|
3531
|
+
});
|
|
3532
|
+
const link = find();
|
|
3533
|
+
if (link) return link;
|
|
3534
|
+
if (Date.now() >= deadline) break;
|
|
3535
|
+
}
|
|
3536
|
+
throw new LinkLostError("No link to the ServiceWorker could be made for this call");
|
|
3537
|
+
}
|
|
3538
|
+
_startKeepAlive() {
|
|
3539
|
+
if (this._keepAliveTimer || !this.options.keepAlive) return;
|
|
3540
|
+
this._keepAliveTimer = setInterval(() => {
|
|
3541
|
+
if ([...this._links].reduce((sum, link) => sum + (link.up?.inflight ?? 0), 0) === 0) {
|
|
3542
|
+
clearInterval(this._keepAliveTimer);
|
|
3543
|
+
this._keepAliveTimer = void 0;
|
|
3544
|
+
return;
|
|
3545
|
+
}
|
|
3546
|
+
this.options.keepAlive?.();
|
|
3547
|
+
}, this.options.keepAliveMs ?? 2e4);
|
|
3548
|
+
}
|
|
3549
|
+
_onControl(link, message) {
|
|
3550
|
+
if (!message || typeof message !== "object") return;
|
|
3551
|
+
switch (message.t) {
|
|
3552
|
+
case "ws-connect":
|
|
3553
|
+
this._acceptSocket(link, message);
|
|
3554
|
+
return;
|
|
3555
|
+
case "ws-opened":
|
|
3556
|
+
if (!this._sockets.settle(message.id, {
|
|
3557
|
+
port: message.port,
|
|
3558
|
+
protocol: message.protocol
|
|
3559
|
+
})) message.port.close();
|
|
3560
|
+
return;
|
|
3561
|
+
case "ws-failed":
|
|
3562
|
+
this._sockets.fail(message.id, new Error(message.message));
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
async _acceptSocket(link, { id, url, protocols, headers }) {
|
|
3567
|
+
const ctl = link.ctl;
|
|
3568
|
+
if (!ctl) return;
|
|
3569
|
+
try {
|
|
3570
|
+
const result = await serveWebSocketUpgrade(this.handler, {
|
|
3571
|
+
url,
|
|
3572
|
+
protocols,
|
|
3573
|
+
headers
|
|
3574
|
+
});
|
|
3575
|
+
if (result.ok) ctl.postMessage({
|
|
3576
|
+
t: "ws-accept",
|
|
3577
|
+
id,
|
|
3578
|
+
protocol: result.protocol,
|
|
3579
|
+
port: result.port
|
|
3580
|
+
}, [result.port]);
|
|
3581
|
+
else ctl.postMessage({
|
|
3582
|
+
t: "ws-refuse",
|
|
3583
|
+
id,
|
|
3584
|
+
status: result.status,
|
|
3585
|
+
message: result.message
|
|
3586
|
+
});
|
|
3587
|
+
} catch (error) {
|
|
3588
|
+
ctl.postMessage({
|
|
3589
|
+
t: "ws-refuse",
|
|
3590
|
+
id,
|
|
3591
|
+
status: 500,
|
|
3592
|
+
message: errorMessage(error)
|
|
3593
|
+
});
|
|
3594
|
+
}
|
|
1738
3595
|
}
|
|
3596
|
+
};
|
|
3597
|
+
//#endregion
|
|
3598
|
+
//#region src/sw/handler-table.ts
|
|
3599
|
+
/**
|
|
3600
|
+
* The default route: the handler with the fewest requests in flight, the
|
|
3601
|
+
* oldest on a tie. With one handler per key — one tab — that is the first
|
|
3602
|
+
* live handler of the key, as before routing was pluggable.
|
|
3603
|
+
*/
|
|
3604
|
+
const leastInflightRoute = (_request, _key, handlers) => {
|
|
3605
|
+
let best;
|
|
3606
|
+
for (const handler of handlers) if (best === void 0 || handler.inflight < best.inflight || handler.inflight === best.inflight && handler.attachedAt < best.attachedAt) best = handler;
|
|
3607
|
+
return best;
|
|
3608
|
+
};
|
|
3609
|
+
var HandlerTable = class {
|
|
3610
|
+
_entries = /* @__PURE__ */ new Map();
|
|
3611
|
+
_waiters = [];
|
|
3612
|
+
/** Adds `entry`. Returns the entry it replaces (same key and id), if any. */
|
|
3613
|
+
add(entry) {
|
|
3614
|
+
let slots = this._entries.get(entry.key);
|
|
3615
|
+
if (!slots) {
|
|
3616
|
+
slots = /* @__PURE__ */ new Map();
|
|
3617
|
+
this._entries.set(entry.key, slots);
|
|
3618
|
+
}
|
|
3619
|
+
const replaced = slots.get(entry.id);
|
|
3620
|
+
slots.set(entry.id, entry);
|
|
3621
|
+
if (!entry.draining) this._waiters = this._waiters.filter(({ key, resolve }) => {
|
|
3622
|
+
if (key !== entry.key) return true;
|
|
3623
|
+
resolve(true);
|
|
3624
|
+
return false;
|
|
3625
|
+
});
|
|
3626
|
+
return replaced;
|
|
3627
|
+
}
|
|
3628
|
+
/** Removes `entry` if it is still the one in its slot. */
|
|
3629
|
+
remove(entry) {
|
|
3630
|
+
const slots = this._entries.get(entry.key);
|
|
3631
|
+
if (slots?.get(entry.id) !== entry) return false;
|
|
3632
|
+
slots.delete(entry.id);
|
|
3633
|
+
if (slots.size === 0) this._entries.delete(entry.key);
|
|
3634
|
+
return true;
|
|
3635
|
+
}
|
|
3636
|
+
get(key, id) {
|
|
3637
|
+
return this._entries.get(key)?.get(id);
|
|
3638
|
+
}
|
|
3639
|
+
/** Every entry of `key`, draining or not. */
|
|
3640
|
+
all(key) {
|
|
3641
|
+
return [...this._entries.get(key)?.values() ?? []];
|
|
3642
|
+
}
|
|
3643
|
+
/** The entries of `key` that take new requests. */
|
|
3644
|
+
live(key) {
|
|
3645
|
+
return this.all(key).filter((entry) => !entry.draining);
|
|
3646
|
+
}
|
|
3647
|
+
entries() {
|
|
3648
|
+
return [...this._entries.values()].flatMap((slots) => [...slots.values()]);
|
|
3649
|
+
}
|
|
3650
|
+
get size() {
|
|
3651
|
+
let size = 0;
|
|
3652
|
+
for (const slots of this._entries.values()) size += slots.size;
|
|
3653
|
+
return size;
|
|
3654
|
+
}
|
|
3655
|
+
/**
|
|
3656
|
+
* Resolves `true` once a live entry for `key` is added (at once if there is
|
|
3657
|
+
* one, unless `next`), `false` after `ms`.
|
|
3658
|
+
*/
|
|
3659
|
+
waitFor(key, ms, next = false) {
|
|
3660
|
+
if (!next && this.live(key).length > 0) return Promise.resolve(true);
|
|
3661
|
+
return new Promise((resolve) => {
|
|
3662
|
+
const waiter = {
|
|
3663
|
+
key,
|
|
3664
|
+
resolve: (found) => {
|
|
3665
|
+
clearTimeout(timer);
|
|
3666
|
+
resolve(found);
|
|
3667
|
+
}
|
|
3668
|
+
};
|
|
3669
|
+
const timer = setTimeout(() => {
|
|
3670
|
+
this._waiters = this._waiters.filter((w) => w !== waiter);
|
|
3671
|
+
resolve(false);
|
|
3672
|
+
}, ms);
|
|
3673
|
+
this._waiters.push(waiter);
|
|
3674
|
+
});
|
|
3675
|
+
}
|
|
3676
|
+
};
|
|
3677
|
+
//#endregion
|
|
3678
|
+
//#region ../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
|
|
3679
|
+
function promisifyRequest(request) {
|
|
3680
|
+
return new Promise((resolve, reject) => {
|
|
3681
|
+
request.oncomplete = request.onsuccess = () => resolve(request.result);
|
|
3682
|
+
request.onabort = request.onerror = () => reject(request.error);
|
|
3683
|
+
});
|
|
3684
|
+
}
|
|
3685
|
+
function createStore(dbName, storeName) {
|
|
3686
|
+
let dbp;
|
|
3687
|
+
const getDB = () => {
|
|
3688
|
+
if (dbp) return dbp;
|
|
3689
|
+
const request = indexedDB.open(dbName);
|
|
3690
|
+
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
|
|
3691
|
+
dbp = promisifyRequest(request);
|
|
3692
|
+
dbp.then((db) => {
|
|
3693
|
+
db.onclose = () => dbp = void 0;
|
|
3694
|
+
}, () => {
|
|
3695
|
+
dbp = void 0;
|
|
3696
|
+
});
|
|
3697
|
+
return dbp;
|
|
3698
|
+
};
|
|
3699
|
+
return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
|
|
3700
|
+
}
|
|
3701
|
+
let defaultGetStoreFunc;
|
|
3702
|
+
function defaultGetStore() {
|
|
3703
|
+
if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
|
|
3704
|
+
return defaultGetStoreFunc;
|
|
3705
|
+
}
|
|
3706
|
+
/**
|
|
3707
|
+
* Get a value by its key.
|
|
3708
|
+
*
|
|
3709
|
+
* @param key
|
|
3710
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
3711
|
+
*/
|
|
3712
|
+
function get(key, customStore = defaultGetStore()) {
|
|
3713
|
+
return customStore("readonly", (store) => promisifyRequest(store.get(key)));
|
|
3714
|
+
}
|
|
3715
|
+
/**
|
|
3716
|
+
* Set a value with a key.
|
|
3717
|
+
*
|
|
3718
|
+
* @param key
|
|
3719
|
+
* @param value
|
|
3720
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
3721
|
+
*/
|
|
3722
|
+
function set(key, value, customStore = defaultGetStore()) {
|
|
3723
|
+
return customStore("readwrite", (store) => {
|
|
3724
|
+
store.put(value, key);
|
|
3725
|
+
return promisifyRequest(store.transaction);
|
|
3726
|
+
});
|
|
3727
|
+
}
|
|
3728
|
+
//#endregion
|
|
3729
|
+
//#region src/core/deadline.ts
|
|
3730
|
+
/**
|
|
3731
|
+
* Settles like `promise` if it settles before `deadline` (a `Date.now()`
|
|
3732
|
+
* value). Otherwise calls `onTimeout`: an `Error` it returns rejects, any
|
|
3733
|
+
* other value resolves. Internal; not re-exported.
|
|
3734
|
+
*/
|
|
3735
|
+
function withDeadline(deadline, promise, onTimeout) {
|
|
3736
|
+
return new Promise((resolve, reject) => {
|
|
3737
|
+
const timer = setTimeout(() => {
|
|
3738
|
+
const outcome = onTimeout();
|
|
3739
|
+
if (outcome instanceof Error) reject(outcome);
|
|
3740
|
+
else resolve(outcome);
|
|
3741
|
+
}, Math.max(0, deadline - Date.now()));
|
|
3742
|
+
promise.then((value) => {
|
|
3743
|
+
clearTimeout(timer);
|
|
3744
|
+
resolve(value);
|
|
3745
|
+
}, (error) => {
|
|
3746
|
+
clearTimeout(timer);
|
|
3747
|
+
reject(error);
|
|
3748
|
+
});
|
|
3749
|
+
});
|
|
3750
|
+
}
|
|
3751
|
+
//#endregion
|
|
3752
|
+
//#region src/core/data-calls.ts
|
|
3753
|
+
const TRANSFER = Symbol.for("webrun-http-browser:transfer");
|
|
3754
|
+
/**
|
|
3755
|
+
* A channel call's result that carries transferables, a `MessagePort` say:
|
|
3756
|
+
* return `withTransfer({ port }, [port])` from a `handleChannelCalls` handler
|
|
3757
|
+
* and `callChannel` resolves with `{ port }`.
|
|
3758
|
+
*/
|
|
3759
|
+
function withTransfer(value, transfer) {
|
|
3760
|
+
return {
|
|
3761
|
+
[TRANSFER]: true,
|
|
3762
|
+
value,
|
|
3763
|
+
transfer
|
|
3764
|
+
};
|
|
3765
|
+
}
|
|
3766
|
+
function isTransferResult(value) {
|
|
3767
|
+
return typeof value === "object" && value !== null && TRANSFER in value;
|
|
3768
|
+
}
|
|
3769
|
+
/** Splits a handler's result into the value to post and its transfer list. */
|
|
3770
|
+
function unwrapTransfer(result) {
|
|
3771
|
+
return isTransferResult(result) ? {
|
|
3772
|
+
value: result.value,
|
|
3773
|
+
transfer: result.transfer
|
|
3774
|
+
} : {
|
|
3775
|
+
value: result,
|
|
3776
|
+
transfer: []
|
|
3777
|
+
};
|
|
3778
|
+
}
|
|
3779
|
+
function callChannel(target, callType, params, ...transfers) {
|
|
3780
|
+
return new Promise((resolve, reject) => {
|
|
3781
|
+
const channel = new MessageChannel();
|
|
3782
|
+
channel.port1.onmessage = (ev) => {
|
|
3783
|
+
const { result, error } = ev.data;
|
|
3784
|
+
if (error) reject(deserializeError(error));
|
|
3785
|
+
else resolve(result);
|
|
3786
|
+
};
|
|
3787
|
+
target.postMessage({
|
|
3788
|
+
type: callType,
|
|
3789
|
+
params
|
|
3790
|
+
}, [channel.port2, ...transfers]);
|
|
3791
|
+
});
|
|
3792
|
+
}
|
|
3793
|
+
function handleChannelCalls(target, callType, handler) {
|
|
3794
|
+
const listener = async (event) => {
|
|
3795
|
+
if (!event.data || event.data.type !== callType) return;
|
|
3796
|
+
const [port, ...transfers] = event.ports ?? [];
|
|
3797
|
+
const response = {};
|
|
3798
|
+
let transfer = [];
|
|
3799
|
+
try {
|
|
3800
|
+
const result = await handler(event, event.data.params, ...transfers);
|
|
3801
|
+
({value: response.result, transfer} = unwrapTransfer(result));
|
|
3802
|
+
} catch (error) {
|
|
3803
|
+
response.error = serializeError(error);
|
|
3804
|
+
}
|
|
3805
|
+
port?.postMessage(response, transfer);
|
|
3806
|
+
};
|
|
3807
|
+
target.addEventListener("message", listener);
|
|
3808
|
+
target.start?.();
|
|
3809
|
+
return () => target.removeEventListener("message", listener);
|
|
3810
|
+
}
|
|
3811
|
+
/**
|
|
3812
|
+
* `callChannel`, failing after `ms` instead of waiting for ever: a peer that
|
|
3813
|
+
* died (a ServiceWorker stopped mid-call) or that does not know `callType` (an
|
|
3814
|
+
* older version) never answers.
|
|
3815
|
+
*/
|
|
3816
|
+
function callChannelWithin(ms, target, callType, params, ...transfers) {
|
|
3817
|
+
return withDeadline(Date.now() + ms, callChannel(target, callType, params, ...transfers), () => /* @__PURE__ */ new Error(`No answer to ${callType} within ${ms} ms`));
|
|
3818
|
+
}
|
|
3819
|
+
//#endregion
|
|
3820
|
+
//#region src/core/service-worker-control.ts
|
|
3821
|
+
/**
|
|
3822
|
+
* How long, by default, the page waits for its ServiceWorker to activate and
|
|
3823
|
+
* to take control before giving up. Generous: a first install downloads and
|
|
3824
|
+
* evaluates the worker script, which on a slow link takes seconds.
|
|
3825
|
+
*/
|
|
3826
|
+
const DEFAULT_SERVICE_WORKER_TIMEOUT = 3e4;
|
|
3827
|
+
/**
|
|
3828
|
+
* How long the page waits for `controllerchange` once the worker has
|
|
3829
|
+
* answered the `CLAIM` request. `clients.claim()` resolves only after the
|
|
3830
|
+
* browser has queued that event, so this is a grace period for delivery, not
|
|
3831
|
+
* a second budget.
|
|
3832
|
+
*/
|
|
3833
|
+
const CLAIM_GRACE_MS = 1e3;
|
|
3834
|
+
/** Channel call a page sends to ask its ServiceWorker to `clients.claim()` it. */
|
|
3835
|
+
const CLAIM_CALL = "CLAIM";
|
|
3836
|
+
/**
|
|
3837
|
+
* Why a page could not get a working ServiceWorker. `reason` says which wait
|
|
3838
|
+
* failed; check it (or `name`) rather than `instanceof`, because each of this
|
|
3839
|
+
* package's bundles carries its own copy of this class.
|
|
3840
|
+
*/
|
|
3841
|
+
var ServiceWorkerControlError = class extends Error {
|
|
3842
|
+
reason;
|
|
3843
|
+
constructor(reason, message) {
|
|
3844
|
+
super(message);
|
|
3845
|
+
this.name = "ServiceWorkerControlError";
|
|
3846
|
+
this.reason = reason;
|
|
3847
|
+
}
|
|
3848
|
+
};
|
|
3849
|
+
/**
|
|
3850
|
+
* Resolves with the registration's worker once it is `activated`. Rejects
|
|
3851
|
+
* with a `ServiceWorkerControlError` (`reason: "activation-timeout"`) if that
|
|
3852
|
+
* takes longer than `timeout` — an install that throws or never finishes
|
|
3853
|
+
* would otherwise leave the caller waiting forever.
|
|
3854
|
+
*/
|
|
3855
|
+
async function awaitActiveServiceWorker(registration, { timeout = DEFAULT_SERVICE_WORKER_TIMEOUT } = {}) {
|
|
3856
|
+
return await withDeadline(Date.now() + timeout, waitForActivated(registration), () => {
|
|
3857
|
+
const worker = registration.installing ?? registration.waiting ?? registration.active;
|
|
3858
|
+
return new ServiceWorkerControlError("activation-timeout", `ServiceWorker ${scriptUrl(worker)} (scope ${registration.scope}) did not activate within ${timeout} ms` + (worker ? `; it is "${worker.state}"` : "") + ". Check the worker script for errors during install (DevTools → Application → Service Workers), or raise the `timeout` option.");
|
|
3859
|
+
});
|
|
3860
|
+
}
|
|
3861
|
+
/**
|
|
3862
|
+
* Resolves with the ServiceWorker that controls this page, once `registration`
|
|
3863
|
+
* has an activated worker and the page is controlled by it.
|
|
3864
|
+
*
|
|
3865
|
+
* A page can stay uncontrolled while its worker is active, and then no
|
|
3866
|
+
* `controllerchange` ever fires on its own:
|
|
3867
|
+
* - a hard reload (Ctrl+Shift+R) bypasses the worker for that load, and the
|
|
3868
|
+
* worker's `clients.claim()` already ran when it activated;
|
|
3869
|
+
* - Firefox can leave a page loaded while the worker is running uncontrolled.
|
|
3870
|
+
*
|
|
3871
|
+
* So when the page is uncontrolled, this asks the active worker to claim it
|
|
3872
|
+
* again (a `CLAIM` channel call — this package's workers answer it) and waits
|
|
3873
|
+
* for `controllerchange`. Every wait is bounded by `timeout`. If control never
|
|
3874
|
+
* comes it reloads once (`reloadIfUncontrolled`) or rejects with a
|
|
3875
|
+
* `ServiceWorkerControlError` (`reason: "uncontrolled"`) that says what
|
|
3876
|
+
* happened and what to do.
|
|
3877
|
+
*/
|
|
3878
|
+
async function awaitServiceWorkerControl(registration, { timeout = DEFAULT_SERVICE_WORKER_TIMEOUT, reloadIfUncontrolled = false, container = navigator.serviceWorker } = {}) {
|
|
3879
|
+
const deadline = Date.now() + timeout;
|
|
3880
|
+
const controlled = waitForController(container);
|
|
3881
|
+
try {
|
|
3882
|
+
const active = await awaitActiveServiceWorker(registration, { timeout });
|
|
3883
|
+
let controller = container.controller;
|
|
3884
|
+
if (!controller) controller = await withDeadline(deadline, (async () => {
|
|
3885
|
+
await Promise.race([callChannel(active, CLAIM_CALL, {}), controlled.promise]);
|
|
3886
|
+
return await Promise.race([controlled.promise, delay(CLAIM_GRACE_MS, null)]);
|
|
3887
|
+
})(), () => null);
|
|
3888
|
+
if (controller) {
|
|
3889
|
+
forgetReload(registration);
|
|
3890
|
+
return controller;
|
|
3891
|
+
}
|
|
3892
|
+
if (reloadIfUncontrolled && markReload(registration)) {
|
|
3893
|
+
location.reload();
|
|
3894
|
+
return await new Promise(() => {});
|
|
3895
|
+
}
|
|
3896
|
+
forgetReload(registration);
|
|
3897
|
+
throw new ServiceWorkerControlError("uncontrolled", `This page is not controlled by its ServiceWorker ${scriptUrl(active)} (scope ${registration.scope}), although the worker is active, and the worker did not take control when asked (clients.claim()) within ${timeout} ms. This happens after a hard reload (Ctrl+Shift+R / Cmd+Shift+R), which bypasses ServiceWorkers for that load, and in Firefox for some pages opened while the worker was already running. Requests from this page would not reach the worker. Reload the page normally, pass \`reloadIfUncontrolled: true\` to do that automatically, check that the page is inside the worker's scope, and that the worker answers the "${CLAIM_CALL}" request (this package's workers do).`);
|
|
3898
|
+
} finally {
|
|
3899
|
+
controlled.cancel();
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
/**
|
|
3903
|
+
* ServiceWorker side: answers the page's `CLAIM` request with
|
|
3904
|
+
* `clients.claim()`, which takes over every uncontrolled client in scope.
|
|
3905
|
+
* Returns a function that stops answering.
|
|
3906
|
+
*/
|
|
3907
|
+
function handleClaimRequests(self) {
|
|
3908
|
+
return handleChannelCalls(self, CLAIM_CALL, (event) => {
|
|
3909
|
+
const claimed = self.clients.claim().then(() => true);
|
|
3910
|
+
event.waitUntil?.(claimed);
|
|
3911
|
+
return claimed;
|
|
3912
|
+
});
|
|
3913
|
+
}
|
|
3914
|
+
function waitForActivated(registration) {
|
|
3915
|
+
return new Promise((resolve) => {
|
|
3916
|
+
const watched = /* @__PURE__ */ new Set();
|
|
3917
|
+
const check = () => {
|
|
3918
|
+
const active = registration.active;
|
|
3919
|
+
if (active?.state === "activated") {
|
|
3920
|
+
registration.removeEventListener("updatefound", watch);
|
|
3921
|
+
for (const worker of watched) worker.removeEventListener("statechange", check);
|
|
3922
|
+
resolve(active);
|
|
3923
|
+
return;
|
|
3924
|
+
}
|
|
3925
|
+
watch();
|
|
3926
|
+
};
|
|
3927
|
+
function watch() {
|
|
3928
|
+
for (const worker of [
|
|
3929
|
+
registration.installing,
|
|
3930
|
+
registration.waiting,
|
|
3931
|
+
registration.active
|
|
3932
|
+
]) {
|
|
3933
|
+
if (!worker || watched.has(worker)) continue;
|
|
3934
|
+
watched.add(worker);
|
|
3935
|
+
worker.addEventListener("statechange", check);
|
|
3936
|
+
}
|
|
3937
|
+
}
|
|
3938
|
+
registration.addEventListener("updatefound", watch);
|
|
3939
|
+
check();
|
|
3940
|
+
});
|
|
3941
|
+
}
|
|
3942
|
+
function waitForController(container) {
|
|
3943
|
+
let cancel = () => {};
|
|
3944
|
+
return {
|
|
3945
|
+
promise: new Promise((resolve) => {
|
|
3946
|
+
const onChange = () => {
|
|
3947
|
+
if (!container.controller) return;
|
|
3948
|
+
cancel();
|
|
3949
|
+
resolve(container.controller);
|
|
3950
|
+
};
|
|
3951
|
+
cancel = () => container.removeEventListener("controllerchange", onChange);
|
|
3952
|
+
container.addEventListener("controllerchange", onChange);
|
|
3953
|
+
}),
|
|
3954
|
+
cancel
|
|
3955
|
+
};
|
|
3956
|
+
}
|
|
3957
|
+
function delay(ms, value) {
|
|
3958
|
+
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
|
|
3959
|
+
}
|
|
3960
|
+
function scriptUrl(worker) {
|
|
3961
|
+
return worker?.scriptURL ? `"${worker.scriptURL}"` : "(no worker)";
|
|
3962
|
+
}
|
|
3963
|
+
function reloadKey(registration) {
|
|
3964
|
+
return `webrun-http-browser:reloaded-uncontrolled:${registration.scope}`;
|
|
3965
|
+
}
|
|
3966
|
+
/** Records the reload about to happen. `false` if one already happened, or if it cannot be recorded. */
|
|
3967
|
+
function markReload(registration) {
|
|
3968
|
+
try {
|
|
3969
|
+
const key = reloadKey(registration);
|
|
3970
|
+
if (sessionStorage.getItem(key)) return false;
|
|
3971
|
+
sessionStorage.setItem(key, "1");
|
|
3972
|
+
return true;
|
|
3973
|
+
} catch {
|
|
3974
|
+
return false;
|
|
3975
|
+
}
|
|
3976
|
+
}
|
|
3977
|
+
function forgetReload(registration) {
|
|
3978
|
+
try {
|
|
3979
|
+
sessionStorage.removeItem(reloadKey(registration));
|
|
3980
|
+
} catch {}
|
|
3981
|
+
}
|
|
3982
|
+
//#endregion
|
|
3983
|
+
//#region src/core/data-channels.ts
|
|
3984
|
+
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
3985
|
+
const MESSAGE_TYPE_RESPONSE = "RESPONSE";
|
|
3986
|
+
let __invocationCounter = 0;
|
|
3987
|
+
function newInvokationChannel({ port, handler = () => {
|
|
3988
|
+
throw new Error("Handler not implemented");
|
|
3989
|
+
}, onError = console.error, newCallId = () => ++__invocationCounter }) {
|
|
3990
|
+
const requests = {};
|
|
3991
|
+
const listener = async (event) => {
|
|
3992
|
+
const data = event.data ?? {};
|
|
3993
|
+
if (data.type === MESSAGE_TYPE_REQUEST) try {
|
|
3994
|
+
const result = await handler(data.request, ...event.ports);
|
|
3995
|
+
const [response, ...transfers] = Array.isArray(result) ? result : result !== void 0 ? [result] : [];
|
|
3996
|
+
port.postMessage({
|
|
3997
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
3998
|
+
callId: data.callId,
|
|
3999
|
+
response
|
|
4000
|
+
}, transfers);
|
|
4001
|
+
} catch (error) {
|
|
4002
|
+
port.postMessage({
|
|
4003
|
+
type: MESSAGE_TYPE_RESPONSE,
|
|
4004
|
+
callId: data.callId,
|
|
4005
|
+
error: serializeError(error)
|
|
4006
|
+
});
|
|
4007
|
+
}
|
|
4008
|
+
else if (data.type === MESSAGE_TYPE_RESPONSE) {
|
|
4009
|
+
const pending = requests[data.callId];
|
|
4010
|
+
delete requests[data.callId];
|
|
4011
|
+
if (!pending) return;
|
|
4012
|
+
if (data.error) pending.reject(deserializeError(data.error));
|
|
4013
|
+
else pending.resolve(data.response);
|
|
4014
|
+
}
|
|
4015
|
+
};
|
|
4016
|
+
const start = async () => {
|
|
4017
|
+
try {
|
|
4018
|
+
port.addEventListener("message", listener);
|
|
4019
|
+
await port.start?.();
|
|
4020
|
+
} catch (e) {
|
|
4021
|
+
onError(e);
|
|
4022
|
+
}
|
|
4023
|
+
};
|
|
4024
|
+
const close = async () => {
|
|
4025
|
+
try {
|
|
4026
|
+
port.removeEventListener("message", listener);
|
|
4027
|
+
await port.close?.();
|
|
4028
|
+
} catch (e) {
|
|
4029
|
+
onError(e);
|
|
4030
|
+
}
|
|
4031
|
+
};
|
|
4032
|
+
const invoke = (request = {}, ...transfers) => {
|
|
4033
|
+
const callId = newCallId();
|
|
4034
|
+
return new Promise((resolve, reject) => {
|
|
4035
|
+
try {
|
|
4036
|
+
requests[callId] = {
|
|
4037
|
+
resolve,
|
|
4038
|
+
reject
|
|
4039
|
+
};
|
|
4040
|
+
port.postMessage({
|
|
4041
|
+
type: MESSAGE_TYPE_REQUEST,
|
|
4042
|
+
callId,
|
|
4043
|
+
request
|
|
4044
|
+
}, transfers);
|
|
4045
|
+
} catch (error) {
|
|
4046
|
+
delete requests[callId];
|
|
4047
|
+
reject(error);
|
|
4048
|
+
}
|
|
4049
|
+
});
|
|
4050
|
+
};
|
|
4051
|
+
return {
|
|
4052
|
+
start,
|
|
4053
|
+
close,
|
|
4054
|
+
invoke
|
|
4055
|
+
};
|
|
4056
|
+
}
|
|
4057
|
+
async function* sendStream(communicationPort, input, params = {}) {
|
|
4058
|
+
const messageChannel = new MessageChannel();
|
|
4059
|
+
communicationPort.postMessage({
|
|
4060
|
+
type: "START_CALL",
|
|
4061
|
+
params
|
|
4062
|
+
}, [messageChannel.port2]);
|
|
4063
|
+
const channel = newStreamChannel(messageChannel.port1);
|
|
4064
|
+
let drained = false;
|
|
4065
|
+
try {
|
|
4066
|
+
await channel.start();
|
|
4067
|
+
channel.sendAll(input);
|
|
4068
|
+
yield* channel.recieveAll();
|
|
4069
|
+
drained = true;
|
|
4070
|
+
} finally {
|
|
4071
|
+
if (!drained) channel.cancel();
|
|
4072
|
+
await channel.close();
|
|
4073
|
+
}
|
|
4074
|
+
}
|
|
4075
|
+
function newStreamChannel(port) {
|
|
4076
|
+
let listeners = [];
|
|
4077
|
+
let iterators = [];
|
|
4078
|
+
const notifyAll = async (data) => {
|
|
4079
|
+
for (const listener of listeners) await listener(data);
|
|
4080
|
+
};
|
|
4081
|
+
/**
|
|
4082
|
+
* Release whatever we are sending. NOT awaited: `.return()` on an async
|
|
4083
|
+
* generator parked awaiting its own source is queued behind that pending
|
|
4084
|
+
* `next()`, so awaiting it here would block the message handler — and the
|
|
4085
|
+
* chunk that would unblock it can only arrive through that same handler.
|
|
4086
|
+
*/
|
|
4087
|
+
const cancelOutgoing = () => {
|
|
4088
|
+
for (const it of [...iterators]) {
|
|
4089
|
+
const iterable = it;
|
|
4090
|
+
Promise.resolve(iterable.return?.()).catch(() => {});
|
|
4091
|
+
}
|
|
4092
|
+
};
|
|
4093
|
+
const channel = newInvokationChannel({
|
|
4094
|
+
port,
|
|
4095
|
+
handler: (data) => {
|
|
4096
|
+
const message = data;
|
|
4097
|
+
if (message?.cancel) {
|
|
4098
|
+
cancelOutgoing();
|
|
4099
|
+
return;
|
|
4100
|
+
}
|
|
4101
|
+
return notifyAll(message);
|
|
4102
|
+
}
|
|
4103
|
+
});
|
|
4104
|
+
const start = () => channel.start();
|
|
4105
|
+
const cancel = () => {
|
|
4106
|
+
channel.invoke({ cancel: true }).catch(() => {});
|
|
4107
|
+
};
|
|
4108
|
+
const close = async () => {
|
|
4109
|
+
await notifyAll({ done: true });
|
|
4110
|
+
for (const it of [...iterators]) await it.return?.();
|
|
4111
|
+
await channel.close();
|
|
4112
|
+
};
|
|
4113
|
+
async function* recieveAll() {
|
|
4114
|
+
yield* recieveIterator((deliver) => {
|
|
4115
|
+
listeners.push(deliver);
|
|
4116
|
+
return () => {
|
|
4117
|
+
listeners = listeners.filter((l) => l !== deliver);
|
|
4118
|
+
};
|
|
4119
|
+
});
|
|
4120
|
+
}
|
|
4121
|
+
async function sendAll(it) {
|
|
4122
|
+
await sendIterator((chunk) => void channel.invoke(chunk), (async function* () {
|
|
4123
|
+
try {
|
|
4124
|
+
iterators.push(it);
|
|
4125
|
+
yield* it;
|
|
4126
|
+
} finally {
|
|
4127
|
+
iterators = iterators.filter((i) => i !== it);
|
|
4128
|
+
}
|
|
4129
|
+
})());
|
|
4130
|
+
}
|
|
4131
|
+
return {
|
|
4132
|
+
start,
|
|
4133
|
+
close,
|
|
4134
|
+
cancel,
|
|
4135
|
+
recieveAll,
|
|
4136
|
+
sendAll
|
|
4137
|
+
};
|
|
4138
|
+
}
|
|
4139
|
+
//#endregion
|
|
4140
|
+
//#region src/http/http-send-recieve.ts
|
|
4141
|
+
async function* httpToIterator(envelopeOrPromise) {
|
|
4142
|
+
const { options, content } = await envelopeOrPromise;
|
|
4143
|
+
yield new TextEncoder().encode(JSON.stringify(options));
|
|
4144
|
+
yield* content;
|
|
4145
|
+
}
|
|
4146
|
+
async function httpFromIterator(iterable) {
|
|
4147
|
+
const it = (await iterable)[Symbol.asyncIterator]();
|
|
4148
|
+
const { done, value } = await it.next();
|
|
4149
|
+
let options = {};
|
|
4150
|
+
if (!done && value) {
|
|
4151
|
+
const str = new TextDecoder().decode(value);
|
|
4152
|
+
options = JSON.parse(str);
|
|
4153
|
+
}
|
|
4154
|
+
return {
|
|
4155
|
+
options,
|
|
4156
|
+
content: { [Symbol.asyncIterator]() {
|
|
4157
|
+
return it;
|
|
4158
|
+
} }
|
|
4159
|
+
};
|
|
4160
|
+
}
|
|
4161
|
+
/**
|
|
4162
|
+
* Ship a `Request` over a `MessageTarget` and await the `Response`, using this
|
|
4163
|
+
* package's own `sendStream` transport.
|
|
4164
|
+
*
|
|
4165
|
+
* @deprecated Prefer the port stack in `@statewalker/webrun-rpc`: open a port
|
|
4166
|
+
* (`multiplexPort` over one pipe, or `transferPortMux` where the platform can
|
|
4167
|
+
* transfer a real `MessagePort`), turn it into a `Duplex` with
|
|
4168
|
+
* `duplexOverPort`, and drive HTTP over it with `httpFetch` from
|
|
4169
|
+
* `@statewalker/webrun-http-streams`.
|
|
4170
|
+
*
|
|
4171
|
+
* Same caveat as {@link handleHttpRequests}: the transport underneath this
|
|
4172
|
+
* helper has no backpressure, no per-stream timeout, and no chunking to a
|
|
4173
|
+
* transport's message ceiling. Kept for existing ServiceWorker setups.
|
|
4174
|
+
*/
|
|
4175
|
+
async function sendHttpRequest(communicationPort, request) {
|
|
4176
|
+
return await newHttpClientStub(async (req) => {
|
|
4177
|
+
return await httpFromIterator(sendStream(communicationPort, httpToIterator(req)));
|
|
4178
|
+
})(request);
|
|
4179
|
+
}
|
|
4180
|
+
//#endregion
|
|
4181
|
+
//#region src/sw/protocol.ts
|
|
4182
|
+
/**
|
|
4183
|
+
* The messages between pages, Dedicated Workers and the same-origin
|
|
4184
|
+
* ServiceWorker. Internal: the shapes may change between versions, which is
|
|
4185
|
+
* why every hand-shake carries `HTTP_LINK_PROTOCOL`.
|
|
4186
|
+
*
|
|
4187
|
+
* THREE PORTS PER HANDLER LINK. A page makes the channels and hands one end of
|
|
4188
|
+
* each to the handler (itself, or a worker) and the other to the
|
|
4189
|
+
* ServiceWorker; after that it carries nothing:
|
|
4190
|
+
*
|
|
4191
|
+
* - `down`: ServiceWorker → handler, the requests the handler serves;
|
|
4192
|
+
* - `ctl`: a raw port next to them, for what HTTP over a stream cannot carry,
|
|
4193
|
+
* transferred `MessagePort`s (WebSocket hand-over);
|
|
4194
|
+
* - `up` (workers only): handler → ServiceWorker, the requests the handler
|
|
4195
|
+
* sends through the router (to other handlers).
|
|
4196
|
+
*/
|
|
4197
|
+
/** Page → ServiceWorker: attach a handler link. The name is the one version 1 used. */
|
|
4198
|
+
const ATTACH_CALL = "UPDATE_COMMUNICATION_PORT";
|
|
4199
|
+
/** Page → ServiceWorker: remove a handler link now. */
|
|
4200
|
+
const DETACH_CALL = "webrun-http:detach";
|
|
4201
|
+
/** Page → ServiceWorker: stop routing to a link, let its requests finish, then remove it. */
|
|
4202
|
+
const DRAIN_CALL = "webrun-http:drain";
|
|
4203
|
+
/** Page → ServiceWorker: open a WebSocket to a handler. */
|
|
4204
|
+
const WS_CONNECT_CALL = "webrun-http:ws-connect";
|
|
4205
|
+
/** ServiceWorker → pages: attach your links again (the ServiceWorker restarted). */
|
|
4206
|
+
const NEED_LINKS_CALL = "webrun-http:need-links";
|
|
4207
|
+
/**
|
|
4208
|
+
* Page → ServiceWorker, plain messages (no reply). A message to the
|
|
4209
|
+
* ServiceWorker object is an event: it starts a stopped worker and resets its
|
|
4210
|
+
* idle timer. Port messages do neither.
|
|
4211
|
+
*/
|
|
4212
|
+
const WAKE_MESSAGE = "webrun-http:wake";
|
|
4213
|
+
const KEEPALIVE_MESSAGE = "webrun-http:keepalive";
|
|
4214
|
+
/** Page ↔ worker: what `attachWorker` and `serveHttpInWorker` exchange. */
|
|
4215
|
+
const WORKER_HELLO = "webrun-http:worker-hello";
|
|
4216
|
+
//#endregion
|
|
4217
|
+
//#region src/sw/http-sw-dispatcher.ts
|
|
4218
|
+
/** One attached handler link, as the ServiceWorker holds it. */
|
|
4219
|
+
var HandlerEntry = class {
|
|
4220
|
+
key;
|
|
4221
|
+
id;
|
|
4222
|
+
owner;
|
|
4223
|
+
meta;
|
|
4224
|
+
link;
|
|
4225
|
+
ctl;
|
|
4226
|
+
clientId;
|
|
4227
|
+
ownerLock;
|
|
4228
|
+
draining = false;
|
|
4229
|
+
attachedAt = Date.now();
|
|
4230
|
+
sockets;
|
|
4231
|
+
stopWatch = () => {};
|
|
4232
|
+
closeUp;
|
|
4233
|
+
constructor(key, id, owner, meta, link, ctl, clientId, ownerLock) {
|
|
4234
|
+
this.key = key;
|
|
4235
|
+
this.id = id;
|
|
4236
|
+
this.owner = owner;
|
|
4237
|
+
this.meta = meta;
|
|
4238
|
+
this.link = link;
|
|
4239
|
+
this.ctl = ctl;
|
|
4240
|
+
this.clientId = clientId;
|
|
4241
|
+
this.ownerLock = ownerLock;
|
|
4242
|
+
this.sockets = new PortRendezvous(`s:${id}`);
|
|
4243
|
+
}
|
|
4244
|
+
get inflight() {
|
|
4245
|
+
return this.link.inflight;
|
|
4246
|
+
}
|
|
4247
|
+
};
|
|
4248
|
+
/** The reason requests fail with when their handler dies under them. */
|
|
4249
|
+
const HANDLER_LOST_MESSAGE = "The handler was lost while this request was in flight";
|
|
4250
|
+
const TIMED_OUT = Symbol("timed-out");
|
|
4251
|
+
/**
|
|
4252
|
+
* The same-origin ServiceWorker: routes `fetch` events under its scope to
|
|
4253
|
+
* handler links that pages attach — handlers in the pages themselves
|
|
4254
|
+
* (`SwHttpAdapter.register`) or in Dedicated Workers
|
|
4255
|
+
* (`SwHttpAdapter.attachWorker` + `serveHttpInWorker`).
|
|
4256
|
+
*
|
|
4257
|
+
* A url `<scope>/<key>/...` belongs to the handlers of `key`. Of those, the
|
|
4258
|
+
* `route` option picks one per request. Requests and responses stream with
|
|
4259
|
+
* backpressure in both directions, and an aborted fetch reaches the handler
|
|
4260
|
+
* as a cancellation (webrun-rpc + webrun-http-streams).
|
|
4261
|
+
*
|
|
4262
|
+
* Urls of keys this worker never served go to the network untouched: the
|
|
4263
|
+
* worker does not call `respondWith` for them.
|
|
4264
|
+
*
|
|
4265
|
+
* RESTARTS. The browser stops an idle ServiceWorker, and every port it held
|
|
4266
|
+
* dies with it. Nothing is persisted but the set of keys ever served: the
|
|
4267
|
+
* first request after a restart asks every window to attach its links again
|
|
4268
|
+
* (`NEED_LINKS`) and waits for them.
|
|
4269
|
+
*
|
|
4270
|
+
* LIVENESS. Each handler holds an owner lock; when it is granted to this
|
|
4271
|
+
* worker, the handler is gone and its requests in flight fail at once (502).
|
|
4272
|
+
* This worker holds a router lock that handlers watch the same way.
|
|
4273
|
+
*/
|
|
4274
|
+
var SwHttpDispatcher = class {
|
|
4275
|
+
self;
|
|
4276
|
+
log;
|
|
4277
|
+
options;
|
|
4278
|
+
table = new HandlerTable();
|
|
4279
|
+
/**
|
|
4280
|
+
* Keys that were served at some point on this worker (sticky, kept in
|
|
4281
|
+
* IndexedDB). Lets a fetch tell "a site url whose handler is gone → 404"
|
|
4282
|
+
* from "an unknown url under the scope → the network".
|
|
4283
|
+
*/
|
|
4284
|
+
claimedKeys = /* @__PURE__ */ new Set();
|
|
4285
|
+
/** The Web Lock this worker holds while it lives; handlers watch it. */
|
|
4286
|
+
routerLock;
|
|
4287
|
+
_routerHeld = Promise.resolve();
|
|
4288
|
+
_restored = Promise.resolve();
|
|
4289
|
+
_restoreSettled = false;
|
|
4290
|
+
_cleanup = [];
|
|
4291
|
+
_livenessTimer;
|
|
4292
|
+
_relinkRounds = /* @__PURE__ */ new Map();
|
|
4293
|
+
/** Keys whose last handler was drained: until the time stored, requests wait for the next. */
|
|
4294
|
+
_vacant = /* @__PURE__ */ new Map();
|
|
4295
|
+
constructor(options) {
|
|
4296
|
+
this.options = options;
|
|
4297
|
+
this.self = options.self;
|
|
4298
|
+
this.log = options.log ?? (() => {});
|
|
4299
|
+
if (locksAvailable()) this.routerLock = newLockName("webrun-http-router");
|
|
4300
|
+
}
|
|
4301
|
+
get scope() {
|
|
4302
|
+
return `${new URL("./", this.self.location.href)}`;
|
|
4303
|
+
}
|
|
4304
|
+
/** The key `url` belongs to: its first path segment under the scope. */
|
|
4305
|
+
keyOf(url) {
|
|
4306
|
+
const href = `${url}`;
|
|
4307
|
+
const scope = this.scope;
|
|
4308
|
+
if (!href.startsWith(scope)) return void 0;
|
|
4309
|
+
const key = href.substring(scope.length).replace(/[?#].*$/, "").split("/")[0];
|
|
4310
|
+
return key ? decodeURIComponent(key) : void 0;
|
|
4311
|
+
}
|
|
4312
|
+
/** Whether `key` has ever been served on this worker. */
|
|
4313
|
+
isClaimedKey(key) {
|
|
4314
|
+
return this.claimedKeys.has(key);
|
|
4315
|
+
}
|
|
4316
|
+
/** Whether requests for `key` are this worker's to answer. */
|
|
4317
|
+
serves(key) {
|
|
4318
|
+
return this.claimedKeys.has(key) || this.table.all(key).length > 0;
|
|
4319
|
+
}
|
|
4320
|
+
start() {
|
|
4321
|
+
const self = this.self;
|
|
4322
|
+
if (this.routerLock) this._routerHeld = holdLock(this.routerLock).then(() => {});
|
|
4323
|
+
this._restored = this._restoreClaimedKeys();
|
|
4324
|
+
const latch = () => {
|
|
4325
|
+
this._restoreSettled = true;
|
|
4326
|
+
};
|
|
4327
|
+
this._restored.then(latch, latch);
|
|
4328
|
+
this._cleanup.push(handleClaimRequests(self), handleChannelCalls(self, ATTACH_CALL, (event, params, ...ports) => this._attach(event, params, ports)), handleChannelCalls(self, DETACH_CALL, (_event, params) => {
|
|
4329
|
+
const entry = this._find(params);
|
|
4330
|
+
if (!entry) return false;
|
|
4331
|
+
this._close(entry, new LinkLostError("The handler was detached"));
|
|
4332
|
+
return true;
|
|
4333
|
+
}), handleChannelCalls(self, DRAIN_CALL, async (_event, params) => {
|
|
4334
|
+
const entry = this._find(params);
|
|
4335
|
+
if (!entry) return false;
|
|
4336
|
+
this._vacant.set(entry.key, Date.now() + (this.options.attachTimeoutMs ?? 15e3));
|
|
4337
|
+
await this._retire(entry, params.ms ?? this.options.handoverMs ?? 5e3);
|
|
4338
|
+
return true;
|
|
4339
|
+
}), handleChannelCalls(self, WS_CONNECT_CALL, async (event, params) => {
|
|
4340
|
+
if (!this._isOwnClient(event)) throw new Error("Only this origin's pages may open sockets");
|
|
4341
|
+
const { url, protocols } = params;
|
|
4342
|
+
const connection = await this.connectWebSocket(url, protocols ?? []);
|
|
4343
|
+
return withTransfer(connection, [connection.port]);
|
|
4344
|
+
}));
|
|
4345
|
+
const onMessage = (event) => {
|
|
4346
|
+
const type = event.data?.type;
|
|
4347
|
+
if (type === "webrun-http:wake") event.waitUntil(this._askForLinks());
|
|
4348
|
+
else if (type === "webrun-http:keepalive") event.waitUntil(Promise.resolve());
|
|
4349
|
+
};
|
|
4350
|
+
self.addEventListener("message", onMessage);
|
|
4351
|
+
this._cleanup.push(() => self.removeEventListener("message", onMessage));
|
|
4352
|
+
const onInstall = (event) => {
|
|
4353
|
+
this.log("Skip waiting on install.");
|
|
4354
|
+
event.waitUntil(self.skipWaiting());
|
|
4355
|
+
};
|
|
4356
|
+
const onActivate = (event) => {
|
|
4357
|
+
this.log("Claim control over all clients.");
|
|
4358
|
+
event.waitUntil(self.clients.claim());
|
|
4359
|
+
};
|
|
4360
|
+
const onFetch = (event) => this._onFetch(event);
|
|
4361
|
+
self.addEventListener("install", onInstall);
|
|
4362
|
+
self.addEventListener("activate", onActivate);
|
|
4363
|
+
self.addEventListener("fetch", onFetch);
|
|
4364
|
+
this._cleanup.push(() => {
|
|
4365
|
+
self.removeEventListener("install", onInstall);
|
|
4366
|
+
self.removeEventListener("activate", onActivate);
|
|
4367
|
+
self.removeEventListener("fetch", onFetch);
|
|
4368
|
+
});
|
|
4369
|
+
}
|
|
4370
|
+
async stop() {
|
|
4371
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
4372
|
+
if (this._livenessTimer) clearInterval(this._livenessTimer);
|
|
4373
|
+
this._livenessTimer = void 0;
|
|
4374
|
+
for (const entry of this.table.entries()) this._close(entry, new LinkLostError("The ServiceWorker dispatcher stopped"));
|
|
4375
|
+
}
|
|
4376
|
+
/**
|
|
4377
|
+
* Answers `request` as a fetch under the scope would be: through the
|
|
4378
|
+
* handler its key routes to. A url outside the scope, or of a key this
|
|
4379
|
+
* worker never served, goes to the network.
|
|
4380
|
+
*/
|
|
4381
|
+
async dispatch(request) {
|
|
4382
|
+
const key = this.keyOf(request.url);
|
|
4383
|
+
if (key === void 0) return await fetch(request);
|
|
4384
|
+
await this._restored.catch(() => {});
|
|
4385
|
+
const entry = await this._acquire(request, key);
|
|
4386
|
+
if (entry === TIMED_OUT) return new Response(null, {
|
|
4387
|
+
status: 503,
|
|
4388
|
+
statusText: "Service Unavailable (no handler attached in time)"
|
|
4389
|
+
});
|
|
4390
|
+
if (!entry) {
|
|
4391
|
+
if (!this.serves(key)) return await fetch(request);
|
|
4392
|
+
return new Response(null, {
|
|
4393
|
+
status: 404,
|
|
4394
|
+
statusText: "Not Found (no active handler)"
|
|
4395
|
+
});
|
|
4396
|
+
}
|
|
4397
|
+
try {
|
|
4398
|
+
return await entry.link.send(request);
|
|
4399
|
+
} catch (error) {
|
|
4400
|
+
this.log("[dispatch] failed", key, error);
|
|
4401
|
+
return new Response(errorMessage(error), {
|
|
4402
|
+
status: 502,
|
|
4403
|
+
statusText: "Bad Gateway",
|
|
4404
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
4405
|
+
});
|
|
4406
|
+
}
|
|
4407
|
+
}
|
|
4408
|
+
/**
|
|
4409
|
+
* Opens a socket to the handler `url` routes to: the handler accepts or
|
|
4410
|
+
* refuses it like an HTTP upgrade, and the socket's port comes back. After
|
|
4411
|
+
* that the socket runs between the caller and the handler directly; this
|
|
4412
|
+
* worker is not on its data path.
|
|
4413
|
+
*/
|
|
4414
|
+
async connectWebSocket(url, protocols = [], headers) {
|
|
4415
|
+
const request = newWebSocketUpgradeRequest(url, {
|
|
4416
|
+
protocols,
|
|
4417
|
+
headers
|
|
4418
|
+
});
|
|
4419
|
+
const key = this.keyOf(request.url);
|
|
4420
|
+
if (key === void 0) throw new Error(`${url} is outside this ServiceWorker's scope`);
|
|
4421
|
+
await this._restored.catch(() => {});
|
|
4422
|
+
const entry = await this._acquire(request, key);
|
|
4423
|
+
if (!entry || entry === TIMED_OUT) throw new Error(`No handler serves ${url}`);
|
|
4424
|
+
if (!entry.ctl) throw new Error(`The handler of ${url} does not accept sockets`);
|
|
4425
|
+
const id = entry.sockets.newId();
|
|
4426
|
+
const answer = entry.sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
|
|
4427
|
+
entry.ctl.postMessage({
|
|
4428
|
+
t: "ws-connect",
|
|
4429
|
+
id,
|
|
4430
|
+
url: request.url,
|
|
4431
|
+
protocols,
|
|
4432
|
+
headers
|
|
4433
|
+
});
|
|
4434
|
+
return await answer;
|
|
4435
|
+
}
|
|
4436
|
+
_onFetch(event) {
|
|
4437
|
+
const request = event.request;
|
|
4438
|
+
const key = this.keyOf(request.url);
|
|
4439
|
+
if (key === void 0) return;
|
|
4440
|
+
if (this._restoreSettled) {
|
|
4441
|
+
if (this.serves(key)) event.respondWith(this.dispatch(request));
|
|
4442
|
+
else if (request.mode === "navigate") event.respondWith(fetch(request));
|
|
4443
|
+
return;
|
|
4444
|
+
}
|
|
4445
|
+
event.respondWith((async () => {
|
|
4446
|
+
await this._restored.catch(() => {});
|
|
4447
|
+
if (!this.serves(key)) return await fetch(request);
|
|
4448
|
+
return await this.dispatch(request);
|
|
4449
|
+
})());
|
|
4450
|
+
}
|
|
4451
|
+
async _attach(event, params, ports) {
|
|
4452
|
+
const clientId = event.source?.id;
|
|
4453
|
+
const [down, ...rest] = ports;
|
|
4454
|
+
if (!down) throw new Error("An attach carries at least one port");
|
|
4455
|
+
this.log("[attach]", clientId, params);
|
|
4456
|
+
if (params.wire === void 0) {
|
|
4457
|
+
const link = trackedLink((request) => sendHttpRequest(down, request), () => down.close());
|
|
4458
|
+
const id = clientId ?? crypto.randomUUID();
|
|
4459
|
+
this._add(new HandlerEntry(params.key, id, id, void 0, link, void 0, clientId, void 0));
|
|
4460
|
+
return { ...params };
|
|
4461
|
+
}
|
|
4462
|
+
if (params.wire !== "webrun-http-link/2") {
|
|
4463
|
+
for (const port of ports) port.close();
|
|
4464
|
+
throw new Error(`This ServiceWorker speaks ${HTTP_LINK_PROTOCOL}, the page ${params.wire}. Reload the page so that both run the same version of @statewalker/webrun-http-browser.`);
|
|
4465
|
+
}
|
|
4466
|
+
const ctl = params.ctl ? rest.shift() : void 0;
|
|
4467
|
+
const up = params.up ? rest.shift() : void 0;
|
|
4468
|
+
const streamTimeout = this.options.streamTimeout;
|
|
4469
|
+
const link = await connectHttpLink(down, { streamTimeout });
|
|
4470
|
+
const entry = new HandlerEntry(params.key, params.id ?? clientId ?? crypto.randomUUID(), params.owner ?? crypto.randomUUID(), params.meta, link, ctl, clientId, params.ownerLock);
|
|
4471
|
+
if (up) entry.closeUp = await serveHttpLink(up, (request) => this.dispatch(request), { streamTimeout });
|
|
4472
|
+
if (ctl) ctl.onmessage = (message) => this._onControl(entry, message.data);
|
|
4473
|
+
if (params.ownerLock) entry.stopWatch = watchLock(params.ownerLock, () => {
|
|
4474
|
+
this.log("[owner lost]", entry.key, entry.id);
|
|
4475
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
4476
|
+
});
|
|
4477
|
+
this._add(entry);
|
|
4478
|
+
await this._routerHeld;
|
|
4479
|
+
return {
|
|
4480
|
+
accepted: HTTP_LINK_PROTOCOL,
|
|
4481
|
+
routerLock: this.routerLock
|
|
4482
|
+
};
|
|
4483
|
+
}
|
|
4484
|
+
_add(entry) {
|
|
4485
|
+
this._vacant.delete(entry.key);
|
|
4486
|
+
const replaced = this.table.add(entry);
|
|
4487
|
+
if (replaced && replaced !== entry) this._retire(replaced, this.options.handoverMs ?? 5e3, false);
|
|
4488
|
+
this._claim(entry.key);
|
|
4489
|
+
if (entry.ownerLock) this._watchLiveness();
|
|
4490
|
+
}
|
|
4491
|
+
/**
|
|
4492
|
+
* The backup of the owner-lock watches: every `livenessCheckMs`, drops the
|
|
4493
|
+
* handlers whose owner lock is no longer held. Runs only while some handler
|
|
4494
|
+
* has an owner lock, and keeps nothing awake: a timer is not an event.
|
|
4495
|
+
*/
|
|
4496
|
+
_watchLiveness() {
|
|
4497
|
+
const period = this.options.livenessCheckMs ?? 5e3;
|
|
4498
|
+
if (this._livenessTimer || period <= 0) return;
|
|
4499
|
+
this._livenessTimer = setInterval(async () => {
|
|
4500
|
+
const watched = this.table.entries().filter((entry) => entry.ownerLock);
|
|
4501
|
+
if (watched.length === 0) {
|
|
4502
|
+
clearInterval(this._livenessTimer);
|
|
4503
|
+
this._livenessTimer = void 0;
|
|
4504
|
+
return;
|
|
4505
|
+
}
|
|
4506
|
+
const held = await heldLockNames();
|
|
4507
|
+
if (!held) return;
|
|
4508
|
+
for (const entry of watched) if (entry.ownerLock && !held.has(entry.ownerLock) && this.table.remove(entry)) {
|
|
4509
|
+
this.log("[owner gone]", entry.key, entry.id);
|
|
4510
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE), false);
|
|
4511
|
+
}
|
|
4512
|
+
}, period);
|
|
4513
|
+
}
|
|
4514
|
+
/** The entry a drain or detach names, if its owner token still matches. */
|
|
4515
|
+
_find({ key, id, owner }) {
|
|
4516
|
+
const entry = this.table.get(key, id);
|
|
4517
|
+
return entry && entry.owner === owner ? entry : void 0;
|
|
4518
|
+
}
|
|
4519
|
+
/**
|
|
4520
|
+
* Stops routing to `entry`, lets its requests in flight run for up to `ms`,
|
|
4521
|
+
* then closes it. Requests that arrive meanwhile wait for the next owner.
|
|
4522
|
+
*/
|
|
4523
|
+
async _retire(entry, ms, inTable = true) {
|
|
4524
|
+
entry.draining = true;
|
|
4525
|
+
let timer;
|
|
4526
|
+
await Promise.race([entry.link.whenIdle(), new Promise((resolve) => {
|
|
4527
|
+
timer = setTimeout(resolve, ms);
|
|
4528
|
+
})]);
|
|
4529
|
+
clearTimeout(timer);
|
|
4530
|
+
this._close(entry, new LinkLostError("The handler was drained"), inTable);
|
|
4531
|
+
}
|
|
4532
|
+
_close(entry, reason, inTable = true) {
|
|
4533
|
+
if (inTable) this.table.remove(entry);
|
|
4534
|
+
entry.stopWatch();
|
|
4535
|
+
entry.sockets.failAll(reason);
|
|
4536
|
+
entry.link.close(reason);
|
|
4537
|
+
entry.closeUp?.().catch(() => {});
|
|
4538
|
+
if (entry.ctl) {
|
|
4539
|
+
entry.ctl.onmessage = null;
|
|
4540
|
+
entry.ctl.close();
|
|
4541
|
+
}
|
|
4542
|
+
}
|
|
4543
|
+
/**
|
|
4544
|
+
* The handler for `request`: picked by `route` among the live handlers of
|
|
4545
|
+
* its key, waiting for one when there is none.
|
|
4546
|
+
*/
|
|
4547
|
+
async _acquire(request, key) {
|
|
4548
|
+
const picked = await this._pick(request, key);
|
|
4549
|
+
if (picked) return picked;
|
|
4550
|
+
if (this.table.all(key).length > 0) return await this.table.waitFor(key, this.options.attachTimeoutMs ?? 15e3, this.table.live(key).length > 0) ? await this._pick(request, key) ?? TIMED_OUT : TIMED_OUT;
|
|
4551
|
+
const vacantUntil = this._vacant.get(key) ?? 0;
|
|
4552
|
+
if (vacantUntil > Date.now()) return await this.table.waitFor(key, vacantUntil - Date.now()) ? await this._pick(request, key) ?? TIMED_OUT : TIMED_OUT;
|
|
4553
|
+
if (!this.serves(key)) return void 0;
|
|
4554
|
+
await this._askForLinks(key);
|
|
4555
|
+
return await this._pick(request, key);
|
|
4556
|
+
}
|
|
4557
|
+
async _pick(request, key) {
|
|
4558
|
+
let live = this.table.live(key);
|
|
4559
|
+
for (const entry of live) {
|
|
4560
|
+
if (entry.ownerLock || !entry.clientId) continue;
|
|
4561
|
+
if (!await this.self.clients.get(entry.clientId)) this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
4562
|
+
}
|
|
4563
|
+
live = this.table.live(key);
|
|
4564
|
+
if (live.length === 0) return void 0;
|
|
4565
|
+
return (this.options.route ?? leastInflightRoute)(request, key, live);
|
|
4566
|
+
}
|
|
4567
|
+
/**
|
|
4568
|
+
* Asks every window to attach its links again, and waits until a handler
|
|
4569
|
+
* for `key` is back, every window answered, or `relinkTimeoutMs` passed.
|
|
4570
|
+
* At most one round per key every 10 s: a key whose tab is simply gone
|
|
4571
|
+
* should not cost every request the wait.
|
|
4572
|
+
*/
|
|
4573
|
+
_askForLinks(key = "") {
|
|
4574
|
+
const round = this._relinkRounds.get(key);
|
|
4575
|
+
if (round && Date.now() - round.at < 1e4) return round.done;
|
|
4576
|
+
const done = this._linkRound(key);
|
|
4577
|
+
this._relinkRounds.set(key, {
|
|
4578
|
+
at: Date.now(),
|
|
4579
|
+
done
|
|
4580
|
+
});
|
|
4581
|
+
return done;
|
|
4582
|
+
}
|
|
4583
|
+
async _linkRound(key) {
|
|
4584
|
+
const timeout = this.options.relinkTimeoutMs ?? 3e3;
|
|
4585
|
+
const windows = await this.self.clients.matchAll({
|
|
4586
|
+
type: "window",
|
|
4587
|
+
includeUncontrolled: true
|
|
4588
|
+
});
|
|
4589
|
+
this.log("[need-links]", key, windows.length);
|
|
4590
|
+
const params = { routerLock: this.routerLock };
|
|
4591
|
+
const pending = new Set(windows);
|
|
4592
|
+
const answered = Promise.allSettled(windows.map((client) => callChannel(client, NEED_LINKS_CALL, params).then(() => pending.delete(client))));
|
|
4593
|
+
let timer;
|
|
4594
|
+
const timedOut = new Promise((resolve) => {
|
|
4595
|
+
timer = setTimeout(resolve, timeout);
|
|
4596
|
+
});
|
|
4597
|
+
await Promise.race([answered, timedOut]);
|
|
4598
|
+
clearTimeout(timer);
|
|
4599
|
+
for (const client of pending) this._askLegacyPage(client);
|
|
4600
|
+
}
|
|
4601
|
+
/** Asks a version-1 page for a fresh port, as version 1's worker did. */
|
|
4602
|
+
_askLegacyPage(client) {
|
|
4603
|
+
const channel = new MessageChannel();
|
|
4604
|
+
callChannel(client, ATTACH_CALL, {}, channel.port2).then((info) => {
|
|
4605
|
+
if (!info?.key || info.wire !== void 0) return;
|
|
4606
|
+
const link = trackedLink((request) => sendHttpRequest(channel.port1, request), () => channel.port1.close());
|
|
4607
|
+
this._add(new HandlerEntry(info.key, client.id, client.id, void 0, link, void 0, client.id, void 0));
|
|
4608
|
+
}, () => channel.port1.close());
|
|
4609
|
+
}
|
|
4610
|
+
_onControl(entry, message) {
|
|
4611
|
+
if (!message || typeof message !== "object") return;
|
|
4612
|
+
switch (message.t) {
|
|
4613
|
+
case "ws-accept":
|
|
4614
|
+
if (!entry.sockets.settle(message.id, {
|
|
4615
|
+
port: message.port,
|
|
4616
|
+
protocol: message.protocol
|
|
4617
|
+
})) message.port.close();
|
|
4618
|
+
return;
|
|
4619
|
+
case "ws-refuse":
|
|
4620
|
+
entry.sockets.fail(message.id, new Error(message.message));
|
|
4621
|
+
return;
|
|
4622
|
+
case "ws-open":
|
|
4623
|
+
this.connectWebSocket(message.url, message.protocols).then(({ port, protocol }) => entry.ctl?.postMessage({
|
|
4624
|
+
t: "ws-opened",
|
|
4625
|
+
id: message.id,
|
|
4626
|
+
protocol,
|
|
4627
|
+
port
|
|
4628
|
+
}, [port]), (error) => entry.ctl?.postMessage({
|
|
4629
|
+
t: "ws-failed",
|
|
4630
|
+
id: message.id,
|
|
4631
|
+
message: errorMessage(error)
|
|
4632
|
+
}));
|
|
4633
|
+
return;
|
|
4634
|
+
}
|
|
4635
|
+
}
|
|
4636
|
+
_isOwnClient(event) {
|
|
4637
|
+
const source = event.source;
|
|
4638
|
+
if (!source?.url) return false;
|
|
4639
|
+
try {
|
|
4640
|
+
return new URL(source.url).origin === this.self.location.origin;
|
|
4641
|
+
} catch {
|
|
4642
|
+
return false;
|
|
4643
|
+
}
|
|
4644
|
+
}
|
|
4645
|
+
async _claim(key) {
|
|
4646
|
+
if (!key || this.claimedKeys.has(key)) return;
|
|
4647
|
+
this.claimedKeys.add(key);
|
|
4648
|
+
try {
|
|
4649
|
+
await set("claimedKeys", [...this.claimedKeys].sort());
|
|
4650
|
+
} catch (error) {
|
|
4651
|
+
this.log("[claimedKeys] not stored", error);
|
|
4652
|
+
}
|
|
4653
|
+
}
|
|
4654
|
+
async _restoreClaimedKeys() {
|
|
4655
|
+
const stored = await get("claimedKeys") ?? [];
|
|
4656
|
+
for (const key of stored) this.claimedKeys.add(key);
|
|
4657
|
+
}
|
|
4658
|
+
};
|
|
4659
|
+
/**
|
|
4660
|
+
* Starts the same-origin dispatcher in a ServiceWorker. Returns a function
|
|
4661
|
+
* that stops it.
|
|
4662
|
+
*/
|
|
4663
|
+
function startHttpDispatcher(options) {
|
|
4664
|
+
const dispatcher = new SwHttpDispatcher(options);
|
|
4665
|
+
dispatcher.start();
|
|
4666
|
+
return () => {
|
|
4667
|
+
dispatcher.stop();
|
|
4668
|
+
};
|
|
4669
|
+
}
|
|
4670
|
+
//#endregion
|
|
4671
|
+
//#region src/core/registry.ts
|
|
4672
|
+
function newRegistry(onError = console.error) {
|
|
4673
|
+
let counter = 0;
|
|
4674
|
+
const registrations = {};
|
|
4675
|
+
const register = (action) => {
|
|
4676
|
+
const id = counter++;
|
|
4677
|
+
const fn = Object.assign((skip) => {
|
|
4678
|
+
try {
|
|
4679
|
+
delete registrations[id];
|
|
4680
|
+
return skip ? void 0 : action();
|
|
4681
|
+
} catch (error) {
|
|
4682
|
+
onError(error);
|
|
4683
|
+
}
|
|
4684
|
+
}, { action });
|
|
4685
|
+
registrations[id] = fn;
|
|
4686
|
+
return fn;
|
|
4687
|
+
};
|
|
4688
|
+
const unregister = (action) => {
|
|
4689
|
+
for (const r of Object.values(registrations)) if (r.action === action) r(true);
|
|
4690
|
+
};
|
|
4691
|
+
const clear = () => {
|
|
4692
|
+
for (const r of Object.values(registrations)) r();
|
|
4693
|
+
};
|
|
4694
|
+
return Object.assign([
|
|
4695
|
+
register,
|
|
4696
|
+
clear,
|
|
4697
|
+
unregister
|
|
4698
|
+
], {
|
|
4699
|
+
register,
|
|
4700
|
+
clear,
|
|
4701
|
+
unregister
|
|
4702
|
+
});
|
|
1739
4703
|
}
|
|
1740
|
-
|
|
4704
|
+
//#endregion
|
|
4705
|
+
//#region src/sw/worker-url.ts
|
|
4706
|
+
/**
|
|
4707
|
+
* Resolve a `serviceWorkerUrl` option the way a page would: relative to the
|
|
4708
|
+
* current document. Absolute urls pass through untouched. A url that cannot
|
|
4709
|
+
* be resolved is reported with the option name and the offending value,
|
|
4710
|
+
* because the raw `TypeError: Failed to construct 'URL': Invalid URL` says
|
|
4711
|
+
* neither.
|
|
4712
|
+
*/
|
|
4713
|
+
function resolveWorkerUrl(serviceWorkerUrl) {
|
|
4714
|
+
const base = globalThis.location?.href;
|
|
1741
4715
|
try {
|
|
1742
|
-
|
|
1743
|
-
} catch {
|
|
4716
|
+
return new URL(serviceWorkerUrl, base);
|
|
4717
|
+
} catch (error) {
|
|
4718
|
+
throw new Error(`Invalid serviceWorkerUrl: ${JSON.stringify(serviceWorkerUrl)}` + (base ? ` (relative to ${base})` : " (no document to resolve it against)"), { cause: error });
|
|
4719
|
+
}
|
|
1744
4720
|
}
|
|
1745
4721
|
//#endregion
|
|
1746
4722
|
//#region src/sw/sw-dispatcher.ts
|
|
@@ -1980,43 +4956,361 @@ var SwPortDispatcher = class {
|
|
|
1980
4956
|
return index;
|
|
1981
4957
|
}
|
|
1982
4958
|
};
|
|
4959
|
+
//#endregion
|
|
4960
|
+
//#region src/ws/client.ts
|
|
4961
|
+
/** RFC 7230 `token`: what a subprotocol name may be. */
|
|
4962
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
1983
4963
|
/**
|
|
1984
|
-
*
|
|
1985
|
-
*
|
|
1986
|
-
*
|
|
1987
|
-
*
|
|
1988
|
-
*
|
|
4964
|
+
* A WHATWG-compatible `WebSocket` class whose transport is a `MessagePort`
|
|
4965
|
+
* from `connect`. Code written against the browser's `WebSocket` runs on it
|
|
4966
|
+
* unchanged:
|
|
4967
|
+
*
|
|
4968
|
+
* ```ts
|
|
4969
|
+
* const WS = createWebSocketClass(adapter.connectWebSocket);
|
|
4970
|
+
* const ws = new WS(`${baseUrl}chat`, ["v1"]);
|
|
4971
|
+
* ws.onmessage = (event) => console.log(event.data);
|
|
4972
|
+
* ```
|
|
4973
|
+
*
|
|
4974
|
+
* It validates as the standard does (url, scheme, fragment, subprotocol
|
|
4975
|
+
* tokens and duplicates, close codes and reasons), has `binaryType`, the `on*`
|
|
4976
|
+
* handlers next to `addEventListener`, and the close handshake.
|
|
4977
|
+
* `bufferedAmount` is real: the server acknowledges what it consumed.
|
|
4978
|
+
*
|
|
4979
|
+
* The real `globalThis.WebSocket` is left alone; install the class where you
|
|
4980
|
+
* want it.
|
|
1989
4981
|
*/
|
|
1990
|
-
function
|
|
1991
|
-
const
|
|
4982
|
+
function createWebSocketClass(connect, options = {}) {
|
|
4983
|
+
const heartbeatMs = options.heartbeatMs ?? 1e4;
|
|
4984
|
+
class WebSocketOverPort extends PortSocketCore {
|
|
4985
|
+
static CONNECTING = 0;
|
|
4986
|
+
static OPEN = 1;
|
|
4987
|
+
static CLOSING = 2;
|
|
4988
|
+
static CLOSED = 3;
|
|
4989
|
+
CONNECTING = 0;
|
|
4990
|
+
OPEN = 1;
|
|
4991
|
+
CLOSING = 2;
|
|
4992
|
+
CLOSED = 3;
|
|
4993
|
+
url;
|
|
4994
|
+
extensions = "";
|
|
4995
|
+
_protocol = "";
|
|
4996
|
+
_binaryType = "blob";
|
|
4997
|
+
_handlers = {};
|
|
4998
|
+
_heartbeat;
|
|
4999
|
+
/** When the oldest ping still waiting for its pong was sent. */
|
|
5000
|
+
_unansweredSince;
|
|
5001
|
+
_onVisibility;
|
|
5002
|
+
/** Sends waiting for a Blob ahead of them to be read, so order is kept. */
|
|
5003
|
+
_chain;
|
|
5004
|
+
constructor(url, protocols = []) {
|
|
5005
|
+
super({
|
|
5006
|
+
timers: options.timers,
|
|
5007
|
+
closeTimeoutMs: options.closeTimeoutMs
|
|
5008
|
+
});
|
|
5009
|
+
this.url = parseUrl(url);
|
|
5010
|
+
const list = typeof protocols === "string" ? [protocols] : [...protocols];
|
|
5011
|
+
validateProtocols(list);
|
|
5012
|
+
for (const type of [
|
|
5013
|
+
"open",
|
|
5014
|
+
"message",
|
|
5015
|
+
"error",
|
|
5016
|
+
"close"
|
|
5017
|
+
]) this.addEventListener(type, (event) => this._handlers[type]?.call(this, event));
|
|
5018
|
+
Promise.resolve().then(() => connect(this.url, list)).then((connection) => {
|
|
5019
|
+
try {
|
|
5020
|
+
this._opened(connection, list);
|
|
5021
|
+
} catch {
|
|
5022
|
+
this._failed();
|
|
5023
|
+
}
|
|
5024
|
+
}, () => this._failed());
|
|
5025
|
+
}
|
|
5026
|
+
get protocol() {
|
|
5027
|
+
return this._protocol;
|
|
5028
|
+
}
|
|
5029
|
+
get binaryType() {
|
|
5030
|
+
return this._binaryType;
|
|
5031
|
+
}
|
|
5032
|
+
set binaryType(value) {
|
|
5033
|
+
if (value === "blob" || value === "arraybuffer") this._binaryType = value;
|
|
5034
|
+
}
|
|
5035
|
+
get onopen() {
|
|
5036
|
+
return this._handlers.open ?? null;
|
|
5037
|
+
}
|
|
5038
|
+
set onopen(fn) {
|
|
5039
|
+
this._handlers.open = typeof fn === "function" ? fn : null;
|
|
5040
|
+
}
|
|
5041
|
+
get onmessage() {
|
|
5042
|
+
return this._handlers.message ?? null;
|
|
5043
|
+
}
|
|
5044
|
+
set onmessage(fn) {
|
|
5045
|
+
this._handlers.message = typeof fn === "function" ? fn : null;
|
|
5046
|
+
}
|
|
5047
|
+
get onerror() {
|
|
5048
|
+
return this._handlers.error ?? null;
|
|
5049
|
+
}
|
|
5050
|
+
set onerror(fn) {
|
|
5051
|
+
this._handlers.error = typeof fn === "function" ? fn : null;
|
|
5052
|
+
}
|
|
5053
|
+
get onclose() {
|
|
5054
|
+
return this._handlers.close ?? null;
|
|
5055
|
+
}
|
|
5056
|
+
set onclose(fn) {
|
|
5057
|
+
this._handlers.close = typeof fn === "function" ? fn : null;
|
|
5058
|
+
}
|
|
5059
|
+
send(data) {
|
|
5060
|
+
if (this._state === 0) throw new DOMException("Still in CONNECTING state.", "InvalidStateError");
|
|
5061
|
+
if (isBlob(data)) {
|
|
5062
|
+
const size = data.size;
|
|
5063
|
+
if (this._state !== 1) {
|
|
5064
|
+
this._sendData(new ArrayBuffer(size));
|
|
5065
|
+
return;
|
|
5066
|
+
}
|
|
5067
|
+
this._reserve(size);
|
|
5068
|
+
this._enqueue(async () => this._sendData(await data.arrayBuffer(), true));
|
|
5069
|
+
return;
|
|
5070
|
+
}
|
|
5071
|
+
const payload = isBinary(data) ? toArrayBuffer(data) : String(data);
|
|
5072
|
+
if (this._chain) this._enqueue(async () => this._sendData(payload));
|
|
5073
|
+
else this._sendData(payload);
|
|
5074
|
+
}
|
|
5075
|
+
close(code, reason) {
|
|
5076
|
+
if (code !== void 0 && !isApplicationCloseCode(code)) throw new DOMException(`The close code must be 1000 or in 3000-4999; ${code} is neither.`, "InvalidAccessError");
|
|
5077
|
+
const text = reason ?? "";
|
|
5078
|
+
if (utf8Length(text) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
|
|
5079
|
+
if (this._state === 2 || this._state === 3) return;
|
|
5080
|
+
if (this._state === 0) {
|
|
5081
|
+
this._state = 2;
|
|
5082
|
+
return;
|
|
5083
|
+
}
|
|
5084
|
+
this._startClose(code ?? 1005, text);
|
|
5085
|
+
}
|
|
5086
|
+
_dispatchMessage(data) {
|
|
5087
|
+
const value = typeof data === "string" || this._binaryType === "arraybuffer" ? data : new Blob([data]);
|
|
5088
|
+
this.dispatchEvent(new MessageEvent("message", {
|
|
5089
|
+
data: value,
|
|
5090
|
+
origin: new URL(this.url).origin
|
|
5091
|
+
}));
|
|
5092
|
+
}
|
|
5093
|
+
_onPong() {
|
|
5094
|
+
this._unansweredSince = void 0;
|
|
5095
|
+
}
|
|
5096
|
+
_onClosed() {
|
|
5097
|
+
if (this._heartbeat !== void 0) this._timers.clearInterval(this._heartbeat);
|
|
5098
|
+
this._heartbeat = void 0;
|
|
5099
|
+
if (this._onVisibility) globalThis.document?.removeEventListener("visibilitychange", this._onVisibility);
|
|
5100
|
+
}
|
|
5101
|
+
_ping(hb = heartbeatMs) {
|
|
5102
|
+
this._unansweredSince ??= Date.now();
|
|
5103
|
+
this._post({
|
|
5104
|
+
t: "p",
|
|
5105
|
+
hb
|
|
5106
|
+
});
|
|
5107
|
+
}
|
|
5108
|
+
_opened(connection, requested) {
|
|
5109
|
+
const { port, protocol = "" } = connection ?? {};
|
|
5110
|
+
if (!port || typeof port.postMessage !== "function") {
|
|
5111
|
+
this._failed();
|
|
5112
|
+
return;
|
|
5113
|
+
}
|
|
5114
|
+
if (this._state !== 0) {
|
|
5115
|
+
try {
|
|
5116
|
+
port.postMessage({
|
|
5117
|
+
t: "c",
|
|
5118
|
+
code: 1006,
|
|
5119
|
+
reason: ""
|
|
5120
|
+
});
|
|
5121
|
+
port.close();
|
|
5122
|
+
} catch {}
|
|
5123
|
+
this._finish(1006, "", false, true);
|
|
5124
|
+
return;
|
|
5125
|
+
}
|
|
5126
|
+
if (protocol !== "" && !requested.includes(protocol)) {
|
|
5127
|
+
port.close();
|
|
5128
|
+
this._failed();
|
|
5129
|
+
return;
|
|
5130
|
+
}
|
|
5131
|
+
this._protocol = protocol;
|
|
5132
|
+
this._attach(port);
|
|
5133
|
+
this._state = 1;
|
|
5134
|
+
this._ping();
|
|
5135
|
+
this._heartbeat = this._timers.setInterval(() => {
|
|
5136
|
+
const since = this._unansweredSince;
|
|
5137
|
+
if (since !== void 0 && Date.now() - since > 2 * heartbeatMs) {
|
|
5138
|
+
this._finish(1006, "", false, true);
|
|
5139
|
+
return;
|
|
5140
|
+
}
|
|
5141
|
+
this._ping();
|
|
5142
|
+
}, heartbeatMs);
|
|
5143
|
+
const doc = globalThis.document;
|
|
5144
|
+
if (doc) {
|
|
5145
|
+
this._onVisibility = () => this._ping(doc.visibilityState === "hidden" ? Math.max(heartbeatMs, 7e4) : heartbeatMs);
|
|
5146
|
+
doc.addEventListener("visibilitychange", this._onVisibility);
|
|
5147
|
+
if (doc.visibilityState === "hidden") this._onVisibility();
|
|
5148
|
+
}
|
|
5149
|
+
this.dispatchEvent(new Event("open"));
|
|
5150
|
+
}
|
|
5151
|
+
_failed() {
|
|
5152
|
+
this._state = 2;
|
|
5153
|
+
this._finish(1006, "", false, true);
|
|
5154
|
+
}
|
|
5155
|
+
_enqueue(task) {
|
|
5156
|
+
const run = (this._chain ?? Promise.resolve()).then(task).catch(() => {});
|
|
5157
|
+
this._chain = run;
|
|
5158
|
+
run.then(() => {
|
|
5159
|
+
if (this._chain === run) this._chain = void 0;
|
|
5160
|
+
});
|
|
5161
|
+
}
|
|
5162
|
+
}
|
|
5163
|
+
return WebSocketOverPort;
|
|
5164
|
+
}
|
|
5165
|
+
function parseUrl(input) {
|
|
5166
|
+
let url;
|
|
1992
5167
|
try {
|
|
1993
|
-
|
|
1994
|
-
} catch
|
|
1995
|
-
throw new
|
|
5168
|
+
url = new URL(`${input}`, globalThis.location?.href);
|
|
5169
|
+
} catch {
|
|
5170
|
+
throw new DOMException(`The URL '${input}' is invalid.`, "SyntaxError");
|
|
5171
|
+
}
|
|
5172
|
+
if (url.protocol === "http:") url.protocol = "ws:";
|
|
5173
|
+
else if (url.protocol === "https:") url.protocol = "wss:";
|
|
5174
|
+
if (url.protocol !== "ws:" && url.protocol !== "wss:") throw new DOMException(`The URL's scheme must be 'ws', 'wss', 'http' or 'https'; '${url.protocol.slice(0, -1)}' is not allowed.`, "SyntaxError");
|
|
5175
|
+
if (url.hash !== "" || `${input}`.includes("#")) throw new DOMException(`The URL contains a fragment identifier ('${url.hash}'). Fragment identifiers are not allowed in WebSocket URLs.`, "SyntaxError");
|
|
5176
|
+
return url.href;
|
|
5177
|
+
}
|
|
5178
|
+
function validateProtocols(protocols) {
|
|
5179
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5180
|
+
for (const protocol of protocols) {
|
|
5181
|
+
if (!TOKEN.test(protocol)) throw new DOMException(`The subprotocol '${protocol}' is invalid.`, "SyntaxError");
|
|
5182
|
+
if (seen.has(protocol)) throw new DOMException(`The subprotocol '${protocol}' is duplicated.`, "SyntaxError");
|
|
5183
|
+
seen.add(protocol);
|
|
1996
5184
|
}
|
|
1997
5185
|
}
|
|
1998
5186
|
//#endregion
|
|
1999
|
-
//#region src/sw/http-
|
|
2000
|
-
|
|
5187
|
+
//#region src/sw/sw-http-adapter.ts
|
|
5188
|
+
/**
|
|
5189
|
+
* The page side of the same-origin ServiceWorker: registers the worker, and
|
|
5190
|
+
* attaches handler links to it.
|
|
5191
|
+
*
|
|
5192
|
+
* - `register(prefix, handler)` serves a handler in this page, under
|
|
5193
|
+
* `<scope>/<key>/...`.
|
|
5194
|
+
* - `attachWorker(worker)` links a Dedicated Worker that runs
|
|
5195
|
+
* `serveHttpInWorker(handler)`: the ServiceWorker then talks to the worker
|
|
5196
|
+
* directly, and this page carries nothing.
|
|
5197
|
+
* - `connectWebSocket(url, protocols)` and `WebSocket` open sockets to
|
|
5198
|
+
* handlers, through the ServiceWorker or straight to a handler of this page.
|
|
5199
|
+
*
|
|
5200
|
+
* Links are attached again whenever the ServiceWorker asks (after a restart),
|
|
5201
|
+
* and requests in flight on a handler that dies fail at once.
|
|
5202
|
+
*/
|
|
5203
|
+
var SwHttpAdapter = class {
|
|
5204
|
+
options;
|
|
2001
5205
|
_handlers = /* @__PURE__ */ new Map();
|
|
2002
|
-
|
|
5206
|
+
_endpoint;
|
|
5207
|
+
_ownerLock = newLockName("webrun-http-owner");
|
|
5208
|
+
_id;
|
|
5209
|
+
_owner = crypto.randomUUID();
|
|
5210
|
+
_workers = /* @__PURE__ */ new Set();
|
|
5211
|
+
_releaseOwner;
|
|
5212
|
+
_serviceWorkerUrl;
|
|
5213
|
+
_serviceWorker;
|
|
5214
|
+
_registration;
|
|
5215
|
+
_registrationPromise;
|
|
5216
|
+
_cleanup = [];
|
|
5217
|
+
_attaching;
|
|
5218
|
+
_routerLock;
|
|
5219
|
+
_WebSocket;
|
|
2003
5220
|
constructor(options) {
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
}
|
|
5221
|
+
this.options = options;
|
|
5222
|
+
if (!this.key) throw new Error("Key is not defined.");
|
|
5223
|
+
if (!this.scope) throw new Error("Scope is not defined");
|
|
5224
|
+
this._id = options.id ?? `page:${crypto.randomUUID()}`;
|
|
5225
|
+
this._endpoint = new HandlerEndpoint((request) => this._handleHttpRequest(request), { streamTimeout: options.streamTimeout });
|
|
2008
5226
|
}
|
|
2009
|
-
|
|
2010
|
-
this.
|
|
2011
|
-
this._cleanupRequestChannel = handleHttpRequests(port, this._handleHttpRequest.bind(this));
|
|
5227
|
+
get key() {
|
|
5228
|
+
return this.options.key;
|
|
2012
5229
|
}
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
5230
|
+
get scope() {
|
|
5231
|
+
return this.options.scope ?? new URL("./", this.serviceWorkerUrl).pathname;
|
|
5232
|
+
}
|
|
5233
|
+
/**
|
|
5234
|
+
* The scope as a url on the worker's origin. Resolved against the worker's
|
|
5235
|
+
* own url when one is given, not against this module's: a bundle that is
|
|
5236
|
+
* not an ES module (an IIFE, Theia's frontend) has no `import.meta.url`, and
|
|
5237
|
+
* `new URL(scope, undefined)` threw `Invalid URL` there. Only without a
|
|
5238
|
+
* worker url does the module's location decide (its default `sw-worker.js`
|
|
5239
|
+
* sits next to it).
|
|
5240
|
+
*/
|
|
5241
|
+
get rootUrl() {
|
|
5242
|
+
const base = this.options.serviceWorkerUrl ? this.serviceWorkerUrl : import.meta.url;
|
|
5243
|
+
return new URL(this.scope, base);
|
|
5244
|
+
}
|
|
5245
|
+
get serviceWorkerUrl() {
|
|
5246
|
+
if (!this._serviceWorkerUrl) {
|
|
5247
|
+
const url = this.options.serviceWorkerUrl ? resolveWorkerUrl(this.options.serviceWorkerUrl) : new URL("./sw-worker.js", this.rootUrl);
|
|
5248
|
+
this._serviceWorkerUrl = `${url}`;
|
|
5249
|
+
}
|
|
5250
|
+
return this._serviceWorkerUrl;
|
|
5251
|
+
}
|
|
5252
|
+
/**
|
|
5253
|
+
* Registers the worker and waits until it is activated and controls this
|
|
5254
|
+
* page, then attaches this page's handler link. The page must be controlled,
|
|
5255
|
+
* because only a controlled page's `fetch()` reaches the worker. When the
|
|
5256
|
+
* page loaded uncontrolled (a hard reload does that), the worker is asked to
|
|
5257
|
+
* claim it. Rejects with a `ServiceWorkerControlError` when that fails or
|
|
5258
|
+
* `timeout` passes (`reason` says which step); a later `start()` tries
|
|
5259
|
+
* again.
|
|
5260
|
+
*/
|
|
5261
|
+
async start() {
|
|
5262
|
+
if (!this._registrationPromise) this._registrationPromise = (async () => {
|
|
5263
|
+
const registration = await navigator.serviceWorker.register(this.serviceWorkerUrl, { scope: this.scope });
|
|
5264
|
+
this._registration = registration;
|
|
5265
|
+
const stopListening = handleChannelCalls(navigator.serviceWorker, NEED_LINKS_CALL, async (_event, params) => {
|
|
5266
|
+
await this.relink(params?.routerLock);
|
|
5267
|
+
return true;
|
|
5268
|
+
});
|
|
5269
|
+
const onControllerChange = () => {
|
|
5270
|
+
const controller = navigator.serviceWorker.controller;
|
|
5271
|
+
if (controller) this._serviceWorker = controller;
|
|
5272
|
+
};
|
|
5273
|
+
navigator.serviceWorker.addEventListener("controllerchange", onControllerChange);
|
|
5274
|
+
this._cleanup.push(stopListening, () => navigator.serviceWorker.removeEventListener("controllerchange", onControllerChange));
|
|
5275
|
+
const timeout = this.options.timeout ?? 3e4;
|
|
5276
|
+
const deadline = Date.now() + timeout;
|
|
5277
|
+
try {
|
|
5278
|
+
this._serviceWorker = await awaitServiceWorkerControl(registration, {
|
|
5279
|
+
timeout,
|
|
5280
|
+
reloadIfUncontrolled: this.options.reloadIfUncontrolled
|
|
5281
|
+
});
|
|
5282
|
+
this._releaseOwner ??= await holdLock(this._ownerLock);
|
|
5283
|
+
await withDeadline(deadline, this._attachPage(), () => new ServiceWorkerControlError("unresponsive", `ServiceWorker "${this._serviceWorker?.scriptURL}" controls this page but did not answer the UPDATE_COMMUNICATION_PORT handshake within ${timeout} ms. Check that the worker script runs this package's same-origin dispatcher (it importScripts \`sw-worker.js\`, or calls \`startHttpDispatcher\`).`));
|
|
5284
|
+
} catch (error) {
|
|
5285
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
5286
|
+
this._registration = void 0;
|
|
5287
|
+
this._registrationPromise = void 0;
|
|
5288
|
+
throw error;
|
|
5289
|
+
}
|
|
5290
|
+
})();
|
|
5291
|
+
return this._registrationPromise;
|
|
5292
|
+
}
|
|
5293
|
+
/** Detaches every link, and unregisters the worker. */
|
|
5294
|
+
async stop() {
|
|
5295
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
5296
|
+
for (const worker of [...this._workers]) await worker.detach().catch(() => {});
|
|
5297
|
+
const sw = this._serviceWorker;
|
|
5298
|
+
if (sw) await callChannel(sw, DETACH_CALL, {
|
|
5299
|
+
key: this.key,
|
|
5300
|
+
id: this._id,
|
|
5301
|
+
owner: this._owner
|
|
5302
|
+
}).catch(() => {});
|
|
5303
|
+
await this._endpoint.unlink();
|
|
5304
|
+
this._releaseOwner?.();
|
|
5305
|
+
this._releaseOwner = void 0;
|
|
5306
|
+
const registration = this._registration;
|
|
5307
|
+
this._registration = void 0;
|
|
5308
|
+
this._registrationPromise = void 0;
|
|
5309
|
+
try {
|
|
5310
|
+
await registration?.unregister();
|
|
5311
|
+
} catch (error) {
|
|
5312
|
+
console.log("Service Worker unregistration failed: ", error);
|
|
5313
|
+
}
|
|
2020
5314
|
}
|
|
2021
5315
|
/**
|
|
2022
5316
|
* Registers an HTTP handler on a prefix. Returns the resulting base URL and a
|
|
@@ -2035,44 +5329,393 @@ var SwHttpAdapter = class extends SwPortHandler {
|
|
|
2035
5329
|
}
|
|
2036
5330
|
};
|
|
2037
5331
|
}
|
|
5332
|
+
/**
|
|
5333
|
+
* Links a Dedicated Worker that runs `serveHttpInWorker(handler)` as a
|
|
5334
|
+
* handler of `key`. The ServiceWorker sends it requests directly, without
|
|
5335
|
+
* this page relaying anything, so a busy or throttled page does not slow
|
|
5336
|
+
* them down.
|
|
5337
|
+
*/
|
|
5338
|
+
async attachWorker(worker, options = {}) {
|
|
5339
|
+
await this.start();
|
|
5340
|
+
const controls = [];
|
|
5341
|
+
let retry;
|
|
5342
|
+
const { control, ownerLock } = await new Promise((resolve, reject) => {
|
|
5343
|
+
const timer = setTimeout(() => {
|
|
5344
|
+
clearInterval(retry);
|
|
5345
|
+
for (const port of controls) port.close();
|
|
5346
|
+
reject(/* @__PURE__ */ new Error("The worker did not answer within the timeout. Does it call serveHttpInWorker()?"));
|
|
5347
|
+
}, this.options.timeout ?? 3e4);
|
|
5348
|
+
const hello = () => {
|
|
5349
|
+
const channel = new MessageChannel();
|
|
5350
|
+
controls.push(channel.port1);
|
|
5351
|
+
channel.port1.onmessage = (event) => {
|
|
5352
|
+
const message = event.data;
|
|
5353
|
+
if (message?.type !== "ready") return;
|
|
5354
|
+
clearTimeout(timer);
|
|
5355
|
+
clearInterval(retry);
|
|
5356
|
+
for (const port of controls) if (port !== channel.port1) port.close();
|
|
5357
|
+
resolve({
|
|
5358
|
+
control: channel.port1,
|
|
5359
|
+
ownerLock: message.ownerLock
|
|
5360
|
+
});
|
|
5361
|
+
};
|
|
5362
|
+
worker.postMessage({ type: WORKER_HELLO }, [channel.port2]);
|
|
5363
|
+
};
|
|
5364
|
+
hello();
|
|
5365
|
+
retry = setInterval(hello, 500);
|
|
5366
|
+
});
|
|
5367
|
+
const key = options.key ?? this.key;
|
|
5368
|
+
const id = options.id ?? `worker:${crypto.randomUUID()}`;
|
|
5369
|
+
for (const old of [...this._workers]) if (old.key === key && old.id === id) old.retire();
|
|
5370
|
+
const link = new WorkerLinkImpl(this, control, {
|
|
5371
|
+
key,
|
|
5372
|
+
id,
|
|
5373
|
+
owner: crypto.randomUUID(),
|
|
5374
|
+
meta: options.meta,
|
|
5375
|
+
ownerLock
|
|
5376
|
+
});
|
|
5377
|
+
this._workers.add(link);
|
|
5378
|
+
await link.attach();
|
|
5379
|
+
return link;
|
|
5380
|
+
}
|
|
5381
|
+
/**
|
|
5382
|
+
* Opens the transport of a socket to the handler `url` routes to: a handler
|
|
5383
|
+
* of this page directly, any other through the ServiceWorker. Resolves once
|
|
5384
|
+
* the handler accepted. An arrow function, so it can be handed around:
|
|
5385
|
+
* `createWebSocketClass(adapter.connectWebSocket)`.
|
|
5386
|
+
*/
|
|
5387
|
+
connectWebSocket = async (url, protocols = []) => {
|
|
5388
|
+
const httpUrl = new URL(`${url}`, globalThis.location?.href);
|
|
5389
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
5390
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
5391
|
+
const local = this._findHandler(`${httpUrl}`);
|
|
5392
|
+
if (local) {
|
|
5393
|
+
const result = await serveWebSocketUpgrade(local, {
|
|
5394
|
+
url: `${httpUrl}`,
|
|
5395
|
+
protocols
|
|
5396
|
+
});
|
|
5397
|
+
if (!result.ok) throw new Error(result.message);
|
|
5398
|
+
return {
|
|
5399
|
+
port: result.port,
|
|
5400
|
+
protocol: result.protocol
|
|
5401
|
+
};
|
|
5402
|
+
}
|
|
5403
|
+
await this.start();
|
|
5404
|
+
return await callChannelWithin(this._callTimeout(), this._worker(), WS_CONNECT_CALL, {
|
|
5405
|
+
url: `${httpUrl}`,
|
|
5406
|
+
protocols
|
|
5407
|
+
});
|
|
5408
|
+
};
|
|
5409
|
+
/**
|
|
5410
|
+
* A WHATWG `WebSocket` class whose sockets reach this adapter's handlers:
|
|
5411
|
+
* `new adapter.WebSocket(`${baseUrl}chat`, ["v1"])`. The global
|
|
5412
|
+
* `WebSocket` is left alone.
|
|
5413
|
+
*/
|
|
5414
|
+
get WebSocket() {
|
|
5415
|
+
this._WebSocket ??= createWebSocketClass(this.connectWebSocket, this.options.webSocket);
|
|
5416
|
+
return this._WebSocket;
|
|
5417
|
+
}
|
|
5418
|
+
/**
|
|
5419
|
+
* Attaches again every link not made for the router holding
|
|
5420
|
+
* `currentRouterLock` (every link, without it). The ServiceWorker asks for
|
|
5421
|
+
* this after a restart; a page may call it too.
|
|
5422
|
+
*/
|
|
5423
|
+
async relink(currentRouterLock) {
|
|
5424
|
+
if (!this._registrationPromise) return;
|
|
5425
|
+
const stale = (routerLock) => currentRouterLock === void 0 || routerLock !== currentRouterLock;
|
|
5426
|
+
const jobs = [];
|
|
5427
|
+
if (stale(this._routerLock)) jobs.push(this._attachPage());
|
|
5428
|
+
for (const worker of this._workers) if (stale(worker.routerLock)) jobs.push(worker.attach());
|
|
5429
|
+
await Promise.allSettled(jobs);
|
|
5430
|
+
}
|
|
5431
|
+
/** @internal Posts a plain message to the ServiceWorker, which starts it if stopped. */
|
|
5432
|
+
_poke(type) {
|
|
5433
|
+
try {
|
|
5434
|
+
this._worker().postMessage({ type });
|
|
5435
|
+
} catch {}
|
|
5436
|
+
}
|
|
5437
|
+
/** @internal */
|
|
5438
|
+
_worker() {
|
|
5439
|
+
const worker = navigator.serviceWorker.controller ?? this._serviceWorker ?? this._registration?.active;
|
|
5440
|
+
if (!worker) throw new Error("The ServiceWorker is not running; call start() first");
|
|
5441
|
+
return worker;
|
|
5442
|
+
}
|
|
5443
|
+
/** @internal */
|
|
5444
|
+
_forget(link) {
|
|
5445
|
+
this._workers.delete(link);
|
|
5446
|
+
}
|
|
5447
|
+
/** @internal How long a call to the ServiceWorker may take. */
|
|
5448
|
+
_callTimeout() {
|
|
5449
|
+
return this.options.timeout ?? 3e4;
|
|
5450
|
+
}
|
|
5451
|
+
_attachPage() {
|
|
5452
|
+
this._attaching ??= (async () => {
|
|
5453
|
+
try {
|
|
5454
|
+
const down = new MessageChannel();
|
|
5455
|
+
const ctl = new MessageChannel();
|
|
5456
|
+
const params = {
|
|
5457
|
+
wire: HTTP_LINK_PROTOCOL,
|
|
5458
|
+
key: this.key,
|
|
5459
|
+
id: this._id,
|
|
5460
|
+
owner: this._owner,
|
|
5461
|
+
ownerLock: this._releaseOwner && locksAvailable() ? this._ownerLock : void 0,
|
|
5462
|
+
meta: this.options.meta,
|
|
5463
|
+
ctl: true
|
|
5464
|
+
};
|
|
5465
|
+
const reply = await callChannelWithin(this._callTimeout(), this._worker(), ATTACH_CALL, params, down.port1, ctl.port1);
|
|
5466
|
+
checkReply(reply, this._worker());
|
|
5467
|
+
await this._endpoint.link(this.key, {
|
|
5468
|
+
down: down.port2,
|
|
5469
|
+
ctl: ctl.port2
|
|
5470
|
+
}, reply.routerLock);
|
|
5471
|
+
this._routerLock = reply.routerLock;
|
|
5472
|
+
} finally {
|
|
5473
|
+
this._attaching = void 0;
|
|
5474
|
+
}
|
|
5475
|
+
})();
|
|
5476
|
+
return this._attaching;
|
|
5477
|
+
}
|
|
5478
|
+
_findHandler(url) {
|
|
5479
|
+
for (const [urlPrefix, handler] of this._handlers) if (url.indexOf(urlPrefix) === 0) return handler;
|
|
5480
|
+
}
|
|
5481
|
+
async _handleHttpRequest(request) {
|
|
5482
|
+
const handler = this._findHandler(request.url);
|
|
5483
|
+
if (handler) return await handler(request);
|
|
5484
|
+
return new Response(null, {
|
|
5485
|
+
status: 404,
|
|
5486
|
+
statusText: "Error 404: Not found"
|
|
5487
|
+
});
|
|
5488
|
+
}
|
|
2038
5489
|
};
|
|
2039
|
-
var
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
5490
|
+
var WorkerLinkImpl = class {
|
|
5491
|
+
_adapter;
|
|
5492
|
+
_control;
|
|
5493
|
+
key;
|
|
5494
|
+
id;
|
|
5495
|
+
owner;
|
|
5496
|
+
routerLock;
|
|
5497
|
+
_meta;
|
|
5498
|
+
_ownerLock;
|
|
5499
|
+
_attaching;
|
|
5500
|
+
_detached = false;
|
|
5501
|
+
constructor(_adapter, _control, init) {
|
|
5502
|
+
this._adapter = _adapter;
|
|
5503
|
+
this._control = _control;
|
|
5504
|
+
this.key = init.key;
|
|
5505
|
+
this.id = init.id;
|
|
5506
|
+
this.owner = init.owner;
|
|
5507
|
+
this._meta = init.meta;
|
|
5508
|
+
this._ownerLock = init.ownerLock;
|
|
5509
|
+
_control.onmessage = (event) => {
|
|
5510
|
+
const message = event.data;
|
|
5511
|
+
if (message?.type === "relink") {
|
|
5512
|
+
this._adapter._poke(WAKE_MESSAGE);
|
|
5513
|
+
this.attach().catch(() => {});
|
|
5514
|
+
} else if (message?.type === "keepalive") this._adapter._poke(KEEPALIVE_MESSAGE);
|
|
5515
|
+
};
|
|
2043
5516
|
}
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
5517
|
+
/**
|
|
5518
|
+
* Forgets this link without telling the ServiceWorker: another attachment
|
|
5519
|
+
* took its slot, and the ServiceWorker retires it by itself.
|
|
5520
|
+
*/
|
|
5521
|
+
retire() {
|
|
5522
|
+
this._detached = true;
|
|
5523
|
+
this._adapter._forget(this);
|
|
5524
|
+
this._control.onmessage = null;
|
|
5525
|
+
}
|
|
5526
|
+
/** Makes fresh channels and attaches them; the worker gets its ends. */
|
|
5527
|
+
attach() {
|
|
5528
|
+
if (this._detached) return Promise.resolve();
|
|
5529
|
+
this._attaching ??= (async () => {
|
|
2047
5530
|
try {
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
if (this.isClaimedKey(key)) return new Response(null, {
|
|
2055
|
-
status: 404,
|
|
2056
|
-
statusText: "Not Found (no active handler)"
|
|
2057
|
-
});
|
|
5531
|
+
if (this._ownerLock) {
|
|
5532
|
+
const held = await heldLockNames();
|
|
5533
|
+
if (held && !held.has(this._ownerLock)) {
|
|
5534
|
+
this.retire();
|
|
5535
|
+
return;
|
|
5536
|
+
}
|
|
2058
5537
|
}
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
5538
|
+
const down = new MessageChannel();
|
|
5539
|
+
const ctl = new MessageChannel();
|
|
5540
|
+
const up = new MessageChannel();
|
|
5541
|
+
const params = {
|
|
5542
|
+
wire: HTTP_LINK_PROTOCOL,
|
|
5543
|
+
key: this.key,
|
|
5544
|
+
id: this.id,
|
|
5545
|
+
owner: this.owner,
|
|
5546
|
+
ownerLock: this._ownerLock,
|
|
5547
|
+
meta: this._meta,
|
|
5548
|
+
ctl: true,
|
|
5549
|
+
up: true
|
|
5550
|
+
};
|
|
5551
|
+
const sw = this._adapter._worker();
|
|
5552
|
+
const reply = await callChannelWithin(this._adapter._callTimeout(), sw, ATTACH_CALL, params, down.port1, ctl.port1, up.port1);
|
|
5553
|
+
checkReply(reply, sw);
|
|
5554
|
+
this.routerLock = reply.routerLock;
|
|
5555
|
+
this._control.postMessage({
|
|
5556
|
+
type: "link",
|
|
5557
|
+
key: this.key,
|
|
5558
|
+
routerLock: reply.routerLock
|
|
5559
|
+
}, [
|
|
5560
|
+
down.port2,
|
|
5561
|
+
ctl.port2,
|
|
5562
|
+
up.port2
|
|
5563
|
+
]);
|
|
5564
|
+
} finally {
|
|
5565
|
+
this._attaching = void 0;
|
|
2066
5566
|
}
|
|
2067
|
-
})()
|
|
5567
|
+
})();
|
|
5568
|
+
return this._attaching;
|
|
5569
|
+
}
|
|
5570
|
+
async drain({ ms } = {}) {
|
|
5571
|
+
if (this._detached) return;
|
|
5572
|
+
this._detached = true;
|
|
5573
|
+
this._adapter._forget(this);
|
|
5574
|
+
try {
|
|
5575
|
+
await callChannel(this._adapter._worker(), DRAIN_CALL, {
|
|
5576
|
+
key: this.key,
|
|
5577
|
+
id: this.id,
|
|
5578
|
+
owner: this.owner,
|
|
5579
|
+
ms
|
|
5580
|
+
});
|
|
5581
|
+
} finally {
|
|
5582
|
+
this._unlink();
|
|
5583
|
+
}
|
|
5584
|
+
}
|
|
5585
|
+
async detach() {
|
|
5586
|
+
if (this._detached) return;
|
|
5587
|
+
this._detached = true;
|
|
5588
|
+
this._adapter._forget(this);
|
|
5589
|
+
await callChannel(this._adapter._worker(), DETACH_CALL, {
|
|
5590
|
+
key: this.key,
|
|
5591
|
+
id: this.id,
|
|
5592
|
+
owner: this.owner
|
|
5593
|
+
}).catch(() => {});
|
|
5594
|
+
this._unlink();
|
|
5595
|
+
}
|
|
5596
|
+
_unlink() {
|
|
5597
|
+
this._control.postMessage({
|
|
5598
|
+
type: "unlink",
|
|
5599
|
+
key: this.key
|
|
5600
|
+
});
|
|
5601
|
+
this._control.onmessage = null;
|
|
2068
5602
|
}
|
|
2069
5603
|
};
|
|
2070
|
-
function
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
5604
|
+
function checkReply(reply, sw) {
|
|
5605
|
+
if (reply?.accepted === "webrun-http-link/2") return;
|
|
5606
|
+
throw new ServiceWorkerControlError("incompatible", `ServiceWorker "${sw.scriptURL}" answered the handshake but does not speak ${HTTP_LINK_PROTOCOL}: it runs an older version of @statewalker/webrun-http-browser. Reload the page once the updated worker is active.`);
|
|
5607
|
+
}
|
|
5608
|
+
//#endregion
|
|
5609
|
+
//#region src/sw/sw-websocket.ts
|
|
5610
|
+
/**
|
|
5611
|
+
* Opens the transport of a socket through the ServiceWorker controlling this
|
|
5612
|
+
* page, for a page that has no adapter of its own: content a handler serves
|
|
5613
|
+
* under the same-origin dispatcher, or under a relay. The ServiceWorker
|
|
5614
|
+
* routes `url` like a fetch, and the handler accepts or refuses the upgrade.
|
|
5615
|
+
*/
|
|
5616
|
+
async function connectWebSocketThroughServiceWorker(url, protocols = [], container = navigator.serviceWorker) {
|
|
5617
|
+
const worker = container.controller;
|
|
5618
|
+
if (!worker) throw new Error("This page is not controlled by a ServiceWorker");
|
|
5619
|
+
const httpUrl = new URL(`${url}`, globalThis.location?.href);
|
|
5620
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
5621
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
5622
|
+
return await callChannel(worker, WS_CONNECT_CALL, {
|
|
5623
|
+
url: `${httpUrl}`,
|
|
5624
|
+
protocols
|
|
5625
|
+
});
|
|
5626
|
+
}
|
|
5627
|
+
/**
|
|
5628
|
+
* A WHATWG `WebSocket` class over `connectWebSocketThroughServiceWorker`.
|
|
5629
|
+
* Install it where the page's code expects `WebSocket`, e.g.
|
|
5630
|
+
* `globalThis.WebSocket = serviceWorkerWebSocketClass()` in content that only
|
|
5631
|
+
* talks to its own handlers.
|
|
5632
|
+
*/
|
|
5633
|
+
function serviceWorkerWebSocketClass(options) {
|
|
5634
|
+
return createWebSocketClass((url, protocols) => connectWebSocketThroughServiceWorker(url, protocols), options);
|
|
5635
|
+
}
|
|
5636
|
+
//#endregion
|
|
5637
|
+
//#region src/sw/worker-service.ts
|
|
5638
|
+
/**
|
|
5639
|
+
* Serves `handler` from a Dedicated Worker, on the links the page attaches
|
|
5640
|
+
* with `adapter.attachWorker(worker)`:
|
|
5641
|
+
*
|
|
5642
|
+
* ```ts
|
|
5643
|
+
* // worker.ts
|
|
5644
|
+
* const service = serveHttpInWorker(async (request) => new Response("hi"));
|
|
5645
|
+
* ```
|
|
5646
|
+
*
|
|
5647
|
+
* The worker holds an owner lock while it lives, so the ServiceWorker notices
|
|
5648
|
+
* at once when it is terminated. It watches the ServiceWorker's router lock,
|
|
5649
|
+
* and asks its page to attach it again when its links died and a call waits.
|
|
5650
|
+
* While calls through the router are in flight it asks its page every 20 s to
|
|
5651
|
+
* keep the ServiceWorker awake — only a message to the ServiceWorker object
|
|
5652
|
+
* counts as an event, and a worker cannot post one.
|
|
5653
|
+
*/
|
|
5654
|
+
function serveHttpInWorker(handler, options = {}) {
|
|
5655
|
+
const scope = options.scope ?? globalThis;
|
|
5656
|
+
const ownerLock = newLockName("webrun-http-owner");
|
|
5657
|
+
const held = holdLock(ownerLock);
|
|
5658
|
+
const controls = /* @__PURE__ */ new Set();
|
|
5659
|
+
const tellPages = (message) => {
|
|
5660
|
+
for (const control of controls) control.postMessage(message);
|
|
5661
|
+
};
|
|
5662
|
+
const endpoint = new HandlerEndpoint(handler, {
|
|
5663
|
+
...options,
|
|
5664
|
+
requestRelink: () => tellPages({ type: "relink" }),
|
|
5665
|
+
keepAlive: () => tellPages({ type: "keepalive" })
|
|
5666
|
+
});
|
|
5667
|
+
const onMessage = (event) => {
|
|
5668
|
+
const { data, ports } = event;
|
|
5669
|
+
if (data?.type !== "webrun-http:worker-hello") return;
|
|
5670
|
+
const control = ports?.[0];
|
|
5671
|
+
if (!control) return;
|
|
5672
|
+
controls.add(control);
|
|
5673
|
+
control.onmessage = (message) => {
|
|
5674
|
+
const msg = message.data;
|
|
5675
|
+
if (msg?.type === "link") {
|
|
5676
|
+
const [down, ctl, up] = message.ports;
|
|
5677
|
+
if (down) endpoint.link(msg.key, {
|
|
5678
|
+
down,
|
|
5679
|
+
ctl,
|
|
5680
|
+
up
|
|
5681
|
+
}, msg.routerLock);
|
|
5682
|
+
} else if (msg?.type === "unlink") endpoint.unlink(msg.key);
|
|
5683
|
+
};
|
|
5684
|
+
held.then(() => control.postMessage({
|
|
5685
|
+
type: "ready",
|
|
5686
|
+
ownerLock: locksAvailable() ? ownerLock : void 0
|
|
5687
|
+
}));
|
|
5688
|
+
};
|
|
5689
|
+
scope.addEventListener("message", onMessage);
|
|
5690
|
+
const baseUrl = () => globalThis.location?.href;
|
|
5691
|
+
const connectWebSocket = (url, protocols = []) => {
|
|
5692
|
+
const httpUrl = new URL(`${url}`, baseUrl());
|
|
5693
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
5694
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
5695
|
+
return endpoint.connectWebSocket(`${httpUrl}`, protocols);
|
|
5696
|
+
};
|
|
5697
|
+
let WebSocketClass;
|
|
5698
|
+
return {
|
|
5699
|
+
fetch(input, init) {
|
|
5700
|
+
const request = input instanceof Request && init === void 0 ? input : new Request(input instanceof Request ? input : new URL(`${input}`, baseUrl()), init);
|
|
5701
|
+
return endpoint.fetch(request);
|
|
5702
|
+
},
|
|
5703
|
+
connectWebSocket,
|
|
5704
|
+
get WebSocket() {
|
|
5705
|
+
WebSocketClass ??= createWebSocketClass(connectWebSocket, options.webSocket);
|
|
5706
|
+
return WebSocketClass;
|
|
5707
|
+
},
|
|
5708
|
+
get linked() {
|
|
5709
|
+
return endpoint.linked;
|
|
5710
|
+
},
|
|
5711
|
+
async close() {
|
|
5712
|
+
scope.removeEventListener("message", onMessage);
|
|
5713
|
+
await endpoint.close();
|
|
5714
|
+
for (const control of controls) control.close();
|
|
5715
|
+
controls.clear();
|
|
5716
|
+
(await held)();
|
|
5717
|
+
}
|
|
2075
5718
|
};
|
|
2076
5719
|
}
|
|
2077
5720
|
//#endregion
|
|
2078
|
-
export { SwHttpAdapter, SwHttpDispatcher, SwPortDispatcher, SwPortHandler, startHttpDispatcher };
|
|
5721
|
+
export { DEFAULT_CLOSE_TIMEOUT_MS, DEFAULT_HEARTBEAT_MS, HANDLER_LOST_MESSAGE, HTTP_LINK_PROTOCOL, HandlerEndpoint, HandlerTable, LinkLostError, PortRendezvous, ROUTER_LOST_MESSAGE, ServerWebSocket, SwHttpAdapter, SwHttpDispatcher, SwPortDispatcher, SwPortHandler, WS_PORT_PROTOCOL_VERSION, WS_VERSION_HEADER, WsCloseEvent, connectHttpLink, connectWebSocketThroughServiceWorker, createWebSocketClass, holdLock, isWebSocketUpgrade, leastInflightRoute, locksAvailable, newLockName, newWebSocketUpgradeRequest, requestedProtocols, serveHttpInWorker, serveHttpLink, serveWebSocketUpgrade, serviceWorkerWebSocketClass, startHttpDispatcher, takePort, takeUpgrade, trackedLink, upgradeWebSocket, watchLock, withHeaders };
|