@statewalker/webrun-http-browser 0.6.4 → 0.7.0
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 +319 -65
- 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 +3907 -266
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.d.ts.map +1 -0
- package/dist/link/http-link.d.ts +58 -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 +1160 -55
- package/dist/relay-worker.js +1161 -55
- 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 +2 -1
- 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 +2075 -210
- package/dist/sw.d.ts +2 -0
- package/dist/sw.d.ts.map +1 -1
- package/dist/sw.js +3853 -480
- package/dist/worker.d.ts +10 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +3507 -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/errors.ts +3 -0
- package/src/link/http-link.ts +222 -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 +205 -29
- 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 +12 -30
- 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/index.js
CHANGED
|
@@ -884,7 +884,56 @@ function toChunks(size = DEFAULT_CHUNK_SIZE) {
|
|
|
884
884
|
};
|
|
885
885
|
}
|
|
886
886
|
//#endregion
|
|
887
|
+
//#region src/core/deadline.ts
|
|
888
|
+
/**
|
|
889
|
+
* Settles like `promise` if it settles before `deadline` (a `Date.now()`
|
|
890
|
+
* value). Otherwise calls `onTimeout`: an `Error` it returns rejects, any
|
|
891
|
+
* other value resolves. Internal; not re-exported.
|
|
892
|
+
*/
|
|
893
|
+
function withDeadline(deadline, promise, onTimeout) {
|
|
894
|
+
return new Promise((resolve, reject) => {
|
|
895
|
+
const timer = setTimeout(() => {
|
|
896
|
+
const outcome = onTimeout();
|
|
897
|
+
if (outcome instanceof Error) reject(outcome);
|
|
898
|
+
else resolve(outcome);
|
|
899
|
+
}, Math.max(0, deadline - Date.now()));
|
|
900
|
+
promise.then((value) => {
|
|
901
|
+
clearTimeout(timer);
|
|
902
|
+
resolve(value);
|
|
903
|
+
}, (error) => {
|
|
904
|
+
clearTimeout(timer);
|
|
905
|
+
reject(error);
|
|
906
|
+
});
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
//#endregion
|
|
887
910
|
//#region src/core/data-calls.ts
|
|
911
|
+
const TRANSFER = Symbol.for("webrun-http-browser:transfer");
|
|
912
|
+
/**
|
|
913
|
+
* A channel call's result that carries transferables, a `MessagePort` say:
|
|
914
|
+
* return `withTransfer({ port }, [port])` from a `handleChannelCalls` handler
|
|
915
|
+
* and `callChannel` resolves with `{ port }`.
|
|
916
|
+
*/
|
|
917
|
+
function withTransfer(value, transfer) {
|
|
918
|
+
return {
|
|
919
|
+
[TRANSFER]: true,
|
|
920
|
+
value,
|
|
921
|
+
transfer
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
function isTransferResult(value) {
|
|
925
|
+
return typeof value === "object" && value !== null && TRANSFER in value;
|
|
926
|
+
}
|
|
927
|
+
/** Splits a handler's result into the value to post and its transfer list. */
|
|
928
|
+
function unwrapTransfer(result) {
|
|
929
|
+
return isTransferResult(result) ? {
|
|
930
|
+
value: result.value,
|
|
931
|
+
transfer: result.transfer
|
|
932
|
+
} : {
|
|
933
|
+
value: result,
|
|
934
|
+
transfer: []
|
|
935
|
+
};
|
|
936
|
+
}
|
|
888
937
|
function callChannel(target, callType, params, ...transfers) {
|
|
889
938
|
return new Promise((resolve, reject) => {
|
|
890
939
|
const channel = new MessageChannel();
|
|
@@ -904,17 +953,27 @@ function handleChannelCalls(target, callType, handler) {
|
|
|
904
953
|
if (!event.data || event.data.type !== callType) return;
|
|
905
954
|
const [port, ...transfers] = event.ports ?? [];
|
|
906
955
|
const response = {};
|
|
956
|
+
let transfer = [];
|
|
907
957
|
try {
|
|
908
|
-
|
|
958
|
+
const result = await handler(event, event.data.params, ...transfers);
|
|
959
|
+
({value: response.result, transfer} = unwrapTransfer(result));
|
|
909
960
|
} catch (error) {
|
|
910
961
|
response.error = serializeError(error);
|
|
911
962
|
}
|
|
912
|
-
port?.postMessage(response);
|
|
963
|
+
port?.postMessage(response, transfer);
|
|
913
964
|
};
|
|
914
965
|
target.addEventListener("message", listener);
|
|
915
966
|
target.start?.();
|
|
916
967
|
return () => target.removeEventListener("message", listener);
|
|
917
968
|
}
|
|
969
|
+
/**
|
|
970
|
+
* `callChannel`, failing after `ms` instead of waiting for ever: a peer that
|
|
971
|
+
* died (a ServiceWorker stopped mid-call) or that does not know `callType` (an
|
|
972
|
+
* older version) never answers.
|
|
973
|
+
*/
|
|
974
|
+
function callChannelWithin(ms, target, callType, params, ...transfers) {
|
|
975
|
+
return withDeadline(Date.now() + ms, callChannel(target, callType, params, ...transfers), () => /* @__PURE__ */ new Error(`No answer to ${callType} within ${ms} ms`));
|
|
976
|
+
}
|
|
918
977
|
//#endregion
|
|
919
978
|
//#region src/core/data-channels.ts
|
|
920
979
|
const MESSAGE_TYPE_REQUEST = "REQUEST";
|
|
@@ -1125,29 +1184,6 @@ function newRegistry(onError = console.error) {
|
|
|
1125
1184
|
});
|
|
1126
1185
|
}
|
|
1127
1186
|
//#endregion
|
|
1128
|
-
//#region src/core/deadline.ts
|
|
1129
|
-
/**
|
|
1130
|
-
* Settles like `promise` if it settles before `deadline` (a `Date.now()`
|
|
1131
|
-
* value). Otherwise calls `onTimeout`: an `Error` it returns rejects, any
|
|
1132
|
-
* other value resolves. Internal; not re-exported.
|
|
1133
|
-
*/
|
|
1134
|
-
function withDeadline(deadline, promise, onTimeout) {
|
|
1135
|
-
return new Promise((resolve, reject) => {
|
|
1136
|
-
const timer = setTimeout(() => {
|
|
1137
|
-
const outcome = onTimeout();
|
|
1138
|
-
if (outcome instanceof Error) reject(outcome);
|
|
1139
|
-
else resolve(outcome);
|
|
1140
|
-
}, Math.max(0, deadline - Date.now()));
|
|
1141
|
-
promise.then((value) => {
|
|
1142
|
-
clearTimeout(timer);
|
|
1143
|
-
resolve(value);
|
|
1144
|
-
}, (error) => {
|
|
1145
|
-
clearTimeout(timer);
|
|
1146
|
-
reject(error);
|
|
1147
|
-
});
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
//#endregion
|
|
1151
1187
|
//#region src/core/service-worker-control.ts
|
|
1152
1188
|
/**
|
|
1153
1189
|
* How long, by default, the page waits for its ServiceWorker to activate and
|
|
@@ -2147,11 +2183,41 @@ async function throwIfPeerError(result, output) {
|
|
|
2147
2183
|
async function httpFetch(call, env, body, options = {}) {
|
|
2148
2184
|
const codec = options.codec ?? defaultCodec;
|
|
2149
2185
|
const output = call(codec.encodeRequest(env, body));
|
|
2150
|
-
const
|
|
2186
|
+
const decoded = await codec.decodeResponse(output, { method: env.method });
|
|
2187
|
+
const release = async () => {
|
|
2188
|
+
try {
|
|
2189
|
+
await output.return?.(void 0);
|
|
2190
|
+
} catch {}
|
|
2191
|
+
};
|
|
2192
|
+
const result = {
|
|
2193
|
+
envelope: decoded.envelope,
|
|
2194
|
+
body: releasingOnExit(decoded.body, release),
|
|
2195
|
+
release
|
|
2196
|
+
};
|
|
2151
2197
|
await throwIfPeerError(result, output);
|
|
2152
2198
|
return result;
|
|
2153
2199
|
}
|
|
2154
2200
|
/**
|
|
2201
|
+
* `body`, but leaving it before its end releases the call.
|
|
2202
|
+
*
|
|
2203
|
+
* The body the codec hands back is a generator of its own over a `ByteReader`,
|
|
2204
|
+
* and `.return()` on it never reaches the call's `output` (see
|
|
2205
|
+
* `throwIfPeerError` for why the codec must not do that itself). So a caller
|
|
2206
|
+
* that stopped reading — an aborted `fetch`, a cancelled response stream —
|
|
2207
|
+
* left the peer's producer parked forever, holding its handler open. Safe here
|
|
2208
|
+
* for the same reason it is safe in `throwIfPeerError`: `output` is this
|
|
2209
|
+
* call's own response-only generator, and the request was fully sent.
|
|
2210
|
+
*/
|
|
2211
|
+
async function* releasingOnExit(body, release) {
|
|
2212
|
+
let completed = false;
|
|
2213
|
+
try {
|
|
2214
|
+
yield* body;
|
|
2215
|
+
completed = true;
|
|
2216
|
+
} finally {
|
|
2217
|
+
if (!completed) await release();
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2155
2221
|
* Wrap an HTTP handler as a `Duplex` so it can be registered with any
|
|
2156
2222
|
* `webrun-streams-*` adapter's `serve`.
|
|
2157
2223
|
*/
|
|
@@ -2174,7 +2240,15 @@ function httpServe(handler, options = {}) {
|
|
|
2174
2240
|
yield* encodeErrorResponse(replyCodec, error, decoded.envelope.method);
|
|
2175
2241
|
return;
|
|
2176
2242
|
}
|
|
2177
|
-
|
|
2243
|
+
let completed = false;
|
|
2244
|
+
try {
|
|
2245
|
+
yield* replyCodec.encodeResponse(result.envelope, result.body, { method: decoded.envelope.method });
|
|
2246
|
+
completed = true;
|
|
2247
|
+
} finally {
|
|
2248
|
+
if (!completed) try {
|
|
2249
|
+
await result.release?.();
|
|
2250
|
+
} catch {}
|
|
2251
|
+
}
|
|
2178
2252
|
};
|
|
2179
2253
|
}
|
|
2180
2254
|
/**
|
|
@@ -2414,7 +2488,7 @@ function asyncIterableToReadable(iter) {
|
|
|
2414
2488
|
* abort terminates the underlying call.
|
|
2415
2489
|
*/
|
|
2416
2490
|
async function fetchOverDuplex(call, request, options = {}) {
|
|
2417
|
-
if (request.signal?.aborted) throw abortReason(request.signal);
|
|
2491
|
+
if (request.signal?.aborted) throw abortReason$1(request.signal);
|
|
2418
2492
|
const env = {
|
|
2419
2493
|
url: request.url,
|
|
2420
2494
|
method: request.method,
|
|
@@ -2426,14 +2500,14 @@ async function fetchOverDuplex(call, request, options = {}) {
|
|
|
2426
2500
|
const buffered = new Uint8Array(await request.arrayBuffer());
|
|
2427
2501
|
if (buffered.byteLength > 0) body = [buffered];
|
|
2428
2502
|
}
|
|
2429
|
-
const { envelope, body: respBody } = await httpFetch(call, env, body, options);
|
|
2503
|
+
const { envelope, body: respBody, release } = await httpFetch(call, env, body, options);
|
|
2430
2504
|
const responseInit = {
|
|
2431
2505
|
status: envelope.status,
|
|
2432
2506
|
statusText: envelope.statusText,
|
|
2433
2507
|
headers: forwardableHeaders(envelope.headers)
|
|
2434
2508
|
};
|
|
2435
2509
|
if (request.method === "HEAD" || request.method === "OPTIONS" || NULL_BODY_STATUSES.has(envelope.status)) {
|
|
2436
|
-
await
|
|
2510
|
+
await release?.();
|
|
2437
2511
|
return new Response(null, responseInit);
|
|
2438
2512
|
}
|
|
2439
2513
|
return new Response(asyncIterableToReadable(withAbort(respBody, request.signal)), responseInit);
|
|
@@ -2469,7 +2543,8 @@ function serveFetchOverDuplex(handler, options = {}) {
|
|
|
2469
2543
|
}
|
|
2470
2544
|
return {
|
|
2471
2545
|
envelope: respEnv,
|
|
2472
|
-
body: response.body ? readableToAsyncIterable(response.body) : void 0
|
|
2546
|
+
body: response.body ? readableToAsyncIterable(response.body) : void 0,
|
|
2547
|
+
release: () => response.body?.cancel()
|
|
2473
2548
|
};
|
|
2474
2549
|
}, options);
|
|
2475
2550
|
}
|
|
@@ -2479,11 +2554,11 @@ async function* withAbort(iter, signal) {
|
|
|
2479
2554
|
return;
|
|
2480
2555
|
}
|
|
2481
2556
|
for await (const chunk of iter) {
|
|
2482
|
-
if (signal.aborted) throw abortReason(signal);
|
|
2557
|
+
if (signal.aborted) throw abortReason$1(signal);
|
|
2483
2558
|
yield chunk;
|
|
2484
2559
|
}
|
|
2485
2560
|
}
|
|
2486
|
-
function abortReason(signal) {
|
|
2561
|
+
function abortReason$1(signal) {
|
|
2487
2562
|
const reason = signal.reason;
|
|
2488
2563
|
if (reason instanceof Error) return reason;
|
|
2489
2564
|
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
@@ -2653,150 +2728,2088 @@ async function sendHttpRequest(communicationPort, request) {
|
|
|
2653
2728
|
})(request);
|
|
2654
2729
|
}
|
|
2655
2730
|
//#endregion
|
|
2656
|
-
//#region
|
|
2731
|
+
//#region ../webrun-rpc/dist/index.js
|
|
2732
|
+
const closeSignals = /* @__PURE__ */ new WeakMap();
|
|
2657
2733
|
/**
|
|
2658
|
-
*
|
|
2659
|
-
*
|
|
2734
|
+
* Internal: register a port's close signal. Called once by `bindBytesToPort`.
|
|
2735
|
+
*
|
|
2736
|
+
* @internal
|
|
2660
2737
|
*/
|
|
2661
|
-
function
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2738
|
+
function setPortCloseSignal(port, signal) {
|
|
2739
|
+
closeSignals.set(port, signal);
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* Return the AbortSignal that fires when `port`'s transport closes, or
|
|
2743
|
+
* `undefined` if `port` is not transport-backed (e.g., a raw
|
|
2744
|
+
* `MessageChannel().port1`).
|
|
2745
|
+
*/
|
|
2746
|
+
function getPortCloseSignal(port) {
|
|
2747
|
+
return closeSignals.get(port);
|
|
2748
|
+
}
|
|
2749
|
+
/**
|
|
2750
|
+
* Pass as `timeout` to install no deadline at all. Used by the stream tier,
|
|
2751
|
+
* where the deadline belongs to the stream rather than to one chunk (spec D8):
|
|
2752
|
+
* a slow consumer is throttled, never failed.
|
|
2753
|
+
*/
|
|
2754
|
+
const NO_TIMEOUT = Number.POSITIVE_INFINITY;
|
|
2755
|
+
/**
|
|
2756
|
+
* Asynchronous request/response over any `MessageTarget`.
|
|
2757
|
+
*
|
|
2758
|
+
* Sends `params` to the peer listening with `listenPort`, waits up to
|
|
2759
|
+
* `timeout` ms for a matching reply, and either resolves with the result or
|
|
2760
|
+
* rejects with the deserialised error.
|
|
2761
|
+
*/
|
|
2762
|
+
function callPort(port, params, { timeout = 1e3, channelName = "", log = () => {}, newCallId = () => `call-${Date.now()}-${String(Math.random()).substring(2)}`, signal } = {}) {
|
|
2763
|
+
const callId = newCallId();
|
|
2764
|
+
log("[callPort]", {
|
|
2765
|
+
channelName,
|
|
2766
|
+
callId,
|
|
2767
|
+
params
|
|
2768
|
+
});
|
|
2769
|
+
const combinedSignal = combineSignals(signal, getPortCloseSignal(port));
|
|
2770
|
+
let timerId;
|
|
2771
|
+
let onMessage;
|
|
2772
|
+
let onAbort;
|
|
2773
|
+
const promise = new Promise((resolve, reject) => {
|
|
2774
|
+
if (combinedSignal?.aborted) {
|
|
2775
|
+
reject(abortReason(combinedSignal));
|
|
2776
|
+
return;
|
|
2777
|
+
}
|
|
2778
|
+
if (Number.isFinite(timeout) && timeout > 0) timerId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Call timeout. CallId: "${callId}".`)), timeout);
|
|
2779
|
+
onMessage = (event) => {
|
|
2780
|
+
const data = event.data;
|
|
2781
|
+
if (!data) return;
|
|
2782
|
+
if (data.channelName !== channelName) return;
|
|
2783
|
+
if (data.callId !== callId) return;
|
|
2784
|
+
if (data.type === "response:error") reject(deserializeError(data.error));
|
|
2785
|
+
else if (data.type === "response:result") resolve(data.result);
|
|
2786
|
+
};
|
|
2787
|
+
port.addEventListener("message", onMessage);
|
|
2788
|
+
if (combinedSignal) {
|
|
2789
|
+
onAbort = () => reject(abortReason(combinedSignal));
|
|
2790
|
+
combinedSignal.addEventListener("abort", onAbort, { once: true });
|
|
2791
|
+
}
|
|
2792
|
+
});
|
|
2793
|
+
promise.catch(() => {}).finally(() => {
|
|
2794
|
+
if (timerId !== void 0) clearTimeout(timerId);
|
|
2795
|
+
if (onMessage) port.removeEventListener("message", onMessage);
|
|
2796
|
+
if (onAbort && combinedSignal) combinedSignal.removeEventListener("abort", onAbort);
|
|
2797
|
+
});
|
|
2798
|
+
port.postMessage({
|
|
2799
|
+
type: "request",
|
|
2800
|
+
channelName,
|
|
2801
|
+
callId,
|
|
2802
|
+
params
|
|
2803
|
+
});
|
|
2804
|
+
return promise;
|
|
2805
|
+
}
|
|
2806
|
+
function abortReason(signal) {
|
|
2807
|
+
const reason = signal.reason;
|
|
2808
|
+
if (reason instanceof Error) return reason;
|
|
2809
|
+
const err = new Error(reason === void 0 ? "Aborted" : String(reason));
|
|
2810
|
+
err.name = "AbortError";
|
|
2811
|
+
return err;
|
|
2812
|
+
}
|
|
2813
|
+
function combineSignals(...signals) {
|
|
2814
|
+
const live = signals.filter((s) => s !== void 0);
|
|
2815
|
+
if (live.length === 0) return void 0;
|
|
2816
|
+
if (live.length === 1) return live[0];
|
|
2817
|
+
return AbortSignal.any(live);
|
|
2818
|
+
}
|
|
2819
|
+
/**
|
|
2820
|
+
* Installs `handler` as the server side of a `callPort` / `listenPort`
|
|
2821
|
+
* request/response pair on `port`.
|
|
2822
|
+
*
|
|
2823
|
+
* Returns a cleanup function that removes the listener.
|
|
2824
|
+
*/
|
|
2825
|
+
function listenPort(port, handler, { channelName = "", log = () => {} } = {}) {
|
|
2826
|
+
const onMessage = async (event) => {
|
|
2827
|
+
const data = event.data;
|
|
2828
|
+
if (!data || data.channelName !== channelName || data.type !== "request") return;
|
|
2829
|
+
const { callId, params } = data;
|
|
2830
|
+
log("[listenPort]", {
|
|
2831
|
+
channelName,
|
|
2832
|
+
callId,
|
|
2833
|
+
params
|
|
2834
|
+
});
|
|
2835
|
+
let result;
|
|
2836
|
+
let error;
|
|
2837
|
+
let type;
|
|
2838
|
+
try {
|
|
2839
|
+
result = await handler(params);
|
|
2840
|
+
type = "response:result";
|
|
2841
|
+
} catch (e) {
|
|
2842
|
+
error = serializeError(e);
|
|
2843
|
+
type = "response:error";
|
|
2844
|
+
}
|
|
2845
|
+
port.postMessage({
|
|
2846
|
+
callId,
|
|
2847
|
+
channelName,
|
|
2848
|
+
type,
|
|
2849
|
+
result,
|
|
2850
|
+
error
|
|
2851
|
+
});
|
|
2668
2852
|
};
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
}
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
else return empty;
|
|
2853
|
+
port.addEventListener("message", onMessage);
|
|
2854
|
+
return () => port.removeEventListener("message", onMessage);
|
|
2855
|
+
}
|
|
2856
|
+
/**
|
|
2857
|
+
* Wraps an async iterable so that an `AbortSignal` firing causes the wrapper
|
|
2858
|
+
* to return cleanly, forwarding `return()` to the underlying iterator so the
|
|
2859
|
+
* producer (e.g., a user-supplied generator) sees its own `finally` blocks
|
|
2860
|
+
* run immediately rather than waiting for the next yield.
|
|
2861
|
+
*/
|
|
2862
|
+
async function* throughAbort(input, signal) {
|
|
2863
|
+
const iter = input[Symbol.asyncIterator] ? input[Symbol.asyncIterator]() : input[Symbol.iterator]();
|
|
2864
|
+
const onAbort = () => {
|
|
2865
|
+
iter.return?.(void 0);
|
|
2866
|
+
};
|
|
2867
|
+
if (signal.aborted) {
|
|
2868
|
+
iter.return?.(void 0);
|
|
2869
|
+
return;
|
|
2687
2870
|
}
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
} else {
|
|
2699
|
-
if (!pathPart.startsWith(`/${separator}`)) return empty;
|
|
2700
|
-
keyStart = separator.length + 1;
|
|
2871
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2872
|
+
try {
|
|
2873
|
+
while (true) {
|
|
2874
|
+
const r = await iter.next();
|
|
2875
|
+
if (r.done) return;
|
|
2876
|
+
if (signal.aborted) return;
|
|
2877
|
+
yield r.value;
|
|
2878
|
+
}
|
|
2879
|
+
} finally {
|
|
2880
|
+
signal.removeEventListener("abort", onAbort);
|
|
2701
2881
|
}
|
|
2702
|
-
const rest = pathPart.slice(keyStart);
|
|
2703
|
-
const slash = rest.indexOf("/");
|
|
2704
|
-
const key = slash < 0 ? rest : rest.slice(0, slash);
|
|
2705
|
-
if (key === "") return empty;
|
|
2706
|
-
return {
|
|
2707
|
-
url: str,
|
|
2708
|
-
key,
|
|
2709
|
-
baseUrl: `${prefix === "" ? rooted ? "/" : "" : `${prefix}/`}${separator}${key}${slash < 0 ? "" : "/"}`,
|
|
2710
|
-
path: slash < 0 ? "" : rest.slice(slash + 1)
|
|
2711
|
-
};
|
|
2712
2882
|
}
|
|
2713
|
-
//#endregion
|
|
2714
|
-
//#region src/relay/index.ts
|
|
2715
2883
|
/**
|
|
2716
|
-
* The
|
|
2717
|
-
*
|
|
2718
|
-
*
|
|
2719
|
-
*
|
|
2720
|
-
*
|
|
2721
|
-
*
|
|
2722
|
-
* that transform.
|
|
2884
|
+
* The `type` of the out-of-band notice a side posts when it abandons a stream.
|
|
2885
|
+
*
|
|
2886
|
+
* Layer 1's `close` is not observable to layer 2 — a closed virtual port drops
|
|
2887
|
+
* its listeners silently and is indistinguishable from a working port nobody
|
|
2888
|
+
* is answering — so the peer would otherwise wait forever. Exported because
|
|
2889
|
+
* tests and adapters assert on it.
|
|
2723
2890
|
*/
|
|
2724
|
-
const
|
|
2891
|
+
const STREAM_ABORT = "webrun-rpc:stream-abort";
|
|
2892
|
+
/** Caller's input travels on this channel; the handler listens on it. */
|
|
2893
|
+
const CHANNEL_IN = "in";
|
|
2894
|
+
/** The handler's output travels on this channel; the caller listens on it. */
|
|
2895
|
+
const CHANNEL_OUT = "out";
|
|
2725
2896
|
/**
|
|
2726
|
-
*
|
|
2727
|
-
*
|
|
2728
|
-
*
|
|
2729
|
-
*
|
|
2897
|
+
* One port in, one `Duplex` out (spec D9).
|
|
2898
|
+
*
|
|
2899
|
+
* The returned `Duplex` runs a single stream on `port`: the caller's `input`
|
|
2900
|
+
* is sent chunk by chunk with `callPort`, and the handler's output arrives the
|
|
2901
|
+
* same way on the other channel. Within each direction the next chunk is never
|
|
2902
|
+
* sent until the previous one has been delivered *and* pulled past by the
|
|
2903
|
+
* consumer (spec D11) — the reply to a chunk call *is* the confirmation, and
|
|
2904
|
+
* `listenPort` withholds it until then.
|
|
2905
|
+
*
|
|
2906
|
+
* A stream port carries exactly one invocation. To make several calls, open
|
|
2907
|
+
* several ports: `mux.openPort({ kind: "stream" })` per call.
|
|
2730
2908
|
*/
|
|
2731
|
-
function
|
|
2732
|
-
|
|
2733
|
-
channel.port1.onmessage = (event) => {
|
|
2734
|
-
(navigator.serviceWorker.controller ?? registration?.active)?.postMessage(event.data, [...event.ports]);
|
|
2735
|
-
};
|
|
2736
|
-
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
2737
|
-
channel.port1.postMessage(event.data, [...event.ports]);
|
|
2738
|
-
});
|
|
2739
|
-
return channel.port2;
|
|
2909
|
+
function duplexOverPort(port, options = {}) {
|
|
2910
|
+
return (input) => runCallerSide(port, input, options);
|
|
2740
2911
|
}
|
|
2741
2912
|
/**
|
|
2742
|
-
*
|
|
2743
|
-
*
|
|
2744
|
-
* page is not controlled. Messaging works either way, which is all the relay
|
|
2745
|
-
* needs; nothing here waits for control, because an uncontrolled page (hard
|
|
2746
|
-
* reload; Firefox) may never get it. Rejects with a
|
|
2747
|
-
* `ServiceWorkerControlError` if activation takes longer than `timeout`.
|
|
2913
|
+
* Installs `handler` as the serving side of one stream on `port`. Returns an
|
|
2914
|
+
* idempotent teardown that abandons the stream and notifies the peer.
|
|
2748
2915
|
*/
|
|
2749
|
-
|
|
2750
|
-
|
|
2916
|
+
function serveDuplexOverPort(port, handler, options = {}) {
|
|
2917
|
+
const controller = new AbortController();
|
|
2918
|
+
const notice = installAbortNotice(port, controller);
|
|
2919
|
+
abortOnPortClose(port, controller);
|
|
2920
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
2921
|
+
const inbound = receiveChunks(port, CHANNEL_IN, controller, clock.touch);
|
|
2922
|
+
let output;
|
|
2923
|
+
try {
|
|
2924
|
+
output = handler(inbound.stream);
|
|
2925
|
+
} catch (err) {
|
|
2926
|
+
const pump = sendChunks(port, CHANNEL_OUT, failing(err), options, controller.signal, clock.touch);
|
|
2927
|
+
pump.catch(() => {});
|
|
2928
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
2929
|
+
return teardownOnce(controller, notice, clock, inbound, void 0);
|
|
2930
|
+
}
|
|
2931
|
+
const pump = sendChunks(port, CHANNEL_OUT, output, options, controller.signal, clock.touch);
|
|
2932
|
+
pump.catch(() => {});
|
|
2933
|
+
disarmClockWhenBothSidesSettle(clock, pump, inbound.ended);
|
|
2934
|
+
return teardownOnce(controller, notice, clock, inbound, output);
|
|
2751
2935
|
}
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2936
|
+
/**
|
|
2937
|
+
* A stream that completes normally has nobody left to call the returned
|
|
2938
|
+
* teardown — the caller only knows the stream ended, not that it must also
|
|
2939
|
+
* dispose the serve-side handle. Without this, the last `touch()`'s timer
|
|
2940
|
+
* stays armed for up to `timeout` ms after real completion, doing nothing
|
|
2941
|
+
* but holding the event loop open.
|
|
2942
|
+
*
|
|
2943
|
+
* Only disarms once BOTH `pump` (our output) and `inboundEnded` (the peer's
|
|
2944
|
+
* declared end of input, or an abort) have settled. Disarming on `pump`
|
|
2945
|
+
* alone is not safe: under half-close the handler can finish producing
|
|
2946
|
+
* output while the caller is still sending input, and a clock stopped then
|
|
2947
|
+
* would leave that still-open half with no deadline at all — worse than the
|
|
2948
|
+
* leak this fixes.
|
|
2949
|
+
*/
|
|
2950
|
+
function disarmClockWhenBothSidesSettle(clock, pump, inboundEnded) {
|
|
2951
|
+
Promise.allSettled([pump, inboundEnded]).then(() => {
|
|
2952
|
+
clock.stop();
|
|
2756
2953
|
});
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2954
|
+
}
|
|
2955
|
+
async function* failing(err) {
|
|
2956
|
+
throw err;
|
|
2957
|
+
}
|
|
2958
|
+
function teardownOnce(controller, notice, clock, inbound, output) {
|
|
2959
|
+
let torn = false;
|
|
2960
|
+
return () => {
|
|
2961
|
+
if (torn) return;
|
|
2962
|
+
torn = true;
|
|
2963
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: stream torn down"));
|
|
2964
|
+
notice.post();
|
|
2965
|
+
notice.stop();
|
|
2966
|
+
clock.stop();
|
|
2967
|
+
inbound.stop();
|
|
2968
|
+
output?.return(void 0).catch(() => {});
|
|
2761
2969
|
};
|
|
2762
2970
|
}
|
|
2971
|
+
function runCallerSide(port, input, options) {
|
|
2972
|
+
const controller = new AbortController();
|
|
2973
|
+
const notice = installAbortNotice(port, controller);
|
|
2974
|
+
abortOnPortClose(port, controller);
|
|
2975
|
+
const clock = installStreamTimeout(controller, options.timeout);
|
|
2976
|
+
const inbound = receiveChunks(port, CHANNEL_OUT, controller, clock.touch);
|
|
2977
|
+
const pump = sendChunks(port, CHANNEL_IN, input, options, controller.signal, clock.touch);
|
|
2978
|
+
pump.catch(() => {});
|
|
2979
|
+
return (async function* () {
|
|
2980
|
+
try {
|
|
2981
|
+
yield* inbound.stream;
|
|
2982
|
+
} finally {
|
|
2983
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the caller abandoned the stream"));
|
|
2984
|
+
notice.post();
|
|
2985
|
+
notice.stop();
|
|
2986
|
+
clock.stop();
|
|
2987
|
+
inbound.stop();
|
|
2988
|
+
await pump.catch(() => {});
|
|
2989
|
+
try {
|
|
2990
|
+
await port.close?.();
|
|
2991
|
+
} catch {}
|
|
2992
|
+
}
|
|
2993
|
+
})();
|
|
2994
|
+
}
|
|
2763
2995
|
/**
|
|
2764
|
-
*
|
|
2765
|
-
*
|
|
2996
|
+
* Listens for the peer's abort notice, and can post our own. The notice is a
|
|
2997
|
+
* plain message with no `channelName` and a `type` that is not `"request"`,
|
|
2998
|
+
* so neither `callPort` nor `listenPort` reacts to it, and it carries no
|
|
2999
|
+
* numeric `id`, so `structuredCodec` never mistakes it for a layer 1 envelope.
|
|
2766
3000
|
*/
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
3001
|
+
function installAbortNotice(port, controller) {
|
|
3002
|
+
const onMessage = (event) => {
|
|
3003
|
+
const data = event.data;
|
|
3004
|
+
if (!data || data.type !== "webrun-rpc:stream-abort") return;
|
|
3005
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error("webrun-rpc: the peer abandoned the stream"));
|
|
3006
|
+
};
|
|
3007
|
+
port.addEventListener("message", onMessage);
|
|
3008
|
+
let posted = false;
|
|
3009
|
+
return {
|
|
3010
|
+
post() {
|
|
3011
|
+
if (posted) return;
|
|
3012
|
+
posted = true;
|
|
3013
|
+
try {
|
|
3014
|
+
port.postMessage({ type: STREAM_ABORT });
|
|
3015
|
+
} catch {}
|
|
3016
|
+
},
|
|
3017
|
+
stop() {
|
|
3018
|
+
port.removeEventListener("message", onMessage);
|
|
2775
3019
|
}
|
|
2776
|
-
}
|
|
3020
|
+
};
|
|
2777
3021
|
}
|
|
2778
3022
|
/**
|
|
2779
|
-
*
|
|
2780
|
-
*
|
|
3023
|
+
* Aborts the stream when its port closes underneath it — the multiplexer was
|
|
3024
|
+
* closed, or the peer closed the port — for ports that report it (see
|
|
3025
|
+
* `getPortCloseSignal`). Without this a stream waiting for the peer's next
|
|
3026
|
+
* chunk would wait forever on a port that can no longer deliver one: the
|
|
3027
|
+
* outbound half's `callPort` already fails on the close signal, but nothing
|
|
3028
|
+
* failed the inbound half.
|
|
2781
3029
|
*/
|
|
2782
|
-
|
|
2783
|
-
const
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
3030
|
+
function abortOnPortClose(port, controller) {
|
|
3031
|
+
const closed = getPortCloseSignal(port);
|
|
3032
|
+
if (!closed) return;
|
|
3033
|
+
const onClose = () => {
|
|
3034
|
+
if (!controller.signal.aborted) controller.abort(closed.reason);
|
|
3035
|
+
};
|
|
3036
|
+
if (closed.aborted) {
|
|
3037
|
+
onClose();
|
|
3038
|
+
return;
|
|
3039
|
+
}
|
|
3040
|
+
closed.addEventListener("abort", onClose, { once: true });
|
|
3041
|
+
controller.signal.addEventListener("abort", () => closed.removeEventListener("abort", onClose), { once: true });
|
|
2789
3042
|
}
|
|
2790
3043
|
/**
|
|
2791
|
-
*
|
|
2792
|
-
*
|
|
2793
|
-
*
|
|
2794
|
-
* call the parent makes on that port is answered with the error, so the
|
|
2795
|
-
* parent's `initHttpService` / `callHttpService` reject instead of waiting.
|
|
3044
|
+
* The per-stream inactivity timeout (spec D8). Reset by any chunk in either
|
|
3045
|
+
* direction; elapsing aborts the stream. Unset, zero or non-finite installs no
|
|
3046
|
+
* timer at all, which is the default: a slow consumer is throttled, not failed.
|
|
2796
3047
|
*/
|
|
2797
|
-
function
|
|
2798
|
-
|
|
2799
|
-
|
|
3048
|
+
function installStreamTimeout(controller, timeout) {
|
|
3049
|
+
if (timeout === void 0 || !Number.isFinite(timeout) || timeout <= 0) return {
|
|
3050
|
+
touch() {},
|
|
3051
|
+
stop() {}
|
|
3052
|
+
};
|
|
3053
|
+
let timer;
|
|
3054
|
+
let stopped = false;
|
|
3055
|
+
const arm = () => {
|
|
3056
|
+
timer = setTimeout(() => {
|
|
3057
|
+
if (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(`webrun-rpc: stream idle for ${timeout} ms`));
|
|
3058
|
+
}, timeout);
|
|
3059
|
+
};
|
|
3060
|
+
arm();
|
|
3061
|
+
return {
|
|
3062
|
+
touch() {
|
|
3063
|
+
if (stopped) return;
|
|
3064
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3065
|
+
arm();
|
|
3066
|
+
},
|
|
3067
|
+
stop() {
|
|
3068
|
+
stopped = true;
|
|
3069
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3070
|
+
timer = void 0;
|
|
3071
|
+
}
|
|
3072
|
+
};
|
|
3073
|
+
}
|
|
3074
|
+
/**
|
|
3075
|
+
* The receiving half of one direction.
|
|
3076
|
+
*
|
|
3077
|
+
* The `listenPort` listener is installed **eagerly**, not lazily inside
|
|
3078
|
+
* `recieveIterator`'s installer, because a handler that never drains its input
|
|
3079
|
+
* would otherwise leave the peer's chunk calls with nobody to answer them. If
|
|
3080
|
+
* the local consumer has not started iterating, an inbound chunk waits for it —
|
|
3081
|
+
* which is the correct backpressure, and different from having no listener.
|
|
3082
|
+
*/
|
|
3083
|
+
function receiveChunks(port, channelName, controller, touch) {
|
|
3084
|
+
let deliver;
|
|
3085
|
+
const waiting = [];
|
|
3086
|
+
let finished = false;
|
|
3087
|
+
let outstanding = false;
|
|
3088
|
+
let poison;
|
|
3089
|
+
let resolveEnded = () => {};
|
|
3090
|
+
const ended = new Promise((resolve) => {
|
|
3091
|
+
resolveEnded = resolve;
|
|
3092
|
+
});
|
|
3093
|
+
let aborted = false;
|
|
3094
|
+
let abortReason;
|
|
3095
|
+
const ready = () => deliver || finished ? Promise.resolve() : new Promise((r) => waiting.push(r));
|
|
3096
|
+
const wake = () => {
|
|
3097
|
+
for (const r of waiting.splice(0)) r();
|
|
3098
|
+
};
|
|
3099
|
+
const off = listenPort(port, async ({ done, value, error }) => {
|
|
3100
|
+
touch();
|
|
3101
|
+
if (poison) throw poison;
|
|
3102
|
+
if (outstanding) {
|
|
3103
|
+
poison = /* @__PURE__ */ new Error("webrun-rpc: peer sent a second unconfirmed chunk; the stream port is closed");
|
|
3104
|
+
controller.abort(poison);
|
|
3105
|
+
setTimeout(() => {
|
|
3106
|
+
try {
|
|
3107
|
+
port.close?.();
|
|
3108
|
+
} catch {}
|
|
3109
|
+
}, 0);
|
|
3110
|
+
throw poison;
|
|
3111
|
+
}
|
|
3112
|
+
outstanding = true;
|
|
3113
|
+
try {
|
|
3114
|
+
await ready();
|
|
3115
|
+
if (finished) throw poison ?? /* @__PURE__ */ new Error("webrun-rpc: the stream is closed");
|
|
3116
|
+
await deliver?.({
|
|
3117
|
+
done,
|
|
3118
|
+
value,
|
|
3119
|
+
error: error ? deserializeError(error) : void 0
|
|
3120
|
+
});
|
|
3121
|
+
} finally {
|
|
3122
|
+
outstanding = false;
|
|
3123
|
+
}
|
|
3124
|
+
if (done) resolveEnded();
|
|
3125
|
+
}, { channelName });
|
|
3126
|
+
const detach = () => {
|
|
3127
|
+
finished = true;
|
|
3128
|
+
wake();
|
|
3129
|
+
off();
|
|
3130
|
+
controller.signal.removeEventListener("abort", onAbort);
|
|
3131
|
+
resolveEnded();
|
|
3132
|
+
};
|
|
3133
|
+
const onAbort = () => {
|
|
3134
|
+
aborted = true;
|
|
3135
|
+
abortReason = controller.signal.reason;
|
|
3136
|
+
finished = true;
|
|
3137
|
+
wake();
|
|
3138
|
+
deliver?.({
|
|
3139
|
+
done: true,
|
|
3140
|
+
error: abortReason
|
|
3141
|
+
});
|
|
3142
|
+
resolveEnded();
|
|
3143
|
+
};
|
|
3144
|
+
controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
3145
|
+
return {
|
|
3146
|
+
stream: recieveIterator((d) => {
|
|
3147
|
+
if (aborted) {
|
|
3148
|
+
d({
|
|
3149
|
+
done: true,
|
|
3150
|
+
error: abortReason
|
|
3151
|
+
});
|
|
3152
|
+
return detach;
|
|
3153
|
+
}
|
|
3154
|
+
deliver = d;
|
|
3155
|
+
wake();
|
|
3156
|
+
return detach;
|
|
3157
|
+
}),
|
|
3158
|
+
stop: detach,
|
|
3159
|
+
ended
|
|
3160
|
+
};
|
|
3161
|
+
}
|
|
3162
|
+
/**
|
|
3163
|
+
* The sending half of one direction: one `callPort` per chunk, one call
|
|
3164
|
+
* outstanding at a time (spec D11/D12), with no per-chunk deadline (spec D8).
|
|
3165
|
+
*/
|
|
3166
|
+
async function sendChunks(port, channelName, output, { maxMessageSize, log }, signal, touch) {
|
|
3167
|
+
const stream = throughAbort(maxMessageSize ? toChunks(maxMessageSize)(output) : output, signal);
|
|
3168
|
+
try {
|
|
3169
|
+
await sendIterator(async ({ done, value, error }) => {
|
|
3170
|
+
if (signal.aborted) return;
|
|
3171
|
+
const chunk = {
|
|
3172
|
+
done,
|
|
3173
|
+
value,
|
|
3174
|
+
error: error === void 0 ? void 0 : serializeError(error)
|
|
3175
|
+
};
|
|
3176
|
+
log?.("[duplexOverPort] send", {
|
|
3177
|
+
channelName,
|
|
3178
|
+
done,
|
|
3179
|
+
size: value?.byteLength
|
|
3180
|
+
});
|
|
3181
|
+
await callPort(port, chunk, {
|
|
3182
|
+
channelName,
|
|
3183
|
+
timeout: NO_TIMEOUT,
|
|
3184
|
+
signal
|
|
3185
|
+
});
|
|
3186
|
+
touch();
|
|
3187
|
+
}, stream);
|
|
3188
|
+
} catch (err) {
|
|
3189
|
+
if (signal.aborted) return;
|
|
3190
|
+
throw err;
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
/**
|
|
3194
|
+
* One virtual port.
|
|
3195
|
+
*
|
|
3196
|
+
* `deliver` and `markClosed` are deliberately not on `port`: the consumer holds
|
|
3197
|
+
* only a `MessageTarget`, so it cannot forge inbound traffic or close the port
|
|
3198
|
+
* out from under the multiplexer's bookkeeping.
|
|
3199
|
+
*/
|
|
3200
|
+
function newVirtualPort(send, requestClose) {
|
|
3201
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
3202
|
+
let closed = false;
|
|
3203
|
+
const closing = new AbortController();
|
|
3204
|
+
const abort = (reason) => {
|
|
3205
|
+
if (closing.signal.aborted) return;
|
|
3206
|
+
closing.abort(reason ?? /* @__PURE__ */ new Error("webrun-rpc: the port was closed"));
|
|
3207
|
+
};
|
|
3208
|
+
const port = {
|
|
3209
|
+
addEventListener(_type, listener) {
|
|
3210
|
+
listeners.add(listener);
|
|
3211
|
+
},
|
|
3212
|
+
removeEventListener(_type, listener) {
|
|
3213
|
+
listeners.delete(listener);
|
|
3214
|
+
},
|
|
3215
|
+
postMessage(message, transfer) {
|
|
3216
|
+
if (closed) return;
|
|
3217
|
+
send(message, transfer);
|
|
3218
|
+
},
|
|
3219
|
+
close() {
|
|
3220
|
+
if (closed) return;
|
|
3221
|
+
closed = true;
|
|
3222
|
+
const notify = requestClose;
|
|
3223
|
+
listeners.clear();
|
|
3224
|
+
notify();
|
|
3225
|
+
abort();
|
|
3226
|
+
}
|
|
3227
|
+
};
|
|
3228
|
+
setPortCloseSignal(port, closing.signal);
|
|
3229
|
+
return {
|
|
3230
|
+
port,
|
|
3231
|
+
deliver(payload) {
|
|
3232
|
+
if (closed) return;
|
|
3233
|
+
const event = new MessageEvent("message", { data: payload });
|
|
3234
|
+
for (const listener of [...listeners]) try {
|
|
3235
|
+
listener(event);
|
|
3236
|
+
} catch {}
|
|
3237
|
+
},
|
|
3238
|
+
markClosed(reason) {
|
|
3239
|
+
closed = true;
|
|
3240
|
+
listeners.clear();
|
|
3241
|
+
abort(reason);
|
|
3242
|
+
},
|
|
3243
|
+
isClosed() {
|
|
3244
|
+
return closed;
|
|
3245
|
+
}
|
|
3246
|
+
};
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* The message of the error that fails the calls still in flight on a
|
|
3250
|
+
* multiplexer when it is closed (`PortMux.close()`).
|
|
3251
|
+
*/
|
|
3252
|
+
const MUX_CLOSED_MESSAGE = "webrun-rpc: the multiplexer was closed";
|
|
3253
|
+
/** Ceiling on concurrently open virtual ports. Bounds the id table only. */
|
|
3254
|
+
const DEFAULT_MAX_PORTS = 1024;
|
|
3255
|
+
/**
|
|
3256
|
+
* The default `PortMux`: emulates multiplexing over a single port.
|
|
3257
|
+
*
|
|
3258
|
+
* A transport that already multiplexes natively supplies its own `PortMux`
|
|
3259
|
+
* instead — this implementation is for transports that offer one pipe.
|
|
3260
|
+
*/
|
|
3261
|
+
function multiplexPort(port, options) {
|
|
3262
|
+
const { codec, onPort, side = "initiator", maxPorts = DEFAULT_MAX_PORTS, maxMessageSize } = options;
|
|
3263
|
+
const open = /* @__PURE__ */ new Map();
|
|
3264
|
+
let nextId = side === "initiator" ? 0 : 1;
|
|
3265
|
+
let muxClosed = false;
|
|
3266
|
+
const post = (envelope, transfer) => {
|
|
3267
|
+
if (muxClosed) return;
|
|
3268
|
+
try {
|
|
3269
|
+
codec.post(port, envelope, transfer);
|
|
3270
|
+
} catch {}
|
|
3271
|
+
};
|
|
3272
|
+
const attach = (id) => {
|
|
3273
|
+
let self;
|
|
3274
|
+
self = newVirtualPort((payload, transfer) => post({
|
|
3275
|
+
type: "message",
|
|
3276
|
+
id,
|
|
3277
|
+
payload
|
|
3278
|
+
}, transfer), (reason) => {
|
|
3279
|
+
post({
|
|
3280
|
+
type: "close",
|
|
3281
|
+
id,
|
|
3282
|
+
reason
|
|
3283
|
+
});
|
|
3284
|
+
open.delete(id);
|
|
3285
|
+
self.markClosed();
|
|
3286
|
+
});
|
|
3287
|
+
open.set(id, self);
|
|
3288
|
+
return self;
|
|
3289
|
+
};
|
|
3290
|
+
const handleEnvelope = (envelope) => {
|
|
3291
|
+
if (muxClosed) return;
|
|
3292
|
+
if (envelope.type === "open") {
|
|
3293
|
+
if (open.has(envelope.id)) return;
|
|
3294
|
+
if (open.size >= maxPorts) {
|
|
3295
|
+
post({
|
|
3296
|
+
type: "close",
|
|
3297
|
+
id: envelope.id,
|
|
3298
|
+
reason: "max-ports"
|
|
3299
|
+
});
|
|
3300
|
+
return;
|
|
3301
|
+
}
|
|
3302
|
+
const handle = attach(envelope.id);
|
|
3303
|
+
let accepted = false;
|
|
3304
|
+
if (onPort) try {
|
|
3305
|
+
accepted = onPort(handle.port, envelope.meta) !== false;
|
|
3306
|
+
} catch {
|
|
3307
|
+
accepted = false;
|
|
3308
|
+
}
|
|
3309
|
+
if (!accepted) {
|
|
3310
|
+
open.delete(envelope.id);
|
|
3311
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the port was rejected"));
|
|
3312
|
+
post({
|
|
3313
|
+
type: "close",
|
|
3314
|
+
id: envelope.id,
|
|
3315
|
+
reason: "rejected"
|
|
3316
|
+
});
|
|
3317
|
+
}
|
|
3318
|
+
return;
|
|
3319
|
+
}
|
|
3320
|
+
const handle = open.get(envelope.id);
|
|
3321
|
+
if (envelope.type === "message") {
|
|
3322
|
+
if (!handle) return;
|
|
3323
|
+
handle.deliver(envelope.payload);
|
|
3324
|
+
return;
|
|
3325
|
+
}
|
|
3326
|
+
if (!handle) return;
|
|
3327
|
+
open.delete(envelope.id);
|
|
3328
|
+
handle.markClosed(/* @__PURE__ */ new Error("webrun-rpc: the peer closed the port"));
|
|
3329
|
+
};
|
|
3330
|
+
const listener = (event) => {
|
|
3331
|
+
const envelope = codec.read(event);
|
|
3332
|
+
if (envelope) handleEnvelope(envelope);
|
|
3333
|
+
};
|
|
3334
|
+
port.addEventListener("message", listener);
|
|
3335
|
+
port.start?.();
|
|
3336
|
+
return {
|
|
3337
|
+
maxMessageSize,
|
|
3338
|
+
async openPort(meta) {
|
|
3339
|
+
if (muxClosed) throw new Error("webrun-rpc: the multiplexer is closed");
|
|
3340
|
+
if (open.size >= maxPorts) throw new RangeError(`webrun-rpc: maxPorts (${maxPorts}) reached`);
|
|
3341
|
+
while (open.has(nextId)) nextId += 2;
|
|
3342
|
+
const id = nextId;
|
|
3343
|
+
nextId += 2;
|
|
3344
|
+
const handle = attach(id);
|
|
3345
|
+
post({
|
|
3346
|
+
type: "open",
|
|
3347
|
+
id,
|
|
3348
|
+
meta
|
|
3349
|
+
});
|
|
3350
|
+
return handle.port;
|
|
3351
|
+
},
|
|
3352
|
+
async close() {
|
|
3353
|
+
if (muxClosed) return;
|
|
3354
|
+
for (const [id, handle] of [...open]) {
|
|
3355
|
+
post({
|
|
3356
|
+
type: "close",
|
|
3357
|
+
id
|
|
3358
|
+
});
|
|
3359
|
+
open.delete(id);
|
|
3360
|
+
handle.markClosed(/* @__PURE__ */ new Error(MUX_CLOSED_MESSAGE));
|
|
3361
|
+
}
|
|
3362
|
+
muxClosed = true;
|
|
3363
|
+
port.removeEventListener("message", listener);
|
|
3364
|
+
await port.close?.();
|
|
3365
|
+
}
|
|
3366
|
+
};
|
|
3367
|
+
}
|
|
3368
|
+
/**
|
|
3369
|
+
* Announced with every port this pair opens. Layer 1 never reads `meta` — it is
|
|
3370
|
+
* here so a peer running something else over the same multiplexer can tell a
|
|
3371
|
+
* stream port from whatever else it hands out, and so a packet capture says
|
|
3372
|
+
* what the port is for.
|
|
3373
|
+
*/
|
|
3374
|
+
const STREAM_META = { kind: "stream" };
|
|
3375
|
+
/**
|
|
3376
|
+
* One port source in, one caller `Duplex` out.
|
|
3377
|
+
*
|
|
3378
|
+
* A call is a port: the mux allocates one, `duplexOverPort` runs the single
|
|
3379
|
+
* invocation on it, and closing the stream closes the port. No stream ids, no
|
|
3380
|
+
* framing and no credit accounting live here — the mux owns the first, and
|
|
3381
|
+
* `duplexOverPort` owns the one-chunk window that makes memory bounded.
|
|
3382
|
+
*/
|
|
3383
|
+
const connect = async ({ mux: factory, timeout }) => {
|
|
3384
|
+
const mux = await factory();
|
|
3385
|
+
const streamOptions = {
|
|
3386
|
+
maxMessageSize: mux.maxMessageSize,
|
|
3387
|
+
timeout
|
|
3388
|
+
};
|
|
3389
|
+
const call = (input) => (async function* () {
|
|
3390
|
+
yield* duplexOverPort(await mux.openPort(STREAM_META), streamOptions)(input);
|
|
3391
|
+
})();
|
|
3392
|
+
return {
|
|
3393
|
+
call,
|
|
3394
|
+
async close() {
|
|
3395
|
+
await mux.close();
|
|
3396
|
+
}
|
|
3397
|
+
};
|
|
3398
|
+
};
|
|
3399
|
+
/**
|
|
3400
|
+
* One port source in, `handler` serving every call that arrives on it.
|
|
3401
|
+
*
|
|
3402
|
+
* Each inbound port is one invocation, so the factory's `onPort` is the accept
|
|
3403
|
+
* loop: it installs `handler` on the new port and nothing else. The returned
|
|
3404
|
+
* teardown abandons the streams still running *before* dropping the mux, so
|
|
3405
|
+
* the peer's callers reject with "the peer abandoned the stream" instead of
|
|
3406
|
+
* parking forever on a port that has silently gone inert — layer 1's close is
|
|
3407
|
+
* not observable to layer 2, which is why the notice has to be posted
|
|
3408
|
+
* deliberately.
|
|
3409
|
+
*/
|
|
3410
|
+
const serve = async ({ mux: factory, timeout }, handler) => {
|
|
3411
|
+
const live = /* @__PURE__ */ new Set();
|
|
3412
|
+
let streamOptions = { timeout };
|
|
3413
|
+
const mux = await factory((port) => {
|
|
3414
|
+
let off;
|
|
3415
|
+
let finished = false;
|
|
3416
|
+
const tracked = (input) => (async function* () {
|
|
3417
|
+
try {
|
|
3418
|
+
yield* handler(input);
|
|
3419
|
+
} finally {
|
|
3420
|
+
finished = true;
|
|
3421
|
+
if (off) live.delete(off);
|
|
3422
|
+
}
|
|
3423
|
+
})();
|
|
3424
|
+
off = serveDuplexOverPort(port, tracked, streamOptions);
|
|
3425
|
+
if (!finished) live.add(off);
|
|
3426
|
+
});
|
|
3427
|
+
streamOptions = {
|
|
3428
|
+
maxMessageSize: mux.maxMessageSize,
|
|
3429
|
+
timeout
|
|
3430
|
+
};
|
|
3431
|
+
let torn = false;
|
|
3432
|
+
return async () => {
|
|
3433
|
+
if (torn) return;
|
|
3434
|
+
torn = true;
|
|
3435
|
+
for (const off of [...live]) {
|
|
3436
|
+
live.delete(off);
|
|
3437
|
+
try {
|
|
3438
|
+
off();
|
|
3439
|
+
} catch {}
|
|
3440
|
+
}
|
|
3441
|
+
await mux.close();
|
|
3442
|
+
};
|
|
3443
|
+
};
|
|
3444
|
+
/**
|
|
3445
|
+
* Ports over ONE PIPE OF BYTES — a `MessagePort`, a worker, a WebSocket.
|
|
3446
|
+
*
|
|
3447
|
+
* There is no second port to be had, so `multiplexPort`'s id table invents
|
|
3448
|
+
* them. Use this when the transport gives you exactly one channel.
|
|
3449
|
+
*/
|
|
3450
|
+
function overPipe(pipe, options) {
|
|
3451
|
+
return (onPort) => multiplexPort(pipe, {
|
|
3452
|
+
...options,
|
|
3453
|
+
onPort
|
|
3454
|
+
});
|
|
3455
|
+
}
|
|
3456
|
+
function isEnvelope(value) {
|
|
3457
|
+
if (typeof value !== "object" || value === null) return false;
|
|
3458
|
+
const candidate = value;
|
|
3459
|
+
if (typeof candidate.id !== "number") return false;
|
|
3460
|
+
if (!Number.isInteger(candidate.id) || candidate.id < 0) return false;
|
|
3461
|
+
return candidate.type === "open" || candidate.type === "message" || candidate.type === "close";
|
|
3462
|
+
}
|
|
3463
|
+
/**
|
|
3464
|
+
* For ports whose messages are structured values — a real `MessagePort`, a
|
|
3465
|
+
* worker, an iframe.
|
|
3466
|
+
*
|
|
3467
|
+
* Envelopes are posted as-is, so nothing is encoded, `ArrayBuffer`s move
|
|
3468
|
+
* zero-copy through the transfer list, and structured clone does the work the
|
|
3469
|
+
* platform already does well. This is a performance choice only: layer 2 may
|
|
3470
|
+
* not send anything a byte codec could not also carry.
|
|
3471
|
+
*/
|
|
3472
|
+
const structuredCodec = {
|
|
3473
|
+
post(port, envelope, transfer) {
|
|
3474
|
+
if (transfer && transfer.length > 0) port.postMessage(envelope, transfer);
|
|
3475
|
+
else port.postMessage(envelope);
|
|
3476
|
+
},
|
|
3477
|
+
read(event) {
|
|
3478
|
+
return isEnvelope(event.data) ? event.data : void 0;
|
|
3479
|
+
}
|
|
3480
|
+
};
|
|
3481
|
+
//#endregion
|
|
3482
|
+
//#region src/link/http-link.ts
|
|
3483
|
+
/**
|
|
3484
|
+
* The version of the HTTP-over-`MessagePort` protocol this package speaks,
|
|
3485
|
+
* sent in every hand-shake that sets up a link. Version 1 was this package's
|
|
3486
|
+
* own `handleStreams` / `sendStream` (no backpressure); version 2 is
|
|
3487
|
+
* webrun-rpc's `connect` / `serve` over `overPipe` with webrun-http-streams'
|
|
3488
|
+
* `fetchOverDuplex` / `serveFetchOverDuplex`: one port per link, calls
|
|
3489
|
+
* multiplexed on it, each call a stream with a one-chunk window in both
|
|
3490
|
+
* directions, and cancellation that reaches the handler.
|
|
3491
|
+
*/
|
|
3492
|
+
const HTTP_LINK_PROTOCOL = "webrun-http-link/2";
|
|
3493
|
+
/**
|
|
3494
|
+
* Why a request failed when its link went away under it: the far side (the
|
|
3495
|
+
* handler, or the ServiceWorker) was lost. The request may or may not have
|
|
3496
|
+
* been applied.
|
|
3497
|
+
*/
|
|
3498
|
+
var LinkLostError = class extends Error {
|
|
3499
|
+
constructor(message = "The link was lost while this request was in flight") {
|
|
3500
|
+
super(`${message}; it may or may not have been applied.`);
|
|
3501
|
+
this.name = "LinkLostError";
|
|
3502
|
+
}
|
|
3503
|
+
};
|
|
3504
|
+
/**
|
|
3505
|
+
* Posted on a link's port by the calling end when it closes the link, so the
|
|
3506
|
+
* answering end can release it: a `MessagePort` never reports that its other
|
|
3507
|
+
* end is gone.
|
|
3508
|
+
*/
|
|
3509
|
+
const LINK_CLOSE = "webrun-http:link-close";
|
|
3510
|
+
/** Opens the calling end of a link on `port` (one port per link). */
|
|
3511
|
+
async function connectHttpLink(port, { streamTimeout } = {}) {
|
|
3512
|
+
const { call, close } = await connect({
|
|
3513
|
+
mux: overPipe(port, {
|
|
3514
|
+
codec: structuredCodec,
|
|
3515
|
+
side: "initiator"
|
|
3516
|
+
}),
|
|
3517
|
+
timeout: streamTimeout
|
|
3518
|
+
});
|
|
3519
|
+
return trackedLink((request) => fetchOverDuplex(call, request), async () => {
|
|
3520
|
+
try {
|
|
3521
|
+
port.postMessage({ type: LINK_CLOSE });
|
|
3522
|
+
} catch {}
|
|
3523
|
+
await close();
|
|
3524
|
+
});
|
|
3525
|
+
}
|
|
3526
|
+
/**
|
|
3527
|
+
* Serves `handler` on the answering end of a link. Resolves with a teardown
|
|
3528
|
+
* that abandons the requests still running (their handlers see the
|
|
3529
|
+
* cancellation) and releases the port.
|
|
3530
|
+
*/
|
|
3531
|
+
async function serveHttpLink(port, handler, { streamTimeout } = {}) {
|
|
3532
|
+
const teardown = await serve({
|
|
3533
|
+
mux: overPipe(port, {
|
|
3534
|
+
codec: structuredCodec,
|
|
3535
|
+
side: "responder"
|
|
3536
|
+
}),
|
|
3537
|
+
timeout: streamTimeout
|
|
3538
|
+
}, serveFetchOverDuplex(async (request) => await handler(request)));
|
|
3539
|
+
const onClose = (event) => {
|
|
3540
|
+
if (event.data?.type === LINK_CLOSE) close();
|
|
3541
|
+
};
|
|
3542
|
+
const close = async () => {
|
|
3543
|
+
port.removeEventListener("message", onClose);
|
|
3544
|
+
await teardown();
|
|
3545
|
+
};
|
|
3546
|
+
port.addEventListener("message", onClose);
|
|
3547
|
+
return close;
|
|
3548
|
+
}
|
|
3549
|
+
/**
|
|
3550
|
+
* Wraps a `send` so the link knows its requests in flight (for draining and
|
|
3551
|
+
* load-based routing) and can fail them all at once when it is closed.
|
|
3552
|
+
*/
|
|
3553
|
+
function trackedLink(send, release) {
|
|
3554
|
+
let inflight = 0;
|
|
3555
|
+
let closed = false;
|
|
3556
|
+
let lostReason;
|
|
3557
|
+
const failers = /* @__PURE__ */ new Set();
|
|
3558
|
+
const idleWaiters = [];
|
|
3559
|
+
const done = () => {
|
|
3560
|
+
inflight--;
|
|
3561
|
+
if (inflight === 0) for (const resolve of idleWaiters.splice(0)) resolve();
|
|
3562
|
+
};
|
|
3563
|
+
return {
|
|
3564
|
+
get inflight() {
|
|
3565
|
+
return inflight;
|
|
3566
|
+
},
|
|
3567
|
+
get closed() {
|
|
3568
|
+
return closed;
|
|
3569
|
+
},
|
|
3570
|
+
whenIdle() {
|
|
3571
|
+
return inflight === 0 ? Promise.resolve() : new Promise((r) => idleWaiters.push(r));
|
|
3572
|
+
},
|
|
3573
|
+
async send(request) {
|
|
3574
|
+
if (closed) throw lostReason ?? new LinkLostError("The link is closed");
|
|
3575
|
+
inflight++;
|
|
3576
|
+
let finished = false;
|
|
3577
|
+
const finish = () => {
|
|
3578
|
+
if (finished) return;
|
|
3579
|
+
finished = true;
|
|
3580
|
+
failers.delete(fail);
|
|
3581
|
+
done();
|
|
3582
|
+
};
|
|
3583
|
+
let fail = () => {};
|
|
3584
|
+
const lost = new Promise((_, reject) => {
|
|
3585
|
+
fail = reject;
|
|
3586
|
+
});
|
|
3587
|
+
failers.add(fail);
|
|
3588
|
+
lost.catch(() => {});
|
|
3589
|
+
let response;
|
|
3590
|
+
try {
|
|
3591
|
+
response = await Promise.race([send(request), lost]);
|
|
3592
|
+
} catch (error) {
|
|
3593
|
+
finish();
|
|
3594
|
+
throw lostReason ?? error;
|
|
3595
|
+
}
|
|
3596
|
+
if (!response.body) {
|
|
3597
|
+
finish();
|
|
3598
|
+
return response;
|
|
3599
|
+
}
|
|
3600
|
+
return new Response(guardBody(response.body, lost, () => lostReason, finish), {
|
|
3601
|
+
status: response.status,
|
|
3602
|
+
statusText: response.statusText,
|
|
3603
|
+
headers: response.headers
|
|
3604
|
+
});
|
|
3605
|
+
},
|
|
3606
|
+
async close(reason) {
|
|
3607
|
+
if (closed) return;
|
|
3608
|
+
closed = true;
|
|
3609
|
+
lostReason = reason ?? new LinkLostError("The link was closed");
|
|
3610
|
+
for (const fail of [...failers]) fail(lostReason);
|
|
3611
|
+
try {
|
|
3612
|
+
await release();
|
|
3613
|
+
} catch {}
|
|
3614
|
+
}
|
|
3615
|
+
};
|
|
3616
|
+
}
|
|
3617
|
+
/**
|
|
3618
|
+
* A response body that reports its end (done, cancelled or failed) and fails
|
|
3619
|
+
* with the link's reason when the link is lost mid-stream.
|
|
3620
|
+
*/
|
|
3621
|
+
function guardBody(body, lost, reason, finish) {
|
|
3622
|
+
const reader = body.getReader();
|
|
3623
|
+
return new ReadableStream({
|
|
3624
|
+
async pull(controller) {
|
|
3625
|
+
try {
|
|
3626
|
+
const { done, value } = await Promise.race([reader.read(), lost]);
|
|
3627
|
+
if (done) {
|
|
3628
|
+
finish();
|
|
3629
|
+
controller.close();
|
|
3630
|
+
return;
|
|
3631
|
+
}
|
|
3632
|
+
controller.enqueue(value);
|
|
3633
|
+
} catch (error) {
|
|
3634
|
+
finish();
|
|
3635
|
+
reader.cancel().catch(() => {});
|
|
3636
|
+
controller.error(reason() ?? error);
|
|
3637
|
+
}
|
|
3638
|
+
},
|
|
3639
|
+
async cancel(why) {
|
|
3640
|
+
finish();
|
|
3641
|
+
await reader.cancel(why).catch(() => {});
|
|
3642
|
+
}
|
|
3643
|
+
});
|
|
3644
|
+
}
|
|
3645
|
+
//#endregion
|
|
3646
|
+
//#region src/link/locks.ts
|
|
3647
|
+
function lockManager() {
|
|
3648
|
+
return globalThis.navigator?.locks;
|
|
3649
|
+
}
|
|
3650
|
+
function locksAvailable() {
|
|
3651
|
+
return lockManager() !== void 0;
|
|
3652
|
+
}
|
|
3653
|
+
/** A fresh lock name: `<prefix>:<uuid>`. */
|
|
3654
|
+
function newLockName(prefix) {
|
|
3655
|
+
return `${prefix}:${crypto.randomUUID()}`;
|
|
3656
|
+
}
|
|
3657
|
+
/**
|
|
3658
|
+
* Takes the lock `name` and holds it until the returned release is called or
|
|
3659
|
+
* this context dies. Resolves once the lock is held; with no Web Locks,
|
|
3660
|
+
* resolves at once.
|
|
3661
|
+
*/
|
|
3662
|
+
async function holdLock(name) {
|
|
3663
|
+
const locks = lockManager();
|
|
3664
|
+
if (!locks) return () => {};
|
|
3665
|
+
let release = () => {};
|
|
3666
|
+
const released = new Promise((resolve) => {
|
|
3667
|
+
release = resolve;
|
|
3668
|
+
});
|
|
3669
|
+
await new Promise((held) => {
|
|
3670
|
+
locks.request(name, {}, () => {
|
|
3671
|
+
held();
|
|
3672
|
+
return released;
|
|
3673
|
+
}).catch(() => held());
|
|
3674
|
+
});
|
|
3675
|
+
return release;
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* Calls `onLost` once the lock `name` is granted to this context — that is,
|
|
3679
|
+
* once whoever holds it is gone — and releases it at once. Returns a function
|
|
3680
|
+
* that stops watching. With no Web Locks, never calls `onLost`.
|
|
3681
|
+
*/
|
|
3682
|
+
function watchLock(name, onLost) {
|
|
3683
|
+
const locks = lockManager();
|
|
3684
|
+
if (!locks) return () => {};
|
|
3685
|
+
const controller = new AbortController();
|
|
3686
|
+
locks.request(name, { signal: controller.signal }, () => {
|
|
3687
|
+
if (!controller.signal.aborted) onLost();
|
|
3688
|
+
}).catch(() => {});
|
|
3689
|
+
return () => controller.abort();
|
|
3690
|
+
}
|
|
3691
|
+
/**
|
|
3692
|
+
* The names of the locks held right now in this origin, or `undefined` where
|
|
3693
|
+
* that cannot be asked. A backup for `watchLock`: a grant can be late, a query
|
|
3694
|
+
* cannot.
|
|
3695
|
+
*/
|
|
3696
|
+
async function heldLockNames() {
|
|
3697
|
+
const locks = lockManager();
|
|
3698
|
+
if (!locks?.query) return void 0;
|
|
3699
|
+
try {
|
|
3700
|
+
const { held = [] } = await locks.query();
|
|
3701
|
+
return new Set(held.map((lock) => lock.name ?? ""));
|
|
3702
|
+
} catch {
|
|
3703
|
+
return;
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
//#endregion
|
|
3707
|
+
//#region src/link/rendezvous.ts
|
|
3708
|
+
/**
|
|
3709
|
+
* Matches replies to requests by id, for the control messages that hand
|
|
3710
|
+
* WebSocket ports across: each waiting request has a deadline, and all of a
|
|
3711
|
+
* peer's waiting requests can be failed at once when the peer is lost.
|
|
3712
|
+
*/
|
|
3713
|
+
var PortRendezvous = class {
|
|
3714
|
+
_prefix;
|
|
3715
|
+
_waiting = /* @__PURE__ */ new Map();
|
|
3716
|
+
_counter = 0;
|
|
3717
|
+
constructor(_prefix = "r") {
|
|
3718
|
+
this._prefix = _prefix;
|
|
3719
|
+
}
|
|
3720
|
+
/** A fresh id for a request. */
|
|
3721
|
+
newId() {
|
|
3722
|
+
return `${this._prefix}:${++this._counter}`;
|
|
3723
|
+
}
|
|
3724
|
+
get size() {
|
|
3725
|
+
return this._waiting.size;
|
|
3726
|
+
}
|
|
3727
|
+
/** Waits for the reply to `id`, failing after `timeoutMs`. */
|
|
3728
|
+
wait(id, timeoutMs, describe = "the reply") {
|
|
3729
|
+
return new Promise((resolve, reject) => {
|
|
3730
|
+
const timer = setTimeout(() => {
|
|
3731
|
+
this._waiting.delete(id);
|
|
3732
|
+
reject(/* @__PURE__ */ new Error(`No answer to ${describe} within ${timeoutMs} ms`));
|
|
3733
|
+
}, timeoutMs);
|
|
3734
|
+
this._waiting.set(id, {
|
|
3735
|
+
resolve,
|
|
3736
|
+
reject,
|
|
3737
|
+
timer
|
|
3738
|
+
});
|
|
3739
|
+
});
|
|
3740
|
+
}
|
|
3741
|
+
/** Delivers the reply to `id`. `false` when nobody waits for it (it timed out). */
|
|
3742
|
+
settle(id, value) {
|
|
3743
|
+
const waiting = this._waiting.get(id);
|
|
3744
|
+
if (!waiting) return false;
|
|
3745
|
+
this._waiting.delete(id);
|
|
3746
|
+
clearTimeout(waiting.timer);
|
|
3747
|
+
waiting.resolve(value);
|
|
3748
|
+
return true;
|
|
3749
|
+
}
|
|
3750
|
+
fail(id, error) {
|
|
3751
|
+
const waiting = this._waiting.get(id);
|
|
3752
|
+
if (!waiting) return;
|
|
3753
|
+
this._waiting.delete(id);
|
|
3754
|
+
clearTimeout(waiting.timer);
|
|
3755
|
+
waiting.reject(error);
|
|
3756
|
+
}
|
|
3757
|
+
failAll(error) {
|
|
3758
|
+
for (const id of [...this._waiting.keys()]) this.fail(id, error);
|
|
3759
|
+
}
|
|
3760
|
+
};
|
|
3761
|
+
//#endregion
|
|
3762
|
+
//#region src/ws/frames.ts
|
|
3763
|
+
/**
|
|
3764
|
+
* The wire protocol of a WebSocket carried over a `MessagePort`.
|
|
3765
|
+
*
|
|
3766
|
+
* A `MessagePort` is a natural carrier for a WebSocket: messages arrive in
|
|
3767
|
+
* order, and strings and transferable `ArrayBuffer`s cross it as they are. The
|
|
3768
|
+
* protocol on top is these frames, the same in both directions:
|
|
3769
|
+
*
|
|
3770
|
+
* - `m` — one message. An `ArrayBuffer` is transferred, never copied.
|
|
3771
|
+
* - `c` — close. The side that closes first sends it; the other answers with
|
|
3772
|
+
* its own `c` (the echo), and both are then closed cleanly.
|
|
3773
|
+
* - `p` — ping, client to server, carrying the client's heartbeat period.
|
|
3774
|
+
* - `q` — pong, server to client.
|
|
3775
|
+
* - `a` — ack: the receiver consumed `n` more bytes of messages. This is the
|
|
3776
|
+
* flow control: what a side has sent and not yet seen acknowledged is its
|
|
3777
|
+
* `bufferedAmount`, and the server end can wait for it to fall
|
|
3778
|
+
* (`whenDrained`). Added in version 2; version 1 had no backpressure.
|
|
3779
|
+
*
|
|
3780
|
+
* HEARTBEAT. A `MessagePort` never reports that the other side died, so the
|
|
3781
|
+
* client pings every `hb` ms and closes with 1006 when pongs stop for `2·hb`;
|
|
3782
|
+
* the server closes with 1006 when pings stop for `3·hb`. That is how a socket
|
|
3783
|
+
* notices a closed tab or a terminated worker.
|
|
3784
|
+
*
|
|
3785
|
+
* Unknown frames are ignored, so a later version can add frames a peer of
|
|
3786
|
+
* this version skips.
|
|
3787
|
+
*/
|
|
3788
|
+
/** The version of this frame protocol. Sent in the upgrade hand-shake. */
|
|
3789
|
+
const WS_PORT_PROTOCOL_VERSION = 2;
|
|
3790
|
+
/** Default heartbeat period of the client, in ms. */
|
|
3791
|
+
const DEFAULT_HEARTBEAT_MS = 1e4;
|
|
3792
|
+
/** How long a side waits for the echo of its close frame, in ms. */
|
|
3793
|
+
const DEFAULT_CLOSE_TIMEOUT_MS = 5e3;
|
|
3794
|
+
const defaultTimers = {
|
|
3795
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
3796
|
+
clearTimeout: (id) => clearTimeout(id),
|
|
3797
|
+
setInterval: (fn, ms) => setInterval(fn, ms),
|
|
3798
|
+
clearInterval: (id) => clearInterval(id)
|
|
3799
|
+
};
|
|
3800
|
+
/** Recovers a frame from a message's data, or `undefined` for anything else. */
|
|
3801
|
+
function readFrame(data) {
|
|
3802
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
3803
|
+
const frame = data;
|
|
3804
|
+
switch (frame.t) {
|
|
3805
|
+
case "m": return typeof frame.d === "string" || frame.d instanceof ArrayBuffer ? frame : void 0;
|
|
3806
|
+
case "c": return {
|
|
3807
|
+
t: "c",
|
|
3808
|
+
code: typeof frame.code === "number" ? frame.code : 1005,
|
|
3809
|
+
reason: typeof frame.reason === "string" ? frame.reason : ""
|
|
3810
|
+
};
|
|
3811
|
+
case "p": {
|
|
3812
|
+
const hb = frame.hb;
|
|
3813
|
+
return {
|
|
3814
|
+
t: "p",
|
|
3815
|
+
hb: typeof hb === "number" && hb > 0 ? hb : DEFAULT_HEARTBEAT_MS
|
|
3816
|
+
};
|
|
3817
|
+
}
|
|
3818
|
+
case "q": return { t: "q" };
|
|
3819
|
+
case "a": {
|
|
3820
|
+
const n = frame.n;
|
|
3821
|
+
return typeof n === "number" && n >= 0 ? {
|
|
3822
|
+
t: "a",
|
|
3823
|
+
n
|
|
3824
|
+
} : void 0;
|
|
3825
|
+
}
|
|
3826
|
+
default: return;
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
/** Posts `frame`, transferring a message's `ArrayBuffer`. */
|
|
3830
|
+
function postFrame(port, frame) {
|
|
3831
|
+
if (frame.t === "m" && frame.d instanceof ArrayBuffer) port.postMessage(frame, [frame.d]);
|
|
3832
|
+
else port.postMessage(frame);
|
|
3833
|
+
}
|
|
3834
|
+
/** The size a message counts for in `bufferedAmount`: UTF-8 bytes, or the buffer's length. */
|
|
3835
|
+
function messageSize(data) {
|
|
3836
|
+
return typeof data === "string" ? utf8Length(data) : data.byteLength;
|
|
3837
|
+
}
|
|
3838
|
+
/** The UTF-8 length of `text`, without encoding it. */
|
|
3839
|
+
function utf8Length(text) {
|
|
3840
|
+
let length = 0;
|
|
3841
|
+
for (let i = 0; i < text.length; i++) {
|
|
3842
|
+
const code = text.charCodeAt(i);
|
|
3843
|
+
if (code < 128) length += 1;
|
|
3844
|
+
else if (code < 2048) length += 2;
|
|
3845
|
+
else if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
|
|
3846
|
+
const next = text.charCodeAt(i + 1);
|
|
3847
|
+
if (next >= 56320 && next <= 57343) {
|
|
3848
|
+
length += 4;
|
|
3849
|
+
i++;
|
|
3850
|
+
} else length += 3;
|
|
3851
|
+
} else length += 3;
|
|
3852
|
+
}
|
|
3853
|
+
return length;
|
|
3854
|
+
}
|
|
3855
|
+
/**
|
|
3856
|
+
* A `CloseEvent` for runtimes that have none: Node 22 has `Event` and
|
|
3857
|
+
* `MessageEvent` as globals, but not `CloseEvent`.
|
|
3858
|
+
*/
|
|
3859
|
+
var WsCloseEvent = class extends Event {
|
|
3860
|
+
code;
|
|
3861
|
+
reason;
|
|
3862
|
+
wasClean;
|
|
3863
|
+
constructor(type, init = {}) {
|
|
3864
|
+
super(type, init);
|
|
3865
|
+
this.code = init.code ?? 0;
|
|
3866
|
+
this.reason = init.reason ?? "";
|
|
3867
|
+
this.wasClean = init.wasClean ?? false;
|
|
3868
|
+
}
|
|
3869
|
+
};
|
|
3870
|
+
/** A `close` event: the platform's `CloseEvent` where there is one. */
|
|
3871
|
+
function newCloseEvent(init) {
|
|
3872
|
+
const Native = globalThis.CloseEvent;
|
|
3873
|
+
return Native ? new Native("close", init) : new WsCloseEvent("close", init);
|
|
3874
|
+
}
|
|
3875
|
+
/**
|
|
3876
|
+
* What both ends of a socket over a `MessagePort` share: the frames, the close
|
|
3877
|
+
* handshake, and the byte accounting behind `bufferedAmount`.
|
|
3878
|
+
*
|
|
3879
|
+
* Not exported from the package: the two ends are `createWebSocketClass`'s
|
|
3880
|
+
* class and `ServerWebSocket`.
|
|
3881
|
+
*/
|
|
3882
|
+
var PortSocketCore = class extends EventTarget {
|
|
3883
|
+
_port;
|
|
3884
|
+
_state = 0;
|
|
3885
|
+
_timers;
|
|
3886
|
+
_closeTimeoutMs;
|
|
3887
|
+
/** Bytes sent and not yet acknowledged by the peer, plus those still being prepared. */
|
|
3888
|
+
_inFlight = 0;
|
|
3889
|
+
/** Bytes of messages "sent" after the socket started closing: counted, never sent. */
|
|
3890
|
+
_discarded = 0;
|
|
3891
|
+
_toAck = 0;
|
|
3892
|
+
_ackScheduled = false;
|
|
3893
|
+
_closeTimer;
|
|
3894
|
+
_drainWaiters = [];
|
|
3895
|
+
constructor(options = {}) {
|
|
3896
|
+
super();
|
|
3897
|
+
this._timers = options.timers ?? defaultTimers;
|
|
3898
|
+
this._closeTimeoutMs = options.closeTimeoutMs ?? 5e3;
|
|
3899
|
+
}
|
|
3900
|
+
get readyState() {
|
|
3901
|
+
return this._state;
|
|
3902
|
+
}
|
|
3903
|
+
/**
|
|
3904
|
+
* Bytes queued by `send()` that the peer has not consumed yet. A peer
|
|
3905
|
+
* acknowledges what it has dispatched, so this falls as the other side reads.
|
|
3906
|
+
*/
|
|
3907
|
+
get bufferedAmount() {
|
|
3908
|
+
return this._inFlight + this._discarded;
|
|
3909
|
+
}
|
|
3910
|
+
/**
|
|
3911
|
+
* Resolves once `bufferedAmount` is at most `limit` (default 0), or the
|
|
3912
|
+
* socket is closed. The backpressure a producer applies:
|
|
3913
|
+
* `if (socket.bufferedAmount > HIGH) await socket.whenDrained(LOW)`.
|
|
3914
|
+
*/
|
|
3915
|
+
whenDrained(limit = 0) {
|
|
3916
|
+
if (this._state === 3 || this._inFlight <= limit) return Promise.resolve();
|
|
3917
|
+
return new Promise((resolve) => this._drainWaiters.push({
|
|
3918
|
+
limit,
|
|
3919
|
+
resolve
|
|
3920
|
+
}));
|
|
3921
|
+
}
|
|
3922
|
+
_attach(port) {
|
|
3923
|
+
this._port = port;
|
|
3924
|
+
port.onmessage = (event) => {
|
|
3925
|
+
const frame = readFrame(event.data);
|
|
3926
|
+
if (frame) this._onFrame(frame);
|
|
3927
|
+
};
|
|
3928
|
+
}
|
|
3929
|
+
_onFrame(frame) {
|
|
3930
|
+
switch (frame.t) {
|
|
3931
|
+
case "m":
|
|
3932
|
+
case "c":
|
|
3933
|
+
this._deliver(frame);
|
|
3934
|
+
return;
|
|
3935
|
+
case "a":
|
|
3936
|
+
this._inFlight = Math.max(0, this._inFlight - frame.n);
|
|
3937
|
+
this._wakeDrainWaiters();
|
|
3938
|
+
return;
|
|
3939
|
+
case "p":
|
|
3940
|
+
this._onPing(frame.hb);
|
|
3941
|
+
return;
|
|
3942
|
+
case "q":
|
|
3943
|
+
this._onPong();
|
|
3944
|
+
return;
|
|
3945
|
+
}
|
|
3946
|
+
}
|
|
3947
|
+
/** A message or close frame the socket is ready to act on. */
|
|
3948
|
+
_deliver(frame) {
|
|
3949
|
+
if (frame.t === "c") {
|
|
3950
|
+
this._onCloseFrame(frame.code, frame.reason);
|
|
3951
|
+
return;
|
|
3952
|
+
}
|
|
3953
|
+
if (this._state !== 1) return;
|
|
3954
|
+
this._dispatchMessage(frame.d);
|
|
3955
|
+
this._consumed(messageSize(frame.d));
|
|
3956
|
+
}
|
|
3957
|
+
_onPing(_hb) {}
|
|
3958
|
+
_onPong() {}
|
|
3959
|
+
_onClosed() {}
|
|
3960
|
+
/** Acknowledge consumed bytes, coalescing the acks of one turn into one frame. */
|
|
3961
|
+
_consumed(bytes) {
|
|
3962
|
+
this._toAck += bytes;
|
|
3963
|
+
if (this._ackScheduled) return;
|
|
3964
|
+
this._ackScheduled = true;
|
|
3965
|
+
queueMicrotask(() => {
|
|
3966
|
+
this._ackScheduled = false;
|
|
3967
|
+
const n = this._toAck;
|
|
3968
|
+
this._toAck = 0;
|
|
3969
|
+
if (n > 0 && this._state !== 3) this._post({
|
|
3970
|
+
t: "a",
|
|
3971
|
+
n
|
|
3972
|
+
});
|
|
3973
|
+
});
|
|
3974
|
+
}
|
|
3975
|
+
/** Reserves `bytes` in `bufferedAmount` for a message still being prepared (a Blob). */
|
|
3976
|
+
_reserve(bytes) {
|
|
3977
|
+
this._inFlight += bytes;
|
|
3978
|
+
}
|
|
3979
|
+
/** Sends one message whose bytes were reserved with `_reserve` (or `reserved = false`). */
|
|
3980
|
+
_sendData(data, reserved = false) {
|
|
3981
|
+
const size = messageSize(data);
|
|
3982
|
+
if (this._state !== 1) {
|
|
3983
|
+
if (reserved) this._inFlight = Math.max(0, this._inFlight - size);
|
|
3984
|
+
this._discarded += size;
|
|
3985
|
+
return;
|
|
3986
|
+
}
|
|
3987
|
+
if (!reserved) this._inFlight += size;
|
|
3988
|
+
this._post({
|
|
3989
|
+
t: "m",
|
|
3990
|
+
d: data
|
|
3991
|
+
});
|
|
3992
|
+
}
|
|
3993
|
+
_post(frame) {
|
|
3994
|
+
try {
|
|
3995
|
+
if (this._port) postFrame(this._port, frame);
|
|
3996
|
+
} catch {}
|
|
3997
|
+
}
|
|
3998
|
+
/** Starts the close handshake. */
|
|
3999
|
+
_startClose(code, reason) {
|
|
4000
|
+
if (this._state === 2 || this._state === 3) return;
|
|
4001
|
+
this._state = 2;
|
|
4002
|
+
this._post({
|
|
4003
|
+
t: "c",
|
|
4004
|
+
code,
|
|
4005
|
+
reason
|
|
4006
|
+
});
|
|
4007
|
+
this._closeTimer = this._timers.setTimeout(() => this._finish(1006, "", false), this._closeTimeoutMs);
|
|
4008
|
+
}
|
|
4009
|
+
_onCloseFrame(code, reason) {
|
|
4010
|
+
if (this._state === 3) return;
|
|
4011
|
+
if (this._state === 2) {
|
|
4012
|
+
this._finish(code, reason, true);
|
|
4013
|
+
return;
|
|
4014
|
+
}
|
|
4015
|
+
this._state = 2;
|
|
4016
|
+
this._post({
|
|
4017
|
+
t: "c",
|
|
4018
|
+
code,
|
|
4019
|
+
reason
|
|
4020
|
+
});
|
|
4021
|
+
this._finish(code, reason, true);
|
|
4022
|
+
}
|
|
4023
|
+
/** The socket is closed: release the port and tell the listeners. */
|
|
4024
|
+
_finish(code, reason, wasClean, error = false) {
|
|
4025
|
+
if (this._state === 3) return;
|
|
4026
|
+
this._state = 3;
|
|
4027
|
+
if (this._closeTimer !== void 0) this._timers.clearTimeout(this._closeTimer);
|
|
4028
|
+
this._closeTimer = void 0;
|
|
4029
|
+
this._onClosed();
|
|
4030
|
+
if (this._port) {
|
|
4031
|
+
this._port.onmessage = null;
|
|
4032
|
+
try {
|
|
4033
|
+
this._port.close();
|
|
4034
|
+
} catch {}
|
|
4035
|
+
}
|
|
4036
|
+
this._wakeDrainWaiters();
|
|
4037
|
+
if (error) this.dispatchEvent(new Event("error"));
|
|
4038
|
+
this.dispatchEvent(newCloseEvent({
|
|
4039
|
+
code,
|
|
4040
|
+
reason,
|
|
4041
|
+
wasClean
|
|
4042
|
+
}));
|
|
4043
|
+
}
|
|
4044
|
+
_wakeDrainWaiters() {
|
|
4045
|
+
if (this._drainWaiters.length === 0) return;
|
|
4046
|
+
const closed = this._state === 3;
|
|
4047
|
+
this._drainWaiters = this._drainWaiters.filter(({ limit, resolve }) => {
|
|
4048
|
+
if (!closed && this._inFlight > limit) return true;
|
|
4049
|
+
resolve();
|
|
4050
|
+
return false;
|
|
4051
|
+
});
|
|
4052
|
+
}
|
|
4053
|
+
};
|
|
4054
|
+
/** Copies `data` into a fresh `ArrayBuffer`: `send()` must never detach the caller's buffer. */
|
|
4055
|
+
function toArrayBuffer(data) {
|
|
4056
|
+
if (data instanceof ArrayBuffer) return data.slice(0);
|
|
4057
|
+
const copy = new Uint8Array(data.byteLength);
|
|
4058
|
+
copy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
4059
|
+
return copy.buffer;
|
|
4060
|
+
}
|
|
4061
|
+
function isBinary(data) {
|
|
4062
|
+
return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
|
|
4063
|
+
}
|
|
4064
|
+
function isBlob(data) {
|
|
4065
|
+
return typeof Blob !== "undefined" && data instanceof Blob;
|
|
4066
|
+
}
|
|
4067
|
+
/** Valid close codes for an application to send: 1000, or 3000–4999. */
|
|
4068
|
+
function isApplicationCloseCode(code) {
|
|
4069
|
+
return code === 1e3 || code >= 3e3 && code <= 4999;
|
|
4070
|
+
}
|
|
4071
|
+
//#endregion
|
|
4072
|
+
//#region src/ws/client.ts
|
|
4073
|
+
/** RFC 7230 `token`: what a subprotocol name may be. */
|
|
4074
|
+
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
4075
|
+
/**
|
|
4076
|
+
* A WHATWG-compatible `WebSocket` class whose transport is a `MessagePort`
|
|
4077
|
+
* from `connect`. Code written against the browser's `WebSocket` runs on it
|
|
4078
|
+
* unchanged:
|
|
4079
|
+
*
|
|
4080
|
+
* ```ts
|
|
4081
|
+
* const WS = createWebSocketClass(adapter.connectWebSocket);
|
|
4082
|
+
* const ws = new WS(`${baseUrl}chat`, ["v1"]);
|
|
4083
|
+
* ws.onmessage = (event) => console.log(event.data);
|
|
4084
|
+
* ```
|
|
4085
|
+
*
|
|
4086
|
+
* It validates as the standard does (url, scheme, fragment, subprotocol
|
|
4087
|
+
* tokens and duplicates, close codes and reasons), has `binaryType`, the `on*`
|
|
4088
|
+
* handlers next to `addEventListener`, and the close handshake.
|
|
4089
|
+
* `bufferedAmount` is real: the server acknowledges what it consumed.
|
|
4090
|
+
*
|
|
4091
|
+
* The real `globalThis.WebSocket` is left alone; install the class where you
|
|
4092
|
+
* want it.
|
|
4093
|
+
*/
|
|
4094
|
+
function createWebSocketClass(connect, options = {}) {
|
|
4095
|
+
const heartbeatMs = options.heartbeatMs ?? 1e4;
|
|
4096
|
+
class WebSocketOverPort extends PortSocketCore {
|
|
4097
|
+
static CONNECTING = 0;
|
|
4098
|
+
static OPEN = 1;
|
|
4099
|
+
static CLOSING = 2;
|
|
4100
|
+
static CLOSED = 3;
|
|
4101
|
+
CONNECTING = 0;
|
|
4102
|
+
OPEN = 1;
|
|
4103
|
+
CLOSING = 2;
|
|
4104
|
+
CLOSED = 3;
|
|
4105
|
+
url;
|
|
4106
|
+
extensions = "";
|
|
4107
|
+
_protocol = "";
|
|
4108
|
+
_binaryType = "blob";
|
|
4109
|
+
_handlers = {};
|
|
4110
|
+
_heartbeat;
|
|
4111
|
+
/** When the oldest ping still waiting for its pong was sent. */
|
|
4112
|
+
_unansweredSince;
|
|
4113
|
+
_onVisibility;
|
|
4114
|
+
/** Sends waiting for a Blob ahead of them to be read, so order is kept. */
|
|
4115
|
+
_chain;
|
|
4116
|
+
constructor(url, protocols = []) {
|
|
4117
|
+
super({
|
|
4118
|
+
timers: options.timers,
|
|
4119
|
+
closeTimeoutMs: options.closeTimeoutMs
|
|
4120
|
+
});
|
|
4121
|
+
this.url = parseUrl(url);
|
|
4122
|
+
const list = typeof protocols === "string" ? [protocols] : [...protocols];
|
|
4123
|
+
validateProtocols(list);
|
|
4124
|
+
for (const type of [
|
|
4125
|
+
"open",
|
|
4126
|
+
"message",
|
|
4127
|
+
"error",
|
|
4128
|
+
"close"
|
|
4129
|
+
]) this.addEventListener(type, (event) => this._handlers[type]?.call(this, event));
|
|
4130
|
+
Promise.resolve().then(() => connect(this.url, list)).then((connection) => {
|
|
4131
|
+
try {
|
|
4132
|
+
this._opened(connection, list);
|
|
4133
|
+
} catch {
|
|
4134
|
+
this._failed();
|
|
4135
|
+
}
|
|
4136
|
+
}, () => this._failed());
|
|
4137
|
+
}
|
|
4138
|
+
get protocol() {
|
|
4139
|
+
return this._protocol;
|
|
4140
|
+
}
|
|
4141
|
+
get binaryType() {
|
|
4142
|
+
return this._binaryType;
|
|
4143
|
+
}
|
|
4144
|
+
set binaryType(value) {
|
|
4145
|
+
if (value === "blob" || value === "arraybuffer") this._binaryType = value;
|
|
4146
|
+
}
|
|
4147
|
+
get onopen() {
|
|
4148
|
+
return this._handlers.open ?? null;
|
|
4149
|
+
}
|
|
4150
|
+
set onopen(fn) {
|
|
4151
|
+
this._handlers.open = typeof fn === "function" ? fn : null;
|
|
4152
|
+
}
|
|
4153
|
+
get onmessage() {
|
|
4154
|
+
return this._handlers.message ?? null;
|
|
4155
|
+
}
|
|
4156
|
+
set onmessage(fn) {
|
|
4157
|
+
this._handlers.message = typeof fn === "function" ? fn : null;
|
|
4158
|
+
}
|
|
4159
|
+
get onerror() {
|
|
4160
|
+
return this._handlers.error ?? null;
|
|
4161
|
+
}
|
|
4162
|
+
set onerror(fn) {
|
|
4163
|
+
this._handlers.error = typeof fn === "function" ? fn : null;
|
|
4164
|
+
}
|
|
4165
|
+
get onclose() {
|
|
4166
|
+
return this._handlers.close ?? null;
|
|
4167
|
+
}
|
|
4168
|
+
set onclose(fn) {
|
|
4169
|
+
this._handlers.close = typeof fn === "function" ? fn : null;
|
|
4170
|
+
}
|
|
4171
|
+
send(data) {
|
|
4172
|
+
if (this._state === 0) throw new DOMException("Still in CONNECTING state.", "InvalidStateError");
|
|
4173
|
+
if (isBlob(data)) {
|
|
4174
|
+
const size = data.size;
|
|
4175
|
+
if (this._state !== 1) {
|
|
4176
|
+
this._sendData(new ArrayBuffer(size));
|
|
4177
|
+
return;
|
|
4178
|
+
}
|
|
4179
|
+
this._reserve(size);
|
|
4180
|
+
this._enqueue(async () => this._sendData(await data.arrayBuffer(), true));
|
|
4181
|
+
return;
|
|
4182
|
+
}
|
|
4183
|
+
const payload = isBinary(data) ? toArrayBuffer(data) : String(data);
|
|
4184
|
+
if (this._chain) this._enqueue(async () => this._sendData(payload));
|
|
4185
|
+
else this._sendData(payload);
|
|
4186
|
+
}
|
|
4187
|
+
close(code, reason) {
|
|
4188
|
+
if (code !== void 0 && !isApplicationCloseCode(code)) throw new DOMException(`The close code must be 1000 or in 3000-4999; ${code} is neither.`, "InvalidAccessError");
|
|
4189
|
+
const text = reason ?? "";
|
|
4190
|
+
if (utf8Length(text) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
|
|
4191
|
+
if (this._state === 2 || this._state === 3) return;
|
|
4192
|
+
if (this._state === 0) {
|
|
4193
|
+
this._state = 2;
|
|
4194
|
+
return;
|
|
4195
|
+
}
|
|
4196
|
+
this._startClose(code ?? 1005, text);
|
|
4197
|
+
}
|
|
4198
|
+
_dispatchMessage(data) {
|
|
4199
|
+
const value = typeof data === "string" || this._binaryType === "arraybuffer" ? data : new Blob([data]);
|
|
4200
|
+
this.dispatchEvent(new MessageEvent("message", {
|
|
4201
|
+
data: value,
|
|
4202
|
+
origin: new URL(this.url).origin
|
|
4203
|
+
}));
|
|
4204
|
+
}
|
|
4205
|
+
_onPong() {
|
|
4206
|
+
this._unansweredSince = void 0;
|
|
4207
|
+
}
|
|
4208
|
+
_onClosed() {
|
|
4209
|
+
if (this._heartbeat !== void 0) this._timers.clearInterval(this._heartbeat);
|
|
4210
|
+
this._heartbeat = void 0;
|
|
4211
|
+
if (this._onVisibility) globalThis.document?.removeEventListener("visibilitychange", this._onVisibility);
|
|
4212
|
+
}
|
|
4213
|
+
_ping(hb = heartbeatMs) {
|
|
4214
|
+
this._unansweredSince ??= Date.now();
|
|
4215
|
+
this._post({
|
|
4216
|
+
t: "p",
|
|
4217
|
+
hb
|
|
4218
|
+
});
|
|
4219
|
+
}
|
|
4220
|
+
_opened(connection, requested) {
|
|
4221
|
+
const { port, protocol = "" } = connection ?? {};
|
|
4222
|
+
if (!port || typeof port.postMessage !== "function") {
|
|
4223
|
+
this._failed();
|
|
4224
|
+
return;
|
|
4225
|
+
}
|
|
4226
|
+
if (this._state !== 0) {
|
|
4227
|
+
try {
|
|
4228
|
+
port.postMessage({
|
|
4229
|
+
t: "c",
|
|
4230
|
+
code: 1006,
|
|
4231
|
+
reason: ""
|
|
4232
|
+
});
|
|
4233
|
+
port.close();
|
|
4234
|
+
} catch {}
|
|
4235
|
+
this._finish(1006, "", false, true);
|
|
4236
|
+
return;
|
|
4237
|
+
}
|
|
4238
|
+
if (protocol !== "" && !requested.includes(protocol)) {
|
|
4239
|
+
port.close();
|
|
4240
|
+
this._failed();
|
|
4241
|
+
return;
|
|
4242
|
+
}
|
|
4243
|
+
this._protocol = protocol;
|
|
4244
|
+
this._attach(port);
|
|
4245
|
+
this._state = 1;
|
|
4246
|
+
this._ping();
|
|
4247
|
+
this._heartbeat = this._timers.setInterval(() => {
|
|
4248
|
+
const since = this._unansweredSince;
|
|
4249
|
+
if (since !== void 0 && Date.now() - since > 2 * heartbeatMs) {
|
|
4250
|
+
this._finish(1006, "", false, true);
|
|
4251
|
+
return;
|
|
4252
|
+
}
|
|
4253
|
+
this._ping();
|
|
4254
|
+
}, heartbeatMs);
|
|
4255
|
+
const doc = globalThis.document;
|
|
4256
|
+
if (doc) {
|
|
4257
|
+
this._onVisibility = () => this._ping(doc.visibilityState === "hidden" ? Math.max(heartbeatMs, 7e4) : heartbeatMs);
|
|
4258
|
+
doc.addEventListener("visibilitychange", this._onVisibility);
|
|
4259
|
+
if (doc.visibilityState === "hidden") this._onVisibility();
|
|
4260
|
+
}
|
|
4261
|
+
this.dispatchEvent(new Event("open"));
|
|
4262
|
+
}
|
|
4263
|
+
_failed() {
|
|
4264
|
+
this._state = 2;
|
|
4265
|
+
this._finish(1006, "", false, true);
|
|
4266
|
+
}
|
|
4267
|
+
_enqueue(task) {
|
|
4268
|
+
const run = (this._chain ?? Promise.resolve()).then(task).catch(() => {});
|
|
4269
|
+
this._chain = run;
|
|
4270
|
+
run.then(() => {
|
|
4271
|
+
if (this._chain === run) this._chain = void 0;
|
|
4272
|
+
});
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
return WebSocketOverPort;
|
|
4276
|
+
}
|
|
4277
|
+
function parseUrl(input) {
|
|
4278
|
+
let url;
|
|
4279
|
+
try {
|
|
4280
|
+
url = new URL(`${input}`, globalThis.location?.href);
|
|
4281
|
+
} catch {
|
|
4282
|
+
throw new DOMException(`The URL '${input}' is invalid.`, "SyntaxError");
|
|
4283
|
+
}
|
|
4284
|
+
if (url.protocol === "http:") url.protocol = "ws:";
|
|
4285
|
+
else if (url.protocol === "https:") url.protocol = "wss:";
|
|
4286
|
+
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");
|
|
4287
|
+
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");
|
|
4288
|
+
return url.href;
|
|
4289
|
+
}
|
|
4290
|
+
function validateProtocols(protocols) {
|
|
4291
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4292
|
+
for (const protocol of protocols) {
|
|
4293
|
+
if (!TOKEN.test(protocol)) throw new DOMException(`The subprotocol '${protocol}' is invalid.`, "SyntaxError");
|
|
4294
|
+
if (seen.has(protocol)) throw new DOMException(`The subprotocol '${protocol}' is duplicated.`, "SyntaxError");
|
|
4295
|
+
seen.add(protocol);
|
|
4296
|
+
}
|
|
4297
|
+
}
|
|
4298
|
+
//#endregion
|
|
4299
|
+
//#region src/link/errors.ts
|
|
4300
|
+
function errorMessage(error) {
|
|
4301
|
+
return error instanceof Error ? error.message : String(error);
|
|
4302
|
+
}
|
|
4303
|
+
//#endregion
|
|
4304
|
+
//#region src/ws/server.ts
|
|
4305
|
+
/**
|
|
4306
|
+
* The server end of a socket over a `MessagePort`: what a handler gets from
|
|
4307
|
+
* `upgradeWebSocket` and talks to.
|
|
4308
|
+
*
|
|
4309
|
+
* - Events are delivered only after `accept()`; frames that arrive earlier are
|
|
4310
|
+
* queued. Pings are answered even before `accept()`, so a slow handler does
|
|
4311
|
+
* not look like a dead one.
|
|
4312
|
+
* - Messages arrive as strings or `ArrayBuffer`s.
|
|
4313
|
+
* - `bufferedAmount` counts what the client has not consumed yet, and
|
|
4314
|
+
* `whenDrained(limit)` waits for it to fall: the backpressure a producer
|
|
4315
|
+
* applies.
|
|
4316
|
+
* - When the client's pings stop for three heartbeat periods (a closed tab, a
|
|
4317
|
+
* terminated worker), the socket closes with 1006.
|
|
4318
|
+
*/
|
|
4319
|
+
var ServerWebSocket = class extends PortSocketCore {
|
|
4320
|
+
static CONNECTING = 0;
|
|
4321
|
+
static OPEN = 1;
|
|
4322
|
+
static CLOSING = 2;
|
|
4323
|
+
static CLOSED = 3;
|
|
4324
|
+
url;
|
|
4325
|
+
protocol;
|
|
4326
|
+
_accepted = false;
|
|
4327
|
+
_queue = [];
|
|
4328
|
+
_heartbeatMs = DEFAULT_HEARTBEAT_MS;
|
|
4329
|
+
_lastPing = Date.now();
|
|
4330
|
+
_watch;
|
|
4331
|
+
constructor(port, options = {}) {
|
|
4332
|
+
super({
|
|
4333
|
+
timers: options.timers,
|
|
4334
|
+
closeTimeoutMs: options.closeTimeoutMs
|
|
4335
|
+
});
|
|
4336
|
+
this.url = options.url ?? "";
|
|
4337
|
+
this.protocol = options.protocol ?? "";
|
|
4338
|
+
this._attach(port);
|
|
4339
|
+
this._state = 1;
|
|
4340
|
+
this._watchHeartbeat();
|
|
4341
|
+
}
|
|
4342
|
+
/** Whether `accept()` was called. */
|
|
4343
|
+
get accepted() {
|
|
4344
|
+
return this._accepted;
|
|
4345
|
+
}
|
|
4346
|
+
/** Starts delivering events, the queued ones first. */
|
|
4347
|
+
accept() {
|
|
4348
|
+
if (this._accepted) return;
|
|
4349
|
+
this._accepted = true;
|
|
4350
|
+
for (const frame of this._queue.splice(0)) super._deliver(frame);
|
|
4351
|
+
}
|
|
4352
|
+
send(data) {
|
|
4353
|
+
if (!this._accepted) throw new DOMException("accept() the socket before sending on it.", "InvalidStateError");
|
|
4354
|
+
this._sendData(isBinary(data) ? toArrayBuffer(data) : String(data));
|
|
4355
|
+
}
|
|
4356
|
+
close(code = 1e3, reason = "") {
|
|
4357
|
+
if (!isSendableCloseCode(code)) throw new DOMException(`${code} is not a close code an endpoint may send.`, "InvalidAccessError");
|
|
4358
|
+
if (utf8Length(reason) > 123) throw new DOMException("The close reason is longer than 123 bytes.", "SyntaxError");
|
|
4359
|
+
this._startClose(code, reason);
|
|
4360
|
+
}
|
|
4361
|
+
_deliver(frame) {
|
|
4362
|
+
if (!this._accepted) {
|
|
4363
|
+
this._queue.push(frame);
|
|
4364
|
+
return;
|
|
4365
|
+
}
|
|
4366
|
+
super._deliver(frame);
|
|
4367
|
+
}
|
|
4368
|
+
_dispatchMessage(data) {
|
|
4369
|
+
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
4370
|
+
}
|
|
4371
|
+
_onPing(hb) {
|
|
4372
|
+
this._post({ t: "q" });
|
|
4373
|
+
this._lastPing = Date.now();
|
|
4374
|
+
if (hb !== this._heartbeatMs) {
|
|
4375
|
+
this._heartbeatMs = hb;
|
|
4376
|
+
this._watchHeartbeat();
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
_onClosed() {
|
|
4380
|
+
if (this._watch !== void 0) this._timers.clearInterval(this._watch);
|
|
4381
|
+
this._watch = void 0;
|
|
4382
|
+
}
|
|
4383
|
+
_watchHeartbeat() {
|
|
4384
|
+
if (this._watch !== void 0) this._timers.clearInterval(this._watch);
|
|
4385
|
+
this._watch = this._timers.setInterval(() => {
|
|
4386
|
+
if (Date.now() - this._lastPing > 3 * this._heartbeatMs) this._finish(1006, "", false, true);
|
|
4387
|
+
}, this._heartbeatMs);
|
|
4388
|
+
}
|
|
4389
|
+
};
|
|
4390
|
+
/** Codes an endpoint may put in a close frame (RFC 6455 §7.4). */
|
|
4391
|
+
function isSendableCloseCode(code) {
|
|
4392
|
+
if (!Number.isInteger(code)) return false;
|
|
4393
|
+
if (code >= 3e3 && code <= 4999) return true;
|
|
4394
|
+
return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006;
|
|
4395
|
+
}
|
|
4396
|
+
//#endregion
|
|
4397
|
+
//#region src/ws/upgrade.ts
|
|
4398
|
+
/**
|
|
4399
|
+
* The upgrade, as an HTTP exchange: a `GET` with `Upgrade: websocket` goes to
|
|
4400
|
+
* an ordinary `(Request) => Response` handler, and a `101` answer carrying a
|
|
4401
|
+
* server socket means accepted. Anything else is a refusal, with its status.
|
|
4402
|
+
*
|
|
4403
|
+
* FORBIDDEN HEADERS. A browser drops `Upgrade`, `Connection` and every
|
|
4404
|
+
* `Sec-*` header from a `new Request()`. The upgrade request therefore carries
|
|
4405
|
+
* its headers as an own `headers` property, a standalone `Headers` that keeps
|
|
4406
|
+
* them, so handler code reads `request.headers.get("upgrade")` as usual.
|
|
4407
|
+
*
|
|
4408
|
+
* NO 101 IN A `Response`. The constructor refuses statuses below 200, so the
|
|
4409
|
+
* response `upgradeWebSocket` returns reports 101 through an own `status`
|
|
4410
|
+
* property; the port that goes back to the caller is found with `takePort`.
|
|
4411
|
+
*/
|
|
4412
|
+
/** The request header carrying the client's version of the frame protocol. */
|
|
4413
|
+
const WS_VERSION_HEADER = "x-webrun-ws-version";
|
|
4414
|
+
/**
|
|
4415
|
+
* The `GET` a handler sees for `new WebSocket(url, protocols)`. A `ws:` or
|
|
4416
|
+
* `wss:` url is given as `http:` or `https:`, as a server sees it.
|
|
4417
|
+
*/
|
|
4418
|
+
function newWebSocketUpgradeRequest(url, { protocols = [], headers } = {}) {
|
|
4419
|
+
const httpUrl = new URL(`${url}`);
|
|
4420
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
4421
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
4422
|
+
const all = new Headers(headers);
|
|
4423
|
+
all.set("upgrade", "websocket");
|
|
4424
|
+
all.set("connection", "Upgrade");
|
|
4425
|
+
all.set("sec-websocket-version", "13");
|
|
4426
|
+
if (!all.has("sec-websocket-key")) all.set("sec-websocket-key", randomKey());
|
|
4427
|
+
if (protocols.length > 0) all.set("sec-websocket-protocol", protocols.join(", "));
|
|
4428
|
+
if (!all.has("x-webrun-ws-version")) all.set(WS_VERSION_HEADER, `2`);
|
|
4429
|
+
return withHeaders(new Request(httpUrl, {
|
|
4430
|
+
method: "GET",
|
|
4431
|
+
headers: all
|
|
4432
|
+
}), all);
|
|
4433
|
+
}
|
|
4434
|
+
/**
|
|
4435
|
+
* Re-attaches `headers` to `request` as its own `headers` property, keeping
|
|
4436
|
+
* the forbidden ones a browser dropped. Returns `request`.
|
|
4437
|
+
*/
|
|
4438
|
+
function withHeaders(request, headers) {
|
|
4439
|
+
Object.defineProperty(request, "headers", {
|
|
4440
|
+
value: headers,
|
|
4441
|
+
configurable: true
|
|
4442
|
+
});
|
|
4443
|
+
return request;
|
|
4444
|
+
}
|
|
4445
|
+
/** Whether `request` asks for a WebSocket. */
|
|
4446
|
+
function isWebSocketUpgrade(request) {
|
|
4447
|
+
return request.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
4448
|
+
}
|
|
4449
|
+
/** The subprotocols `request` asks for, in order of preference. */
|
|
4450
|
+
function requestedProtocols(request) {
|
|
4451
|
+
const header = request.headers.get("sec-websocket-protocol");
|
|
4452
|
+
if (!header) return [];
|
|
4453
|
+
return header.split(",").map((protocol) => protocol.trim()).filter((protocol) => protocol !== "");
|
|
4454
|
+
}
|
|
4455
|
+
/**
|
|
4456
|
+
* Where a response from `upgradeWebSocket` keeps its port. A registered
|
|
4457
|
+
* symbol, not a module-level `WeakMap`: the handler and the host that takes
|
|
4458
|
+
* the port often run different bundles of this package (a page's adapter from
|
|
4459
|
+
* `dist/sw.js`, its handler code importing `dist/worker.js`), and each bundle
|
|
4460
|
+
* has its own copy of every module.
|
|
4461
|
+
*/
|
|
4462
|
+
const UPGRADE = Symbol.for("webrun-http-browser:websocket-upgrade");
|
|
4463
|
+
/**
|
|
4464
|
+
* Accepts a WebSocket upgrade in a handler:
|
|
4465
|
+
*
|
|
4466
|
+
* ```ts
|
|
4467
|
+
* if (isWebSocketUpgrade(request)) {
|
|
4468
|
+
* const { socket, response } = upgradeWebSocket(request, { protocol: "v1" });
|
|
4469
|
+
* socket.accept();
|
|
4470
|
+
* socket.addEventListener("message", (event) => socket.send(event.data));
|
|
4471
|
+
* return response;
|
|
4472
|
+
* }
|
|
4473
|
+
* ```
|
|
4474
|
+
*
|
|
4475
|
+
* The host takes the client's port from the response with `takePort` and
|
|
4476
|
+
* hands it to the caller.
|
|
4477
|
+
*/
|
|
4478
|
+
function upgradeWebSocket(request, options = {}) {
|
|
4479
|
+
const protocol = options.protocol ?? "";
|
|
4480
|
+
const channel = new MessageChannel();
|
|
4481
|
+
const socket = new ServerWebSocket(channel.port1, {
|
|
4482
|
+
...options,
|
|
4483
|
+
url: request.url,
|
|
4484
|
+
protocol
|
|
4485
|
+
});
|
|
4486
|
+
const response = new Response(null, {
|
|
4487
|
+
status: 200,
|
|
4488
|
+
headers: protocol ? { "sec-websocket-protocol": protocol } : {}
|
|
4489
|
+
});
|
|
4490
|
+
Object.defineProperties(response, {
|
|
4491
|
+
status: {
|
|
4492
|
+
value: 101,
|
|
4493
|
+
configurable: true
|
|
4494
|
+
},
|
|
4495
|
+
statusText: {
|
|
4496
|
+
value: "Switching Protocols",
|
|
4497
|
+
configurable: true
|
|
4498
|
+
},
|
|
4499
|
+
webSocket: {
|
|
4500
|
+
value: socket,
|
|
4501
|
+
configurable: true
|
|
4502
|
+
},
|
|
4503
|
+
[UPGRADE]: {
|
|
4504
|
+
value: {
|
|
4505
|
+
port: channel.port2,
|
|
4506
|
+
protocol
|
|
4507
|
+
},
|
|
4508
|
+
configurable: true,
|
|
4509
|
+
writable: true
|
|
4510
|
+
}
|
|
4511
|
+
});
|
|
4512
|
+
return {
|
|
4513
|
+
socket,
|
|
4514
|
+
response
|
|
4515
|
+
};
|
|
4516
|
+
}
|
|
4517
|
+
/**
|
|
4518
|
+
* The port to hand to the caller, for a response from `upgradeWebSocket`.
|
|
4519
|
+
* Taken once: a second call returns `undefined`.
|
|
4520
|
+
*/
|
|
4521
|
+
function takePort(response) {
|
|
4522
|
+
return takeUpgrade(response)?.port;
|
|
4523
|
+
}
|
|
4524
|
+
/** `takePort`, with the subprotocol the server picked. */
|
|
4525
|
+
function takeUpgrade(response) {
|
|
4526
|
+
const holder = response;
|
|
4527
|
+
const upgrade = holder[UPGRADE];
|
|
4528
|
+
if (upgrade) holder[UPGRADE] = void 0;
|
|
4529
|
+
return upgrade;
|
|
4530
|
+
}
|
|
4531
|
+
/**
|
|
4532
|
+
* Runs an upgrade through `handler`, as a host does when a caller asks for a
|
|
4533
|
+
* socket: builds the upgrade request, calls the handler, and either takes the
|
|
4534
|
+
* port of a `101` or reports the refusal. A subprotocol the caller did not ask
|
|
4535
|
+
* for is a refusal, as in the standard.
|
|
4536
|
+
*/
|
|
4537
|
+
async function serveWebSocketUpgrade(handler, { url, protocols = [], headers }) {
|
|
4538
|
+
let response;
|
|
4539
|
+
try {
|
|
4540
|
+
response = await handler(newWebSocketUpgradeRequest(url, {
|
|
4541
|
+
protocols,
|
|
4542
|
+
headers
|
|
4543
|
+
}));
|
|
4544
|
+
} catch (error) {
|
|
4545
|
+
return {
|
|
4546
|
+
ok: false,
|
|
4547
|
+
status: 500,
|
|
4548
|
+
message: errorMessage(error)
|
|
4549
|
+
};
|
|
4550
|
+
}
|
|
4551
|
+
const upgrade = takeUpgrade(response);
|
|
4552
|
+
if (!upgrade || response.status !== 101) {
|
|
4553
|
+
upgrade?.port.close();
|
|
4554
|
+
try {
|
|
4555
|
+
await response.body?.cancel();
|
|
4556
|
+
} catch {}
|
|
4557
|
+
return {
|
|
4558
|
+
ok: false,
|
|
4559
|
+
status: response.status,
|
|
4560
|
+
message: `The server refused the upgrade: ${response.status} ${response.statusText}`.trim()
|
|
4561
|
+
};
|
|
4562
|
+
}
|
|
4563
|
+
if (upgrade.protocol !== "" && !protocols.includes(upgrade.protocol)) {
|
|
4564
|
+
upgrade.port.close();
|
|
4565
|
+
return {
|
|
4566
|
+
ok: false,
|
|
4567
|
+
status: 400,
|
|
4568
|
+
message: `The server picked the subprotocol '${upgrade.protocol}', which was not requested.`
|
|
4569
|
+
};
|
|
4570
|
+
}
|
|
4571
|
+
return {
|
|
4572
|
+
ok: true,
|
|
4573
|
+
port: upgrade.port,
|
|
4574
|
+
protocol: upgrade.protocol
|
|
4575
|
+
};
|
|
4576
|
+
}
|
|
4577
|
+
function randomKey() {
|
|
4578
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
4579
|
+
crypto.getRandomValues(bytes);
|
|
4580
|
+
return btoa(String.fromCharCode(...bytes));
|
|
4581
|
+
}
|
|
4582
|
+
//#endregion
|
|
4583
|
+
//#region src/relay/split-service-url.ts
|
|
4584
|
+
/**
|
|
4585
|
+
* Splits a URL of the form `<base>/<separator><key>/<path>` into parts.
|
|
4586
|
+
* Example: `https://host/~FS/a/b` → `{ baseUrl: "https://host/~FS/", key: "FS", path: "a/b" }`.
|
|
4587
|
+
*/
|
|
4588
|
+
function splitServiceUrl(url, separator = "~") {
|
|
4589
|
+
const str = `${url}`;
|
|
4590
|
+
const empty = {
|
|
4591
|
+
url: str,
|
|
4592
|
+
key: "",
|
|
4593
|
+
baseUrl: "",
|
|
4594
|
+
path: ""
|
|
4595
|
+
};
|
|
4596
|
+
const hashIdx = str.indexOf("#");
|
|
4597
|
+
const queryIdx = str.indexOf("?");
|
|
4598
|
+
let strippedEnd = str.length;
|
|
4599
|
+
if (hashIdx >= 0) strippedEnd = Math.min(strippedEnd, hashIdx);
|
|
4600
|
+
if (queryIdx >= 0) strippedEnd = Math.min(strippedEnd, queryIdx);
|
|
4601
|
+
const stripped = str.slice(0, strippedEnd);
|
|
4602
|
+
let prefixEnd = 0;
|
|
4603
|
+
const schemeMatch = stripped.match(/^[a-zA-Z][a-zA-Z0-9+\-.]*:\/\//);
|
|
4604
|
+
if (schemeMatch) {
|
|
4605
|
+
prefixEnd = schemeMatch[0].length;
|
|
4606
|
+
const slashIdx = stripped.indexOf("/", prefixEnd);
|
|
4607
|
+
if (slashIdx >= 0) prefixEnd = slashIdx;
|
|
4608
|
+
else return empty;
|
|
4609
|
+
} else if (stripped.startsWith("//")) {
|
|
4610
|
+
prefixEnd = 2;
|
|
4611
|
+
const slashIdx = stripped.indexOf("/", prefixEnd);
|
|
4612
|
+
if (slashIdx >= 0) prefixEnd = slashIdx;
|
|
4613
|
+
else return empty;
|
|
4614
|
+
}
|
|
4615
|
+
const prefix = stripped.slice(0, prefixEnd);
|
|
4616
|
+
const pathPart = stripped.slice(prefixEnd);
|
|
4617
|
+
let keyStart;
|
|
4618
|
+
let rooted = false;
|
|
4619
|
+
if (prefix === "") {
|
|
4620
|
+
if (pathPart.startsWith(`/${separator}`)) {
|
|
4621
|
+
rooted = true;
|
|
4622
|
+
keyStart = separator.length + 1;
|
|
4623
|
+
} else if (pathPart.startsWith(separator)) keyStart = separator.length;
|
|
4624
|
+
else return empty;
|
|
4625
|
+
} else {
|
|
4626
|
+
if (!pathPart.startsWith(`/${separator}`)) return empty;
|
|
4627
|
+
keyStart = separator.length + 1;
|
|
4628
|
+
}
|
|
4629
|
+
const rest = pathPart.slice(keyStart);
|
|
4630
|
+
const slash = rest.indexOf("/");
|
|
4631
|
+
const key = slash < 0 ? rest : rest.slice(0, slash);
|
|
4632
|
+
if (key === "") return empty;
|
|
4633
|
+
return {
|
|
4634
|
+
url: str,
|
|
4635
|
+
key,
|
|
4636
|
+
baseUrl: `${prefix === "" ? rooted ? "/" : "" : `${prefix}/`}${separator}${key}${slash < 0 ? "" : "/"}`,
|
|
4637
|
+
path: slash < 0 ? "" : rest.slice(slash + 1)
|
|
4638
|
+
};
|
|
4639
|
+
}
|
|
4640
|
+
//#endregion
|
|
4641
|
+
//#region src/relay/index.ts
|
|
4642
|
+
/**
|
|
4643
|
+
* The URL of this module, kept in a variable on purpose. Bundlers (Vite
|
|
4644
|
+
* among them) rewrite every literal `new URL("<path>", import.meta.url)` into
|
|
4645
|
+
* an emitted asset at build time, before tree-shaking — so the defaults below
|
|
4646
|
+
* made every Vite consumer of this entry emit a dead copy of the package's
|
|
4647
|
+
* own `dist/index.js` (`"../"` resolves to the package, hence to its `main`).
|
|
4648
|
+
* Resolving against a variable is the same URL at run time and invisible to
|
|
4649
|
+
* that transform.
|
|
4650
|
+
*/
|
|
4651
|
+
const moduleUrl = import.meta.url;
|
|
4652
|
+
/**
|
|
4653
|
+
* Returns a MessagePort that transparently bridges messages to/from the
|
|
4654
|
+
* page's ServiceWorker: the one controlling the page, or — when the page is
|
|
4655
|
+
* not controlled (a hard reload, or a page Firefox left uncontrolled) — the
|
|
4656
|
+
* active worker of `registration`, which answers messages all the same.
|
|
4657
|
+
*/
|
|
4658
|
+
function newServiceWorkerPort(registration) {
|
|
4659
|
+
const channel = new MessageChannel();
|
|
4660
|
+
channel.port1.onmessage = (event) => {
|
|
4661
|
+
(navigator.serviceWorker.controller ?? registration?.active)?.postMessage(event.data, [...event.ports]);
|
|
4662
|
+
};
|
|
4663
|
+
navigator.serviceWorker.addEventListener("message", (event) => {
|
|
4664
|
+
channel.port1.postMessage(event.data, [...event.ports]);
|
|
4665
|
+
});
|
|
4666
|
+
return channel.port2;
|
|
4667
|
+
}
|
|
4668
|
+
/**
|
|
4669
|
+
* Registers a ServiceWorker and resolves with it once it is activated: the
|
|
4670
|
+
* worker controlling the page, or the registration's active worker when the
|
|
4671
|
+
* page is not controlled. Messaging works either way, which is all the relay
|
|
4672
|
+
* needs; nothing here waits for control, because an uncontrolled page (hard
|
|
4673
|
+
* reload; Firefox) may never get it. Rejects with a
|
|
4674
|
+
* `ServiceWorkerControlError` if activation takes longer than `timeout`.
|
|
4675
|
+
*/
|
|
4676
|
+
async function initServiceWorker(options) {
|
|
4677
|
+
return (await registerServiceWorker(options)).worker;
|
|
4678
|
+
}
|
|
4679
|
+
async function registerServiceWorker({ swUrl, scopeUrl, type, timeout = DEFAULT_SERVICE_WORKER_TIMEOUT }) {
|
|
4680
|
+
const registration = await navigator.serviceWorker.register(swUrl, {
|
|
4681
|
+
type,
|
|
4682
|
+
scope: scopeUrl
|
|
4683
|
+
});
|
|
4684
|
+
const active = await awaitActiveServiceWorker(registration, { timeout });
|
|
4685
|
+
return {
|
|
4686
|
+
registration,
|
|
4687
|
+
worker: navigator.serviceWorker.controller ?? active
|
|
4688
|
+
};
|
|
4689
|
+
}
|
|
4690
|
+
/**
|
|
4691
|
+
* Serves a service's side of one `CONNECT`: an HTTP link on `callPort`, or a
|
|
4692
|
+
* WebSocket upgrade run through `handler`.
|
|
4693
|
+
*/
|
|
4694
|
+
async function answerConnect(handler, data, callPort, options = {}) {
|
|
4695
|
+
const params = data ?? {};
|
|
4696
|
+
if (params.type === "ws") {
|
|
4697
|
+
callPort?.close();
|
|
4698
|
+
const { url, protocols = [], headers } = params;
|
|
4699
|
+
const result = await serveWebSocketUpgrade(handler, {
|
|
4700
|
+
url,
|
|
4701
|
+
protocols,
|
|
4702
|
+
headers
|
|
4703
|
+
});
|
|
4704
|
+
if (!result.ok) throw new Error(result.message);
|
|
4705
|
+
return withTransfer({
|
|
4706
|
+
port: result.port,
|
|
4707
|
+
protocol: result.protocol
|
|
4708
|
+
}, [result.port]);
|
|
4709
|
+
}
|
|
4710
|
+
if (!callPort) throw new Error("A CONNECT for HTTP carries a port");
|
|
4711
|
+
if (params.wire === "webrun-http-link/2") {
|
|
4712
|
+
await serveHttpLink(callPort, handler, options);
|
|
4713
|
+
return {
|
|
4714
|
+
accepted: true,
|
|
4715
|
+
wire: HTTP_LINK_PROTOCOL
|
|
4716
|
+
};
|
|
4717
|
+
}
|
|
4718
|
+
handleHttpRequests(callPort, handler);
|
|
4719
|
+
return true;
|
|
4720
|
+
}
|
|
4721
|
+
/**
|
|
4722
|
+
* Registers `handler` as the server for the given service `key` on the relay:
|
|
4723
|
+
* it answers HTTP requests and WebSocket upgrades. Returns a function that
|
|
4724
|
+
* unregisters the service; its promise settles once the relay acknowledged.
|
|
4725
|
+
*/
|
|
4726
|
+
async function initHttpService(handler, { key, path, port, streamTimeout }) {
|
|
4727
|
+
return await registerConnectionsHandler({
|
|
4728
|
+
key,
|
|
4729
|
+
path,
|
|
4730
|
+
communicationPort: port,
|
|
4731
|
+
handler: (_event, data, callPort) => answerConnect(handler, data, callPort, { streamTimeout })
|
|
4732
|
+
});
|
|
4733
|
+
}
|
|
4734
|
+
/**
|
|
4735
|
+
* Sends a `Request` to the service registered under `key` on the relay and
|
|
4736
|
+
* resolves with the corresponding `Response`, whose body streams with
|
|
4737
|
+
* backpressure.
|
|
4738
|
+
*/
|
|
4739
|
+
async function callHttpService(request, { key, port, streamTimeout }) {
|
|
4740
|
+
const channel = new MessageChannel();
|
|
4741
|
+
const reply = await callChannel(port, "CONNECT", {
|
|
4742
|
+
key,
|
|
4743
|
+
type: "http",
|
|
4744
|
+
wire: HTTP_LINK_PROTOCOL
|
|
4745
|
+
}, channel.port2);
|
|
4746
|
+
if (!reply) {
|
|
4747
|
+
channel.port1.close();
|
|
4748
|
+
throw new Error(`No service with key "${key}"`);
|
|
4749
|
+
}
|
|
4750
|
+
return await sendOverConnection(channel.port1, reply, request, { streamTimeout });
|
|
4751
|
+
}
|
|
4752
|
+
/**
|
|
4753
|
+
* Sends `request` on a port a service accepted with `reply`: over an HTTP link
|
|
4754
|
+
* when the service speaks `HTTP_LINK_PROTOCOL`, over version 1's transport
|
|
4755
|
+
* when it answered `true`. The link is closed once the response is done.
|
|
4756
|
+
*/
|
|
4757
|
+
async function sendOverConnection(port, reply, request, options = {}) {
|
|
4758
|
+
if (reply === true) return await sendHttpRequest(port, request);
|
|
4759
|
+
const link = await connectHttpLink(port, options);
|
|
4760
|
+
try {
|
|
4761
|
+
const response = await link.send(request);
|
|
4762
|
+
link.whenIdle().then(() => link.close());
|
|
4763
|
+
return response;
|
|
4764
|
+
} catch (error) {
|
|
4765
|
+
await link.close();
|
|
4766
|
+
throw error;
|
|
4767
|
+
}
|
|
4768
|
+
}
|
|
4769
|
+
/**
|
|
4770
|
+
* Opens the transport of a socket to the service registered under `key` on
|
|
4771
|
+
* the relay: the service runs the upgrade through its handler, and the
|
|
4772
|
+
* socket's port comes back through the relay. After that, the socket runs
|
|
4773
|
+
* between the caller and the service directly.
|
|
4774
|
+
*/
|
|
4775
|
+
async function callWebSocketService(url, protocols, { key, port, timeout = 15e3 }) {
|
|
4776
|
+
const httpUrl = new URL(`${url}`, globalThis.location?.href);
|
|
4777
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
4778
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
4779
|
+
const channel = new MessageChannel();
|
|
4780
|
+
try {
|
|
4781
|
+
const connection = await callChannelWithin(timeout, port, "CONNECT", {
|
|
4782
|
+
type: "ws",
|
|
4783
|
+
key,
|
|
4784
|
+
url: `${httpUrl}`,
|
|
4785
|
+
protocols
|
|
4786
|
+
}, channel.port2);
|
|
4787
|
+
if (!(connection?.port instanceof MessagePort)) throw new Error(`The service "${key}" does not accept WebSockets (an older version?)`);
|
|
4788
|
+
return {
|
|
4789
|
+
port: connection.port,
|
|
4790
|
+
protocol: connection.protocol ?? ""
|
|
4791
|
+
};
|
|
4792
|
+
} finally {
|
|
4793
|
+
channel.port1.close();
|
|
4794
|
+
}
|
|
4795
|
+
}
|
|
4796
|
+
/**
|
|
4797
|
+
* A WHATWG `WebSocket` class whose sockets reach the service registered under
|
|
4798
|
+
* `key` on the relay.
|
|
4799
|
+
*/
|
|
4800
|
+
function relayWebSocketClass(service, options) {
|
|
4801
|
+
return createWebSocketClass((url, protocols) => callWebSocketService(url, protocols, service), options);
|
|
4802
|
+
}
|
|
4803
|
+
/**
|
|
4804
|
+
* Returns a `window.onmessage` handler for use inside the relay iframe:
|
|
4805
|
+
* it accepts a CONNECT message, starts the relay ServiceWorker, and bridges
|
|
4806
|
+
* the parent's MessagePort with the SW. If the worker cannot be started, every
|
|
4807
|
+
* call the parent makes on that port is answered with the error, so the
|
|
4808
|
+
* parent's `initHttpService` / `callHttpService` reject instead of waiting.
|
|
4809
|
+
*/
|
|
4810
|
+
function getRelayWindowMessageHandler({ swUrl = `${new URL("./relay-sw.js", moduleUrl)}`, scopeUrl = `${new URL("./", moduleUrl)}`, timeout } = {}) {
|
|
4811
|
+
let externalPort;
|
|
4812
|
+
return async (ev) => {
|
|
2800
4813
|
if (ev.data?.type !== "CONNECT") return;
|
|
2801
4814
|
const newExternalPort = ev.ports?.[0];
|
|
2802
4815
|
if (!newExternalPort) return;
|
|
@@ -2804,141 +4817,1769 @@ function getRelayWindowMessageHandler({ swUrl = `${new URL("./index-sw.js", modu
|
|
|
2804
4817
|
newExternalPort.close();
|
|
2805
4818
|
return;
|
|
2806
4819
|
}
|
|
2807
|
-
externalPort = newExternalPort;
|
|
2808
|
-
let registration;
|
|
4820
|
+
externalPort = newExternalPort;
|
|
4821
|
+
let registration;
|
|
4822
|
+
try {
|
|
4823
|
+
({registration} = await registerServiceWorker({
|
|
4824
|
+
swUrl,
|
|
4825
|
+
scopeUrl,
|
|
4826
|
+
timeout
|
|
4827
|
+
}));
|
|
4828
|
+
} catch (error) {
|
|
4829
|
+
const serialized = serializeError(error);
|
|
4830
|
+
externalPort.onmessage = (event) => event.ports[0]?.postMessage({ error: serialized });
|
|
4831
|
+
throw error;
|
|
4832
|
+
}
|
|
4833
|
+
const serviceWorkerPort = newServiceWorkerPort(registration);
|
|
4834
|
+
serviceWorkerPort.onmessage = (event) => {
|
|
4835
|
+
externalPort?.postMessage(event.data, [...event.ports]);
|
|
4836
|
+
};
|
|
4837
|
+
externalPort.onmessage = (event) => {
|
|
4838
|
+
serviceWorkerPort.postMessage(event.data, [...event.ports]);
|
|
4839
|
+
};
|
|
4840
|
+
};
|
|
4841
|
+
}
|
|
4842
|
+
/**
|
|
4843
|
+
* Embeds a hidden relay iframe, establishes a MessageChannel with it, and
|
|
4844
|
+
* returns the port to be used with `initHttpService` / `callHttpService`.
|
|
4845
|
+
*/
|
|
4846
|
+
async function newRemoteRelayChannel({ baseUrl = new URL("../public-relay/", moduleUrl), url = new URL("relay.html", baseUrl), container = document.body } = {}) {
|
|
4847
|
+
const messageChannel = new MessageChannel();
|
|
4848
|
+
const { iframe, promise } = newIFrame(url);
|
|
4849
|
+
Object.assign(iframe.style, {
|
|
4850
|
+
position: "fixed",
|
|
4851
|
+
width: "1px",
|
|
4852
|
+
height: "1px",
|
|
4853
|
+
top: "-1000px",
|
|
4854
|
+
left: "-1000px",
|
|
4855
|
+
display: "block",
|
|
4856
|
+
opacity: "0",
|
|
4857
|
+
border: "none",
|
|
4858
|
+
outline: "none"
|
|
4859
|
+
});
|
|
4860
|
+
container.appendChild(iframe);
|
|
4861
|
+
promise.then(() => {
|
|
4862
|
+
iframe.contentWindow?.postMessage({ type: "CONNECT" }, "*", [messageChannel.port1]);
|
|
4863
|
+
});
|
|
4864
|
+
return {
|
|
4865
|
+
baseUrl,
|
|
4866
|
+
port: messageChannel.port2,
|
|
4867
|
+
close: () => {
|
|
4868
|
+
iframe.parentElement?.removeChild(iframe);
|
|
4869
|
+
messageChannel.port1.close();
|
|
4870
|
+
messageChannel.port2.close();
|
|
4871
|
+
}
|
|
4872
|
+
};
|
|
4873
|
+
function newIFrame(src) {
|
|
4874
|
+
const iframe = document.createElement("iframe");
|
|
4875
|
+
iframe.src = `${src}`;
|
|
4876
|
+
Object.assign(iframe.style, {
|
|
4877
|
+
padding: "0",
|
|
4878
|
+
margin: "0",
|
|
4879
|
+
border: "none",
|
|
4880
|
+
outline: "none",
|
|
4881
|
+
width: "100%",
|
|
4882
|
+
height: "100%"
|
|
4883
|
+
});
|
|
4884
|
+
return {
|
|
4885
|
+
iframe,
|
|
4886
|
+
promise: new Promise((resolve, reject) => {
|
|
4887
|
+
iframe.onerror = () => reject(/* @__PURE__ */ new Error(`Failed to load ${src}`));
|
|
4888
|
+
iframe.onload = () => resolve(iframe);
|
|
4889
|
+
})
|
|
4890
|
+
};
|
|
4891
|
+
}
|
|
4892
|
+
}
|
|
4893
|
+
async function initializeConnection({ key, communicationPort, ...options }) {
|
|
4894
|
+
const channel = new MessageChannel();
|
|
4895
|
+
if (!await callChannel(communicationPort, "CONNECT", {
|
|
4896
|
+
key,
|
|
4897
|
+
...options
|
|
4898
|
+
}, channel.port2)) {
|
|
4899
|
+
channel.port1.close();
|
|
4900
|
+
channel.port2.close();
|
|
4901
|
+
return null;
|
|
4902
|
+
}
|
|
4903
|
+
return channel.port1;
|
|
4904
|
+
}
|
|
4905
|
+
/**
|
|
4906
|
+
* Registers `key` on the relay and answers its `CONNECT`s with `handler`.
|
|
4907
|
+
* Resolves with a function that unregisters it. That function's promise
|
|
4908
|
+
* settles once the relay acknowledged the `UNREGISTER`, so a caller can stop
|
|
4909
|
+
* its services and only then close the connection: closing first tore the
|
|
4910
|
+
* ports down before the message landed, and left the mount behind.
|
|
4911
|
+
*/
|
|
4912
|
+
async function registerConnectionsHandler({ key, path, handler, communicationPort }) {
|
|
4913
|
+
await callChannel(communicationPort, "REGISTER", path == null ? { key } : {
|
|
4914
|
+
key,
|
|
4915
|
+
path
|
|
4916
|
+
});
|
|
4917
|
+
const stopAnswering = handleKeyedChannelCalls(communicationPort, "CONNECT", key, async (event, data, port) => await handler(event, data, port));
|
|
4918
|
+
let stopped;
|
|
4919
|
+
return () => {
|
|
4920
|
+
stopped ??= (async () => {
|
|
4921
|
+
try {
|
|
4922
|
+
await callChannel(communicationPort, "UNREGISTER", { key });
|
|
4923
|
+
} catch (error) {
|
|
4924
|
+
console.warn(`[relay] UNREGISTER of "${key}" failed`, error);
|
|
4925
|
+
} finally {
|
|
4926
|
+
stopAnswering();
|
|
4927
|
+
}
|
|
4928
|
+
})();
|
|
4929
|
+
return stopped;
|
|
4930
|
+
};
|
|
4931
|
+
}
|
|
4932
|
+
/**
|
|
4933
|
+
* `handleChannelCalls`, but only for calls whose `params.key` is `key`.
|
|
4934
|
+
*
|
|
4935
|
+
* ONE CONNECTION CARRIES SEVERAL SERVICES — an app at `/` and a mesh gateway
|
|
4936
|
+
* at `/peers/` over one relay iframe is the shape mounts exist for. Plain
|
|
4937
|
+
* `handleChannelCalls` cannot do that: every listener it has for a call type
|
|
4938
|
+
* runs on every message, and each is handed the SAME reply port and the SAME
|
|
4939
|
+
* transferred stream port. Two services then both serve the one channel the
|
|
4940
|
+
* worker is reading, and its response comes back with both bodies in it.
|
|
4941
|
+
*
|
|
4942
|
+
* WHY NOT A FILTER INSIDE THE HANDLER. Returning `false` for a foreign key
|
|
4943
|
+
* does not help: `handleChannelCalls` still replies, `callChannel` resolves on
|
|
4944
|
+
* the FIRST reply it receives, and the loser's `false` reaches the worker as
|
|
4945
|
+
* "the client refused" — a 403, non-deterministically. A service that is not
|
|
4946
|
+
* the addressee must stay SILENT and leave the transferred port untouched.
|
|
4947
|
+
*
|
|
4948
|
+
* Local to this module on purpose. `handleChannelCalls` is also used where a
|
|
4949
|
+
* call carries no key (REGISTER/UNREGISTER, and the worker's own CONNECT in
|
|
4950
|
+
* `index-sw.ts`, which is the other direction), so its semantics must not
|
|
4951
|
+
* change.
|
|
4952
|
+
*/
|
|
4953
|
+
function handleKeyedChannelCalls(target, callType, key, handler) {
|
|
4954
|
+
const listener = async (event) => {
|
|
4955
|
+
const data = event.data;
|
|
4956
|
+
if (!data || data.type !== callType) return;
|
|
4957
|
+
if (data.params?.key !== key) return;
|
|
4958
|
+
const [port, ...transfers] = event.ports ?? [];
|
|
4959
|
+
const response = {};
|
|
4960
|
+
let transfer = [];
|
|
4961
|
+
try {
|
|
4962
|
+
const result = await handler(event, data.params, ...transfers);
|
|
4963
|
+
({value: response.result, transfer} = unwrapTransfer(result));
|
|
4964
|
+
} catch (error) {
|
|
4965
|
+
response.error = serializeError(error);
|
|
4966
|
+
}
|
|
4967
|
+
port?.postMessage(response, transfer);
|
|
4968
|
+
};
|
|
4969
|
+
target.addEventListener("message", listener);
|
|
4970
|
+
target.start?.();
|
|
4971
|
+
return () => target.removeEventListener("message", listener);
|
|
4972
|
+
}
|
|
4973
|
+
//#endregion
|
|
4974
|
+
//#region src/sw/handler-endpoint.ts
|
|
4975
|
+
/** The message calls through a lost ServiceWorker fail with. */
|
|
4976
|
+
const ROUTER_LOST_MESSAGE = "The ServiceWorker was lost while this call was in flight";
|
|
4977
|
+
/**
|
|
4978
|
+
* The handler's end of its links to the ServiceWorker, the same in a page and
|
|
4979
|
+
* in a Dedicated Worker.
|
|
4980
|
+
*
|
|
4981
|
+
* - Serves `handler` on each link's `down` port, and answers WebSocket
|
|
4982
|
+
* upgrades arriving on its `ctl` port by running them through `handler`.
|
|
4983
|
+
* - Sends requests through the router on `up` (`fetch`) and opens sockets to
|
|
4984
|
+
* other handlers over `ctl` (`connectWebSocket`).
|
|
4985
|
+
* - Watches the ServiceWorker's router lock. When the ServiceWorker dies, the
|
|
4986
|
+
* links made for it are dropped: calls in flight on them fail with
|
|
4987
|
+
* `LinkLostError` ("may or may not have been applied") instead of hanging,
|
|
4988
|
+
* and new calls wait for a link, asking for one (`requestRelink`) every
|
|
4989
|
+
* `relinkRetryMs` until it comes.
|
|
4990
|
+
* - While calls are in flight, calls `keepAlive` every `keepAliveMs`: port
|
|
4991
|
+
* messages are not events, so without it the browser may stop the
|
|
4992
|
+
* ServiceWorker in the middle of a long call.
|
|
4993
|
+
*/
|
|
4994
|
+
var HandlerEndpoint = class {
|
|
4995
|
+
handler;
|
|
4996
|
+
options;
|
|
4997
|
+
_links = /* @__PURE__ */ new Set();
|
|
4998
|
+
_waiters = [];
|
|
4999
|
+
_sockets = new PortRendezvous("o");
|
|
5000
|
+
_keepAliveTimer;
|
|
5001
|
+
_closed = false;
|
|
5002
|
+
constructor(handler, options = {}) {
|
|
5003
|
+
this.handler = handler;
|
|
5004
|
+
this.options = options;
|
|
5005
|
+
}
|
|
5006
|
+
/** Whether any link is live. */
|
|
5007
|
+
get linked() {
|
|
5008
|
+
return this._links.size > 0;
|
|
5009
|
+
}
|
|
5010
|
+
/** Installs a fresh link made for the router holding `routerLock`. */
|
|
5011
|
+
async link(key, ports, routerLock) {
|
|
5012
|
+
if (this._closed) {
|
|
5013
|
+
for (const port of Object.values(ports)) port?.close();
|
|
5014
|
+
return;
|
|
5015
|
+
}
|
|
5016
|
+
const closeDown = await serveHttpLink(ports.down, this.handler, this.options);
|
|
5017
|
+
const up = ports.up ? await connectHttpLink(ports.up, this.options) : void 0;
|
|
5018
|
+
const link = {
|
|
5019
|
+
key,
|
|
5020
|
+
routerLock,
|
|
5021
|
+
ctl: ports.ctl,
|
|
5022
|
+
up,
|
|
5023
|
+
closeDown,
|
|
5024
|
+
stopWatch: () => {}
|
|
5025
|
+
};
|
|
5026
|
+
if (ports.ctl) ports.ctl.onmessage = (event) => this._onControl(link, event.data);
|
|
5027
|
+
if (routerLock) link.stopWatch = watchLock(routerLock, () => this._routerLost(routerLock));
|
|
5028
|
+
for (const old of [...this._links]) {
|
|
5029
|
+
if (old.key !== key) continue;
|
|
5030
|
+
if (old.routerLock !== routerLock) this._drop(old, new LinkLostError(ROUTER_LOST_MESSAGE));
|
|
5031
|
+
else if (!old.superseded) {
|
|
5032
|
+
old.superseded = true;
|
|
5033
|
+
setTimeout(() => void this._drop(old), this.options.supersededLinkMs ?? 3e4);
|
|
5034
|
+
}
|
|
5035
|
+
}
|
|
5036
|
+
this._links.add(link);
|
|
5037
|
+
for (const wake of this._waiters.splice(0)) wake();
|
|
5038
|
+
}
|
|
5039
|
+
/** Drops the links attached under `key` (all of them without a key). */
|
|
5040
|
+
async unlink(key, reason) {
|
|
5041
|
+
const dropped = [...this._links].filter((link) => key === void 0 || link.key === key);
|
|
5042
|
+
await Promise.all(dropped.map((link) => this._drop(link, reason)));
|
|
5043
|
+
}
|
|
5044
|
+
/** The routers this endpoint has live links for. */
|
|
5045
|
+
routerLocks() {
|
|
5046
|
+
return new Set([...this._links].map((link) => link.routerLock));
|
|
5047
|
+
}
|
|
5048
|
+
/**
|
|
5049
|
+
* Sends `request` through the ServiceWorker's router, as if the browser had
|
|
5050
|
+
* fetched it: it reaches the handler its url routes to.
|
|
5051
|
+
*/
|
|
5052
|
+
async fetch(request) {
|
|
5053
|
+
const link = await this._linkWith("up");
|
|
5054
|
+
this._startKeepAlive();
|
|
5055
|
+
return await link.up.send(request);
|
|
5056
|
+
}
|
|
5057
|
+
/** Opens a socket to the handler `url` routes to, through the ServiceWorker. */
|
|
5058
|
+
async connectWebSocket(url, protocols = []) {
|
|
5059
|
+
const link = await this._linkWith("ctl");
|
|
5060
|
+
const id = this._sockets.newId();
|
|
5061
|
+
const answer = this._sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
|
|
5062
|
+
link.ctl?.postMessage({
|
|
5063
|
+
t: "ws-open",
|
|
5064
|
+
id,
|
|
5065
|
+
url,
|
|
5066
|
+
protocols
|
|
5067
|
+
});
|
|
5068
|
+
return await answer;
|
|
5069
|
+
}
|
|
5070
|
+
async close() {
|
|
5071
|
+
this._closed = true;
|
|
5072
|
+
if (this._keepAliveTimer) clearInterval(this._keepAliveTimer);
|
|
5073
|
+
await this.unlink(void 0, new LinkLostError("The handler was closed"));
|
|
5074
|
+
for (const wake of this._waiters.splice(0)) wake();
|
|
5075
|
+
}
|
|
5076
|
+
async _drop(link, reason) {
|
|
5077
|
+
if (!this._links.delete(link)) return;
|
|
5078
|
+
link.stopWatch();
|
|
5079
|
+
await link.up?.close(reason);
|
|
5080
|
+
try {
|
|
5081
|
+
await link.closeDown();
|
|
5082
|
+
} catch {}
|
|
5083
|
+
if (link.ctl) {
|
|
5084
|
+
link.ctl.onmessage = null;
|
|
5085
|
+
link.ctl.close();
|
|
5086
|
+
}
|
|
5087
|
+
}
|
|
5088
|
+
_routerLost(routerLock) {
|
|
5089
|
+
const reason = new LinkLostError(ROUTER_LOST_MESSAGE);
|
|
5090
|
+
for (const link of [...this._links]) if (link.routerLock === routerLock) this._drop(link, reason);
|
|
5091
|
+
this._sockets.failAll(reason);
|
|
5092
|
+
}
|
|
5093
|
+
/** A live link with `port`, waiting (and asking) for one when there is none. */
|
|
5094
|
+
async _linkWith(port) {
|
|
5095
|
+
const find = () => [...this._links].filter((link) => !link.superseded).reverse().find((link) => port === "up" ? link.up && !link.up.closed : link.ctl);
|
|
5096
|
+
const found = find();
|
|
5097
|
+
if (found) return found;
|
|
5098
|
+
const retryMs = this.options.relinkRetryMs ?? 2e3;
|
|
5099
|
+
const deadline = Date.now() + (this.options.relinkTimeoutMs ?? 3e4);
|
|
5100
|
+
while (!this._closed) {
|
|
5101
|
+
this.options.requestRelink?.();
|
|
5102
|
+
await new Promise((resolve) => {
|
|
5103
|
+
const timer = setTimeout(resolve, Math.max(0, Math.min(retryMs, deadline - Date.now())));
|
|
5104
|
+
this._waiters.push(() => {
|
|
5105
|
+
clearTimeout(timer);
|
|
5106
|
+
resolve();
|
|
5107
|
+
});
|
|
5108
|
+
});
|
|
5109
|
+
const link = find();
|
|
5110
|
+
if (link) return link;
|
|
5111
|
+
if (Date.now() >= deadline) break;
|
|
5112
|
+
}
|
|
5113
|
+
throw new LinkLostError("No link to the ServiceWorker could be made for this call");
|
|
5114
|
+
}
|
|
5115
|
+
_startKeepAlive() {
|
|
5116
|
+
if (this._keepAliveTimer || !this.options.keepAlive) return;
|
|
5117
|
+
this._keepAliveTimer = setInterval(() => {
|
|
5118
|
+
if ([...this._links].reduce((sum, link) => sum + (link.up?.inflight ?? 0), 0) === 0) {
|
|
5119
|
+
clearInterval(this._keepAliveTimer);
|
|
5120
|
+
this._keepAliveTimer = void 0;
|
|
5121
|
+
return;
|
|
5122
|
+
}
|
|
5123
|
+
this.options.keepAlive?.();
|
|
5124
|
+
}, this.options.keepAliveMs ?? 2e4);
|
|
5125
|
+
}
|
|
5126
|
+
_onControl(link, message) {
|
|
5127
|
+
if (!message || typeof message !== "object") return;
|
|
5128
|
+
switch (message.t) {
|
|
5129
|
+
case "ws-connect":
|
|
5130
|
+
this._acceptSocket(link, message);
|
|
5131
|
+
return;
|
|
5132
|
+
case "ws-opened":
|
|
5133
|
+
if (!this._sockets.settle(message.id, {
|
|
5134
|
+
port: message.port,
|
|
5135
|
+
protocol: message.protocol
|
|
5136
|
+
})) message.port.close();
|
|
5137
|
+
return;
|
|
5138
|
+
case "ws-failed":
|
|
5139
|
+
this._sockets.fail(message.id, new Error(message.message));
|
|
5140
|
+
return;
|
|
5141
|
+
}
|
|
5142
|
+
}
|
|
5143
|
+
async _acceptSocket(link, { id, url, protocols, headers }) {
|
|
5144
|
+
const ctl = link.ctl;
|
|
5145
|
+
if (!ctl) return;
|
|
5146
|
+
try {
|
|
5147
|
+
const result = await serveWebSocketUpgrade(this.handler, {
|
|
5148
|
+
url,
|
|
5149
|
+
protocols,
|
|
5150
|
+
headers
|
|
5151
|
+
});
|
|
5152
|
+
if (result.ok) ctl.postMessage({
|
|
5153
|
+
t: "ws-accept",
|
|
5154
|
+
id,
|
|
5155
|
+
protocol: result.protocol,
|
|
5156
|
+
port: result.port
|
|
5157
|
+
}, [result.port]);
|
|
5158
|
+
else ctl.postMessage({
|
|
5159
|
+
t: "ws-refuse",
|
|
5160
|
+
id,
|
|
5161
|
+
status: result.status,
|
|
5162
|
+
message: result.message
|
|
5163
|
+
});
|
|
5164
|
+
} catch (error) {
|
|
5165
|
+
ctl.postMessage({
|
|
5166
|
+
t: "ws-refuse",
|
|
5167
|
+
id,
|
|
5168
|
+
status: 500,
|
|
5169
|
+
message: errorMessage(error)
|
|
5170
|
+
});
|
|
5171
|
+
}
|
|
5172
|
+
}
|
|
5173
|
+
};
|
|
5174
|
+
//#endregion
|
|
5175
|
+
//#region src/sw/handler-table.ts
|
|
5176
|
+
/**
|
|
5177
|
+
* The default route: the handler with the fewest requests in flight, the
|
|
5178
|
+
* oldest on a tie. With one handler per key — one tab — that is the first
|
|
5179
|
+
* live handler of the key, as before routing was pluggable.
|
|
5180
|
+
*/
|
|
5181
|
+
const leastInflightRoute = (_request, _key, handlers) => {
|
|
5182
|
+
let best;
|
|
5183
|
+
for (const handler of handlers) if (best === void 0 || handler.inflight < best.inflight || handler.inflight === best.inflight && handler.attachedAt < best.attachedAt) best = handler;
|
|
5184
|
+
return best;
|
|
5185
|
+
};
|
|
5186
|
+
var HandlerTable = class {
|
|
5187
|
+
_entries = /* @__PURE__ */ new Map();
|
|
5188
|
+
_waiters = [];
|
|
5189
|
+
/** Adds `entry`. Returns the entry it replaces (same key and id), if any. */
|
|
5190
|
+
add(entry) {
|
|
5191
|
+
let slots = this._entries.get(entry.key);
|
|
5192
|
+
if (!slots) {
|
|
5193
|
+
slots = /* @__PURE__ */ new Map();
|
|
5194
|
+
this._entries.set(entry.key, slots);
|
|
5195
|
+
}
|
|
5196
|
+
const replaced = slots.get(entry.id);
|
|
5197
|
+
slots.set(entry.id, entry);
|
|
5198
|
+
if (!entry.draining) this._waiters = this._waiters.filter(({ key, resolve }) => {
|
|
5199
|
+
if (key !== entry.key) return true;
|
|
5200
|
+
resolve(true);
|
|
5201
|
+
return false;
|
|
5202
|
+
});
|
|
5203
|
+
return replaced;
|
|
5204
|
+
}
|
|
5205
|
+
/** Removes `entry` if it is still the one in its slot. */
|
|
5206
|
+
remove(entry) {
|
|
5207
|
+
const slots = this._entries.get(entry.key);
|
|
5208
|
+
if (slots?.get(entry.id) !== entry) return false;
|
|
5209
|
+
slots.delete(entry.id);
|
|
5210
|
+
if (slots.size === 0) this._entries.delete(entry.key);
|
|
5211
|
+
return true;
|
|
5212
|
+
}
|
|
5213
|
+
get(key, id) {
|
|
5214
|
+
return this._entries.get(key)?.get(id);
|
|
5215
|
+
}
|
|
5216
|
+
/** Every entry of `key`, draining or not. */
|
|
5217
|
+
all(key) {
|
|
5218
|
+
return [...this._entries.get(key)?.values() ?? []];
|
|
5219
|
+
}
|
|
5220
|
+
/** The entries of `key` that take new requests. */
|
|
5221
|
+
live(key) {
|
|
5222
|
+
return this.all(key).filter((entry) => !entry.draining);
|
|
5223
|
+
}
|
|
5224
|
+
entries() {
|
|
5225
|
+
return [...this._entries.values()].flatMap((slots) => [...slots.values()]);
|
|
5226
|
+
}
|
|
5227
|
+
get size() {
|
|
5228
|
+
let size = 0;
|
|
5229
|
+
for (const slots of this._entries.values()) size += slots.size;
|
|
5230
|
+
return size;
|
|
5231
|
+
}
|
|
5232
|
+
/**
|
|
5233
|
+
* Resolves `true` once a live entry for `key` is added (at once if there is
|
|
5234
|
+
* one, unless `next`), `false` after `ms`.
|
|
5235
|
+
*/
|
|
5236
|
+
waitFor(key, ms, next = false) {
|
|
5237
|
+
if (!next && this.live(key).length > 0) return Promise.resolve(true);
|
|
5238
|
+
return new Promise((resolve) => {
|
|
5239
|
+
const waiter = {
|
|
5240
|
+
key,
|
|
5241
|
+
resolve: (found) => {
|
|
5242
|
+
clearTimeout(timer);
|
|
5243
|
+
resolve(found);
|
|
5244
|
+
}
|
|
5245
|
+
};
|
|
5246
|
+
const timer = setTimeout(() => {
|
|
5247
|
+
this._waiters = this._waiters.filter((w) => w !== waiter);
|
|
5248
|
+
resolve(false);
|
|
5249
|
+
}, ms);
|
|
5250
|
+
this._waiters.push(waiter);
|
|
5251
|
+
});
|
|
5252
|
+
}
|
|
5253
|
+
};
|
|
5254
|
+
//#endregion
|
|
5255
|
+
//#region ../../node_modules/.pnpm/idb-keyval@6.3.0/node_modules/idb-keyval/dist/index.js
|
|
5256
|
+
function promisifyRequest(request) {
|
|
5257
|
+
return new Promise((resolve, reject) => {
|
|
5258
|
+
request.oncomplete = request.onsuccess = () => resolve(request.result);
|
|
5259
|
+
request.onabort = request.onerror = () => reject(request.error);
|
|
5260
|
+
});
|
|
5261
|
+
}
|
|
5262
|
+
function createStore(dbName, storeName) {
|
|
5263
|
+
let dbp;
|
|
5264
|
+
const getDB = () => {
|
|
5265
|
+
if (dbp) return dbp;
|
|
5266
|
+
const request = indexedDB.open(dbName);
|
|
5267
|
+
request.onupgradeneeded = () => request.result.createObjectStore(storeName);
|
|
5268
|
+
dbp = promisifyRequest(request);
|
|
5269
|
+
dbp.then((db) => {
|
|
5270
|
+
db.onclose = () => dbp = void 0;
|
|
5271
|
+
}, () => {
|
|
5272
|
+
dbp = void 0;
|
|
5273
|
+
});
|
|
5274
|
+
return dbp;
|
|
5275
|
+
};
|
|
5276
|
+
return (txMode, callback) => getDB().then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
|
|
5277
|
+
}
|
|
5278
|
+
let defaultGetStoreFunc;
|
|
5279
|
+
function defaultGetStore() {
|
|
5280
|
+
if (!defaultGetStoreFunc) defaultGetStoreFunc = createStore("keyval-store", "keyval");
|
|
5281
|
+
return defaultGetStoreFunc;
|
|
5282
|
+
}
|
|
5283
|
+
/**
|
|
5284
|
+
* Get a value by its key.
|
|
5285
|
+
*
|
|
5286
|
+
* @param key
|
|
5287
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
5288
|
+
*/
|
|
5289
|
+
function get(key, customStore = defaultGetStore()) {
|
|
5290
|
+
return customStore("readonly", (store) => promisifyRequest(store.get(key)));
|
|
5291
|
+
}
|
|
5292
|
+
/**
|
|
5293
|
+
* Set a value with a key.
|
|
5294
|
+
*
|
|
5295
|
+
* @param key
|
|
5296
|
+
* @param value
|
|
5297
|
+
* @param customStore Method to get a custom store. Use with caution (see the docs).
|
|
5298
|
+
*/
|
|
5299
|
+
function set(key, value, customStore = defaultGetStore()) {
|
|
5300
|
+
return customStore("readwrite", (store) => {
|
|
5301
|
+
store.put(value, key);
|
|
5302
|
+
return promisifyRequest(store.transaction);
|
|
5303
|
+
});
|
|
5304
|
+
}
|
|
5305
|
+
//#endregion
|
|
5306
|
+
//#region src/sw/protocol.ts
|
|
5307
|
+
/**
|
|
5308
|
+
* The messages between pages, Dedicated Workers and the same-origin
|
|
5309
|
+
* ServiceWorker. Internal: the shapes may change between versions, which is
|
|
5310
|
+
* why every hand-shake carries `HTTP_LINK_PROTOCOL`.
|
|
5311
|
+
*
|
|
5312
|
+
* THREE PORTS PER HANDLER LINK. A page makes the channels and hands one end of
|
|
5313
|
+
* each to the handler (itself, or a worker) and the other to the
|
|
5314
|
+
* ServiceWorker; after that it carries nothing:
|
|
5315
|
+
*
|
|
5316
|
+
* - `down`: ServiceWorker → handler, the requests the handler serves;
|
|
5317
|
+
* - `ctl`: a raw port next to them, for what HTTP over a stream cannot carry,
|
|
5318
|
+
* transferred `MessagePort`s (WebSocket hand-over);
|
|
5319
|
+
* - `up` (workers only): handler → ServiceWorker, the requests the handler
|
|
5320
|
+
* sends through the router (to other handlers).
|
|
5321
|
+
*/
|
|
5322
|
+
/** Page → ServiceWorker: attach a handler link. The name is the one version 1 used. */
|
|
5323
|
+
const ATTACH_CALL = "UPDATE_COMMUNICATION_PORT";
|
|
5324
|
+
/** Page → ServiceWorker: remove a handler link now. */
|
|
5325
|
+
const DETACH_CALL = "webrun-http:detach";
|
|
5326
|
+
/** Page → ServiceWorker: stop routing to a link, let its requests finish, then remove it. */
|
|
5327
|
+
const DRAIN_CALL = "webrun-http:drain";
|
|
5328
|
+
/** Page → ServiceWorker: open a WebSocket to a handler. */
|
|
5329
|
+
const WS_CONNECT_CALL = "webrun-http:ws-connect";
|
|
5330
|
+
/** ServiceWorker → pages: attach your links again (the ServiceWorker restarted). */
|
|
5331
|
+
const NEED_LINKS_CALL = "webrun-http:need-links";
|
|
5332
|
+
/**
|
|
5333
|
+
* Page → ServiceWorker, plain messages (no reply). A message to the
|
|
5334
|
+
* ServiceWorker object is an event: it starts a stopped worker and resets its
|
|
5335
|
+
* idle timer. Port messages do neither.
|
|
5336
|
+
*/
|
|
5337
|
+
const WAKE_MESSAGE = "webrun-http:wake";
|
|
5338
|
+
const KEEPALIVE_MESSAGE = "webrun-http:keepalive";
|
|
5339
|
+
/** Page ↔ worker: what `attachWorker` and `serveHttpInWorker` exchange. */
|
|
5340
|
+
const WORKER_HELLO = "webrun-http:worker-hello";
|
|
5341
|
+
//#endregion
|
|
5342
|
+
//#region src/sw/http-sw-dispatcher.ts
|
|
5343
|
+
/** One attached handler link, as the ServiceWorker holds it. */
|
|
5344
|
+
var HandlerEntry = class {
|
|
5345
|
+
key;
|
|
5346
|
+
id;
|
|
5347
|
+
owner;
|
|
5348
|
+
meta;
|
|
5349
|
+
link;
|
|
5350
|
+
ctl;
|
|
5351
|
+
clientId;
|
|
5352
|
+
ownerLock;
|
|
5353
|
+
draining = false;
|
|
5354
|
+
attachedAt = Date.now();
|
|
5355
|
+
sockets;
|
|
5356
|
+
stopWatch = () => {};
|
|
5357
|
+
closeUp;
|
|
5358
|
+
constructor(key, id, owner, meta, link, ctl, clientId, ownerLock) {
|
|
5359
|
+
this.key = key;
|
|
5360
|
+
this.id = id;
|
|
5361
|
+
this.owner = owner;
|
|
5362
|
+
this.meta = meta;
|
|
5363
|
+
this.link = link;
|
|
5364
|
+
this.ctl = ctl;
|
|
5365
|
+
this.clientId = clientId;
|
|
5366
|
+
this.ownerLock = ownerLock;
|
|
5367
|
+
this.sockets = new PortRendezvous(`s:${id}`);
|
|
5368
|
+
}
|
|
5369
|
+
get inflight() {
|
|
5370
|
+
return this.link.inflight;
|
|
5371
|
+
}
|
|
5372
|
+
};
|
|
5373
|
+
/** The reason requests fail with when their handler dies under them. */
|
|
5374
|
+
const HANDLER_LOST_MESSAGE = "The handler was lost while this request was in flight";
|
|
5375
|
+
const TIMED_OUT = Symbol("timed-out");
|
|
5376
|
+
/**
|
|
5377
|
+
* The same-origin ServiceWorker: routes `fetch` events under its scope to
|
|
5378
|
+
* handler links that pages attach — handlers in the pages themselves
|
|
5379
|
+
* (`SwHttpAdapter.register`) or in Dedicated Workers
|
|
5380
|
+
* (`SwHttpAdapter.attachWorker` + `serveHttpInWorker`).
|
|
5381
|
+
*
|
|
5382
|
+
* A url `<scope>/<key>/...` belongs to the handlers of `key`. Of those, the
|
|
5383
|
+
* `route` option picks one per request. Requests and responses stream with
|
|
5384
|
+
* backpressure in both directions, and an aborted fetch reaches the handler
|
|
5385
|
+
* as a cancellation (webrun-rpc + webrun-http-streams).
|
|
5386
|
+
*
|
|
5387
|
+
* Urls of keys this worker never served go to the network untouched: the
|
|
5388
|
+
* worker does not call `respondWith` for them.
|
|
5389
|
+
*
|
|
5390
|
+
* RESTARTS. The browser stops an idle ServiceWorker, and every port it held
|
|
5391
|
+
* dies with it. Nothing is persisted but the set of keys ever served: the
|
|
5392
|
+
* first request after a restart asks every window to attach its links again
|
|
5393
|
+
* (`NEED_LINKS`) and waits for them.
|
|
5394
|
+
*
|
|
5395
|
+
* LIVENESS. Each handler holds an owner lock; when it is granted to this
|
|
5396
|
+
* worker, the handler is gone and its requests in flight fail at once (502).
|
|
5397
|
+
* This worker holds a router lock that handlers watch the same way.
|
|
5398
|
+
*/
|
|
5399
|
+
var SwHttpDispatcher = class {
|
|
5400
|
+
self;
|
|
5401
|
+
log;
|
|
5402
|
+
options;
|
|
5403
|
+
table = new HandlerTable();
|
|
5404
|
+
/**
|
|
5405
|
+
* Keys that were served at some point on this worker (sticky, kept in
|
|
5406
|
+
* IndexedDB). Lets a fetch tell "a site url whose handler is gone → 404"
|
|
5407
|
+
* from "an unknown url under the scope → the network".
|
|
5408
|
+
*/
|
|
5409
|
+
claimedKeys = /* @__PURE__ */ new Set();
|
|
5410
|
+
/** The Web Lock this worker holds while it lives; handlers watch it. */
|
|
5411
|
+
routerLock;
|
|
5412
|
+
_routerHeld = Promise.resolve();
|
|
5413
|
+
_restored = Promise.resolve();
|
|
5414
|
+
_restoreSettled = false;
|
|
5415
|
+
_cleanup = [];
|
|
5416
|
+
_livenessTimer;
|
|
5417
|
+
_relinkRounds = /* @__PURE__ */ new Map();
|
|
5418
|
+
/** Keys whose last handler was drained: until the time stored, requests wait for the next. */
|
|
5419
|
+
_vacant = /* @__PURE__ */ new Map();
|
|
5420
|
+
constructor(options) {
|
|
5421
|
+
this.options = options;
|
|
5422
|
+
this.self = options.self;
|
|
5423
|
+
this.log = options.log ?? (() => {});
|
|
5424
|
+
if (locksAvailable()) this.routerLock = newLockName("webrun-http-router");
|
|
5425
|
+
}
|
|
5426
|
+
get scope() {
|
|
5427
|
+
return `${new URL("./", this.self.location.href)}`;
|
|
5428
|
+
}
|
|
5429
|
+
/** The key `url` belongs to: its first path segment under the scope. */
|
|
5430
|
+
keyOf(url) {
|
|
5431
|
+
const href = `${url}`;
|
|
5432
|
+
const scope = this.scope;
|
|
5433
|
+
if (!href.startsWith(scope)) return void 0;
|
|
5434
|
+
const key = href.substring(scope.length).replace(/[?#].*$/, "").split("/")[0];
|
|
5435
|
+
return key ? decodeURIComponent(key) : void 0;
|
|
5436
|
+
}
|
|
5437
|
+
/** Whether `key` has ever been served on this worker. */
|
|
5438
|
+
isClaimedKey(key) {
|
|
5439
|
+
return this.claimedKeys.has(key);
|
|
5440
|
+
}
|
|
5441
|
+
/** Whether requests for `key` are this worker's to answer. */
|
|
5442
|
+
serves(key) {
|
|
5443
|
+
return this.claimedKeys.has(key) || this.table.all(key).length > 0;
|
|
5444
|
+
}
|
|
5445
|
+
start() {
|
|
5446
|
+
const self = this.self;
|
|
5447
|
+
if (this.routerLock) this._routerHeld = holdLock(this.routerLock).then(() => {});
|
|
5448
|
+
this._restored = this._restoreClaimedKeys();
|
|
5449
|
+
const latch = () => {
|
|
5450
|
+
this._restoreSettled = true;
|
|
5451
|
+
};
|
|
5452
|
+
this._restored.then(latch, latch);
|
|
5453
|
+
this._cleanup.push(handleClaimRequests(self), handleChannelCalls(self, ATTACH_CALL, (event, params, ...ports) => this._attach(event, params, ports)), handleChannelCalls(self, DETACH_CALL, (_event, params) => {
|
|
5454
|
+
const entry = this._find(params);
|
|
5455
|
+
if (!entry) return false;
|
|
5456
|
+
this._close(entry, new LinkLostError("The handler was detached"));
|
|
5457
|
+
return true;
|
|
5458
|
+
}), handleChannelCalls(self, DRAIN_CALL, async (_event, params) => {
|
|
5459
|
+
const entry = this._find(params);
|
|
5460
|
+
if (!entry) return false;
|
|
5461
|
+
this._vacant.set(entry.key, Date.now() + (this.options.attachTimeoutMs ?? 15e3));
|
|
5462
|
+
await this._retire(entry, params.ms ?? this.options.handoverMs ?? 5e3);
|
|
5463
|
+
return true;
|
|
5464
|
+
}), handleChannelCalls(self, WS_CONNECT_CALL, async (event, params) => {
|
|
5465
|
+
if (!this._isOwnClient(event)) throw new Error("Only this origin's pages may open sockets");
|
|
5466
|
+
const { url, protocols } = params;
|
|
5467
|
+
const connection = await this.connectWebSocket(url, protocols ?? []);
|
|
5468
|
+
return withTransfer(connection, [connection.port]);
|
|
5469
|
+
}));
|
|
5470
|
+
const onMessage = (event) => {
|
|
5471
|
+
const type = event.data?.type;
|
|
5472
|
+
if (type === "webrun-http:wake") event.waitUntil(this._askForLinks());
|
|
5473
|
+
else if (type === "webrun-http:keepalive") event.waitUntil(Promise.resolve());
|
|
5474
|
+
};
|
|
5475
|
+
self.addEventListener("message", onMessage);
|
|
5476
|
+
this._cleanup.push(() => self.removeEventListener("message", onMessage));
|
|
5477
|
+
const onInstall = (event) => {
|
|
5478
|
+
this.log("Skip waiting on install.");
|
|
5479
|
+
event.waitUntil(self.skipWaiting());
|
|
5480
|
+
};
|
|
5481
|
+
const onActivate = (event) => {
|
|
5482
|
+
this.log("Claim control over all clients.");
|
|
5483
|
+
event.waitUntil(self.clients.claim());
|
|
5484
|
+
};
|
|
5485
|
+
const onFetch = (event) => this._onFetch(event);
|
|
5486
|
+
self.addEventListener("install", onInstall);
|
|
5487
|
+
self.addEventListener("activate", onActivate);
|
|
5488
|
+
self.addEventListener("fetch", onFetch);
|
|
5489
|
+
this._cleanup.push(() => {
|
|
5490
|
+
self.removeEventListener("install", onInstall);
|
|
5491
|
+
self.removeEventListener("activate", onActivate);
|
|
5492
|
+
self.removeEventListener("fetch", onFetch);
|
|
5493
|
+
});
|
|
5494
|
+
}
|
|
5495
|
+
async stop() {
|
|
5496
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
5497
|
+
if (this._livenessTimer) clearInterval(this._livenessTimer);
|
|
5498
|
+
this._livenessTimer = void 0;
|
|
5499
|
+
for (const entry of this.table.entries()) this._close(entry, new LinkLostError("The ServiceWorker dispatcher stopped"));
|
|
5500
|
+
}
|
|
5501
|
+
/**
|
|
5502
|
+
* Answers `request` as a fetch under the scope would be: through the
|
|
5503
|
+
* handler its key routes to. A url outside the scope, or of a key this
|
|
5504
|
+
* worker never served, goes to the network.
|
|
5505
|
+
*/
|
|
5506
|
+
async dispatch(request) {
|
|
5507
|
+
const key = this.keyOf(request.url);
|
|
5508
|
+
if (key === void 0) return await fetch(request);
|
|
5509
|
+
await this._restored.catch(() => {});
|
|
5510
|
+
const entry = await this._acquire(request, key);
|
|
5511
|
+
if (entry === TIMED_OUT) return new Response(null, {
|
|
5512
|
+
status: 503,
|
|
5513
|
+
statusText: "Service Unavailable (no handler attached in time)"
|
|
5514
|
+
});
|
|
5515
|
+
if (!entry) {
|
|
5516
|
+
if (!this.serves(key)) return await fetch(request);
|
|
5517
|
+
return new Response(null, {
|
|
5518
|
+
status: 404,
|
|
5519
|
+
statusText: "Not Found (no active handler)"
|
|
5520
|
+
});
|
|
5521
|
+
}
|
|
5522
|
+
try {
|
|
5523
|
+
return await entry.link.send(request);
|
|
5524
|
+
} catch (error) {
|
|
5525
|
+
this.log("[dispatch] failed", key, error);
|
|
5526
|
+
return new Response(errorMessage(error), {
|
|
5527
|
+
status: 502,
|
|
5528
|
+
statusText: "Bad Gateway",
|
|
5529
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
5530
|
+
});
|
|
5531
|
+
}
|
|
5532
|
+
}
|
|
5533
|
+
/**
|
|
5534
|
+
* Opens a socket to the handler `url` routes to: the handler accepts or
|
|
5535
|
+
* refuses it like an HTTP upgrade, and the socket's port comes back. After
|
|
5536
|
+
* that the socket runs between the caller and the handler directly; this
|
|
5537
|
+
* worker is not on its data path.
|
|
5538
|
+
*/
|
|
5539
|
+
async connectWebSocket(url, protocols = [], headers) {
|
|
5540
|
+
const request = newWebSocketUpgradeRequest(url, {
|
|
5541
|
+
protocols,
|
|
5542
|
+
headers
|
|
5543
|
+
});
|
|
5544
|
+
const key = this.keyOf(request.url);
|
|
5545
|
+
if (key === void 0) throw new Error(`${url} is outside this ServiceWorker's scope`);
|
|
5546
|
+
await this._restored.catch(() => {});
|
|
5547
|
+
const entry = await this._acquire(request, key);
|
|
5548
|
+
if (!entry || entry === TIMED_OUT) throw new Error(`No handler serves ${url}`);
|
|
5549
|
+
if (!entry.ctl) throw new Error(`The handler of ${url} does not accept sockets`);
|
|
5550
|
+
const id = entry.sockets.newId();
|
|
5551
|
+
const answer = entry.sockets.wait(id, this.options.wsConnectTimeoutMs ?? 15e3, `the socket request for ${url}`);
|
|
5552
|
+
entry.ctl.postMessage({
|
|
5553
|
+
t: "ws-connect",
|
|
5554
|
+
id,
|
|
5555
|
+
url: request.url,
|
|
5556
|
+
protocols,
|
|
5557
|
+
headers
|
|
5558
|
+
});
|
|
5559
|
+
return await answer;
|
|
5560
|
+
}
|
|
5561
|
+
_onFetch(event) {
|
|
5562
|
+
const request = event.request;
|
|
5563
|
+
const key = this.keyOf(request.url);
|
|
5564
|
+
if (key === void 0) return;
|
|
5565
|
+
if (this._restoreSettled) {
|
|
5566
|
+
if (this.serves(key)) event.respondWith(this.dispatch(request));
|
|
5567
|
+
else if (request.mode === "navigate") event.respondWith(fetch(request));
|
|
5568
|
+
return;
|
|
5569
|
+
}
|
|
5570
|
+
event.respondWith((async () => {
|
|
5571
|
+
await this._restored.catch(() => {});
|
|
5572
|
+
if (!this.serves(key)) return await fetch(request);
|
|
5573
|
+
return await this.dispatch(request);
|
|
5574
|
+
})());
|
|
5575
|
+
}
|
|
5576
|
+
async _attach(event, params, ports) {
|
|
5577
|
+
const clientId = event.source?.id;
|
|
5578
|
+
const [down, ...rest] = ports;
|
|
5579
|
+
if (!down) throw new Error("An attach carries at least one port");
|
|
5580
|
+
this.log("[attach]", clientId, params);
|
|
5581
|
+
if (params.wire === void 0) {
|
|
5582
|
+
const link = trackedLink((request) => sendHttpRequest(down, request), () => down.close());
|
|
5583
|
+
const id = clientId ?? crypto.randomUUID();
|
|
5584
|
+
this._add(new HandlerEntry(params.key, id, id, void 0, link, void 0, clientId, void 0));
|
|
5585
|
+
return { ...params };
|
|
5586
|
+
}
|
|
5587
|
+
if (params.wire !== "webrun-http-link/2") {
|
|
5588
|
+
for (const port of ports) port.close();
|
|
5589
|
+
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.`);
|
|
5590
|
+
}
|
|
5591
|
+
const ctl = params.ctl ? rest.shift() : void 0;
|
|
5592
|
+
const up = params.up ? rest.shift() : void 0;
|
|
5593
|
+
const streamTimeout = this.options.streamTimeout;
|
|
5594
|
+
const link = await connectHttpLink(down, { streamTimeout });
|
|
5595
|
+
const entry = new HandlerEntry(params.key, params.id ?? clientId ?? crypto.randomUUID(), params.owner ?? crypto.randomUUID(), params.meta, link, ctl, clientId, params.ownerLock);
|
|
5596
|
+
if (up) entry.closeUp = await serveHttpLink(up, (request) => this.dispatch(request), { streamTimeout });
|
|
5597
|
+
if (ctl) ctl.onmessage = (message) => this._onControl(entry, message.data);
|
|
5598
|
+
if (params.ownerLock) entry.stopWatch = watchLock(params.ownerLock, () => {
|
|
5599
|
+
this.log("[owner lost]", entry.key, entry.id);
|
|
5600
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
5601
|
+
});
|
|
5602
|
+
this._add(entry);
|
|
5603
|
+
await this._routerHeld;
|
|
5604
|
+
return {
|
|
5605
|
+
accepted: HTTP_LINK_PROTOCOL,
|
|
5606
|
+
routerLock: this.routerLock
|
|
5607
|
+
};
|
|
5608
|
+
}
|
|
5609
|
+
_add(entry) {
|
|
5610
|
+
this._vacant.delete(entry.key);
|
|
5611
|
+
const replaced = this.table.add(entry);
|
|
5612
|
+
if (replaced && replaced !== entry) this._retire(replaced, this.options.handoverMs ?? 5e3, false);
|
|
5613
|
+
this._claim(entry.key);
|
|
5614
|
+
if (entry.ownerLock) this._watchLiveness();
|
|
5615
|
+
}
|
|
5616
|
+
/**
|
|
5617
|
+
* The backup of the owner-lock watches: every `livenessCheckMs`, drops the
|
|
5618
|
+
* handlers whose owner lock is no longer held. Runs only while some handler
|
|
5619
|
+
* has an owner lock, and keeps nothing awake: a timer is not an event.
|
|
5620
|
+
*/
|
|
5621
|
+
_watchLiveness() {
|
|
5622
|
+
const period = this.options.livenessCheckMs ?? 5e3;
|
|
5623
|
+
if (this._livenessTimer || period <= 0) return;
|
|
5624
|
+
this._livenessTimer = setInterval(async () => {
|
|
5625
|
+
const watched = this.table.entries().filter((entry) => entry.ownerLock);
|
|
5626
|
+
if (watched.length === 0) {
|
|
5627
|
+
clearInterval(this._livenessTimer);
|
|
5628
|
+
this._livenessTimer = void 0;
|
|
5629
|
+
return;
|
|
5630
|
+
}
|
|
5631
|
+
const held = await heldLockNames();
|
|
5632
|
+
if (!held) return;
|
|
5633
|
+
for (const entry of watched) if (entry.ownerLock && !held.has(entry.ownerLock) && this.table.remove(entry)) {
|
|
5634
|
+
this.log("[owner gone]", entry.key, entry.id);
|
|
5635
|
+
this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE), false);
|
|
5636
|
+
}
|
|
5637
|
+
}, period);
|
|
5638
|
+
}
|
|
5639
|
+
/** The entry a drain or detach names, if its owner token still matches. */
|
|
5640
|
+
_find({ key, id, owner }) {
|
|
5641
|
+
const entry = this.table.get(key, id);
|
|
5642
|
+
return entry && entry.owner === owner ? entry : void 0;
|
|
5643
|
+
}
|
|
5644
|
+
/**
|
|
5645
|
+
* Stops routing to `entry`, lets its requests in flight run for up to `ms`,
|
|
5646
|
+
* then closes it. Requests that arrive meanwhile wait for the next owner.
|
|
5647
|
+
*/
|
|
5648
|
+
async _retire(entry, ms, inTable = true) {
|
|
5649
|
+
entry.draining = true;
|
|
5650
|
+
let timer;
|
|
5651
|
+
await Promise.race([entry.link.whenIdle(), new Promise((resolve) => {
|
|
5652
|
+
timer = setTimeout(resolve, ms);
|
|
5653
|
+
})]);
|
|
5654
|
+
clearTimeout(timer);
|
|
5655
|
+
this._close(entry, new LinkLostError("The handler was drained"), inTable);
|
|
5656
|
+
}
|
|
5657
|
+
_close(entry, reason, inTable = true) {
|
|
5658
|
+
if (inTable) this.table.remove(entry);
|
|
5659
|
+
entry.stopWatch();
|
|
5660
|
+
entry.sockets.failAll(reason);
|
|
5661
|
+
entry.link.close(reason);
|
|
5662
|
+
entry.closeUp?.().catch(() => {});
|
|
5663
|
+
if (entry.ctl) {
|
|
5664
|
+
entry.ctl.onmessage = null;
|
|
5665
|
+
entry.ctl.close();
|
|
5666
|
+
}
|
|
5667
|
+
}
|
|
5668
|
+
/**
|
|
5669
|
+
* The handler for `request`: picked by `route` among the live handlers of
|
|
5670
|
+
* its key, waiting for one when there is none.
|
|
5671
|
+
*/
|
|
5672
|
+
async _acquire(request, key) {
|
|
5673
|
+
const picked = await this._pick(request, key);
|
|
5674
|
+
if (picked) return picked;
|
|
5675
|
+
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;
|
|
5676
|
+
const vacantUntil = this._vacant.get(key) ?? 0;
|
|
5677
|
+
if (vacantUntil > Date.now()) return await this.table.waitFor(key, vacantUntil - Date.now()) ? await this._pick(request, key) ?? TIMED_OUT : TIMED_OUT;
|
|
5678
|
+
if (!this.serves(key)) return void 0;
|
|
5679
|
+
await this._askForLinks(key);
|
|
5680
|
+
return await this._pick(request, key);
|
|
5681
|
+
}
|
|
5682
|
+
async _pick(request, key) {
|
|
5683
|
+
let live = this.table.live(key);
|
|
5684
|
+
for (const entry of live) {
|
|
5685
|
+
if (entry.ownerLock || !entry.clientId) continue;
|
|
5686
|
+
if (!await this.self.clients.get(entry.clientId)) this._close(entry, new LinkLostError(HANDLER_LOST_MESSAGE));
|
|
5687
|
+
}
|
|
5688
|
+
live = this.table.live(key);
|
|
5689
|
+
if (live.length === 0) return void 0;
|
|
5690
|
+
return (this.options.route ?? leastInflightRoute)(request, key, live);
|
|
5691
|
+
}
|
|
5692
|
+
/**
|
|
5693
|
+
* Asks every window to attach its links again, and waits until a handler
|
|
5694
|
+
* for `key` is back, every window answered, or `relinkTimeoutMs` passed.
|
|
5695
|
+
* At most one round per key every 10 s: a key whose tab is simply gone
|
|
5696
|
+
* should not cost every request the wait.
|
|
5697
|
+
*/
|
|
5698
|
+
_askForLinks(key = "") {
|
|
5699
|
+
const round = this._relinkRounds.get(key);
|
|
5700
|
+
if (round && Date.now() - round.at < 1e4) return round.done;
|
|
5701
|
+
const done = this._linkRound(key);
|
|
5702
|
+
this._relinkRounds.set(key, {
|
|
5703
|
+
at: Date.now(),
|
|
5704
|
+
done
|
|
5705
|
+
});
|
|
5706
|
+
return done;
|
|
5707
|
+
}
|
|
5708
|
+
async _linkRound(key) {
|
|
5709
|
+
const timeout = this.options.relinkTimeoutMs ?? 3e3;
|
|
5710
|
+
const windows = await this.self.clients.matchAll({
|
|
5711
|
+
type: "window",
|
|
5712
|
+
includeUncontrolled: true
|
|
5713
|
+
});
|
|
5714
|
+
this.log("[need-links]", key, windows.length);
|
|
5715
|
+
const params = { routerLock: this.routerLock };
|
|
5716
|
+
const pending = new Set(windows);
|
|
5717
|
+
const answered = Promise.allSettled(windows.map((client) => callChannel(client, NEED_LINKS_CALL, params).then(() => pending.delete(client))));
|
|
5718
|
+
let timer;
|
|
5719
|
+
const timedOut = new Promise((resolve) => {
|
|
5720
|
+
timer = setTimeout(resolve, timeout);
|
|
5721
|
+
});
|
|
5722
|
+
await Promise.race([answered, timedOut]);
|
|
5723
|
+
clearTimeout(timer);
|
|
5724
|
+
for (const client of pending) this._askLegacyPage(client);
|
|
5725
|
+
}
|
|
5726
|
+
/** Asks a version-1 page for a fresh port, as version 1's worker did. */
|
|
5727
|
+
_askLegacyPage(client) {
|
|
5728
|
+
const channel = new MessageChannel();
|
|
5729
|
+
callChannel(client, ATTACH_CALL, {}, channel.port2).then((info) => {
|
|
5730
|
+
if (!info?.key || info.wire !== void 0) return;
|
|
5731
|
+
const link = trackedLink((request) => sendHttpRequest(channel.port1, request), () => channel.port1.close());
|
|
5732
|
+
this._add(new HandlerEntry(info.key, client.id, client.id, void 0, link, void 0, client.id, void 0));
|
|
5733
|
+
}, () => channel.port1.close());
|
|
5734
|
+
}
|
|
5735
|
+
_onControl(entry, message) {
|
|
5736
|
+
if (!message || typeof message !== "object") return;
|
|
5737
|
+
switch (message.t) {
|
|
5738
|
+
case "ws-accept":
|
|
5739
|
+
if (!entry.sockets.settle(message.id, {
|
|
5740
|
+
port: message.port,
|
|
5741
|
+
protocol: message.protocol
|
|
5742
|
+
})) message.port.close();
|
|
5743
|
+
return;
|
|
5744
|
+
case "ws-refuse":
|
|
5745
|
+
entry.sockets.fail(message.id, new Error(message.message));
|
|
5746
|
+
return;
|
|
5747
|
+
case "ws-open":
|
|
5748
|
+
this.connectWebSocket(message.url, message.protocols).then(({ port, protocol }) => entry.ctl?.postMessage({
|
|
5749
|
+
t: "ws-opened",
|
|
5750
|
+
id: message.id,
|
|
5751
|
+
protocol,
|
|
5752
|
+
port
|
|
5753
|
+
}, [port]), (error) => entry.ctl?.postMessage({
|
|
5754
|
+
t: "ws-failed",
|
|
5755
|
+
id: message.id,
|
|
5756
|
+
message: errorMessage(error)
|
|
5757
|
+
}));
|
|
5758
|
+
return;
|
|
5759
|
+
}
|
|
5760
|
+
}
|
|
5761
|
+
_isOwnClient(event) {
|
|
5762
|
+
const source = event.source;
|
|
5763
|
+
if (!source?.url) return false;
|
|
5764
|
+
try {
|
|
5765
|
+
return new URL(source.url).origin === this.self.location.origin;
|
|
5766
|
+
} catch {
|
|
5767
|
+
return false;
|
|
5768
|
+
}
|
|
5769
|
+
}
|
|
5770
|
+
async _claim(key) {
|
|
5771
|
+
if (!key || this.claimedKeys.has(key)) return;
|
|
5772
|
+
this.claimedKeys.add(key);
|
|
5773
|
+
try {
|
|
5774
|
+
await set("claimedKeys", [...this.claimedKeys].sort());
|
|
5775
|
+
} catch (error) {
|
|
5776
|
+
this.log("[claimedKeys] not stored", error);
|
|
5777
|
+
}
|
|
5778
|
+
}
|
|
5779
|
+
async _restoreClaimedKeys() {
|
|
5780
|
+
const stored = await get("claimedKeys") ?? [];
|
|
5781
|
+
for (const key of stored) this.claimedKeys.add(key);
|
|
5782
|
+
}
|
|
5783
|
+
};
|
|
5784
|
+
/**
|
|
5785
|
+
* Starts the same-origin dispatcher in a ServiceWorker. Returns a function
|
|
5786
|
+
* that stops it.
|
|
5787
|
+
*/
|
|
5788
|
+
function startHttpDispatcher(options) {
|
|
5789
|
+
const dispatcher = new SwHttpDispatcher(options);
|
|
5790
|
+
dispatcher.start();
|
|
5791
|
+
return () => {
|
|
5792
|
+
dispatcher.stop();
|
|
5793
|
+
};
|
|
5794
|
+
}
|
|
5795
|
+
//#endregion
|
|
5796
|
+
//#region src/sw/worker-url.ts
|
|
5797
|
+
/**
|
|
5798
|
+
* Resolve a `serviceWorkerUrl` option the way a page would: relative to the
|
|
5799
|
+
* current document. Absolute urls pass through untouched. A url that cannot
|
|
5800
|
+
* be resolved is reported with the option name and the offending value,
|
|
5801
|
+
* because the raw `TypeError: Failed to construct 'URL': Invalid URL` says
|
|
5802
|
+
* neither.
|
|
5803
|
+
*/
|
|
5804
|
+
function resolveWorkerUrl(serviceWorkerUrl) {
|
|
5805
|
+
const base = globalThis.location?.href;
|
|
5806
|
+
try {
|
|
5807
|
+
return new URL(serviceWorkerUrl, base);
|
|
5808
|
+
} catch (error) {
|
|
5809
|
+
throw new Error(`Invalid serviceWorkerUrl: ${JSON.stringify(serviceWorkerUrl)}` + (base ? ` (relative to ${base})` : " (no document to resolve it against)"), { cause: error });
|
|
5810
|
+
}
|
|
5811
|
+
}
|
|
5812
|
+
//#endregion
|
|
5813
|
+
//#region src/sw/sw-dispatcher.ts
|
|
5814
|
+
/**
|
|
5815
|
+
* Page-side counterpart: registers a ServiceWorker and sets up a
|
|
5816
|
+
* MessageChannel with it, re-establishing the connection after SW wake-ups.
|
|
5817
|
+
*/
|
|
5818
|
+
var SwPortHandler = class {
|
|
5819
|
+
options;
|
|
5820
|
+
_serviceWorkerUrl;
|
|
5821
|
+
_serviceWorker;
|
|
5822
|
+
_registrationPromise;
|
|
5823
|
+
_registration;
|
|
5824
|
+
_cleanupRegistrations;
|
|
5825
|
+
constructor(options) {
|
|
5826
|
+
this.options = options;
|
|
5827
|
+
if (!this.key) throw new Error("Key is not defined.");
|
|
5828
|
+
if (!this.scope) throw new Error("Scope is not defined");
|
|
5829
|
+
}
|
|
5830
|
+
get key() {
|
|
5831
|
+
return this.options.key;
|
|
5832
|
+
}
|
|
5833
|
+
get scope() {
|
|
5834
|
+
return this.options.scope ?? new URL("./", this.serviceWorkerUrl).pathname;
|
|
5835
|
+
}
|
|
5836
|
+
/**
|
|
5837
|
+
* The scope as a url on the worker's origin. Resolved against the worker's
|
|
5838
|
+
* own url when one is given, not against this module's: a bundle that is
|
|
5839
|
+
* not an ES module (an IIFE, Theia's frontend) has no `import.meta.url`, and
|
|
5840
|
+
* `new URL(scope, undefined)` threw `Invalid URL` there. Only without a
|
|
5841
|
+
* worker url does the module's location decide (its default `sw-worker.js`
|
|
5842
|
+
* sits next to it).
|
|
5843
|
+
*/
|
|
5844
|
+
get rootUrl() {
|
|
5845
|
+
const base = this.options.serviceWorkerUrl ? this.serviceWorkerUrl : import.meta.url;
|
|
5846
|
+
return new URL(this.scope, base);
|
|
5847
|
+
}
|
|
5848
|
+
get serviceWorkerUrl() {
|
|
5849
|
+
if (!this._serviceWorkerUrl) {
|
|
5850
|
+
const url = this.options.serviceWorkerUrl ? resolveWorkerUrl(this.options.serviceWorkerUrl) : new URL("./sw-worker.js", this.rootUrl);
|
|
5851
|
+
this._serviceWorkerUrl = `${url}`;
|
|
5852
|
+
}
|
|
5853
|
+
return this._serviceWorkerUrl;
|
|
5854
|
+
}
|
|
5855
|
+
async _newCommunicationChannel() {
|
|
5856
|
+
const messageChannel = new MessageChannel();
|
|
5857
|
+
return [messageChannel.port1, messageChannel.port2];
|
|
5858
|
+
}
|
|
5859
|
+
async _setCommunicationPort(port) {
|
|
5860
|
+
await this.options.bindPort(port);
|
|
5861
|
+
}
|
|
5862
|
+
async _updateCommunicationChannel() {
|
|
5863
|
+
if (!this._serviceWorker) return;
|
|
5864
|
+
const [port1, port2] = await this._newCommunicationChannel();
|
|
5865
|
+
await this._setCommunicationPort(port1);
|
|
5866
|
+
await callChannel(this._serviceWorker, "UPDATE_COMMUNICATION_PORT", this._getRegistrationInfo(), port2);
|
|
5867
|
+
}
|
|
5868
|
+
_getRegistrationInfo() {
|
|
5869
|
+
return { key: this.key };
|
|
5870
|
+
}
|
|
5871
|
+
/**
|
|
5872
|
+
* Registers the worker and waits until it is activated and controls this
|
|
5873
|
+
* page, then opens the port to it. The page must be controlled, because
|
|
5874
|
+
* only a controlled page's `fetch()` reaches the worker. When the page
|
|
5875
|
+
* loaded uncontrolled (a hard reload does that), the worker is asked to
|
|
5876
|
+
* claim it. Rejects with a `ServiceWorkerControlError` when that fails or
|
|
5877
|
+
* `timeout` passes (`reason` says which step); a later `start()` tries
|
|
5878
|
+
* again.
|
|
5879
|
+
*/
|
|
5880
|
+
async start() {
|
|
5881
|
+
if (!this._registrationPromise) this._registrationPromise = (async () => {
|
|
5882
|
+
const [register, cleanup] = newRegistry();
|
|
5883
|
+
this._cleanupRegistrations = cleanup;
|
|
5884
|
+
register(() => {
|
|
5885
|
+
this._cleanupRegistrations = void 0;
|
|
5886
|
+
});
|
|
5887
|
+
const registration = await navigator.serviceWorker.register(this.serviceWorkerUrl, { scope: this.scope });
|
|
5888
|
+
this._registration = registration;
|
|
5889
|
+
const stopListening = handleChannelCalls(navigator.serviceWorker, "UPDATE_COMMUNICATION_PORT", async (_event, _params, port) => {
|
|
5890
|
+
await this._setCommunicationPort(port);
|
|
5891
|
+
return this._getRegistrationInfo();
|
|
5892
|
+
});
|
|
5893
|
+
register(stopListening);
|
|
5894
|
+
const timeout = this.options.timeout ?? 3e4;
|
|
5895
|
+
const deadline = Date.now() + timeout;
|
|
5896
|
+
try {
|
|
5897
|
+
this._serviceWorker = await awaitServiceWorkerControl(registration, {
|
|
5898
|
+
timeout,
|
|
5899
|
+
reloadIfUncontrolled: this.options.reloadIfUncontrolled
|
|
5900
|
+
});
|
|
5901
|
+
await withDeadline(deadline, this._updateCommunicationChannel(), () => 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\`).`));
|
|
5902
|
+
} catch (error) {
|
|
5903
|
+
stopListening();
|
|
5904
|
+
this._cleanupRegistrations = void 0;
|
|
5905
|
+
this._registration = void 0;
|
|
5906
|
+
this._registrationPromise = void 0;
|
|
5907
|
+
throw error;
|
|
5908
|
+
}
|
|
5909
|
+
})();
|
|
5910
|
+
return this._registrationPromise;
|
|
5911
|
+
}
|
|
5912
|
+
async stop() {
|
|
5913
|
+
this._cleanupRegistrations?.();
|
|
5914
|
+
const registration = this._registration;
|
|
5915
|
+
this._registration = void 0;
|
|
2809
5916
|
try {
|
|
2810
|
-
|
|
2811
|
-
swUrl,
|
|
2812
|
-
scopeUrl,
|
|
2813
|
-
timeout
|
|
2814
|
-
}));
|
|
5917
|
+
await registration?.unregister();
|
|
2815
5918
|
} catch (error) {
|
|
2816
|
-
|
|
2817
|
-
externalPort.onmessage = (event) => event.ports[0]?.postMessage({ error: serialized });
|
|
2818
|
-
throw error;
|
|
5919
|
+
console.log("Service Worker unregistration failed: ", error);
|
|
2819
5920
|
}
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
5921
|
+
}
|
|
5922
|
+
};
|
|
5923
|
+
/**
|
|
5924
|
+
* ServiceWorker-side counterpart: maintains an index of connected clients keyed by
|
|
5925
|
+
* clientId, persisted in IndexedDB so it can reclaim ports across SW restarts.
|
|
5926
|
+
*/
|
|
5927
|
+
var SwPortDispatcher = class {
|
|
5928
|
+
self;
|
|
5929
|
+
log;
|
|
5930
|
+
handlersIndex = /* @__PURE__ */ new Map();
|
|
5931
|
+
/**
|
|
5932
|
+
* Set of keys that were registered at some point on this SW (sticky —
|
|
5933
|
+
* survives client closures + SW wake-ups via IndexedDB). Lets the fetch
|
|
5934
|
+
* handler distinguish "site URL whose owner is gone → 404" from
|
|
5935
|
+
* "unknown URL under scope → pass through to the network".
|
|
5936
|
+
*/
|
|
5937
|
+
claimedKeys = /* @__PURE__ */ new Set();
|
|
5938
|
+
_cleanup;
|
|
5939
|
+
_activationPromise;
|
|
5940
|
+
constructor({ self, log = () => {} }) {
|
|
5941
|
+
this.self = self;
|
|
5942
|
+
this.log = log;
|
|
5943
|
+
}
|
|
5944
|
+
get scope() {
|
|
5945
|
+
return `${new URL("./", this.self.location.href)}`;
|
|
5946
|
+
}
|
|
5947
|
+
/**
|
|
5948
|
+
* Look up the active channel for a key. Returns `undefined` when there
|
|
5949
|
+
* is no registration (or the registering client has gone away — stale
|
|
5950
|
+
* entries are pruned in place).
|
|
5951
|
+
*/
|
|
5952
|
+
async loadChannelInfo(key) {
|
|
5953
|
+
await this._checkActivation();
|
|
5954
|
+
for (const channelInfo of this.handlersIndex.values()) {
|
|
5955
|
+
if (channelInfo.key !== key) continue;
|
|
5956
|
+
const clientId = channelInfo.clientId;
|
|
5957
|
+
if (!clientId) continue;
|
|
5958
|
+
if (!await this.self.clients.get(clientId)) {
|
|
5959
|
+
this.handlersIndex.delete(clientId);
|
|
5960
|
+
continue;
|
|
5961
|
+
}
|
|
5962
|
+
return channelInfo;
|
|
5963
|
+
}
|
|
5964
|
+
}
|
|
5965
|
+
/** Whether `key` has ever been registered on this SW. */
|
|
5966
|
+
isClaimedKey(key) {
|
|
5967
|
+
return this.claimedKeys.has(key);
|
|
5968
|
+
}
|
|
5969
|
+
start() {
|
|
5970
|
+
const stopClaims = handleClaimRequests(this.self);
|
|
5971
|
+
const stopPortUpdates = handleChannelCalls(this.self, "UPDATE_COMMUNICATION_PORT", async (event, channelInfo, port) => {
|
|
5972
|
+
const clientId = event.source?.id;
|
|
5973
|
+
this.log("[UPDATE_COMMUNICATION_PORT]", clientId, channelInfo);
|
|
5974
|
+
await this._updateChannelInfo({
|
|
5975
|
+
...channelInfo,
|
|
5976
|
+
port,
|
|
5977
|
+
clientId
|
|
5978
|
+
});
|
|
5979
|
+
return { ...channelInfo };
|
|
5980
|
+
});
|
|
5981
|
+
this._cleanup = () => {
|
|
5982
|
+
stopClaims();
|
|
5983
|
+
stopPortUpdates();
|
|
2826
5984
|
};
|
|
2827
|
-
|
|
2828
|
-
|
|
5985
|
+
this.self.addEventListener("install", (event) => {
|
|
5986
|
+
this.log("Skip waiting on install.", event);
|
|
5987
|
+
this.self.skipWaiting();
|
|
5988
|
+
});
|
|
5989
|
+
this.self.addEventListener("activate", (event) => {
|
|
5990
|
+
this.log("Claim control over all clients.", event);
|
|
5991
|
+
event.waitUntil((async () => {
|
|
5992
|
+
await this.self.clients.claim();
|
|
5993
|
+
await this._checkActivation();
|
|
5994
|
+
})());
|
|
5995
|
+
});
|
|
5996
|
+
}
|
|
5997
|
+
async stop() {
|
|
5998
|
+
if (this._cleanup) {
|
|
5999
|
+
this._cleanup();
|
|
6000
|
+
this._cleanup = void 0;
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
6003
|
+
_checkActivation() {
|
|
6004
|
+
if (!this._activationPromise) this._activationPromise = this._activate();
|
|
6005
|
+
return this._activationPromise;
|
|
6006
|
+
}
|
|
6007
|
+
async _activate() {
|
|
6008
|
+
this.log("[checkActivation]");
|
|
6009
|
+
const clientsIndex = await this._loadClientIds();
|
|
6010
|
+
for (const [clientId, client] of clientsIndex.entries()) {
|
|
6011
|
+
const messageChannel = new MessageChannel();
|
|
6012
|
+
const port = messageChannel.port1;
|
|
6013
|
+
const channelInfo = await callChannel(client, "UPDATE_COMMUNICATION_PORT", {}, messageChannel.port2);
|
|
6014
|
+
await this._updateChannelInfo({
|
|
6015
|
+
...channelInfo,
|
|
6016
|
+
port,
|
|
6017
|
+
clientId
|
|
6018
|
+
});
|
|
6019
|
+
}
|
|
6020
|
+
}
|
|
6021
|
+
async _updateChannelInfo(channelInfo) {
|
|
6022
|
+
this.log("[updateClientInfo]", channelInfo);
|
|
6023
|
+
if (!channelInfo.clientId) return;
|
|
6024
|
+
this.handlersIndex.set(channelInfo.clientId, channelInfo);
|
|
6025
|
+
if (channelInfo.key && !this.claimedKeys.has(channelInfo.key)) {
|
|
6026
|
+
this.claimedKeys.add(channelInfo.key);
|
|
6027
|
+
await set("claimedKeys", [...this.claimedKeys].sort());
|
|
6028
|
+
}
|
|
6029
|
+
await this._updateClientIds([]);
|
|
6030
|
+
}
|
|
6031
|
+
async _loadClientIds() {
|
|
6032
|
+
const storedKeys = await get("claimedKeys") ?? [];
|
|
6033
|
+
for (const key of storedKeys) this.claimedKeys.add(key);
|
|
6034
|
+
const stored = await get("clientIds") ?? [];
|
|
6035
|
+
return await this._updateClientIds(new Set(stored));
|
|
6036
|
+
}
|
|
6037
|
+
async _updateClientIds(clientIds) {
|
|
6038
|
+
const ids = new Set(clientIds);
|
|
6039
|
+
for (const clientId of this.handlersIndex.keys()) ids.add(clientId);
|
|
6040
|
+
const index = /* @__PURE__ */ new Map();
|
|
6041
|
+
for (const clientId of ids) {
|
|
6042
|
+
const client = await this.self.clients.get(clientId);
|
|
6043
|
+
if (client) index.set(clientId, client);
|
|
6044
|
+
else this.handlersIndex.delete(clientId);
|
|
6045
|
+
}
|
|
6046
|
+
await set("clientIds", [...index.keys()].sort());
|
|
6047
|
+
return index;
|
|
6048
|
+
}
|
|
6049
|
+
};
|
|
6050
|
+
//#endregion
|
|
6051
|
+
//#region src/sw/sw-http-adapter.ts
|
|
2829
6052
|
/**
|
|
2830
|
-
*
|
|
2831
|
-
*
|
|
6053
|
+
* The page side of the same-origin ServiceWorker: registers the worker, and
|
|
6054
|
+
* attaches handler links to it.
|
|
6055
|
+
*
|
|
6056
|
+
* - `register(prefix, handler)` serves a handler in this page, under
|
|
6057
|
+
* `<scope>/<key>/...`.
|
|
6058
|
+
* - `attachWorker(worker)` links a Dedicated Worker that runs
|
|
6059
|
+
* `serveHttpInWorker(handler)`: the ServiceWorker then talks to the worker
|
|
6060
|
+
* directly, and this page carries nothing.
|
|
6061
|
+
* - `connectWebSocket(url, protocols)` and `WebSocket` open sockets to
|
|
6062
|
+
* handlers, through the ServiceWorker or straight to a handler of this page.
|
|
6063
|
+
*
|
|
6064
|
+
* Links are attached again whenever the ServiceWorker asks (after a restart),
|
|
6065
|
+
* and requests in flight on a handler that dies fail at once.
|
|
2832
6066
|
*/
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
6067
|
+
var SwHttpAdapter = class {
|
|
6068
|
+
options;
|
|
6069
|
+
_handlers = /* @__PURE__ */ new Map();
|
|
6070
|
+
_endpoint;
|
|
6071
|
+
_ownerLock = newLockName("webrun-http-owner");
|
|
6072
|
+
_id;
|
|
6073
|
+
_owner = crypto.randomUUID();
|
|
6074
|
+
_workers = /* @__PURE__ */ new Set();
|
|
6075
|
+
_releaseOwner;
|
|
6076
|
+
_serviceWorkerUrl;
|
|
6077
|
+
_serviceWorker;
|
|
6078
|
+
_registration;
|
|
6079
|
+
_registrationPromise;
|
|
6080
|
+
_cleanup = [];
|
|
6081
|
+
_attaching;
|
|
6082
|
+
_routerLock;
|
|
6083
|
+
_WebSocket;
|
|
6084
|
+
constructor(options) {
|
|
6085
|
+
this.options = options;
|
|
6086
|
+
if (!this.key) throw new Error("Key is not defined.");
|
|
6087
|
+
if (!this.scope) throw new Error("Scope is not defined");
|
|
6088
|
+
this._id = options.id ?? `page:${crypto.randomUUID()}`;
|
|
6089
|
+
this._endpoint = new HandlerEndpoint((request) => this._handleHttpRequest(request), { streamTimeout: options.streamTimeout });
|
|
6090
|
+
}
|
|
6091
|
+
get key() {
|
|
6092
|
+
return this.options.key;
|
|
6093
|
+
}
|
|
6094
|
+
get scope() {
|
|
6095
|
+
return this.options.scope ?? new URL("./", this.serviceWorkerUrl).pathname;
|
|
6096
|
+
}
|
|
6097
|
+
/**
|
|
6098
|
+
* The scope as a url on the worker's origin. Resolved against the worker's
|
|
6099
|
+
* own url when one is given, not against this module's: a bundle that is
|
|
6100
|
+
* not an ES module (an IIFE, Theia's frontend) has no `import.meta.url`, and
|
|
6101
|
+
* `new URL(scope, undefined)` threw `Invalid URL` there. Only without a
|
|
6102
|
+
* worker url does the module's location decide (its default `sw-worker.js`
|
|
6103
|
+
* sits next to it).
|
|
6104
|
+
*/
|
|
6105
|
+
get rootUrl() {
|
|
6106
|
+
const base = this.options.serviceWorkerUrl ? this.serviceWorkerUrl : import.meta.url;
|
|
6107
|
+
return new URL(this.scope, base);
|
|
6108
|
+
}
|
|
6109
|
+
get serviceWorkerUrl() {
|
|
6110
|
+
if (!this._serviceWorkerUrl) {
|
|
6111
|
+
const url = this.options.serviceWorkerUrl ? resolveWorkerUrl(this.options.serviceWorkerUrl) : new URL("./sw-worker.js", this.rootUrl);
|
|
6112
|
+
this._serviceWorkerUrl = `${url}`;
|
|
6113
|
+
}
|
|
6114
|
+
return this._serviceWorkerUrl;
|
|
6115
|
+
}
|
|
6116
|
+
/**
|
|
6117
|
+
* Registers the worker and waits until it is activated and controls this
|
|
6118
|
+
* page, then attaches this page's handler link. The page must be controlled,
|
|
6119
|
+
* because only a controlled page's `fetch()` reaches the worker. When the
|
|
6120
|
+
* page loaded uncontrolled (a hard reload does that), the worker is asked to
|
|
6121
|
+
* claim it. Rejects with a `ServiceWorkerControlError` when that fails or
|
|
6122
|
+
* `timeout` passes (`reason` says which step); a later `start()` tries
|
|
6123
|
+
* again.
|
|
6124
|
+
*/
|
|
6125
|
+
async start() {
|
|
6126
|
+
if (!this._registrationPromise) this._registrationPromise = (async () => {
|
|
6127
|
+
const registration = await navigator.serviceWorker.register(this.serviceWorkerUrl, { scope: this.scope });
|
|
6128
|
+
this._registration = registration;
|
|
6129
|
+
const stopListening = handleChannelCalls(navigator.serviceWorker, NEED_LINKS_CALL, async (_event, params) => {
|
|
6130
|
+
await this.relink(params?.routerLock);
|
|
6131
|
+
return true;
|
|
6132
|
+
});
|
|
6133
|
+
const onControllerChange = () => {
|
|
6134
|
+
const controller = navigator.serviceWorker.controller;
|
|
6135
|
+
if (controller) this._serviceWorker = controller;
|
|
6136
|
+
};
|
|
6137
|
+
navigator.serviceWorker.addEventListener("controllerchange", onControllerChange);
|
|
6138
|
+
this._cleanup.push(stopListening, () => navigator.serviceWorker.removeEventListener("controllerchange", onControllerChange));
|
|
6139
|
+
const timeout = this.options.timeout ?? 3e4;
|
|
6140
|
+
const deadline = Date.now() + timeout;
|
|
6141
|
+
try {
|
|
6142
|
+
this._serviceWorker = await awaitServiceWorkerControl(registration, {
|
|
6143
|
+
timeout,
|
|
6144
|
+
reloadIfUncontrolled: this.options.reloadIfUncontrolled
|
|
6145
|
+
});
|
|
6146
|
+
this._releaseOwner ??= await holdLock(this._ownerLock);
|
|
6147
|
+
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\`).`));
|
|
6148
|
+
} catch (error) {
|
|
6149
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
6150
|
+
this._registration = void 0;
|
|
6151
|
+
this._registrationPromise = void 0;
|
|
6152
|
+
throw error;
|
|
6153
|
+
}
|
|
6154
|
+
})();
|
|
6155
|
+
return this._registrationPromise;
|
|
6156
|
+
}
|
|
6157
|
+
/** Detaches every link, and unregisters the worker. */
|
|
6158
|
+
async stop() {
|
|
6159
|
+
for (const cleanup of this._cleanup.splice(0)) cleanup();
|
|
6160
|
+
for (const worker of [...this._workers]) await worker.detach().catch(() => {});
|
|
6161
|
+
const sw = this._serviceWorker;
|
|
6162
|
+
if (sw) await callChannel(sw, DETACH_CALL, {
|
|
6163
|
+
key: this.key,
|
|
6164
|
+
id: this._id,
|
|
6165
|
+
owner: this._owner
|
|
6166
|
+
}).catch(() => {});
|
|
6167
|
+
await this._endpoint.unlink();
|
|
6168
|
+
this._releaseOwner?.();
|
|
6169
|
+
this._releaseOwner = void 0;
|
|
6170
|
+
const registration = this._registration;
|
|
6171
|
+
this._registration = void 0;
|
|
6172
|
+
this._registrationPromise = void 0;
|
|
6173
|
+
try {
|
|
6174
|
+
await registration?.unregister();
|
|
6175
|
+
} catch (error) {
|
|
6176
|
+
console.log("Service Worker unregistration failed: ", error);
|
|
6177
|
+
}
|
|
6178
|
+
}
|
|
6179
|
+
/**
|
|
6180
|
+
* Registers an HTTP handler on a prefix. Returns the resulting base URL and a
|
|
6181
|
+
* disposer.
|
|
6182
|
+
*/
|
|
6183
|
+
async register(prefix, handler) {
|
|
6184
|
+
const cleanPrefix = `./${(prefix ?? "").replace(/^[./]+/, "")}`;
|
|
6185
|
+
const baseUrl = `${new URL(cleanPrefix, this.rootUrl)}`;
|
|
6186
|
+
this._handlers.set(baseUrl, handler);
|
|
6187
|
+
const handlers = this._handlers;
|
|
6188
|
+
return {
|
|
6189
|
+
baseUrl,
|
|
6190
|
+
prefix: cleanPrefix,
|
|
6191
|
+
async remove() {
|
|
6192
|
+
handlers.delete(baseUrl);
|
|
6193
|
+
}
|
|
6194
|
+
};
|
|
6195
|
+
}
|
|
6196
|
+
/**
|
|
6197
|
+
* Links a Dedicated Worker that runs `serveHttpInWorker(handler)` as a
|
|
6198
|
+
* handler of `key`. The ServiceWorker sends it requests directly, without
|
|
6199
|
+
* this page relaying anything, so a busy or throttled page does not slow
|
|
6200
|
+
* them down.
|
|
6201
|
+
*/
|
|
6202
|
+
async attachWorker(worker, options = {}) {
|
|
6203
|
+
await this.start();
|
|
6204
|
+
const controls = [];
|
|
6205
|
+
let retry;
|
|
6206
|
+
const { control, ownerLock } = await new Promise((resolve, reject) => {
|
|
6207
|
+
const timer = setTimeout(() => {
|
|
6208
|
+
clearInterval(retry);
|
|
6209
|
+
for (const port of controls) port.close();
|
|
6210
|
+
reject(/* @__PURE__ */ new Error("The worker did not answer within the timeout. Does it call serveHttpInWorker()?"));
|
|
6211
|
+
}, this.options.timeout ?? 3e4);
|
|
6212
|
+
const hello = () => {
|
|
6213
|
+
const channel = new MessageChannel();
|
|
6214
|
+
controls.push(channel.port1);
|
|
6215
|
+
channel.port1.onmessage = (event) => {
|
|
6216
|
+
const message = event.data;
|
|
6217
|
+
if (message?.type !== "ready") return;
|
|
6218
|
+
clearTimeout(timer);
|
|
6219
|
+
clearInterval(retry);
|
|
6220
|
+
for (const port of controls) if (port !== channel.port1) port.close();
|
|
6221
|
+
resolve({
|
|
6222
|
+
control: channel.port1,
|
|
6223
|
+
ownerLock: message.ownerLock
|
|
6224
|
+
});
|
|
6225
|
+
};
|
|
6226
|
+
worker.postMessage({ type: WORKER_HELLO }, [channel.port2]);
|
|
6227
|
+
};
|
|
6228
|
+
hello();
|
|
6229
|
+
retry = setInterval(hello, 500);
|
|
6230
|
+
});
|
|
6231
|
+
const key = options.key ?? this.key;
|
|
6232
|
+
const id = options.id ?? `worker:${crypto.randomUUID()}`;
|
|
6233
|
+
for (const old of [...this._workers]) if (old.key === key && old.id === id) old.retire();
|
|
6234
|
+
const link = new WorkerLinkImpl(this, control, {
|
|
6235
|
+
key,
|
|
6236
|
+
id,
|
|
6237
|
+
owner: crypto.randomUUID(),
|
|
6238
|
+
meta: options.meta,
|
|
6239
|
+
ownerLock
|
|
6240
|
+
});
|
|
6241
|
+
this._workers.add(link);
|
|
6242
|
+
await link.attach();
|
|
6243
|
+
return link;
|
|
6244
|
+
}
|
|
6245
|
+
/**
|
|
6246
|
+
* Opens the transport of a socket to the handler `url` routes to: a handler
|
|
6247
|
+
* of this page directly, any other through the ServiceWorker. Resolves once
|
|
6248
|
+
* the handler accepted. An arrow function, so it can be handed around:
|
|
6249
|
+
* `createWebSocketClass(adapter.connectWebSocket)`.
|
|
6250
|
+
*/
|
|
6251
|
+
connectWebSocket = async (url, protocols = []) => {
|
|
6252
|
+
const httpUrl = new URL(`${url}`, globalThis.location?.href);
|
|
6253
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
6254
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
6255
|
+
const local = this._findHandler(`${httpUrl}`);
|
|
6256
|
+
if (local) {
|
|
6257
|
+
const result = await serveWebSocketUpgrade(local, {
|
|
6258
|
+
url: `${httpUrl}`,
|
|
6259
|
+
protocols
|
|
6260
|
+
});
|
|
6261
|
+
if (!result.ok) throw new Error(result.message);
|
|
6262
|
+
return {
|
|
6263
|
+
port: result.port,
|
|
6264
|
+
protocol: result.protocol
|
|
6265
|
+
};
|
|
2858
6266
|
}
|
|
6267
|
+
await this.start();
|
|
6268
|
+
return await callChannelWithin(this._callTimeout(), this._worker(), WS_CONNECT_CALL, {
|
|
6269
|
+
url: `${httpUrl}`,
|
|
6270
|
+
protocols
|
|
6271
|
+
});
|
|
2859
6272
|
};
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
6273
|
+
/**
|
|
6274
|
+
* A WHATWG `WebSocket` class whose sockets reach this adapter's handlers:
|
|
6275
|
+
* `new adapter.WebSocket(`${baseUrl}chat`, ["v1"])`. The global
|
|
6276
|
+
* `WebSocket` is left alone.
|
|
6277
|
+
*/
|
|
6278
|
+
get WebSocket() {
|
|
6279
|
+
this._WebSocket ??= createWebSocketClass(this.connectWebSocket, this.options.webSocket);
|
|
6280
|
+
return this._WebSocket;
|
|
6281
|
+
}
|
|
6282
|
+
/**
|
|
6283
|
+
* Attaches again every link not made for the router holding
|
|
6284
|
+
* `currentRouterLock` (every link, without it). The ServiceWorker asks for
|
|
6285
|
+
* this after a restart; a page may call it too.
|
|
6286
|
+
*/
|
|
6287
|
+
async relink(currentRouterLock) {
|
|
6288
|
+
if (!this._registrationPromise) return;
|
|
6289
|
+
const stale = (routerLock) => currentRouterLock === void 0 || routerLock !== currentRouterLock;
|
|
6290
|
+
const jobs = [];
|
|
6291
|
+
if (stale(this._routerLock)) jobs.push(this._attachPage());
|
|
6292
|
+
for (const worker of this._workers) if (stale(worker.routerLock)) jobs.push(worker.attach());
|
|
6293
|
+
await Promise.allSettled(jobs);
|
|
6294
|
+
}
|
|
6295
|
+
/** @internal Posts a plain message to the ServiceWorker, which starts it if stopped. */
|
|
6296
|
+
_poke(type) {
|
|
6297
|
+
try {
|
|
6298
|
+
this._worker().postMessage({ type });
|
|
6299
|
+
} catch {}
|
|
6300
|
+
}
|
|
6301
|
+
/** @internal */
|
|
6302
|
+
_worker() {
|
|
6303
|
+
const worker = navigator.serviceWorker.controller ?? this._serviceWorker ?? this._registration?.active;
|
|
6304
|
+
if (!worker) throw new Error("The ServiceWorker is not running; call start() first");
|
|
6305
|
+
return worker;
|
|
6306
|
+
}
|
|
6307
|
+
/** @internal */
|
|
6308
|
+
_forget(link) {
|
|
6309
|
+
this._workers.delete(link);
|
|
6310
|
+
}
|
|
6311
|
+
/** @internal How long a call to the ServiceWorker may take. */
|
|
6312
|
+
_callTimeout() {
|
|
6313
|
+
return this.options.timeout ?? 3e4;
|
|
6314
|
+
}
|
|
6315
|
+
_attachPage() {
|
|
6316
|
+
this._attaching ??= (async () => {
|
|
6317
|
+
try {
|
|
6318
|
+
const down = new MessageChannel();
|
|
6319
|
+
const ctl = new MessageChannel();
|
|
6320
|
+
const params = {
|
|
6321
|
+
wire: HTTP_LINK_PROTOCOL,
|
|
6322
|
+
key: this.key,
|
|
6323
|
+
id: this._id,
|
|
6324
|
+
owner: this._owner,
|
|
6325
|
+
ownerLock: this._releaseOwner && locksAvailable() ? this._ownerLock : void 0,
|
|
6326
|
+
meta: this.options.meta,
|
|
6327
|
+
ctl: true
|
|
6328
|
+
};
|
|
6329
|
+
const reply = await callChannelWithin(this._callTimeout(), this._worker(), ATTACH_CALL, params, down.port1, ctl.port1);
|
|
6330
|
+
checkReply(reply, this._worker());
|
|
6331
|
+
await this._endpoint.link(this.key, {
|
|
6332
|
+
down: down.port2,
|
|
6333
|
+
ctl: ctl.port2
|
|
6334
|
+
}, reply.routerLock);
|
|
6335
|
+
this._routerLock = reply.routerLock;
|
|
6336
|
+
} finally {
|
|
6337
|
+
this._attaching = void 0;
|
|
6338
|
+
}
|
|
6339
|
+
})();
|
|
6340
|
+
return this._attaching;
|
|
6341
|
+
}
|
|
6342
|
+
_findHandler(url) {
|
|
6343
|
+
for (const [urlPrefix, handler] of this._handlers) if (url.indexOf(urlPrefix) === 0) return handler;
|
|
6344
|
+
}
|
|
6345
|
+
async _handleHttpRequest(request) {
|
|
6346
|
+
const handler = this._findHandler(request.url);
|
|
6347
|
+
if (handler) return await handler(request);
|
|
6348
|
+
return new Response(null, {
|
|
6349
|
+
status: 404,
|
|
6350
|
+
statusText: "Error 404: Not found"
|
|
2870
6351
|
});
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
|
|
6352
|
+
}
|
|
6353
|
+
};
|
|
6354
|
+
var WorkerLinkImpl = class {
|
|
6355
|
+
_adapter;
|
|
6356
|
+
_control;
|
|
6357
|
+
key;
|
|
6358
|
+
id;
|
|
6359
|
+
owner;
|
|
6360
|
+
routerLock;
|
|
6361
|
+
_meta;
|
|
6362
|
+
_ownerLock;
|
|
6363
|
+
_attaching;
|
|
6364
|
+
_detached = false;
|
|
6365
|
+
constructor(_adapter, _control, init) {
|
|
6366
|
+
this._adapter = _adapter;
|
|
6367
|
+
this._control = _control;
|
|
6368
|
+
this.key = init.key;
|
|
6369
|
+
this.id = init.id;
|
|
6370
|
+
this.owner = init.owner;
|
|
6371
|
+
this._meta = init.meta;
|
|
6372
|
+
this._ownerLock = init.ownerLock;
|
|
6373
|
+
_control.onmessage = (event) => {
|
|
6374
|
+
const message = event.data;
|
|
6375
|
+
if (message?.type === "relink") {
|
|
6376
|
+
this._adapter._poke(WAKE_MESSAGE);
|
|
6377
|
+
this.attach().catch(() => {});
|
|
6378
|
+
} else if (message?.type === "keepalive") this._adapter._poke(KEEPALIVE_MESSAGE);
|
|
2877
6379
|
};
|
|
2878
6380
|
}
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
channel.port2.close();
|
|
2888
|
-
return null;
|
|
6381
|
+
/**
|
|
6382
|
+
* Forgets this link without telling the ServiceWorker: another attachment
|
|
6383
|
+
* took its slot, and the ServiceWorker retires it by itself.
|
|
6384
|
+
*/
|
|
6385
|
+
retire() {
|
|
6386
|
+
this._detached = true;
|
|
6387
|
+
this._adapter._forget(this);
|
|
6388
|
+
this._control.onmessage = null;
|
|
2889
6389
|
}
|
|
2890
|
-
|
|
6390
|
+
/** Makes fresh channels and attaches them; the worker gets its ends. */
|
|
6391
|
+
attach() {
|
|
6392
|
+
if (this._detached) return Promise.resolve();
|
|
6393
|
+
this._attaching ??= (async () => {
|
|
6394
|
+
try {
|
|
6395
|
+
if (this._ownerLock) {
|
|
6396
|
+
const held = await heldLockNames();
|
|
6397
|
+
if (held && !held.has(this._ownerLock)) {
|
|
6398
|
+
this.retire();
|
|
6399
|
+
return;
|
|
6400
|
+
}
|
|
6401
|
+
}
|
|
6402
|
+
const down = new MessageChannel();
|
|
6403
|
+
const ctl = new MessageChannel();
|
|
6404
|
+
const up = new MessageChannel();
|
|
6405
|
+
const params = {
|
|
6406
|
+
wire: HTTP_LINK_PROTOCOL,
|
|
6407
|
+
key: this.key,
|
|
6408
|
+
id: this.id,
|
|
6409
|
+
owner: this.owner,
|
|
6410
|
+
ownerLock: this._ownerLock,
|
|
6411
|
+
meta: this._meta,
|
|
6412
|
+
ctl: true,
|
|
6413
|
+
up: true
|
|
6414
|
+
};
|
|
6415
|
+
const sw = this._adapter._worker();
|
|
6416
|
+
const reply = await callChannelWithin(this._adapter._callTimeout(), sw, ATTACH_CALL, params, down.port1, ctl.port1, up.port1);
|
|
6417
|
+
checkReply(reply, sw);
|
|
6418
|
+
this.routerLock = reply.routerLock;
|
|
6419
|
+
this._control.postMessage({
|
|
6420
|
+
type: "link",
|
|
6421
|
+
key: this.key,
|
|
6422
|
+
routerLock: reply.routerLock
|
|
6423
|
+
}, [
|
|
6424
|
+
down.port2,
|
|
6425
|
+
ctl.port2,
|
|
6426
|
+
up.port2
|
|
6427
|
+
]);
|
|
6428
|
+
} finally {
|
|
6429
|
+
this._attaching = void 0;
|
|
6430
|
+
}
|
|
6431
|
+
})();
|
|
6432
|
+
return this._attaching;
|
|
6433
|
+
}
|
|
6434
|
+
async drain({ ms } = {}) {
|
|
6435
|
+
if (this._detached) return;
|
|
6436
|
+
this._detached = true;
|
|
6437
|
+
this._adapter._forget(this);
|
|
6438
|
+
try {
|
|
6439
|
+
await callChannel(this._adapter._worker(), DRAIN_CALL, {
|
|
6440
|
+
key: this.key,
|
|
6441
|
+
id: this.id,
|
|
6442
|
+
owner: this.owner,
|
|
6443
|
+
ms
|
|
6444
|
+
});
|
|
6445
|
+
} finally {
|
|
6446
|
+
this._unlink();
|
|
6447
|
+
}
|
|
6448
|
+
}
|
|
6449
|
+
async detach() {
|
|
6450
|
+
if (this._detached) return;
|
|
6451
|
+
this._detached = true;
|
|
6452
|
+
this._adapter._forget(this);
|
|
6453
|
+
await callChannel(this._adapter._worker(), DETACH_CALL, {
|
|
6454
|
+
key: this.key,
|
|
6455
|
+
id: this.id,
|
|
6456
|
+
owner: this.owner
|
|
6457
|
+
}).catch(() => {});
|
|
6458
|
+
this._unlink();
|
|
6459
|
+
}
|
|
6460
|
+
_unlink() {
|
|
6461
|
+
this._control.postMessage({
|
|
6462
|
+
type: "unlink",
|
|
6463
|
+
key: this.key
|
|
6464
|
+
});
|
|
6465
|
+
this._control.onmessage = null;
|
|
6466
|
+
}
|
|
6467
|
+
};
|
|
6468
|
+
function checkReply(reply, sw) {
|
|
6469
|
+
if (reply?.accepted === "webrun-http-link/2") return;
|
|
6470
|
+
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.`);
|
|
2891
6471
|
}
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
6472
|
+
//#endregion
|
|
6473
|
+
//#region src/sw/sw-websocket.ts
|
|
6474
|
+
/**
|
|
6475
|
+
* Opens the transport of a socket through the ServiceWorker controlling this
|
|
6476
|
+
* page, for a page that has no adapter of its own: content a handler serves
|
|
6477
|
+
* under the same-origin dispatcher, or under a relay. The ServiceWorker
|
|
6478
|
+
* routes `url` like a fetch, and the handler accepts or refuses the upgrade.
|
|
6479
|
+
*/
|
|
6480
|
+
async function connectWebSocketThroughServiceWorker(url, protocols = [], container = navigator.serviceWorker) {
|
|
6481
|
+
const worker = container.controller;
|
|
6482
|
+
if (!worker) throw new Error("This page is not controlled by a ServiceWorker");
|
|
6483
|
+
const httpUrl = new URL(`${url}`, globalThis.location?.href);
|
|
6484
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
6485
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
6486
|
+
return await callChannel(worker, WS_CONNECT_CALL, {
|
|
6487
|
+
url: `${httpUrl}`,
|
|
6488
|
+
protocols
|
|
2897
6489
|
});
|
|
2898
|
-
register(() => callChannel(communicationPort, "UNREGISTER", { key }));
|
|
2899
|
-
register(handleKeyedChannelCalls(communicationPort, "CONNECT", key, async (event, data, port) => {
|
|
2900
|
-
return await handler(event, data, port);
|
|
2901
|
-
}));
|
|
2902
|
-
return cleanup;
|
|
2903
6490
|
}
|
|
2904
6491
|
/**
|
|
2905
|
-
*
|
|
2906
|
-
*
|
|
2907
|
-
*
|
|
2908
|
-
*
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
|
|
6492
|
+
* A WHATWG `WebSocket` class over `connectWebSocketThroughServiceWorker`.
|
|
6493
|
+
* Install it where the page's code expects `WebSocket`, e.g.
|
|
6494
|
+
* `globalThis.WebSocket = serviceWorkerWebSocketClass()` in content that only
|
|
6495
|
+
* talks to its own handlers.
|
|
6496
|
+
*/
|
|
6497
|
+
function serviceWorkerWebSocketClass(options) {
|
|
6498
|
+
return createWebSocketClass((url, protocols) => connectWebSocketThroughServiceWorker(url, protocols), options);
|
|
6499
|
+
}
|
|
6500
|
+
//#endregion
|
|
6501
|
+
//#region src/sw/worker-service.ts
|
|
6502
|
+
/**
|
|
6503
|
+
* Serves `handler` from a Dedicated Worker, on the links the page attaches
|
|
6504
|
+
* with `adapter.attachWorker(worker)`:
|
|
2913
6505
|
*
|
|
2914
|
-
*
|
|
2915
|
-
*
|
|
2916
|
-
*
|
|
2917
|
-
*
|
|
2918
|
-
* the addressee must stay SILENT and leave the transferred port untouched.
|
|
6506
|
+
* ```ts
|
|
6507
|
+
* // worker.ts
|
|
6508
|
+
* const service = serveHttpInWorker(async (request) => new Response("hi"));
|
|
6509
|
+
* ```
|
|
2919
6510
|
*
|
|
2920
|
-
*
|
|
2921
|
-
*
|
|
2922
|
-
*
|
|
2923
|
-
*
|
|
6511
|
+
* The worker holds an owner lock while it lives, so the ServiceWorker notices
|
|
6512
|
+
* at once when it is terminated. It watches the ServiceWorker's router lock,
|
|
6513
|
+
* and asks its page to attach it again when its links died and a call waits.
|
|
6514
|
+
* While calls through the router are in flight it asks its page every 20 s to
|
|
6515
|
+
* keep the ServiceWorker awake — only a message to the ServiceWorker object
|
|
6516
|
+
* counts as an event, and a worker cannot post one.
|
|
2924
6517
|
*/
|
|
2925
|
-
function
|
|
2926
|
-
const
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
const
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
6518
|
+
function serveHttpInWorker(handler, options = {}) {
|
|
6519
|
+
const scope = options.scope ?? globalThis;
|
|
6520
|
+
const ownerLock = newLockName("webrun-http-owner");
|
|
6521
|
+
const held = holdLock(ownerLock);
|
|
6522
|
+
const controls = /* @__PURE__ */ new Set();
|
|
6523
|
+
const tellPages = (message) => {
|
|
6524
|
+
for (const control of controls) control.postMessage(message);
|
|
6525
|
+
};
|
|
6526
|
+
const endpoint = new HandlerEndpoint(handler, {
|
|
6527
|
+
...options,
|
|
6528
|
+
requestRelink: () => tellPages({ type: "relink" }),
|
|
6529
|
+
keepAlive: () => tellPages({ type: "keepalive" })
|
|
6530
|
+
});
|
|
6531
|
+
const onMessage = (event) => {
|
|
6532
|
+
const { data, ports } = event;
|
|
6533
|
+
if (data?.type !== "webrun-http:worker-hello") return;
|
|
6534
|
+
const control = ports?.[0];
|
|
6535
|
+
if (!control) return;
|
|
6536
|
+
controls.add(control);
|
|
6537
|
+
control.onmessage = (message) => {
|
|
6538
|
+
const msg = message.data;
|
|
6539
|
+
if (msg?.type === "link") {
|
|
6540
|
+
const [down, ctl, up] = message.ports;
|
|
6541
|
+
if (down) endpoint.link(msg.key, {
|
|
6542
|
+
down,
|
|
6543
|
+
ctl,
|
|
6544
|
+
up
|
|
6545
|
+
}, msg.routerLock);
|
|
6546
|
+
} else if (msg?.type === "unlink") endpoint.unlink(msg.key);
|
|
6547
|
+
};
|
|
6548
|
+
held.then(() => control.postMessage({
|
|
6549
|
+
type: "ready",
|
|
6550
|
+
ownerLock: locksAvailable() ? ownerLock : void 0
|
|
6551
|
+
}));
|
|
6552
|
+
};
|
|
6553
|
+
scope.addEventListener("message", onMessage);
|
|
6554
|
+
const baseUrl = () => globalThis.location?.href;
|
|
6555
|
+
const connectWebSocket = (url, protocols = []) => {
|
|
6556
|
+
const httpUrl = new URL(`${url}`, baseUrl());
|
|
6557
|
+
if (httpUrl.protocol === "ws:") httpUrl.protocol = "http:";
|
|
6558
|
+
else if (httpUrl.protocol === "wss:") httpUrl.protocol = "https:";
|
|
6559
|
+
return endpoint.connectWebSocket(`${httpUrl}`, protocols);
|
|
6560
|
+
};
|
|
6561
|
+
let WebSocketClass;
|
|
6562
|
+
return {
|
|
6563
|
+
fetch(input, init) {
|
|
6564
|
+
const request = input instanceof Request && init === void 0 ? input : new Request(input instanceof Request ? input : new URL(`${input}`, baseUrl()), init);
|
|
6565
|
+
return endpoint.fetch(request);
|
|
6566
|
+
},
|
|
6567
|
+
connectWebSocket,
|
|
6568
|
+
get WebSocket() {
|
|
6569
|
+
WebSocketClass ??= createWebSocketClass(connectWebSocket, options.webSocket);
|
|
6570
|
+
return WebSocketClass;
|
|
6571
|
+
},
|
|
6572
|
+
get linked() {
|
|
6573
|
+
return endpoint.linked;
|
|
6574
|
+
},
|
|
6575
|
+
async close() {
|
|
6576
|
+
scope.removeEventListener("message", onMessage);
|
|
6577
|
+
await endpoint.close();
|
|
6578
|
+
for (const control of controls) control.close();
|
|
6579
|
+
controls.clear();
|
|
6580
|
+
(await held)();
|
|
2936
6581
|
}
|
|
2937
|
-
port?.postMessage(response);
|
|
2938
6582
|
};
|
|
2939
|
-
target.addEventListener("message", listener);
|
|
2940
|
-
target.start?.();
|
|
2941
|
-
return () => target.removeEventListener("message", listener);
|
|
2942
6583
|
}
|
|
2943
6584
|
//#endregion
|
|
2944
|
-
export { CLAIM_CALL, DEFAULT_SERVICE_WORKER_TIMEOUT, DuplexSiteBuilder, HttpError, HttpParseError, PEER_ERROR_HEADER, ServiceWorkerControlError, TransportClosedError, awaitActiveServiceWorker, awaitServiceWorkerControl, callChannel, callHttpService, collect, collectBytes, collectString, decodeJsonl, decodeMessage, decodeText, defaultCodec, deserializeError, emulateMux, encodeJsonl, encodeMessage, encodeText, fetchOverDuplex, fromReadableStream, getRelayWindowMessageHandler, handleChannelCalls, handleClaimRequests, handleHttpRequests, handleStreams, httpCodec, httpFetch, httpServe, initHttpService, initServiceWorker, initializeConnection, joinLines, jsonEnvelopeCodec, map, newAsyncGenerator, newCreditGrantor, newCreditLedger, newHttpClientStub, newHttpCodec, newHttpServerStub, newInvokationChannel, newRegistry, newRemoteRelayChannel, newServiceWorkerPort, newSniffingCodec, normalizeToUint8Array, recieveIterator, registerConnectionsHandler, sendHttpRequest, sendIterator, sendStream, serializeError, serveFetchOverDuplex, splitLines, splitServiceUrl, toChunks, toReadableStream };
|
|
6585
|
+
export { CLAIM_CALL, DEFAULT_CLOSE_TIMEOUT_MS, DEFAULT_HEARTBEAT_MS, DEFAULT_SERVICE_WORKER_TIMEOUT, DuplexSiteBuilder, HANDLER_LOST_MESSAGE, HTTP_LINK_PROTOCOL, HandlerEndpoint, HandlerTable, HttpError, HttpParseError, LinkLostError, PEER_ERROR_HEADER, PortRendezvous, ROUTER_LOST_MESSAGE, ServerWebSocket, ServiceWorkerControlError, SwHttpAdapter, SwHttpDispatcher, SwPortDispatcher, SwPortHandler, TransportClosedError, WS_PORT_PROTOCOL_VERSION, WS_VERSION_HEADER, WsCloseEvent, answerConnect, awaitActiveServiceWorker, awaitServiceWorkerControl, callChannel, callChannelWithin, callHttpService, callWebSocketService, collect, collectBytes, collectString, connectHttpLink, connectWebSocketThroughServiceWorker, createWebSocketClass, decodeJsonl, decodeMessage, decodeText, defaultCodec, deserializeError, emulateMux, encodeJsonl, encodeMessage, encodeText, fetchOverDuplex, fromReadableStream, getRelayWindowMessageHandler, handleChannelCalls, handleClaimRequests, handleHttpRequests, handleStreams, holdLock, httpCodec, httpFetch, httpServe, initHttpService, initServiceWorker, initializeConnection, isWebSocketUpgrade, joinLines, jsonEnvelopeCodec, leastInflightRoute, locksAvailable, map, newAsyncGenerator, newCreditGrantor, newCreditLedger, newHttpClientStub, newHttpCodec, newHttpServerStub, newInvokationChannel, newLockName, newRegistry, newRemoteRelayChannel, newServiceWorkerPort, newSniffingCodec, newWebSocketUpgradeRequest, normalizeToUint8Array, recieveIterator, registerConnectionsHandler, relayWebSocketClass, requestedProtocols, sendHttpRequest, sendIterator, sendOverConnection, sendStream, serializeError, serveFetchOverDuplex, serveHttpInWorker, serveHttpLink, serveWebSocketUpgrade, serviceWorkerWebSocketClass, splitLines, splitServiceUrl, startHttpDispatcher, takePort, takeUpgrade, toChunks, toReadableStream, trackedLink, unwrapTransfer, upgradeWebSocket, watchLock, withHeaders, withTransfer };
|