@nexum-hub/browser 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +2962 -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,35 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "Nexum browser",
4
+ "version": "0.0.2",
5
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp/TY/BToqqO0ffPCJMqzl7pq3uw42ysfz/kWyY3Jw4MVsiNrHEPZJ403p7N/3lTgALqO+/oHEPsfnbdXB1woDfuwyBPxSthfNaEDj1S0koYMa5Ocb6tUMTBzuZOLqXr7s97is0rpgb3oEy7uGmwJUvtf8Klgh1JgzL5D0lGYws97NfLAxS1lFXcRmxmQ0RrnVwkeUAjKeYnEemqRIX7yAbKvjq63I1GDTZMngg6cxbFhFOPz+7q3mwdy4nbBgCzsVf1pk8itNMbFzCngakRoV1wruLNlQLBFhDxtRrbwB9xaEnkXBXI1j3Pl9E7Z1W8yGTkzSxxNTXeOUg277UluHwIDAQAB",
6
+ "minimum_chrome_version": "125",
7
+ "background": {
8
+ "service_worker": "worker.js",
9
+ "type": "module"
10
+ },
11
+ "action": {
12
+ "default_title": "Nexum browser"
13
+ },
14
+ "permissions": [
15
+ "debugger",
16
+ "tabs",
17
+ "scripting",
18
+ "storage",
19
+ "alarms",
20
+ "downloads",
21
+ "history",
22
+ "tabGroups",
23
+ "bookmarks",
24
+ "clipboardRead",
25
+ "clipboardWrite",
26
+ "webNavigation"
27
+ ],
28
+ "host_permissions": [
29
+ "http://*/*",
30
+ "https://*/*"
31
+ ],
32
+ "content_security_policy": {
33
+ "extension_pages": "script-src 'self'; object-src 'self'; connect-src ws://127.0.0.1:43831;"
34
+ }
35
+ }
@@ -0,0 +1,85 @@
1
+ /** Serialized by Runtime.callFunctionOn with its receiver bound to a native resolved DOM node. */
2
+ export function nativeNodeCommand(input) {
3
+ const check = (condition, message) => {
4
+ if (!condition) throw new Error(message);
5
+ };
6
+ check(this?.isConnected, "The observed node is no longer connected.");
7
+ if (input.command === "setValue") {
8
+ check(
9
+ typeof input.value === "string" && !this.readOnly && !this.disabled,
10
+ "The target is not editable.",
11
+ );
12
+ if (this.isContentEditable) this.textContent = input.value;
13
+ else {
14
+ const view = this.ownerDocument.defaultView;
15
+ const prototype =
16
+ this.tagName === "INPUT"
17
+ ? view.HTMLInputElement.prototype
18
+ : this.tagName === "TEXTAREA"
19
+ ? view.HTMLTextAreaElement.prototype
20
+ : null;
21
+ check(prototype, "The target is not a text input.");
22
+ Object.getOwnPropertyDescriptor(prototype, "value").set.call(
23
+ this,
24
+ input.value,
25
+ );
26
+ }
27
+ const EventClass = this.ownerDocument.defaultView.Event;
28
+ this.dispatchEvent(new EventClass("input", { bubbles: true }));
29
+ this.dispatchEvent(new EventClass("change", { bubbles: true }));
30
+ return true;
31
+ }
32
+ if (input.command === "selectText") {
33
+ const content =
34
+ typeof this.value === "string" ? this.value : (this.textContent ?? "");
35
+ const matches = [];
36
+ let at = 0;
37
+ while (at <= content.length) {
38
+ const found = content.indexOf(input.text, at);
39
+ if (found < 0) break;
40
+ if (
41
+ (!input.prefix || content.slice(0, found).endsWith(input.prefix)) &&
42
+ (!input.suffix ||
43
+ content.slice(found + input.text.length).startsWith(input.suffix))
44
+ )
45
+ matches.push(found);
46
+ at = found + Math.max(1, input.text.length);
47
+ check(matches.length <= 1, "The requested text is ambiguous.");
48
+ }
49
+ check(matches.length === 1, "The requested text was not found.");
50
+ let start = matches[0],
51
+ end = start + input.text.length;
52
+ if (input.selectionType === "cursor_before") end = start;
53
+ if (input.selectionType === "cursor_after") start = end;
54
+ this.focus();
55
+ if (typeof this.setSelectionRange === "function")
56
+ this.setSelectionRange(start, end);
57
+ else {
58
+ const doc = this.ownerDocument,
59
+ walk = doc.createTreeWalker(this, 4),
60
+ range = doc.createRange();
61
+ let offset = 0,
62
+ node,
63
+ begin,
64
+ finish;
65
+ while ((node = walk.nextNode())) {
66
+ const length = node.textContent.length;
67
+ if (!begin && start <= offset + length)
68
+ begin = { node, offset: start - offset };
69
+ if (end <= offset + length) {
70
+ finish = { node, offset: end - offset };
71
+ break;
72
+ }
73
+ offset += length;
74
+ }
75
+ check(begin && finish, "The requested text selection is unavailable.");
76
+ range.setStart(begin.node, begin.offset);
77
+ range.setEnd(finish.node, finish.offset);
78
+ const selection = doc.getSelection();
79
+ selection.removeAllRanges();
80
+ selection.addRange(range);
81
+ }
82
+ return true;
83
+ }
84
+ throw new Error("Unknown native node operation.");
85
+ }
@@ -0,0 +1,497 @@
1
+ import { requireValue } from "./errors.js";
2
+
3
+ /** Serialized into the actual document's isolated world; network reads retain its browser credentials and CORS policy. */
4
+ export async function pageDataCommand(input) {
5
+ const check = (
6
+ condition,
7
+ code = "INVALID_ARGUMENT",
8
+ message = "The browser data request is invalid.",
9
+ ) => {
10
+ if (!condition) throw Object.assign(new Error(message), { code });
11
+ };
12
+ const maximum = 128 * 1024 * 1024;
13
+ const filename = (url, fallback) => {
14
+ let name;
15
+ try {
16
+ name = decodeURIComponent(new URL(url).pathname.split("/").pop());
17
+ } catch {}
18
+ return (name || fallback)
19
+ .replace(/[\\/\x00-\x1f\x7f]/g, "_")
20
+ .slice(0, 180)
21
+ .replace(/^\.+$/, "asset");
22
+ };
23
+ try {
24
+ const slot = Symbol.for("nexum.browser.data.v1");
25
+ let state = globalThis[slot];
26
+ if (!state || state.document !== document) {
27
+ state = { document, stages: new Map(), cancelled: new Map() };
28
+ Object.defineProperty(globalThis, slot, {
29
+ configurable: true,
30
+ value: state,
31
+ });
32
+ }
33
+ let stage = state.stages.get(input.token);
34
+ if (input.command === "cancel") {
35
+ state.cancelled.set(input.token, input.leaseId);
36
+ while (state.cancelled.size > 128)
37
+ state.cancelled.delete(state.cancelled.keys().next().value);
38
+ if (stage?.leaseId === input.leaseId) stage.controller?.abort();
39
+ return { ok: true, value: null };
40
+ }
41
+ if (input.command === "drop") {
42
+ if (stage?.leaseId === input.leaseId) {
43
+ stage.controller?.abort();
44
+ for (const url of stage.objectUrls ?? []) URL.revokeObjectURL(url);
45
+ state.stages.delete(input.token);
46
+ }
47
+ if (state.cancelled.get(input.token) === input.leaseId)
48
+ state.cancelled.delete(input.token);
49
+ return { ok: true, value: null };
50
+ }
51
+ check(
52
+ state.cancelled.get(input.token) !== input.leaseId,
53
+ "CANCELLED",
54
+ "The original browser data request was cancelled.",
55
+ );
56
+ if (!stage) {
57
+ check(
58
+ ["inventory", "fetch", "export"].includes(input.command),
59
+ "STALE_REF",
60
+ "The original native document data is no longer available.",
61
+ );
62
+ check(
63
+ state.stages.size < 16,
64
+ "QUEUE_FULL",
65
+ "The document's native data staging budget is full.",
66
+ );
67
+ stage = {
68
+ leaseId: input.leaseId,
69
+ pageVersion: input.pageVersion,
70
+ objectUrls: [],
71
+ objectBytes: 0,
72
+ };
73
+ state.stages.set(input.token, stage);
74
+ }
75
+ check(
76
+ stage.leaseId === input.leaseId &&
77
+ stage.pageVersion === input.pageVersion,
78
+ "STALE_REF",
79
+ "The original browser-data document is no longer current.",
80
+ );
81
+ if (input.command === "inventoryCheck") {
82
+ check(
83
+ stage.inventory,
84
+ "STALE_REF",
85
+ "The original native page inventory is no longer available.",
86
+ );
87
+ return { ok: true, value: { pageUrl: location.href } };
88
+ }
89
+ if (input.command === "chunk") {
90
+ check(
91
+ stage.blob &&
92
+ Number.isSafeInteger(input.offset) &&
93
+ input.offset >= 0 &&
94
+ Number.isInteger(input.length) &&
95
+ input.length >= 0 &&
96
+ input.length <= 16384 &&
97
+ input.offset + input.length <= stage.blob.size,
98
+ );
99
+ return {
100
+ ok: true,
101
+ value: Array.from(
102
+ new Uint8Array(
103
+ await stage.blob
104
+ .slice(input.offset, input.offset + input.length)
105
+ .arrayBuffer(),
106
+ ),
107
+ ),
108
+ };
109
+ }
110
+ if (input.command === "export") {
111
+ check(["html", "text"].includes(input.format));
112
+ const copy =
113
+ input.format === "html"
114
+ ? document.documentElement.cloneNode(true)
115
+ : null;
116
+ if (copy)
117
+ for (const node of copy.querySelectorAll(
118
+ '[data-nexum-visual-layer="v1"],[data-nexum-visual-icon="v1"]',
119
+ ))
120
+ node.remove();
121
+ const value =
122
+ input.format === "html"
123
+ ? `${document.doctype ? "<!DOCTYPE html>\n" : ""}${copy.outerHTML}`
124
+ : (document.body?.innerText ??
125
+ document.documentElement.textContent ??
126
+ "");
127
+ const blob = new Blob([value], {
128
+ type:
129
+ input.format === "html"
130
+ ? "text/html;charset=utf-8"
131
+ : "text/plain;charset=utf-8",
132
+ });
133
+ check(
134
+ blob.size <= maximum,
135
+ "OUTPUT_TOO_LARGE",
136
+ "The exported document exceeds its byte budget.",
137
+ );
138
+ stage.blob = blob;
139
+ return {
140
+ ok: true,
141
+ value: {
142
+ size: blob.size,
143
+ mimeType: blob.type,
144
+ url: location.href,
145
+ title: document.title,
146
+ },
147
+ };
148
+ }
149
+ if (input.command === "transcript") {
150
+ check(
151
+ stage.blob &&
152
+ stage.blob.size > 0 &&
153
+ stage.blob.size <= 16 * 1024 * 1024,
154
+ "FILE_UNAVAILABLE",
155
+ "The actual caption response is empty or exceeds its transcript budget.",
156
+ );
157
+ const raw = await stage.blob.text();
158
+ let lines;
159
+ if (raw.trimStart().startsWith("{")) {
160
+ const value = JSON.parse(raw);
161
+ check(
162
+ Array.isArray(value.events) && value.events.length <= 20000,
163
+ "FILE_UNAVAILABLE",
164
+ "The caption response has no timed transcript events.",
165
+ );
166
+ lines = value.events
167
+ .map((event) =>
168
+ (event.segs ?? [])
169
+ .map((segment) => segment.utf8 ?? "")
170
+ .join("")
171
+ .trim(),
172
+ )
173
+ .filter(Boolean);
174
+ } else {
175
+ const xml = new DOMParser().parseFromString(raw, "text/xml");
176
+ check(
177
+ !xml.querySelector("parsererror"),
178
+ "FILE_UNAVAILABLE",
179
+ "The caption response is not readable timed text.",
180
+ );
181
+ const nodes = [...xml.querySelectorAll("text,p")];
182
+ check(
183
+ nodes.length > 0 && nodes.length <= 20000,
184
+ "FILE_UNAVAILABLE",
185
+ "The caption response has no timed text segments.",
186
+ );
187
+ lines = nodes.map((node) => node.textContent.trim()).filter(Boolean);
188
+ }
189
+ check(
190
+ lines.length > 0,
191
+ "FILE_UNAVAILABLE",
192
+ "The actual caption response contains no transcript text.",
193
+ );
194
+ stage.blob = new Blob([lines.join("\n")], {
195
+ type: "text/plain;charset=utf-8",
196
+ });
197
+ check(stage.blob.size <= 16 * 1024 * 1024, "OUTPUT_TOO_LARGE");
198
+ return {
199
+ ok: true,
200
+ value: {
201
+ size: stage.blob.size,
202
+ mimeType: stage.blob.type,
203
+ url: location.href,
204
+ },
205
+ };
206
+ }
207
+ if (input.command === "inventory") {
208
+ const assets = [],
209
+ byUrl = new Map(),
210
+ inlineSvgs = [],
211
+ ownedUrls = new Set(
212
+ [...document.querySelectorAll('[data-nexum-visual-icon="v1"]')]
213
+ .map((node) => node.href)
214
+ .filter(Boolean),
215
+ );
216
+ const classify = (url, hint) =>
217
+ ["font", "image", "stylesheet", "video", "script"].includes(hint)
218
+ ? hint
219
+ : /\.(?:woff2?|ttf|otf)(?:[?#]|$)/i.test(url)
220
+ ? "font"
221
+ : /\.(?:png|jpe?g|gif|webp|svg|avif|ico)(?:[?#]|$)/i.test(url)
222
+ ? "image"
223
+ : /\.css(?:[?#]|$)/i.test(url)
224
+ ? "stylesheet"
225
+ : /\.(?:mp4|webm|mov|m3u8)(?:[?#]|$)/i.test(url)
226
+ ? "video"
227
+ : /\.m?js(?:[?#]|$)/i.test(url)
228
+ ? "script"
229
+ : "other";
230
+ const add = (raw, hint, source) => {
231
+ if (typeof raw !== "string" || !raw) return;
232
+ let url;
233
+ try {
234
+ url = new URL(raw, document.baseURI).href;
235
+ } catch {
236
+ return;
237
+ }
238
+ if (!/^(?:https?:|blob:|data:)/.test(url)) return;
239
+ if (ownedUrls.has(url)) return;
240
+ let asset = byUrl.get(url);
241
+ if (!asset) {
242
+ check(
243
+ assets.length < 4096,
244
+ "OUTPUT_TOO_LARGE",
245
+ "The page asset count exceeds its inventory budget.",
246
+ );
247
+ asset = {
248
+ id: `asset_${assets.length + 1}`,
249
+ kind: classify(url, hint),
250
+ name: filename(url, `asset_${assets.length + 1}`),
251
+ url,
252
+ sources: [],
253
+ };
254
+ byUrl.set(url, asset);
255
+ assets.push(asset);
256
+ }
257
+ if (asset.kind === "other" && classify(url, hint) !== "other")
258
+ asset.kind = classify(url, hint);
259
+ if (
260
+ source &&
261
+ asset.sources.length < 16 &&
262
+ !asset.sources.some(
263
+ (entry) =>
264
+ entry.kind === source.kind && entry.property === source.property,
265
+ )
266
+ )
267
+ asset.sources.push(source);
268
+ };
269
+ const nodes = document.querySelectorAll("*");
270
+ check(
271
+ nodes.length <= 20000,
272
+ "OUTPUT_TOO_LARGE",
273
+ "The current page exceeds the asset-observation node budget.",
274
+ );
275
+ for (const node of nodes) {
276
+ if (
277
+ node.closest?.(
278
+ '[data-nexum-visual-layer="v1"],[data-nexum-visual-icon="v1"]',
279
+ )
280
+ )
281
+ continue;
282
+ const tag = node.tagName;
283
+ for (const attribute of ["src", "poster", "href"]) {
284
+ if (attribute === "href" && tag !== "LINK") continue;
285
+ const hint =
286
+ tag === "SCRIPT"
287
+ ? "script"
288
+ : tag === "VIDEO" || tag === "SOURCE"
289
+ ? "video"
290
+ : tag === "LINK" && /stylesheet/i.test(node.rel ?? "")
291
+ ? "stylesheet"
292
+ : tag === "IMG" || attribute === "poster"
293
+ ? "image"
294
+ : undefined;
295
+ add(node.getAttribute(attribute), hint, {
296
+ kind: "attribute",
297
+ property: attribute,
298
+ });
299
+ }
300
+ if (node.currentSrc)
301
+ add(node.currentSrc, tag === "VIDEO" ? "video" : "image", {
302
+ kind: "attribute",
303
+ property: "currentSrc",
304
+ });
305
+ const style = getComputedStyle(node);
306
+ for (const property of [
307
+ "background-image",
308
+ "border-image-source",
309
+ "mask-image",
310
+ "list-style-image",
311
+ ])
312
+ for (const match of style
313
+ .getPropertyValue(property)
314
+ .matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/g))
315
+ add(match[1] ?? match[2] ?? match[3], "image", {
316
+ kind: "computedStyle",
317
+ property,
318
+ });
319
+ if (tag === "svg" || tag === "SVG") {
320
+ const markup = node.outerHTML;
321
+ check(
322
+ new TextEncoder().encode(markup).byteLength <= 1024 * 1024,
323
+ "OUTPUT_TOO_LARGE",
324
+ "An inline SVG exceeds its export budget.",
325
+ );
326
+ const blob = new Blob([markup], { type: "image/svg+xml" }),
327
+ url = URL.createObjectURL(blob);
328
+ stage.objectUrls.push(url);
329
+ stage.objectBytes += blob.size;
330
+ check(
331
+ stage.objectBytes <= maximum,
332
+ "OUTPUT_TOO_LARGE",
333
+ "The inline asset bytes exceed their inventory budget.",
334
+ );
335
+ add(url, "image", { kind: "attribute", property: "outerHTML" });
336
+ const asset = byUrl.get(url);
337
+ asset.name = `${asset.id}.svg`;
338
+ inlineSvgs.push({ id: asset.id, markup, name: asset.name });
339
+ }
340
+ }
341
+ for (const resource of input.resources ?? [])
342
+ add(resource.url, resource.kind, { kind: "resource" });
343
+ for (const resource of performance.getEntriesByType("resource"))
344
+ add(
345
+ resource.name,
346
+ resource.initiatorType === "img"
347
+ ? "image"
348
+ : resource.initiatorType === "script"
349
+ ? "script"
350
+ : undefined,
351
+ { kind: "resource" },
352
+ );
353
+ for (const asset of assets)
354
+ if (asset.url.startsWith("data:")) {
355
+ check(
356
+ asset.url.length <= Math.ceil((maximum * 4) / 3) + 4096,
357
+ "OUTPUT_TOO_LARGE",
358
+ "An embedded asset exceeds its byte budget.",
359
+ );
360
+ const response = await fetch(asset.url),
361
+ blob = await response.blob();
362
+ check(
363
+ stage.objectBytes + blob.size <= maximum,
364
+ "OUTPUT_TOO_LARGE",
365
+ "The embedded asset bytes exceed their inventory budget.",
366
+ );
367
+ const url = URL.createObjectURL(blob);
368
+ stage.objectUrls.push(url);
369
+ stage.objectBytes += blob.size;
370
+ asset.url = url;
371
+ }
372
+ const summary = {
373
+ byKind: {},
374
+ inlineSvgCount: inlineSvgs.length,
375
+ totalCount: assets.length,
376
+ };
377
+ for (const asset of assets)
378
+ summary.byKind[asset.kind] = (summary.byKind[asset.kind] ?? 0) + 1;
379
+ const value = { assets, inlineSvgs, pageUrl: location.href, summary };
380
+ check(
381
+ new TextEncoder().encode(JSON.stringify(value)).byteLength <=
382
+ 1024 * 1024,
383
+ "OUTPUT_TOO_LARGE",
384
+ "The page inventory exceeds its metadata budget.",
385
+ );
386
+ stage.inventory = value;
387
+ return { ok: true, value };
388
+ }
389
+ if (input.command === "fetch") {
390
+ check(
391
+ typeof input.url === "string" &&
392
+ /^(?:https?:|blob:|data:)/.test(input.url),
393
+ );
394
+ const limit = Math.min(input.maxBytes ?? maximum, maximum);
395
+ check(Number.isSafeInteger(limit) && limit >= 0);
396
+ const controller = new AbortController();
397
+ stage.controller = controller;
398
+ if (state.cancelled.get(input.token) === input.leaseId)
399
+ controller.abort();
400
+ const response = await fetch(input.url, {
401
+ credentials: "include",
402
+ redirect: "error",
403
+ signal: controller.signal,
404
+ });
405
+ check(
406
+ response.ok && response.type !== "opaque",
407
+ "FILE_UNAVAILABLE",
408
+ "The browser could not read the requested native response.",
409
+ );
410
+ const declared = Number(response.headers.get("content-length"));
411
+ check(
412
+ !Number.isFinite(declared) || declared <= limit,
413
+ "OUTPUT_TOO_LARGE",
414
+ "The browser response exceeds its declared byte budget.",
415
+ );
416
+ const chunks = [],
417
+ reader = response.body?.getReader();
418
+ let total = 0;
419
+ try {
420
+ if (reader)
421
+ while (true) {
422
+ const next = await reader.read();
423
+ if (next.done) break;
424
+ total += next.value.byteLength;
425
+ check(
426
+ total <= limit,
427
+ "OUTPUT_TOO_LARGE",
428
+ "The browser response exceeds its byte budget.",
429
+ );
430
+ chunks.push(next.value);
431
+ }
432
+ } finally {
433
+ if (reader) {
434
+ await reader.cancel().catch(() => {});
435
+ reader.releaseLock();
436
+ }
437
+ }
438
+ const mimeType =
439
+ response.headers.get("content-type")?.slice(0, 256) ||
440
+ "application/octet-stream";
441
+ stage.blob = new Blob(chunks, { type: mimeType });
442
+ stage.controller = undefined;
443
+ return {
444
+ ok: true,
445
+ value: { size: total, mimeType, url: response.url || input.url },
446
+ };
447
+ }
448
+ check(false);
449
+ } catch (cause) {
450
+ return {
451
+ ok: false,
452
+ error: {
453
+ code:
454
+ typeof cause?.code === "string"
455
+ ? cause.code
456
+ : cause?.name === "AbortError"
457
+ ? "CANCELLED"
458
+ : "FILE_UNAVAILABLE",
459
+ message:
460
+ typeof cause?.code === "string"
461
+ ? cause.message
462
+ : "The browser rejected the native document-data operation.",
463
+ },
464
+ };
465
+ }
466
+ }
467
+
468
+ export async function readPageBytes(ctx, token, metadata) {
469
+ requireValue(
470
+ Number.isSafeInteger(metadata.size) &&
471
+ metadata.size >= 0 &&
472
+ metadata.size <= 128 * 1024 * 1024,
473
+ "OUTPUT_TOO_LARGE",
474
+ "The native document bytes exceed their transfer budget.",
475
+ );
476
+ const data = new Uint8Array(metadata.size);
477
+ for (let offset = 0; offset < data.length; offset += 16384) {
478
+ const length = Math.min(16384, data.length - offset),
479
+ bytes = await ctx.router.dataPage(ctx, {
480
+ command: "chunk",
481
+ token,
482
+ offset,
483
+ length,
484
+ });
485
+ requireValue(
486
+ Array.isArray(bytes) &&
487
+ bytes.length === length &&
488
+ bytes.every(
489
+ (value) => Number.isInteger(value) && value >= 0 && value <= 255,
490
+ ),
491
+ "PROTOCOL_MISMATCH",
492
+ "The native document byte chunk was invalid.",
493
+ );
494
+ data.set(bytes, offset);
495
+ }
496
+ return data;
497
+ }