@opendatalabs/personal-server-ts-lite 0.0.1-canary.052d47e → 0.0.1-canary.05cdd81
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/dist/account-mode-store.d.ts +11 -0
- package/dist/account-mode-store.d.ts.map +1 -0
- package/dist/account-mode-store.js +68 -0
- package/dist/account-mode-store.js.map +1 -0
- package/dist/additions-crypto.d.ts +3 -0
- package/dist/additions-crypto.d.ts.map +1 -0
- package/dist/additions-crypto.js +42 -0
- package/dist/additions-crypto.js.map +1 -0
- package/dist/additions-protocol.d.ts +56 -0
- package/dist/additions-protocol.d.ts.map +1 -0
- package/dist/additions-protocol.js +17 -0
- package/dist/additions-protocol.js.map +1 -0
- package/dist/additions-session.d.ts +20 -0
- package/dist/additions-session.d.ts.map +1 -0
- package/dist/additions-session.js +215 -0
- package/dist/additions-session.js.map +1 -0
- package/dist/additions-transport.d.ts +72 -0
- package/dist/additions-transport.d.ts.map +1 -0
- package/dist/additions-transport.js +428 -0
- package/dist/additions-transport.js.map +1 -0
- package/dist/additions-worker.bundle.js +31252 -0
- package/dist/additions-worker.d.ts +2 -0
- package/dist/additions-worker.d.ts.map +1 -0
- package/dist/additions-worker.js +308 -0
- package/dist/additions-worker.js.map +1 -0
- package/dist/bridge.d.ts +3 -0
- package/dist/bridge.d.ts.map +1 -1
- package/dist/bridge.js +4 -0
- package/dist/bridge.js.map +1 -1
- package/dist/browser-runtime.d.ts +111 -1
- package/dist/browser-runtime.d.ts.map +1 -1
- package/dist/browser-runtime.js +176 -11
- package/dist/browser-runtime.js.map +1 -1
- package/dist/canonical-persistence.d.ts +53 -0
- package/dist/canonical-persistence.d.ts.map +1 -0
- package/dist/canonical-persistence.js +13 -0
- package/dist/canonical-persistence.js.map +1 -0
- package/dist/canonical-store.d.ts +395 -0
- package/dist/canonical-store.d.ts.map +1 -0
- package/dist/canonical-store.js +1807 -0
- package/dist/canonical-store.js.map +1 -0
- package/dist/client.d.ts +24 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +214 -1
- package/dist/client.js.map +1 -1
- package/dist/derivatives.d.ts.map +1 -1
- package/dist/derivatives.js +4 -2
- package/dist/derivatives.js.map +1 -1
- package/dist/diagnostics.d.ts +3 -0
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +9 -1
- package/dist/diagnostics.js.map +1 -1
- package/dist/history-probe-worker.bundle.js +31274 -0
- package/dist/history-probe.worker.d.ts +35 -0
- package/dist/history-probe.worker.d.ts.map +1 -0
- package/dist/history-probe.worker.js +161 -0
- package/dist/history-probe.worker.js.map +1 -0
- package/dist/index.d.ts +17 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -1
- package/dist/localdb-port.d.ts +28 -0
- package/dist/localdb-port.d.ts.map +1 -0
- package/dist/localdb-port.js +30 -0
- package/dist/localdb-port.js.map +1 -0
- package/dist/mcp-store.d.ts +1 -1
- package/dist/mcp-store.d.ts.map +1 -1
- package/dist/mcp-store.js +144 -15
- package/dist/mcp-store.js.map +1 -1
- package/dist/oura-import.d.ts +2 -0
- package/dist/oura-import.d.ts.map +1 -0
- package/dist/oura-import.js +3 -0
- package/dist/oura-import.js.map +1 -0
- package/dist/owner-binding.d.ts +5 -0
- package/dist/owner-binding.d.ts.map +1 -1
- package/dist/owner-binding.js +4 -8
- package/dist/owner-binding.js.map +1 -1
- package/dist/persistence.d.ts +1 -1
- package/dist/persistence.d.ts.map +1 -1
- package/dist/persistence.js +2 -2
- package/dist/persistence.js.map +1 -1
- package/dist/pull-signals.d.ts +38 -0
- package/dist/pull-signals.d.ts.map +1 -0
- package/dist/pull-signals.js +73 -0
- package/dist/pull-signals.js.map +1 -0
- package/dist/relay-tls.d.ts.map +1 -1
- package/dist/relay-tls.js +10 -0
- package/dist/relay-tls.js.map +1 -1
- package/dist/relay.d.ts +91 -3
- package/dist/relay.d.ts.map +1 -1
- package/dist/relay.js +522 -75
- package/dist/relay.js.map +1 -1
- package/dist/replication-coordinator-state.d.ts +19 -0
- package/dist/replication-coordinator-state.d.ts.map +1 -0
- package/dist/replication-coordinator-state.js +20 -0
- package/dist/replication-coordinator-state.js.map +1 -0
- package/dist/replication-door.d.ts +17 -0
- package/dist/replication-door.d.ts.map +1 -0
- package/dist/replication-door.js +23 -0
- package/dist/replication-door.js.map +1 -0
- package/dist/replication-engine.d.ts +49 -0
- package/dist/replication-engine.d.ts.map +1 -0
- package/dist/replication-engine.js +589 -0
- package/dist/replication-engine.js.map +1 -0
- package/dist/replication-host.d.ts +92 -0
- package/dist/replication-host.d.ts.map +1 -0
- package/dist/replication-host.js +135 -0
- package/dist/replication-host.js.map +1 -0
- package/dist/replication-ports.d.ts +194 -0
- package/dist/replication-ports.d.ts.map +1 -0
- package/dist/replication-ports.js +58 -0
- package/dist/replication-ports.js.map +1 -0
- package/dist/replication-runtime.d.ts +64 -0
- package/dist/replication-runtime.d.ts.map +1 -0
- package/dist/replication-runtime.js +79 -0
- package/dist/replication-runtime.js.map +1 -0
- package/dist/replication-storage.d.ts +42 -0
- package/dist/replication-storage.d.ts.map +1 -0
- package/dist/replication-storage.js +173 -0
- package/dist/replication-storage.js.map +1 -0
- package/dist/runtime.d.ts +85 -6
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +561 -37
- package/dist/runtime.js.map +1 -1
- package/dist/seed-staging.d.ts +8 -0
- package/dist/seed-staging.d.ts.map +1 -0
- package/dist/seed-staging.js +106 -0
- package/dist/seed-staging.js.map +1 -0
- package/dist/state.d.ts +16 -1
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +93 -23
- package/dist/state.js.map +1 -1
- package/dist/storage-utils.d.ts.map +1 -1
- package/dist/storage-utils.js +11 -3
- package/dist/storage-utils.js.map +1 -1
- package/dist/storage.d.ts +59 -1
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +601 -150
- package/dist/storage.js.map +1 -1
- package/dist/stream-sync-budget.d.ts +3 -0
- package/dist/stream-sync-budget.d.ts.map +1 -0
- package/dist/stream-sync-budget.js +3 -0
- package/dist/stream-sync-budget.js.map +1 -0
- package/dist/sync.d.ts +104 -3
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +377 -62
- package/dist/sync.js.map +1 -1
- package/package.json +12 -5
package/dist/relay.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseDataScopeContract } from "@opendatalabs/personal-server-ts-core/contracts";
|
|
1
2
|
import { handlePsLiteBridgeRequest, } from "./bridge.js";
|
|
2
3
|
import { createRustlsPsLiteRelayTlsFactory } from "./relay-tls.js";
|
|
3
4
|
const DATA_FRAME_TYPE = 1;
|
|
@@ -20,8 +21,9 @@ export const RELAY_CLOSE_SESSION_REPLACED = 1012;
|
|
|
20
21
|
* instead of closing on stale elapsed time (BUI-665).
|
|
21
22
|
*/
|
|
22
23
|
const HEARTBEAT_LATE_FIRE_FACTOR = 2;
|
|
23
|
-
export function psLiteRelayControlUrl(sessionId, controlUrl = DEFAULT_CONTROL_URL) {
|
|
24
|
-
|
|
24
|
+
export function psLiteRelayControlUrl(sessionId, controlUrl = DEFAULT_CONTROL_URL, connTag) {
|
|
25
|
+
const base = `${controlUrl.replace(/\/+$/, "")}/browser/${sessionId}`;
|
|
26
|
+
return connTag ? `${base}?tag=${encodeURIComponent(connTag)}` : base;
|
|
25
27
|
}
|
|
26
28
|
export function psLiteRelayPublicUrl(sessionId, publicSuffix = DEFAULT_PUBLIC_SUFFIX) {
|
|
27
29
|
return `https://${sessionId}.${publicSuffix.replace(/^\./, "")}`;
|
|
@@ -63,17 +65,16 @@ export function startPsLiteRelayClient(options) {
|
|
|
63
65
|
const streams = new Map();
|
|
64
66
|
const pendingStreamData = new Map();
|
|
65
67
|
const origin = options.origin ?? DEFAULT_ORIGIN;
|
|
66
|
-
//
|
|
67
|
-
//
|
|
68
|
-
//
|
|
69
|
-
const heartbeatIntervalMs = options.heartbeatIntervalMs ??
|
|
70
|
-
const heartbeatTimeoutMs = options.heartbeatTimeoutMs ??
|
|
68
|
+
// On-schedule timers detect a half-open socket within 14s and start the
|
|
69
|
+
// first reconnect within 15s, below the consumer's 20s request budget.
|
|
70
|
+
// Throttled timers retain the evidence-based grace window below.
|
|
71
|
+
const heartbeatIntervalMs = options.heartbeatIntervalMs ?? 2_000;
|
|
72
|
+
const heartbeatTimeoutMs = options.heartbeatTimeoutMs ?? 10_000;
|
|
71
73
|
const reconnectInitialDelayMs = options.reconnectInitialDelayMs ?? 1_000;
|
|
72
74
|
const reconnectMaxDelayMs = options.reconnectMaxDelayMs ?? 30_000;
|
|
73
75
|
let issueToken;
|
|
74
76
|
let closed = false;
|
|
75
|
-
//
|
|
76
|
-
// lazily at call time, so they always act on the current socket.
|
|
77
|
+
// Every stream and callback belongs to one socket, never its replacement.
|
|
77
78
|
let socket;
|
|
78
79
|
let reconnectAttempts = 0;
|
|
79
80
|
let heartbeatTimer;
|
|
@@ -89,49 +90,266 @@ export function startPsLiteRelayClient(options) {
|
|
|
89
90
|
let unansweredPingSentAt;
|
|
90
91
|
let lastHeartbeatCheckAt = 0;
|
|
91
92
|
let heartbeatGraceUsed = false;
|
|
93
|
+
// Fresh per WebSocket connection; joins device and relay telemetry.
|
|
94
|
+
let connTag = randomConnTag();
|
|
92
95
|
const log = (line) => options.logger?.(line);
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
+
const emitStatus = (status, detail) => options.onStatus?.(status, { ...detail, connTag });
|
|
97
|
+
const logHookError = (error) => log(`relay read event hook failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
98
|
+
const readQueue = [];
|
|
99
|
+
let readFlushTimer;
|
|
100
|
+
let droppedReadEvents = 0;
|
|
101
|
+
const flushReadEvents = () => {
|
|
102
|
+
readFlushTimer = undefined;
|
|
103
|
+
const batch = readQueue.splice(0);
|
|
104
|
+
const hook = options.onReadEvent;
|
|
105
|
+
if (closed || !hook)
|
|
106
|
+
return;
|
|
107
|
+
if (droppedReadEvents > 0) {
|
|
108
|
+
log(`relay read events dropped (queue full): ${droppedReadEvents}`);
|
|
109
|
+
droppedReadEvents = 0;
|
|
110
|
+
}
|
|
111
|
+
for (const produce of batch) {
|
|
112
|
+
// A producer may still await the grantee lookup when close() runs;
|
|
113
|
+
// re-check so nothing reaches the hook after close.
|
|
114
|
+
void Promise.resolve()
|
|
115
|
+
.then(produce)
|
|
116
|
+
.then((event) => (closed ? undefined : hook(event)))
|
|
117
|
+
.catch(logHookError);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const dispatchReadEvent = (produce) => {
|
|
121
|
+
if (closed || !options.onReadEvent)
|
|
122
|
+
return;
|
|
123
|
+
if (readQueue.length >= MAX_QUEUED_READ_EVENTS) {
|
|
124
|
+
readQueue.shift();
|
|
125
|
+
droppedReadEvents += 1;
|
|
126
|
+
}
|
|
127
|
+
readQueue.push(produce);
|
|
128
|
+
readFlushTimer ??= setTimeout(flushReadEvents, 0);
|
|
129
|
+
};
|
|
130
|
+
const stopReadEvents = () => {
|
|
131
|
+
readQueue.length = 0;
|
|
132
|
+
if (readFlushTimer !== undefined) {
|
|
133
|
+
clearTimeout(readFlushTimer);
|
|
134
|
+
readFlushTimer = undefined;
|
|
96
135
|
}
|
|
97
136
|
};
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
137
|
+
// The host decides where visibility comes from (see
|
|
138
|
+
// PsLiteRelayClientOptions.appVisibility); the document is the default.
|
|
139
|
+
const appVisibility = () => {
|
|
140
|
+
try {
|
|
141
|
+
const state = options.appVisibility
|
|
142
|
+
? options.appVisibility()
|
|
143
|
+
: documentVisibility();
|
|
144
|
+
return state === "visible" || state === "hidden" ? state : "unknown";
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
return "unknown";
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const sampleHidden = (tracker) => {
|
|
151
|
+
const visibility = appVisibility();
|
|
152
|
+
if (visibility === "hidden")
|
|
153
|
+
tracker.hiddenDuring = true;
|
|
154
|
+
else if (visibility === "visible")
|
|
155
|
+
tracker.hiddenDuring ??= false;
|
|
156
|
+
return visibility;
|
|
157
|
+
};
|
|
158
|
+
const beginRead = (stream, request) => {
|
|
159
|
+
const seq = stream.requestSeq;
|
|
160
|
+
stream.requestSeq += 1;
|
|
161
|
+
const scope = relayReadScope(request);
|
|
162
|
+
if (scope === undefined)
|
|
163
|
+
return undefined;
|
|
164
|
+
const tracker = {
|
|
165
|
+
ids: {
|
|
166
|
+
readRef: `${stream.streamRef ?? crypto.randomUUID()}:${seq}`,
|
|
167
|
+
...(stream.streamRef ? { streamRef: stream.streamRef } : {}),
|
|
168
|
+
connTag: stream.connTag,
|
|
169
|
+
scope,
|
|
170
|
+
method: request.method.toUpperCase(),
|
|
171
|
+
},
|
|
172
|
+
startedAt: Date.now(),
|
|
173
|
+
hiddenDuring: undefined,
|
|
174
|
+
done: false,
|
|
175
|
+
};
|
|
176
|
+
const visibility = sampleHidden(tracker);
|
|
177
|
+
stream.activeRead = tracker;
|
|
178
|
+
const received = {
|
|
179
|
+
type: "ps_read_received",
|
|
180
|
+
at: tracker.startedAt,
|
|
181
|
+
...tracker.ids,
|
|
182
|
+
appVisibility: visibility,
|
|
183
|
+
};
|
|
184
|
+
dispatchReadEvent(() => received);
|
|
185
|
+
return tracker;
|
|
186
|
+
};
|
|
187
|
+
/** Records the end synchronously; builds and dispatches the event later. */
|
|
188
|
+
const finishRead = (tracker, result) => {
|
|
189
|
+
if (!tracker || tracker.done)
|
|
190
|
+
return;
|
|
191
|
+
tracker.done = true;
|
|
192
|
+
sampleHidden(tracker);
|
|
193
|
+
const finishedAt = Date.now();
|
|
194
|
+
const durationMs = Math.max(0, finishedAt - tracker.startedAt);
|
|
195
|
+
const hiddenDuring = tracker.hiddenDuring;
|
|
196
|
+
// Keep only what the empty check can use: a body over the cap is never
|
|
197
|
+
// empty, so a large body is not held while the event waits.
|
|
198
|
+
const emptyCheckBody = result.body && result.body.length <= EMPTY_CHECK_MAX_BYTES
|
|
199
|
+
? result.body
|
|
200
|
+
: undefined;
|
|
201
|
+
const { status, contentType, granteeRef: granteeRefPromise } = result;
|
|
202
|
+
const outcomeOrClassify = result.outcome;
|
|
203
|
+
const bytesOut = result.bytesOut ?? 0;
|
|
204
|
+
const gzip = result.gzip ?? false;
|
|
205
|
+
dispatchReadEvent(async () => {
|
|
206
|
+
const outcome = outcomeOrClassify === "classify"
|
|
207
|
+
? classifyReadOutcome(status ?? 0, emptyCheckBody, contentType)
|
|
208
|
+
: outcomeOrClassify;
|
|
209
|
+
const granteeRef = validGranteeRef(granteeRefPromise
|
|
210
|
+
? await withTimeout(granteeRefPromise, GRANTEE_REF_WAIT_MS)
|
|
211
|
+
: undefined);
|
|
212
|
+
return {
|
|
213
|
+
type: "ps_read_finished",
|
|
214
|
+
at: finishedAt,
|
|
215
|
+
...tracker.ids,
|
|
216
|
+
...(granteeRef ? { granteeRef } : {}),
|
|
217
|
+
...(status !== undefined ? { status } : {}),
|
|
218
|
+
outcome,
|
|
219
|
+
bytesOut,
|
|
220
|
+
gzip,
|
|
221
|
+
durationMs,
|
|
222
|
+
...(hiddenDuring !== undefined ? { hiddenDuring } : {}),
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
// hidden_during: a read in flight while the page/webview goes hidden. Only
|
|
227
|
+
// the document's own events when the document is the visibility source.
|
|
228
|
+
const visibilityDocument = options.appVisibility
|
|
229
|
+
? undefined
|
|
230
|
+
: readVisibilityDocument();
|
|
231
|
+
const onVisibilityChange = () => {
|
|
232
|
+
if (visibilityDocument?.visibilityState !== "hidden")
|
|
233
|
+
return;
|
|
234
|
+
for (const stream of streams.values()) {
|
|
235
|
+
if (stream.activeRead && !stream.activeRead.done) {
|
|
236
|
+
stream.activeRead.hiddenDuring = true;
|
|
237
|
+
}
|
|
101
238
|
}
|
|
102
239
|
};
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
240
|
+
let visibilityListening = false;
|
|
241
|
+
if (visibilityDocument) {
|
|
242
|
+
try {
|
|
243
|
+
visibilityDocument.addEventListener("visibilitychange", onVisibilityChange);
|
|
244
|
+
visibilityListening = true;
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
// No listener: hiddenDuring falls back to the received/finished samples.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const stopVisibilityListener = () => {
|
|
251
|
+
if (!visibilityListening || !visibilityDocument)
|
|
252
|
+
return;
|
|
253
|
+
visibilityListening = false;
|
|
254
|
+
try {
|
|
255
|
+
visibilityDocument.removeEventListener("visibilitychange", onVisibilityChange);
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
// Ignore.
|
|
259
|
+
}
|
|
109
260
|
};
|
|
261
|
+
const isLive = (stream) => !closed &&
|
|
262
|
+
!stream.closed &&
|
|
263
|
+
stream.socket === socket &&
|
|
264
|
+
socket.readyState === socket.OPEN &&
|
|
265
|
+
streams.get(stream.streamId) === stream;
|
|
266
|
+
const sendText = (message, target = socket) => {
|
|
267
|
+
if (!closed && target === socket && target.readyState === target.OPEN) {
|
|
268
|
+
target.send(JSON.stringify(message));
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
const sendData = (stream, payload) => {
|
|
272
|
+
if (isLive(stream)) {
|
|
273
|
+
stream.socket.send(encodeDataFrame(stream.streamId, payload));
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
const disposeStream = (stream) => {
|
|
277
|
+
if (stream.closed)
|
|
278
|
+
return;
|
|
279
|
+
stream.closed = true;
|
|
280
|
+
// A read still in flight when its stream dies never reaches the wire.
|
|
281
|
+
finishRead(stream.activeRead, { outcome: "stream_closed" });
|
|
282
|
+
if (streams.get(stream.streamId) === stream) {
|
|
283
|
+
streams.delete(stream.streamId);
|
|
284
|
+
pendingStreamData.delete(stream.streamId);
|
|
285
|
+
}
|
|
286
|
+
// Invalidate before calling external code that may re-enter the client.
|
|
287
|
+
const connection = stream.tls;
|
|
288
|
+
stream.tls = undefined;
|
|
289
|
+
connection?.close?.();
|
|
290
|
+
};
|
|
291
|
+
const closeStream = (stream, reason) => {
|
|
292
|
+
if (!isLive(stream))
|
|
293
|
+
return;
|
|
294
|
+
disposeStream(stream);
|
|
295
|
+
sendText({ type: "stream.close", streamId: stream.streamId, reason }, stream.socket);
|
|
296
|
+
};
|
|
297
|
+
const disposeStreams = () => {
|
|
298
|
+
for (const stream of [...streams.values()])
|
|
299
|
+
disposeStream(stream);
|
|
300
|
+
pendingStreamData.clear();
|
|
301
|
+
};
|
|
302
|
+
/** Returns false when the stream died before the last chunk was sent. */
|
|
110
303
|
const writePlaintextResponse = (stream, responseBytes) => {
|
|
304
|
+
if (!isLive(stream))
|
|
305
|
+
return false;
|
|
111
306
|
if (!stream.tls) {
|
|
112
307
|
for (const chunk of chunks(responseBytes, RESPONSE_CHUNK_BYTES)) {
|
|
113
|
-
sendData(stream
|
|
308
|
+
sendData(stream, chunk);
|
|
114
309
|
}
|
|
115
|
-
return;
|
|
310
|
+
return isLive(stream);
|
|
116
311
|
}
|
|
117
312
|
const responseChunks = chunks(responseBytes, RESPONSE_CHUNK_BYTES);
|
|
118
313
|
for (let index = 0; index < responseChunks.length; index += 1) {
|
|
314
|
+
if (!isLive(stream))
|
|
315
|
+
return false;
|
|
119
316
|
const step = stream.tls.writePlaintext(responseChunks[index], index === responseChunks.length - 1);
|
|
120
317
|
for (const chunk of chunks(step.tls, RESPONSE_CHUNK_BYTES)) {
|
|
121
318
|
if (chunk.length > 0) {
|
|
122
|
-
sendData(stream
|
|
319
|
+
sendData(stream, chunk);
|
|
123
320
|
}
|
|
124
321
|
}
|
|
125
322
|
}
|
|
323
|
+
return isLive(stream);
|
|
126
324
|
};
|
|
127
325
|
const drainHttpRequests = async (stream) => {
|
|
128
|
-
while (
|
|
326
|
+
while (isLive(stream)) {
|
|
129
327
|
const parsed = parseHttpRequest(stream.plaintext);
|
|
130
328
|
if (!parsed) {
|
|
131
329
|
return;
|
|
132
330
|
}
|
|
133
331
|
stream.plaintext = stream.plaintext.slice(parsed.consumedBytes);
|
|
134
|
-
const
|
|
332
|
+
const read = beginRead(stream, parsed.request);
|
|
333
|
+
let relayed;
|
|
334
|
+
try {
|
|
335
|
+
relayed = await handleRelayHttpRequest(options.runtime, parsed.request, origin, Boolean(read));
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
finishRead(read, { outcome: "handler_error" });
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
const { response } = relayed;
|
|
342
|
+
const finish = (outcome) => ({
|
|
343
|
+
outcome,
|
|
344
|
+
status: relayed.status,
|
|
345
|
+
granteeRef: relayed.granteeRef,
|
|
346
|
+
bytesOut: response.length,
|
|
347
|
+
gzip: relayed.gzip,
|
|
348
|
+
});
|
|
349
|
+
if (!isLive(stream)) {
|
|
350
|
+
finishRead(read, { ...finish("stream_closed"), bytesOut: 0 });
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
135
353
|
// `response` is a binary (latin1) string: buildHttpResponse appends the
|
|
136
354
|
// body via bytesToBinary, so each char code 0x00–0xFF is one body byte.
|
|
137
355
|
// It must be turned back into bytes the same way (binaryToBytes), NOT
|
|
@@ -139,22 +357,44 @@ export function startPsLiteRelayClient(options) {
|
|
|
139
357
|
// 2-byte sequence, corrupting binary payloads (e.g. OpenPGP-encrypted
|
|
140
358
|
// files fail downstream with "not a valid OpenPGP message"). ASCII/JSON
|
|
141
359
|
// bodies survive UTF-8, which is why only encrypted binary downloads broke.
|
|
142
|
-
|
|
143
|
-
|
|
360
|
+
let written;
|
|
361
|
+
try {
|
|
362
|
+
written = writePlaintextResponse(stream, binaryToBytes(response));
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
finishRead(read, { ...finish("tls_error"), bytesOut: 0 });
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
// Finish before closeStream: disposal would report stream_closed.
|
|
369
|
+
finishRead(read, written
|
|
370
|
+
? {
|
|
371
|
+
...finish("classify"),
|
|
372
|
+
body: relayed.plainBody,
|
|
373
|
+
contentType: relayed.contentType,
|
|
374
|
+
}
|
|
375
|
+
: finish("stream_closed"));
|
|
376
|
+
closeStream(stream, "http_response_sent");
|
|
144
377
|
return;
|
|
145
378
|
}
|
|
146
379
|
};
|
|
147
380
|
const handlePlaintext = (stream, plaintext) => {
|
|
148
|
-
if (plaintext.length === 0) {
|
|
381
|
+
if (!isLive(stream) || stream.handling || plaintext.length === 0) {
|
|
149
382
|
return;
|
|
150
383
|
}
|
|
151
384
|
stream.plaintext += bytesToBinary(plaintext);
|
|
385
|
+
if (!parseHttpRequest(stream.plaintext))
|
|
386
|
+
return;
|
|
387
|
+
stream.handling = true;
|
|
152
388
|
void drainHttpRequests(stream).catch((error) => {
|
|
389
|
+
if (!isLive(stream))
|
|
390
|
+
return;
|
|
153
391
|
log(error instanceof Error ? error.message : String(error));
|
|
154
|
-
closeStream(stream
|
|
392
|
+
closeStream(stream, "handler_error");
|
|
155
393
|
});
|
|
156
394
|
};
|
|
157
395
|
const processPayload = (stream, payload) => {
|
|
396
|
+
if (!isLive(stream) || !stream.ready)
|
|
397
|
+
return;
|
|
158
398
|
if (!stream.tls) {
|
|
159
399
|
handlePlaintext(stream, payload);
|
|
160
400
|
return;
|
|
@@ -162,38 +402,64 @@ export function startPsLiteRelayClient(options) {
|
|
|
162
402
|
try {
|
|
163
403
|
const step = stream.tls.processTls(payload);
|
|
164
404
|
if (step.tls.length > 0) {
|
|
165
|
-
sendData(stream
|
|
405
|
+
sendData(stream, step.tls);
|
|
166
406
|
}
|
|
167
407
|
handlePlaintext(stream, step.plaintext);
|
|
168
408
|
}
|
|
169
409
|
catch (error) {
|
|
170
410
|
log(error instanceof Error ? error.message : String(error));
|
|
171
|
-
closeStream(stream
|
|
411
|
+
closeStream(stream, "tls_error");
|
|
172
412
|
}
|
|
173
413
|
};
|
|
174
|
-
const openStream = async (streamId) => {
|
|
414
|
+
const openStream = async (streamId, streamRef) => {
|
|
415
|
+
const previous = streams.get(streamId);
|
|
416
|
+
if (previous)
|
|
417
|
+
disposeStream(previous);
|
|
175
418
|
const stream = {
|
|
176
419
|
streamId,
|
|
177
420
|
plaintext: "",
|
|
421
|
+
socket,
|
|
422
|
+
closed: false,
|
|
423
|
+
ready: !tls,
|
|
424
|
+
handling: false,
|
|
425
|
+
...(streamRef ? { streamRef } : {}),
|
|
426
|
+
connTag,
|
|
427
|
+
requestSeq: 0,
|
|
178
428
|
};
|
|
179
|
-
|
|
180
|
-
stream.tls = await tls.createStream({
|
|
181
|
-
sessionId: options.sessionId,
|
|
182
|
-
streamId,
|
|
183
|
-
issueToken,
|
|
184
|
-
});
|
|
185
|
-
}
|
|
429
|
+
// Register before awaiting creation so cancellation can invalidate it.
|
|
186
430
|
streams.set(streamId, stream);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
431
|
+
try {
|
|
432
|
+
if (tls) {
|
|
433
|
+
const connection = await tls.createStream({
|
|
434
|
+
sessionId: options.sessionId,
|
|
435
|
+
streamId,
|
|
436
|
+
issueToken,
|
|
437
|
+
});
|
|
438
|
+
if (!isLive(stream)) {
|
|
439
|
+
connection.close?.();
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
stream.tls = connection;
|
|
443
|
+
stream.ready = true;
|
|
444
|
+
}
|
|
445
|
+
if (!isLive(stream))
|
|
446
|
+
return;
|
|
447
|
+
const buffered = pendingStreamData.get(streamId) ?? [];
|
|
448
|
+
pendingStreamData.delete(streamId);
|
|
449
|
+
for (const payload of buffered)
|
|
450
|
+
processPayload(stream, payload);
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
if (!isLive(stream))
|
|
454
|
+
return;
|
|
455
|
+
log(error instanceof Error ? error.message : String(error));
|
|
456
|
+
closeStream(stream, "stream_open_error");
|
|
191
457
|
}
|
|
192
458
|
};
|
|
193
459
|
const handleControl = (message) => {
|
|
194
460
|
if (message.type === "session.ready") {
|
|
195
461
|
issueToken = message.issueToken;
|
|
196
|
-
|
|
462
|
+
emitStatus("connected");
|
|
197
463
|
if (tls && tls.prepare) {
|
|
198
464
|
void tls
|
|
199
465
|
.prepare({
|
|
@@ -213,18 +479,14 @@ export function startPsLiteRelayClient(options) {
|
|
|
213
479
|
}
|
|
214
480
|
if (message.type === "stream.open" &&
|
|
215
481
|
typeof message.streamId === "number") {
|
|
216
|
-
void openStream(message.streamId
|
|
217
|
-
log(error instanceof Error ? error.message : String(error));
|
|
218
|
-
if (typeof message.streamId === "number") {
|
|
219
|
-
closeStream(message.streamId, "stream_open_error");
|
|
220
|
-
}
|
|
221
|
-
});
|
|
482
|
+
void openStream(message.streamId, parseStreamRef(message.streamRef));
|
|
222
483
|
return;
|
|
223
484
|
}
|
|
224
485
|
if (message.type === "stream.close" &&
|
|
225
486
|
typeof message.streamId === "number") {
|
|
226
|
-
streams.get(message.streamId)
|
|
227
|
-
|
|
487
|
+
const stream = streams.get(message.streamId);
|
|
488
|
+
if (stream)
|
|
489
|
+
disposeStream(stream);
|
|
228
490
|
pendingStreamData.delete(message.streamId);
|
|
229
491
|
}
|
|
230
492
|
};
|
|
@@ -234,7 +496,7 @@ export function startPsLiteRelayClient(options) {
|
|
|
234
496
|
return;
|
|
235
497
|
}
|
|
236
498
|
const stream = streams.get(frame.streamId);
|
|
237
|
-
if (!stream) {
|
|
499
|
+
if (!stream || !stream.ready) {
|
|
238
500
|
const buffered = pendingStreamData.get(frame.streamId) ?? [];
|
|
239
501
|
buffered.push(frame.payload);
|
|
240
502
|
pendingStreamData.set(frame.streamId, buffered);
|
|
@@ -319,15 +581,23 @@ export function startPsLiteRelayClient(options) {
|
|
|
319
581
|
return;
|
|
320
582
|
}
|
|
321
583
|
issueToken = undefined;
|
|
322
|
-
|
|
584
|
+
connTag = randomConnTag();
|
|
585
|
+
socket = createSocket(options.webSocketFactory, psLiteRelayControlUrl(options.sessionId, baseControlUrl, connTag));
|
|
586
|
+
const currentSocket = socket;
|
|
587
|
+
const isCurrent = () => !closed && socket === currentSocket;
|
|
588
|
+
const acceptsFrames = () => isCurrent() && currentSocket.readyState === currentSocket.OPEN;
|
|
323
589
|
socket.binaryType = "arraybuffer";
|
|
324
|
-
|
|
590
|
+
emitStatus("connecting");
|
|
325
591
|
socket.onopen = () => {
|
|
592
|
+
if (!acceptsFrames())
|
|
593
|
+
return;
|
|
326
594
|
reconnectAttempts = 0;
|
|
327
595
|
startHeartbeat();
|
|
328
|
-
|
|
596
|
+
emitStatus("connected");
|
|
329
597
|
};
|
|
330
598
|
socket.onmessage = (event) => {
|
|
599
|
+
if (!acceptsFrames())
|
|
600
|
+
return;
|
|
331
601
|
lastFrameReceivedAt = Date.now();
|
|
332
602
|
if (typeof event.data === "string") {
|
|
333
603
|
handleControl(JSON.parse(event.data));
|
|
@@ -336,14 +606,16 @@ export function startPsLiteRelayClient(options) {
|
|
|
336
606
|
handleDataFrame(event.data);
|
|
337
607
|
};
|
|
338
608
|
socket.onclose = (event) => {
|
|
609
|
+
if (socket !== currentSocket)
|
|
610
|
+
return;
|
|
339
611
|
stopHeartbeat();
|
|
340
|
-
|
|
341
|
-
streams.clear();
|
|
342
|
-
pendingStreamData.clear();
|
|
612
|
+
disposeStreams();
|
|
343
613
|
issueToken = undefined;
|
|
344
614
|
const detail = { code: event?.code, reason: event?.reason };
|
|
345
615
|
if (closed) {
|
|
346
|
-
|
|
616
|
+
stopVisibilityListener();
|
|
617
|
+
stopReadEvents();
|
|
618
|
+
emitStatus("closed", detail);
|
|
347
619
|
return;
|
|
348
620
|
}
|
|
349
621
|
if (event?.code === RELAY_CLOSE_SESSION_REPLACED) {
|
|
@@ -351,6 +623,8 @@ export function startPsLiteRelayClient(options) {
|
|
|
351
623
|
// Reconnecting would evict it and start a session tug-of-war, so this
|
|
352
624
|
// client steps down for good and lets the host surface the handoff.
|
|
353
625
|
closed = true;
|
|
626
|
+
stopVisibilityListener();
|
|
627
|
+
stopReadEvents();
|
|
354
628
|
// Cancel any reconnect already scheduled by an earlier drop so a
|
|
355
629
|
// pending timer can't fire connect() after we've stepped down.
|
|
356
630
|
if (reconnectTimer !== undefined) {
|
|
@@ -358,17 +632,17 @@ export function startPsLiteRelayClient(options) {
|
|
|
358
632
|
reconnectTimer = undefined;
|
|
359
633
|
}
|
|
360
634
|
log("relay session replaced by another connection — not reconnecting");
|
|
361
|
-
|
|
635
|
+
emitStatus("replaced", detail);
|
|
362
636
|
return;
|
|
363
637
|
}
|
|
364
|
-
|
|
638
|
+
emitStatus("disconnected", detail);
|
|
365
639
|
scheduleReconnect();
|
|
366
640
|
};
|
|
367
641
|
socket.onerror = () => {
|
|
368
|
-
if (
|
|
642
|
+
if (!isCurrent() || currentSocket.readyState > currentSocket.OPEN) {
|
|
369
643
|
return;
|
|
370
644
|
}
|
|
371
|
-
|
|
645
|
+
emitStatus("error");
|
|
372
646
|
};
|
|
373
647
|
}
|
|
374
648
|
connect();
|
|
@@ -394,20 +668,22 @@ export function startPsLiteRelayClient(options) {
|
|
|
394
668
|
}
|
|
395
669
|
},
|
|
396
670
|
close(reason = "closed") {
|
|
671
|
+
if (closed)
|
|
672
|
+
return;
|
|
397
673
|
closed = true;
|
|
398
674
|
stopHeartbeat();
|
|
675
|
+
stopVisibilityListener();
|
|
676
|
+
stopReadEvents();
|
|
399
677
|
if (reconnectTimer !== undefined) {
|
|
400
678
|
clearTimeout(reconnectTimer);
|
|
401
679
|
reconnectTimer = undefined;
|
|
402
680
|
}
|
|
403
|
-
|
|
404
|
-
streams.clear();
|
|
405
|
-
pendingStreamData.clear();
|
|
681
|
+
disposeStreams();
|
|
406
682
|
socket.close(1000, reason);
|
|
407
683
|
},
|
|
408
684
|
};
|
|
409
685
|
}
|
|
410
|
-
async function handleRelayHttpRequest(runtime, request, origin) {
|
|
686
|
+
async function handleRelayHttpRequest(runtime, request, origin, isRead) {
|
|
411
687
|
const bridgeRequest = {
|
|
412
688
|
requestId: crypto.randomUUID(),
|
|
413
689
|
method: request.method,
|
|
@@ -416,9 +692,20 @@ async function handleRelayHttpRequest(runtime, request, origin) {
|
|
|
416
692
|
headers: request.headers,
|
|
417
693
|
body: encodeBase64(request.body),
|
|
418
694
|
};
|
|
695
|
+
// The grantee label travels in-process (an observer on the Request
|
|
696
|
+
// object), never as a header a requester could set or read.
|
|
697
|
+
let granteeRef;
|
|
419
698
|
const bridgeResponse = await handlePsLiteBridgeRequest(runtime, bridgeRequest, {
|
|
420
699
|
origin,
|
|
700
|
+
...(isRead
|
|
701
|
+
? {
|
|
702
|
+
onReadGrantee: (ref) => {
|
|
703
|
+
granteeRef = ref;
|
|
704
|
+
},
|
|
705
|
+
}
|
|
706
|
+
: {}),
|
|
421
707
|
});
|
|
708
|
+
const contentType = headerValue(bridgeResponse.headers, "content-type");
|
|
422
709
|
// Large exports (e.g. chatgpt.conversations) are big JSON streamed over the
|
|
423
710
|
// relay's WebSocket tunnel; an uncompressed body inflates transfer time and the
|
|
424
711
|
// window for a mid-stream drop (truncated read → UND_ERR_RES_CONTENT_LENGTH_MISMATCH).
|
|
@@ -427,17 +714,174 @@ async function handleRelayHttpRequest(runtime, request, origin) {
|
|
|
427
714
|
const bodyBytes = decodeBase64(bridgeResponse.body);
|
|
428
715
|
const acceptsGzip = (request.headers["accept-encoding"] ?? "").includes("gzip");
|
|
429
716
|
const alreadyEncoded = Boolean(bridgeResponse.headers?.["content-encoding"]);
|
|
717
|
+
const base = {
|
|
718
|
+
status: bridgeResponse.status,
|
|
719
|
+
plainBody: bodyBytes,
|
|
720
|
+
...(contentType !== undefined ? { contentType } : {}),
|
|
721
|
+
...(granteeRef ? { granteeRef } : {}),
|
|
722
|
+
};
|
|
430
723
|
if (acceptsGzip &&
|
|
431
724
|
!alreadyEncoded &&
|
|
432
725
|
bodyBytes.length >= GZIP_MIN_BYTES &&
|
|
433
726
|
typeof CompressionStream !== "undefined") {
|
|
434
727
|
const gzipped = await gzipBytes(bodyBytes);
|
|
435
|
-
return
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
728
|
+
return {
|
|
729
|
+
...base,
|
|
730
|
+
gzip: true,
|
|
731
|
+
response: buildHttpResponse(bridgeResponse, {
|
|
732
|
+
bodyOverride: gzipped,
|
|
733
|
+
contentEncoding: "gzip",
|
|
734
|
+
}),
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
return {
|
|
738
|
+
...base,
|
|
739
|
+
gzip: false,
|
|
740
|
+
response: buildHttpResponse(bridgeResponse, { bodyOverride: bodyBytes }),
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
function headerValue(headers, name) {
|
|
744
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
745
|
+
if (key.toLowerCase() === name)
|
|
746
|
+
return value;
|
|
747
|
+
}
|
|
748
|
+
return undefined;
|
|
749
|
+
}
|
|
750
|
+
const DATA_PATH_PREFIX = "/v1/data/";
|
|
751
|
+
/** Scope of a relayed read, or undefined when the request is not a read. */
|
|
752
|
+
function relayReadScope(request) {
|
|
753
|
+
const method = request.method.toUpperCase();
|
|
754
|
+
// Only GET reads data: core answers HEAD on `/v1/data/<scope>` with 405, so
|
|
755
|
+
// counting HEAD would show every probe as a failed read.
|
|
756
|
+
if (method !== "GET")
|
|
757
|
+
return undefined;
|
|
758
|
+
if (!request.path.startsWith(DATA_PATH_PREFIX))
|
|
759
|
+
return undefined;
|
|
760
|
+
// Only the data read itself (`/v1/data/<scope>`) counts. Sub-routes such as
|
|
761
|
+
// `/versions` and `/lineage` are metadata reads and would skew read rates.
|
|
762
|
+
const rest = request.path.slice(DATA_PATH_PREFIX.length).split("?")[0];
|
|
763
|
+
if (!rest || rest.includes("/"))
|
|
764
|
+
return undefined;
|
|
765
|
+
const segment = rest;
|
|
766
|
+
let scope;
|
|
767
|
+
try {
|
|
768
|
+
scope = decodeURIComponent(segment);
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
return INVALID_SCOPE;
|
|
772
|
+
}
|
|
773
|
+
if (scope.length > MAX_SCOPE_LENGTH)
|
|
774
|
+
return INVALID_SCOPE;
|
|
775
|
+
const parsed = parseDataScopeContract(scope);
|
|
776
|
+
return parsed.ok ? parsed.scope : INVALID_SCOPE;
|
|
777
|
+
}
|
|
778
|
+
const INVALID_SCOPE = "invalid";
|
|
779
|
+
const MAX_SCOPE_LENGTH = 128;
|
|
780
|
+
// Hashing resolves in microseconds; the cap only keeps a stuck promise from
|
|
781
|
+
// holding back later events.
|
|
782
|
+
const GRANTEE_REF_WAIT_MS = 1_000;
|
|
783
|
+
// Read events waiting for the next flush; the oldest are dropped beyond this.
|
|
784
|
+
const MAX_QUEUED_READ_EVENTS = 200;
|
|
785
|
+
function validGranteeRef(value) {
|
|
786
|
+
return typeof value === "string" && /^(owner|[0-9a-f]{12})$/.test(value)
|
|
787
|
+
? value
|
|
788
|
+
: undefined;
|
|
789
|
+
}
|
|
790
|
+
async function withTimeout(promise, ms) {
|
|
791
|
+
let timer;
|
|
792
|
+
try {
|
|
793
|
+
return await Promise.race([
|
|
794
|
+
promise.catch(() => undefined),
|
|
795
|
+
new Promise((resolve) => {
|
|
796
|
+
timer = setTimeout(() => resolve(undefined), ms);
|
|
797
|
+
}),
|
|
798
|
+
]);
|
|
799
|
+
}
|
|
800
|
+
finally {
|
|
801
|
+
if (timer !== undefined)
|
|
802
|
+
clearTimeout(timer);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
// Bodies larger than this are never "empty"; skip parsing them.
|
|
806
|
+
const EMPTY_CHECK_MAX_BYTES = 64 * 1024;
|
|
807
|
+
function classifyReadOutcome(status, body, contentType) {
|
|
808
|
+
if (status === 401 || status === 403)
|
|
809
|
+
return "denied";
|
|
810
|
+
if (status === 402)
|
|
811
|
+
return "payment_required";
|
|
812
|
+
if (status === 404)
|
|
813
|
+
return "not_found";
|
|
814
|
+
if (status >= 400)
|
|
815
|
+
return "error";
|
|
816
|
+
if (status < 200 || status >= 300)
|
|
817
|
+
return "ok";
|
|
818
|
+
return body && isEmptyJsonBody(body, contentType) ? "empty" : "ok";
|
|
819
|
+
}
|
|
820
|
+
function isEmptyJsonBody(body, contentType) {
|
|
821
|
+
if (body.length === 0 || body.length > EMPTY_CHECK_MAX_BYTES)
|
|
822
|
+
return false;
|
|
823
|
+
if (contentType !== undefined && !/json/i.test(contentType))
|
|
824
|
+
return false;
|
|
825
|
+
let value;
|
|
826
|
+
try {
|
|
827
|
+
value = JSON.parse(new TextDecoder().decode(body));
|
|
828
|
+
}
|
|
829
|
+
catch {
|
|
830
|
+
return false;
|
|
439
831
|
}
|
|
440
|
-
|
|
832
|
+
if (isEmptyValue(value))
|
|
833
|
+
return true;
|
|
834
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
835
|
+
const record = value;
|
|
836
|
+
if (!("data" in record))
|
|
837
|
+
return false;
|
|
838
|
+
const data = record.data;
|
|
839
|
+
if (isEmptyValue(data))
|
|
840
|
+
return true;
|
|
841
|
+
// `{ data: { sleep: [], readiness: [] } }`: every collection empty.
|
|
842
|
+
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
843
|
+
const values = Object.values(data);
|
|
844
|
+
return values.length > 0 && values.every(isEmptyValue);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return false;
|
|
848
|
+
}
|
|
849
|
+
function isEmptyValue(value) {
|
|
850
|
+
if (value === null || value === undefined || value === "")
|
|
851
|
+
return true;
|
|
852
|
+
if (Array.isArray(value))
|
|
853
|
+
return value.length === 0;
|
|
854
|
+
if (typeof value === "object") {
|
|
855
|
+
return Object.keys(value).length === 0;
|
|
856
|
+
}
|
|
857
|
+
return false;
|
|
858
|
+
}
|
|
859
|
+
function parseStreamRef(value) {
|
|
860
|
+
return typeof value === "string" && /^[A-Za-z0-9-]{1,64}$/.test(value)
|
|
861
|
+
? value
|
|
862
|
+
: undefined;
|
|
863
|
+
}
|
|
864
|
+
function randomConnTag() {
|
|
865
|
+
const bytes = new Uint8Array(8);
|
|
866
|
+
crypto.getRandomValues(bytes);
|
|
867
|
+
let hex = "";
|
|
868
|
+
for (const byte of bytes)
|
|
869
|
+
hex += byte.toString(16).padStart(2, "0");
|
|
870
|
+
return hex;
|
|
871
|
+
}
|
|
872
|
+
function readVisibilityDocument() {
|
|
873
|
+
const candidate = globalThis.document;
|
|
874
|
+
if (!candidate ||
|
|
875
|
+
typeof candidate.addEventListener !== "function" ||
|
|
876
|
+
typeof candidate.removeEventListener !== "function") {
|
|
877
|
+
return undefined;
|
|
878
|
+
}
|
|
879
|
+
return candidate;
|
|
880
|
+
}
|
|
881
|
+
function documentVisibility() {
|
|
882
|
+
const state = globalThis
|
|
883
|
+
.document?.visibilityState;
|
|
884
|
+
return state === "visible" || state === "hidden" ? state : "unknown";
|
|
441
885
|
}
|
|
442
886
|
// Responses below this size aren't worth the gzip overhead, and small reads
|
|
443
887
|
// already complete reliably over the relay.
|
|
@@ -482,8 +926,11 @@ export function buildHttpResponse(response, opts) {
|
|
|
482
926
|
// bridge lowercases it, so without this the head would carry two conflicting
|
|
483
927
|
// content-length values and clients reject that (the same mismatch class this
|
|
484
928
|
// change fixes). Match case-insensitively in case the name wasn't normalized.
|
|
929
|
+
// Transfer-Encoding framed the hop from the runtime, whose body is now
|
|
930
|
+
// buffered whole; copied onward it would override content-length.
|
|
485
931
|
for (const key of Object.keys(responseHeaders)) {
|
|
486
|
-
|
|
932
|
+
const name = key.toLowerCase();
|
|
933
|
+
if (name === "content-length" || name === "transfer-encoding") {
|
|
487
934
|
delete responseHeaders[key];
|
|
488
935
|
}
|
|
489
936
|
}
|