@nexum-hub/browser 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +22 -2
  2. package/browser-extension/assets.js +654 -0
  3. package/browser-extension/build.mjs +111 -0
  4. package/browser-extension/clipboard.js +397 -0
  5. package/browser-extension/connection.js +880 -0
  6. package/browser-extension/dist/development/assets.js +654 -0
  7. package/browser-extension/dist/development/clipboard.js +397 -0
  8. package/browser-extension/dist/development/connection.js +880 -0
  9. package/browser-extension/dist/development/errors.js +106 -0
  10. package/browser-extension/dist/development/evaluate.js +160 -0
  11. package/browser-extension/dist/development/frames.js +256 -0
  12. package/browser-extension/dist/development/keyboard.js +167 -0
  13. package/browser-extension/dist/development/manifest.json +35 -0
  14. package/browser-extension/dist/development/native-node.js +85 -0
  15. package/browser-extension/dist/development/page-data.js +497 -0
  16. package/browser-extension/dist/development/page.js +772 -0
  17. package/browser-extension/dist/development/profile.js +2 -0
  18. package/browser-extension/dist/development/router.js +5961 -0
  19. package/browser-extension/dist/development/site-source.js +149 -0
  20. package/browser-extension/dist/development/transport.js +405 -0
  21. package/browser-extension/dist/development/visual.js +976 -0
  22. package/browser-extension/dist/development/worker.js +24 -0
  23. package/browser-extension/dist/production/assets.js +654 -0
  24. package/browser-extension/dist/production/clipboard.js +397 -0
  25. package/browser-extension/dist/production/connection.js +880 -0
  26. package/browser-extension/dist/production/errors.js +106 -0
  27. package/browser-extension/dist/production/evaluate.js +160 -0
  28. package/browser-extension/dist/production/frames.js +256 -0
  29. package/browser-extension/dist/production/keyboard.js +167 -0
  30. package/browser-extension/dist/production/manifest.json +35 -0
  31. package/browser-extension/dist/production/native-node.js +85 -0
  32. package/browser-extension/dist/production/page-data.js +497 -0
  33. package/browser-extension/dist/production/page.js +772 -0
  34. package/browser-extension/dist/production/profile.js +2 -0
  35. package/browser-extension/dist/production/router.js +5961 -0
  36. package/browser-extension/dist/production/site-source.js +149 -0
  37. package/browser-extension/dist/production/transport.js +405 -0
  38. package/browser-extension/dist/production/visual.js +976 -0
  39. package/browser-extension/dist/production/worker.js +24 -0
  40. package/browser-extension/errors.js +106 -0
  41. package/browser-extension/evaluate.js +160 -0
  42. package/browser-extension/frames.js +256 -0
  43. package/browser-extension/keyboard.js +167 -0
  44. package/browser-extension/native-node.js +85 -0
  45. package/browser-extension/page-data.js +497 -0
  46. package/browser-extension/page.js +772 -0
  47. package/browser-extension/release-info.json +21 -0
  48. package/browser-extension/route-manifest.json +807 -0
  49. package/browser-extension/router.js +5961 -0
  50. package/browser-extension/site-source.js +149 -0
  51. package/browser-extension/transport.js +405 -0
  52. package/browser-extension/visual.js +976 -0
  53. package/browser-extension/worker.js +24 -0
  54. package/dist/client/index.d.ts +6 -0
  55. package/dist/client/index.js +894 -0
  56. package/dist/client/index.js.map +1 -0
  57. package/dist/client/routes.d.ts +6 -0
  58. package/dist/client/routes.js +777 -0
  59. package/dist/client/routes.js.map +1 -0
  60. package/dist/client/serialize.d.ts +16 -0
  61. package/dist/client/serialize.js +355 -0
  62. package/dist/client/serialize.js.map +1 -0
  63. package/dist/client/types.d.ts +1342 -0
  64. package/dist/client/types.js +2 -0
  65. package/dist/client/types.js.map +1 -0
  66. package/dist/extension/artifacts.d.ts +60 -0
  67. package/dist/extension/artifacts.js +493 -0
  68. package/dist/extension/artifacts.js.map +1 -0
  69. package/dist/extension/assets.d.ts +10 -0
  70. package/dist/extension/assets.js +90 -0
  71. package/dist/extension/assets.js.map +1 -0
  72. package/dist/extension/batch.d.ts +6 -0
  73. package/dist/extension/batch.js +138 -0
  74. package/dist/extension/batch.js.map +1 -0
  75. package/dist/extension/files.d.ts +16 -0
  76. package/dist/extension/files.js +594 -0
  77. package/dist/extension/files.js.map +1 -0
  78. package/dist/extension/index.d.ts +3 -0
  79. package/dist/extension/index.js +623 -0
  80. package/dist/extension/index.js.map +1 -0
  81. package/dist/extension/protocol.d.ts +81 -0
  82. package/dist/extension/protocol.js +475 -0
  83. package/dist/extension/protocol.js.map +1 -0
  84. package/dist/extension/scope.d.ts +55 -0
  85. package/dist/extension/scope.js +563 -0
  86. package/dist/extension/scope.js.map +1 -0
  87. package/dist/extension/service.d.ts +113 -0
  88. package/dist/extension/service.js +905 -0
  89. package/dist/extension/service.js.map +1 -0
  90. package/docs/README.md +10 -0
  91. package/docs/api.md +1375 -0
  92. package/docs/connection.md +9 -0
  93. package/docs/lifecycle.md +17 -0
  94. package/docs/usage.md +75 -0
  95. package/implementation.json +2352 -0
  96. package/instructions/README.md +8 -0
  97. package/package.json +80 -4
  98. package/scripts/discover.js +12 -0
  99. package/scripts/screenshot.js +9 -0
  100. package/skills/browser-control/SKILL.md +12 -0
@@ -0,0 +1,149 @@
1
+ /** MAIN-world current-site observation. No network or UI actions are performed here. */
2
+ export function observeSiteSource(input) {
3
+ const fail = (message) => ({
4
+ ok: false,
5
+ error: { code: "FILE_UNAVAILABLE", message },
6
+ });
7
+ try {
8
+ const page = new URL(location.href);
9
+ if (input.method === "content.exportGsuite") {
10
+ if (page.hostname !== "docs.google.com")
11
+ return fail(
12
+ "The current document is not a supported Google Workspace editor.",
13
+ );
14
+ const match = page.pathname.match(
15
+ /^\/(document|spreadsheets|presentation)\/(?:u\/\d+\/)?d\/([A-Za-z0-9_-]+)(?:\/|$)/,
16
+ );
17
+ if (!match)
18
+ return fail(
19
+ "The current Google Workspace document has no observable export identity.",
20
+ );
21
+ const [, kind, id] = match,
22
+ allowed = {
23
+ document: ["pdf", "docx", "md"],
24
+ spreadsheets: ["pdf", "xlsx", "csv"],
25
+ presentation: ["pdf", "pptx"],
26
+ };
27
+ if (!allowed[kind].includes(input.format))
28
+ return fail("This document does not export the requested format.");
29
+ const url = new URL(
30
+ `/${kind}/d/${id}/export${kind === "presentation" ? `/${input.format}` : ""}`,
31
+ page.origin,
32
+ );
33
+ if (kind !== "presentation") url.searchParams.set("format", input.format);
34
+ if (kind === "spreadsheets" && input.format === "csv") {
35
+ const gid =
36
+ new URLSearchParams(page.hash.slice(1)).get("gid") ??
37
+ page.searchParams.get("gid");
38
+ if (gid && /^\d+$/.test(gid)) url.searchParams.set("gid", gid);
39
+ }
40
+ return {
41
+ ok: true,
42
+ value: {
43
+ kind: "gsuite",
44
+ url: url.href,
45
+ title: document.title,
46
+ pageUrl: page.href,
47
+ format: input.format,
48
+ },
49
+ };
50
+ }
51
+ if (
52
+ input.method !== "content.exportYouTubeTranscript" ||
53
+ !/(^|\.)youtube\.com$/.test(page.hostname)
54
+ )
55
+ return fail(
56
+ "The current page is not a supported YouTube video document.",
57
+ );
58
+ const videoId =
59
+ page.searchParams.get("v") ??
60
+ page.pathname.match(/^\/(?:shorts|live)\/([A-Za-z0-9_-]+)/)?.[1];
61
+ if (!videoId || !/^[A-Za-z0-9_-]{6,64}$/.test(videoId))
62
+ return fail("The current YouTube document has no video identity.");
63
+ const response =
64
+ document.querySelector("#movie_player")?.getPlayerResponse?.() ??
65
+ globalThis.ytInitialPlayerResponse;
66
+ if (
67
+ response?.videoDetails?.videoId &&
68
+ response.videoDetails.videoId !== videoId
69
+ )
70
+ return fail("The player response belongs to an earlier video.");
71
+ const layouts = [
72
+ {
73
+ selector: "transcript-segment-view-model",
74
+ timestamp: ".ytwTranscriptSegmentViewModelTimestamp",
75
+ text: '.ytAttributedStringHost[role="text"]',
76
+ },
77
+ {
78
+ selector: "ytd-transcript-segment-renderer",
79
+ timestamp: ".segment-timestamp",
80
+ text: ".segment-text",
81
+ },
82
+ ];
83
+ for (const layout of layouts) {
84
+ const segments = [...document.querySelectorAll(layout.selector)];
85
+ if (!segments.length) continue;
86
+ if (segments.length > 20000)
87
+ return fail("The rendered transcript exceeds its segment budget.");
88
+ const transcript = segments
89
+ .map((node) => {
90
+ const stamp = node
91
+ .querySelector(layout.timestamp)
92
+ ?.textContent?.trim(),
93
+ body = node.querySelector(layout.text)?.textContent?.trim();
94
+ return body ? `${stamp ? `[${stamp}] ` : ""}${body}` : "";
95
+ })
96
+ .filter(Boolean)
97
+ .join("\n");
98
+ if (
99
+ transcript &&
100
+ new TextEncoder().encode(transcript).byteLength <= 1024 * 1024
101
+ )
102
+ return {
103
+ ok: true,
104
+ value: {
105
+ kind: "transcript-dom",
106
+ text: transcript,
107
+ title: document.title,
108
+ pageUrl: page.href,
109
+ videoId,
110
+ },
111
+ };
112
+ }
113
+ const tracks =
114
+ response?.captions?.playerCaptionsTracklistRenderer?.captionTracks;
115
+ if (!Array.isArray(tracks) || !tracks.length || tracks.length > 64)
116
+ return fail(
117
+ "This video has no observable caption track or rendered transcript.",
118
+ );
119
+ const track = tracks.find(
120
+ (value) =>
121
+ typeof value.baseUrl === "string" && value.baseUrl.length <= 65536,
122
+ );
123
+ if (!track) return fail("The actual caption track has no readable URL.");
124
+ const url = new URL(track.baseUrl);
125
+ if (
126
+ url.protocol !== "https:" ||
127
+ url.username ||
128
+ url.password ||
129
+ !/(^|\.)(?:youtube\.com|googlevideo\.com)$/.test(url.hostname)
130
+ )
131
+ return fail(
132
+ "The observed caption URL is outside this site's supported source.",
133
+ );
134
+ return {
135
+ ok: true,
136
+ value: {
137
+ kind: "transcript-track",
138
+ url: url.href,
139
+ title: response.videoDetails?.title ?? document.title,
140
+ pageUrl: page.href,
141
+ videoId,
142
+ },
143
+ };
144
+ } catch {
145
+ return fail(
146
+ "The browser could not observe this site's actual content source.",
147
+ );
148
+ }
149
+ }
@@ -0,0 +1,405 @@
1
+ import { BrowserActionError, requireValue, record, text } from "./errors.js";
2
+
3
+ export const transportLimits = Object.freeze({
4
+ controlBytes: 1048576,
5
+ headerBytes: 4096,
6
+ chunkBytes: 65536,
7
+ maxStreams: 8,
8
+ maxAttachments: 1024,
9
+ valueBytes: 128 * 1024 * 1024,
10
+ inFlight: 64,
11
+ });
12
+ const encode = new TextEncoder(),
13
+ decode = new TextDecoder("utf-8", { fatal: true });
14
+ const same = (a, b) =>
15
+ a.actionId === b.actionId &&
16
+ a.operationId === b.operationId &&
17
+ a.generation === b.generation;
18
+ const digest = async (bytes) =>
19
+ [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))]
20
+ .map((v) => v.toString(16).padStart(2, "0"))
21
+ .join("");
22
+ export function parseControl(raw) {
23
+ requireValue(
24
+ typeof raw === "string" &&
25
+ encode.encode(raw).byteLength <= transportLimits.controlBytes,
26
+ "PROTOCOL_MISMATCH",
27
+ "The control frame is not bounded UTF-8 JSON.",
28
+ );
29
+ let value;
30
+ try {
31
+ value = JSON.parse(raw);
32
+ } catch {
33
+ throw new BrowserActionError(
34
+ "PROTOCOL_MISMATCH",
35
+ "The control frame is not JSON.",
36
+ );
37
+ }
38
+ record(value);
39
+ requireValue(
40
+ value.v === 1 && typeof value.type === "string",
41
+ "PROTOCOL_MISMATCH",
42
+ "The control envelope is unsupported.",
43
+ );
44
+ return value;
45
+ }
46
+ export class BrowserBinaryInbox {
47
+ #streams = new Map();
48
+ #reserved = 0;
49
+ begin(meta, accept) {
50
+ record(meta);
51
+ text(meta.streamId, 256);
52
+ text(meta.actionId, 256);
53
+ text(meta.operationId, 256);
54
+ requireValue(
55
+ Number.isSafeInteger(meta.generation) &&
56
+ ["bytes", "json"].includes(meta.kind) &&
57
+ Number.isSafeInteger(meta.size) &&
58
+ meta.size >= 0 &&
59
+ meta.size <= transportLimits.valueBytes &&
60
+ typeof meta.sha256 === "string" &&
61
+ /^[a-f0-9]{64}$/.test(meta.sha256),
62
+ "PROTOCOL_MISMATCH",
63
+ "The binary declaration is invalid.",
64
+ );
65
+ requireValue(
66
+ accept(meta) &&
67
+ !this.#streams.has(meta.streamId) &&
68
+ this.#streams.size < transportLimits.maxAttachments &&
69
+ [...this.#streams.values()].filter((v) => !v.complete).length <
70
+ transportLimits.maxStreams &&
71
+ this.#reserved + meta.size <= transportLimits.valueBytes,
72
+ "PROTOCOL_MISMATCH",
73
+ "The binary stream is unbound, duplicate or exceeds its budget.",
74
+ );
75
+ this.#streams.set(meta.streamId, {
76
+ meta,
77
+ sequence: 0,
78
+ received: 0,
79
+ chunks: [],
80
+ complete: false,
81
+ });
82
+ this.#reserved += meta.size;
83
+ }
84
+ push(frame, ignore = () => false) {
85
+ const bytes = frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame;
86
+ requireValue(
87
+ bytes instanceof Uint8Array && bytes.byteLength >= 4,
88
+ "PROTOCOL_MISMATCH",
89
+ "The binary frame is invalid.",
90
+ );
91
+ const size = new DataView(
92
+ bytes.buffer,
93
+ bytes.byteOffset,
94
+ bytes.byteLength,
95
+ ).getUint32(0);
96
+ requireValue(
97
+ size > 0 &&
98
+ size <= transportLimits.headerBytes &&
99
+ bytes.byteLength >= 4 + size &&
100
+ bytes.byteLength - 4 - size <= transportLimits.chunkBytes,
101
+ "PROTOCOL_MISMATCH",
102
+ "The binary header or payload exceeds its budget.",
103
+ );
104
+ let header;
105
+ try {
106
+ header = JSON.parse(decode.decode(bytes.subarray(4, 4 + size)));
107
+ } catch {
108
+ throw new BrowserActionError(
109
+ "PROTOCOL_MISMATCH",
110
+ "The binary header is invalid.",
111
+ );
112
+ }
113
+ if (ignore(header)) return false;
114
+ const state = this.#streams.get(header.streamId);
115
+ requireValue(
116
+ state &&
117
+ !state.complete &&
118
+ !state.ending &&
119
+ same(header, state.meta) &&
120
+ header.kind === state.meta.kind &&
121
+ header.sequence === state.sequence,
122
+ "PROTOCOL_MISMATCH",
123
+ "The binary chunk is stale or out of order.",
124
+ );
125
+ const payload = bytes.subarray(4 + size);
126
+ requireValue(
127
+ payload.byteLength > 0 &&
128
+ state.received + payload.byteLength <= state.meta.size,
129
+ "PROTOCOL_MISMATCH",
130
+ "The binary byte count differs from its declaration.",
131
+ );
132
+ state.sequence++;
133
+ state.received += payload.byteLength;
134
+ state.chunks.push(payload.slice());
135
+ }
136
+ async end(meta) {
137
+ record(meta);
138
+ const state = this.#streams.get(meta.streamId);
139
+ requireValue(
140
+ state &&
141
+ !state.complete &&
142
+ !state.ending &&
143
+ same(meta, state.meta) &&
144
+ state.received === state.meta.size &&
145
+ meta.size === state.received &&
146
+ meta.sha256 === state.meta.sha256,
147
+ "PROTOCOL_MISMATCH",
148
+ "The binary end does not match its source.",
149
+ );
150
+ state.ending = true;
151
+ const value = new Uint8Array(state.received);
152
+ let offset = 0;
153
+ for (const chunk of state.chunks) {
154
+ value.set(chunk, offset);
155
+ offset += chunk.byteLength;
156
+ }
157
+ requireValue(
158
+ (await digest(value)) === state.meta.sha256,
159
+ "PROTOCOL_MISMATCH",
160
+ "The binary hash does not match.",
161
+ );
162
+ requireValue(
163
+ this.#streams.get(meta.streamId) === state,
164
+ "PROTOCOL_MISMATCH",
165
+ "The stream was cancelled before validation completed.",
166
+ );
167
+ state.value = value;
168
+ state.chunks = [];
169
+ state.complete = true;
170
+ }
171
+ complete(id, binding) {
172
+ const state = this.#streams.get(id);
173
+ return !!(state?.complete && same(state.meta, binding));
174
+ }
175
+ take(id, binding) {
176
+ const state = this.#streams.get(id);
177
+ requireValue(
178
+ state?.complete && same(state.meta, binding),
179
+ "PROTOCOL_MISMATCH",
180
+ "The result refers to an unrelated or incomplete binary stream.",
181
+ );
182
+ this.#streams.delete(id);
183
+ this.#reserved -= state.meta.size;
184
+ return state.value;
185
+ }
186
+ discard(actionId) {
187
+ for (const [id, state] of this.#streams)
188
+ if (!actionId || state.meta.actionId === actionId) {
189
+ this.#streams.delete(id);
190
+ this.#reserved -= state.meta.size;
191
+ }
192
+ }
193
+ }
194
+ export function unpackBrowserValue(
195
+ value,
196
+ attachments,
197
+ valueStream,
198
+ inbox,
199
+ binding,
200
+ ) {
201
+ let result = valueStream
202
+ ? JSON.parse(decode.decode(inbox.take(valueStream, binding)))
203
+ : value;
204
+ requireValue(
205
+ attachments === undefined ||
206
+ (Array.isArray(attachments) &&
207
+ attachments.length <= transportLimits.maxAttachments),
208
+ "PROTOCOL_MISMATCH",
209
+ "The attachment manifest is invalid.",
210
+ );
211
+ const paths = new Set();
212
+ for (const entry of attachments ?? []) {
213
+ record(entry);
214
+ text(entry.streamId, 256);
215
+ requireValue(
216
+ Array.isArray(entry.path) &&
217
+ entry.path.length <= 64 &&
218
+ entry.path.every(
219
+ (p) =>
220
+ (typeof p === "string" &&
221
+ !["__proto__", "prototype", "constructor"].includes(p)) ||
222
+ (Number.isSafeInteger(p) && p >= 0),
223
+ ),
224
+ "PROTOCOL_MISMATCH",
225
+ "The attachment path is invalid.",
226
+ );
227
+ const path = JSON.stringify(entry.path);
228
+ requireValue(
229
+ !paths.has(path),
230
+ "PROTOCOL_MISMATCH",
231
+ "An attachment path cannot be replaced twice.",
232
+ );
233
+ paths.add(path);
234
+ const bytes = inbox.take(entry.streamId, binding);
235
+ if (entry.path.length === 0) {
236
+ requireValue(
237
+ result === null,
238
+ "PROTOCOL_MISMATCH",
239
+ "The root byte attachment must replace a null placeholder.",
240
+ );
241
+ result = bytes;
242
+ continue;
243
+ }
244
+ let parent = result;
245
+ for (const part of entry.path.slice(0, -1)) {
246
+ requireValue(
247
+ parent && typeof parent === "object" && Object.hasOwn(parent, part),
248
+ "PROTOCOL_MISMATCH",
249
+ "An attachment escapes its declared value.",
250
+ );
251
+ parent = parent[part];
252
+ }
253
+ const last = entry.path.at(-1);
254
+ requireValue(
255
+ parent &&
256
+ typeof parent === "object" &&
257
+ Object.hasOwn(parent, last) &&
258
+ parent[last] === null,
259
+ "PROTOCOL_MISMATCH",
260
+ "An attachment must replace a null placeholder.",
261
+ );
262
+ Object.defineProperty(parent, last, {
263
+ value: bytes,
264
+ enumerable: true,
265
+ writable: true,
266
+ configurable: true,
267
+ });
268
+ }
269
+ return result;
270
+ }
271
+ export async function packBrowserValue(value, binding) {
272
+ const streams = [],
273
+ attachments = [],
274
+ active = new Set();
275
+ let count = 0,
276
+ total = 0,
277
+ jsonBytes = 0;
278
+ const stream = async (bytes, kind) => {
279
+ total += bytes.byteLength;
280
+ requireValue(
281
+ total <= transportLimits.valueBytes &&
282
+ streams.length < transportLimits.maxAttachments,
283
+ "OUTPUT_TOO_LARGE",
284
+ "The browser result exceeds its byte or attachment budget.",
285
+ );
286
+ const streamId = crypto.randomUUID();
287
+ streams.push({
288
+ meta: {
289
+ ...binding,
290
+ streamId,
291
+ kind,
292
+ size: bytes.byteLength,
293
+ sha256: await digest(bytes),
294
+ },
295
+ bytes,
296
+ });
297
+ return streamId;
298
+ };
299
+ const visit = async (value, path, depth) => {
300
+ requireValue(
301
+ ++count <= 100000 && depth <= 64,
302
+ "OUTPUT_TOO_LARGE",
303
+ "The browser data graph exceeds its budget.",
304
+ );
305
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
306
+ const bytes =
307
+ value instanceof ArrayBuffer
308
+ ? new Uint8Array(value).slice()
309
+ : new Uint8Array(
310
+ value.buffer,
311
+ value.byteOffset,
312
+ value.byteLength,
313
+ ).slice();
314
+ attachments.push({ streamId: await stream(bytes, "bytes"), path });
315
+ return null;
316
+ }
317
+ if (value === null || value === undefined) return null;
318
+ if (typeof value === "string") {
319
+ jsonBytes += encode.encode(value).byteLength;
320
+ requireValue(
321
+ total + jsonBytes <= transportLimits.valueBytes,
322
+ "OUTPUT_TOO_LARGE",
323
+ );
324
+ return value;
325
+ }
326
+ if (
327
+ typeof value === "boolean" ||
328
+ (typeof value === "number" && Number.isFinite(value))
329
+ )
330
+ return value;
331
+ requireValue(
332
+ typeof value === "object" && !active.has(value),
333
+ "INVALID_ARGUMENT",
334
+ "Only acyclic browser data can cross the connection.",
335
+ );
336
+ active.add(value);
337
+ try {
338
+ if (Array.isArray(value)) {
339
+ requireValue(value.length <= 100000);
340
+ const result = [];
341
+ for (let i = 0; i < value.length; i++) {
342
+ const field = Object.getOwnPropertyDescriptor(value, String(i));
343
+ requireValue(field && "value" in field);
344
+ result.push(await visit(field.value, [...path, i], depth + 1));
345
+ }
346
+ return result;
347
+ }
348
+ record(value);
349
+ const result = Object.create(null);
350
+ for (const key of Object.keys(value)) {
351
+ jsonBytes += encode.encode(key).byteLength;
352
+ requireValue(
353
+ total + jsonBytes <= transportLimits.valueBytes,
354
+ "OUTPUT_TOO_LARGE",
355
+ );
356
+ if (value[key] !== undefined)
357
+ Object.defineProperty(result, key, {
358
+ value: await visit(value[key], [...path, key], depth + 1),
359
+ enumerable: true,
360
+ writable: true,
361
+ configurable: true,
362
+ });
363
+ }
364
+ return result;
365
+ } finally {
366
+ active.delete(value);
367
+ }
368
+ };
369
+ const copied = await visit(value, [], 0),
370
+ encoded = encode.encode(JSON.stringify(copied));
371
+ requireValue(
372
+ encoded.byteLength +
373
+ streams.reduce((sum, item) => sum + item.bytes.byteLength, 0) <=
374
+ transportLimits.valueBytes,
375
+ "OUTPUT_TOO_LARGE",
376
+ "The result exceeds its aggregate byte budget.",
377
+ );
378
+ if (encoded.byteLength > transportLimits.controlBytes / 2)
379
+ return {
380
+ value: null,
381
+ valueStream: await stream(encoded, "json"),
382
+ attachments,
383
+ streams,
384
+ };
385
+ return { value: copied, attachments, streams };
386
+ }
387
+ export function* browserFrames(meta, bytes) {
388
+ for (
389
+ let offset = 0, sequence = 0;
390
+ offset < bytes.byteLength;
391
+ offset += transportLimits.chunkBytes, sequence++
392
+ ) {
393
+ const header = encode.encode(JSON.stringify({ ...meta, sequence }));
394
+ requireValue(header.byteLength <= transportLimits.headerBytes);
395
+ const size = Math.min(
396
+ transportLimits.chunkBytes,
397
+ bytes.byteLength - offset,
398
+ ),
399
+ frame = new Uint8Array(4 + header.byteLength + size);
400
+ new DataView(frame.buffer).setUint32(0, header.byteLength);
401
+ frame.set(header, 4);
402
+ frame.set(bytes.subarray(offset, offset + size), 4 + header.byteLength);
403
+ yield frame;
404
+ }
405
+ }