omowright 0.1.0 → 0.2.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/src/owner-only.js CHANGED
@@ -3,24 +3,40 @@
3
3
  // read-only attribute, so the same property is a protected DACL that grants the
4
4
  // current user alone: inherited entries (the parent's grants to other users or
5
5
  // groups) are dropped, and files created inside a directory inherit its grant.
6
- // Explicit entries already on the object are kept, as macOS keeps a file's
7
- // extended ACL through a chmod; on a fresh directory those are Windows' own
8
- // SYSTEM and Administrators entries, the root equivalents.
6
+ // A directory keeps its explicit entries for Windows' root equivalents (SYSTEM,
7
+ // Administrators, TrustedInstaller) and for OWNER RIGHTS and CREATOR OWNER; an
8
+ // explicit grant to anyone else is removed.
9
9
  // The Windows tools are spawned by absolute path: a bare name is resolved from
10
10
  // the process cwd before PATH, and a cwd another user can write would let them
11
11
  // substitute the tool. Any failure throws, so a caller never goes on with the
12
12
  // inherited ACL in place. A volume without ACLs (FAT32, exFAT, some network
13
13
  // shares) cannot hold the grant, so icacls fails there and so does the caller.
14
14
  import { execFile } from "node:child_process";
15
- import { chmod, mkdtemp, readFile, rm } from "node:fs/promises";
15
+ import { chmod, mkdtemp, readFile, rm, stat } from "node:fs/promises";
16
16
  import { tmpdir } from "node:os";
17
17
  import path from "node:path";
18
18
  import { promisify } from "node:util";
19
19
 
20
20
  const execFileAsync = promisify(execFile);
21
21
  const WINDOWS_COMMAND_TIMEOUT_MS = 15_000;
22
- // Directories this process restricted or found restricted, by lower-cased path.
22
+ // Directories this process restricted or found restricted, by volume and file
23
+ // id rather than by name: a directory that later takes a restricted one's name
24
+ // never got the grant, and on a case-sensitive NTFS directory two names that
25
+ // differ only in case are two directories.
23
26
  const ownerOnlyDirectories = new Set();
27
+ // SDDL trustees that may hold allow entries on an owner-only directory besides
28
+ // the user: SYSTEM, Administrators and TrustedInstaller (the trusted set of
29
+ // src/native-host-win32.js), OWNER RIGHTS (the owner, the user) and CREATOR
30
+ // OWNER (whoever creates a child, on that child). SDDL writes well-known SIDs
31
+ // as aliases; their numeric forms are listed too.
32
+ const TRUSTED_TRUSTEES = new Set([
33
+ "SY", "S-1-5-18",
34
+ "BA", "S-1-5-32-544",
35
+ "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464",
36
+ "OW", "S-1-3-4",
37
+ "CO", "S-1-3-0",
38
+ ]);
39
+ const DENY_ACE_TYPES = new Set(["D", "OD", "XD"]);
24
40
  let currentUserSid;
25
41
 
26
42
  export function windowsSystemTool(name, env = process.env) {
@@ -63,16 +79,72 @@ async function readDirectoryDacl(dir, run) {
63
79
  }
64
80
  }
65
81
 
66
- // True when the DACL is already what the directory grant below leaves:
67
- // protected, with the user's one entry being the inheritable full-control
68
- // allow. SDDL names the built-in Administrator and Guest accounts LA and LG.
69
- function isOwnerOnlyDirectoryDacl(dacl, sid) {
70
- const match = /^D:([A-Z]*)((?:\([^()]*\))*)/.exec(dacl);
71
- if (!match || !match[1].includes("P")) return false;
82
+ // The flags and ACE fields of an SDDL DACL (`D:` flags, then parenthesized
83
+ // ACEs, up to the SACL `S:` that may follow), or null when it does not parse,
84
+ // as for `D:NO_ACCESS_CONTROL`. A conditional ACE nests parentheses and may
85
+ // quote strings, so ACEs are split at depth zero, skipping quoted text.
86
+ function parseDacl(dacl) {
87
+ const head = /^D:([A-Z]*)/.exec(dacl);
88
+ if (!head) return null;
89
+ const aces = [];
90
+ let depth = 0;
91
+ let start = 0;
92
+ let i = head[0].length;
93
+ for (; i < dacl.length; i++) {
94
+ const c = dacl[i];
95
+ if (c === '"' && depth > 0) {
96
+ i = dacl.indexOf('"', i + 1);
97
+ if (i === -1) return null;
98
+ } else if (c === "(") {
99
+ if (depth++ === 0) start = i + 1;
100
+ } else if (c === ")") {
101
+ if (depth === 0) return null;
102
+ if (--depth === 0) aces.push(dacl.slice(start, i).split(";"));
103
+ } else if (depth === 0) {
104
+ break;
105
+ }
106
+ }
107
+ if (depth !== 0 || (i < dacl.length && !dacl.startsWith("S:", i))) return null;
108
+ return { flags: head[1], aces };
109
+ }
110
+
111
+ // Reads a directory DACL against the grant below. `ownerOnly`: already what
112
+ // the grant leaves, protected, with the user's one entry being the inheritable
113
+ // full-control allow and no allow entry for a trustee outside the trusted set.
114
+ // `foreign`: the trustees outside it with explicit allow entries, which the
115
+ // grant removes (it drops inherited entries itself). Deny entries grant nothing
116
+ // and stay. `parsed` is false for a DACL that could not be read, whose entries
117
+ // are unknown. SDDL names the built-in Administrator and Guest accounts LA and LG.
118
+ function inspectDirectoryDacl(text, sid) {
119
+ const dacl = parseDacl(text);
120
+ if (!dacl) return { parsed: false, ownerOnly: false, foreign: [] };
72
121
  const isUser = (trustee) =>
73
122
  trustee === sid || (trustee === "LA" && sid.endsWith("-500")) || (trustee === "LG" && sid.endsWith("-501"));
74
- const own = [...match[2].matchAll(/\(([^()]*)\)/g)].map(([, ace]) => ace.split(";")).filter((fields) => isUser(fields[5]));
75
- return own.length === 1 && own[0][0] === "A" && own[0][1] === "OICI" && own[0][2] === "FA";
123
+ const own = dacl.aces.filter((fields) => isUser(fields[5]));
124
+ const others = dacl.aces.filter(([type, , , , , trustee]) => !isUser(trustee) && !TRUSTED_TRUSTEES.has(trustee) && !DENY_ACE_TYPES.has(type));
125
+ return {
126
+ parsed: true,
127
+ ownerOnly: dacl.flags.includes("P") && others.length === 0 &&
128
+ own.length === 1 && own[0][0] === "A" && own[0][1] === "OICI" && own[0][2] === "FA",
129
+ foreign: [...new Set(others.filter(([, flags]) => !flags.includes("ID")).map(([, , , , , trustee]) => trustee))],
130
+ };
131
+ }
132
+
133
+ // The memo key: volume, file id and creation time. The 64-bit id Node reports
134
+ // can name a later directory too (ReFS ids are 128-bit, and a file system may
135
+ // reuse a deleted directory's id); the creation time tells them apart. A file
136
+ // system that reports no file id gives none, and its directories are not
137
+ // remembered.
138
+ async function directoryIdentity(dir) {
139
+ const { dev, ino, birthtimeNs } = await stat(dir, { bigint: true });
140
+ return ino === 0n ? null : `${dev}:${ino}:${birthtimeNs}`;
141
+ }
142
+
143
+ // The memo only spares later tool runs, so a directory whose identity cannot
144
+ // be read is not remembered and files created in it get their own grant.
145
+ async function rememberOwnerOnlyDirectory(dir) {
146
+ const identity = await directoryIdentity(dir).catch(() => null);
147
+ if (identity) ownerOnlyDirectories.add(identity);
76
148
  }
77
149
 
78
150
  // `platform` and `run` let the security contract above (absolute tool paths,
@@ -87,8 +159,9 @@ export async function restrictToOwner(target, kind, { platform = process.platfor
87
159
  // Re-granting an inheritable entry makes Windows rewrite the inherited
88
160
  // entries of everything below the directory, thousands of files in a used
89
161
  // browser profile, so a directory that already holds the grant is left as is.
90
- if (kind === "directory" && isOwnerOnlyDirectoryDacl(await readDirectoryDacl(target, command), sid)) {
91
- ownerOnlyDirectories.add(path.win32.resolve(target).toLowerCase());
162
+ const dacl = kind === "directory" ? inspectDirectoryDacl(await readDirectoryDacl(target, command), sid) : null;
163
+ if (dacl?.ownerOnly) {
164
+ await rememberOwnerOnlyDirectory(target);
92
165
  return;
93
166
  }
94
167
  const grant = kind === "directory" ? `*${sid}:(OI)(CI)F` : `*${sid}:F`;
@@ -96,7 +169,17 @@ export async function restrictToOwner(target, kind, { platform = process.platfor
96
169
  timeout: WINDOWS_COMMAND_TIMEOUT_MS,
97
170
  windowsHide: true,
98
171
  });
99
- if (kind === "directory") ownerOnlyDirectories.add(path.win32.resolve(target).toLowerCase());
172
+ if (!dacl) return;
173
+ // The grant keeps explicit entries; another trustee's is removed by SID (an
174
+ // SDDL alias such as WD is a SID string icacls accepts after `*`).
175
+ if (dacl.foreign.length > 0) {
176
+ await command(windowsSystemTool("icacls.exe"), [target, "/remove:g", ...dacl.foreign.map((trustee) => `*${trustee}`), "/Q"], {
177
+ timeout: WINDOWS_COMMAND_TIMEOUT_MS,
178
+ windowsHide: true,
179
+ });
180
+ }
181
+ // Entries of a DACL that could not be read may still grant someone else.
182
+ if (dacl.parsed) await rememberOwnerOnlyDirectory(target);
100
183
  }
101
184
 
102
185
  // For a file the caller has just created. On Windows a file created inside a
@@ -104,6 +187,10 @@ export async function restrictToOwner(target, kind, { platform = process.platfor
104
187
  // owner-only grant at creation, so no tool runs for it.
105
188
  export async function restrictNewFileToOwner(target, options = {}) {
106
189
  const platform = options.platform ?? process.platform;
107
- if (platform === "win32" && ownerOnlyDirectories.has(path.win32.dirname(path.win32.resolve(target)).toLowerCase())) return;
190
+ if (platform === "win32") {
191
+ // A parent that cannot be identified is not trusted: the file gets its own grant.
192
+ const parent = await directoryIdentity(path.dirname(path.resolve(target))).catch(() => null);
193
+ if (parent && ownerOnlyDirectories.has(parent)) return;
194
+ }
108
195
  await restrictToOwner(target, "file", options);
109
196
  }
@@ -149,6 +149,34 @@
149
149
  "details",
150
150
  "summary"
151
151
  ]);
152
+ // Longest label an interactive read keeps for a clickable generic; matches normalizeName.
153
+ const INTERACTIVE_LABEL_MAX = 100;
154
+ // Roles that are live regions by default; their text is state feedback an interactive read keeps.
155
+ const LIVE_REGION_ROLES = /* @__PURE__ */ new Set([
156
+ "alert",
157
+ "alertdialog",
158
+ "status",
159
+ "log",
160
+ "timer",
161
+ "marquee"
162
+ ]);
163
+ // The live region an element sits in: the nearest ancestor (or the element itself) that sets
164
+ // aria-live polite/assertive or has a live role, or null outside one. An explicit aria-live wins on
165
+ // its own element, so aria-live="off" opts out; an invalid value counts as unset, as in ARIA.
166
+ function getLiveRegionRoot(element) {
167
+ for (let current = element; current; current = getParentElementAcrossShadowBoundary(current)) {
168
+ const live = (current.getAttribute("aria-live") || "").trim().toLowerCase();
169
+ if (live === "polite" || live === "assertive") return current;
170
+ if (live === "off") return null;
171
+ if (LIVE_REGION_ROLES.has(getRole(current))) return current;
172
+ }
173
+ return null;
174
+ }
175
+ // True when `ancestor` is `element` itself or one of its ancestors, across shadow boundaries.
176
+ function isSelfOrAncestor(ancestor, element) {
177
+ for (let current = element; current; current = getParentElementAcrossShadowBoundary(current)) if (current === ancestor) return true;
178
+ return false;
179
+ }
152
180
  const INTERACTIVE_REF_ROLES = /* @__PURE__ */ new Set([
153
181
  "button",
154
182
  "link",
@@ -749,7 +777,7 @@
749
777
  }
750
778
  function shouldIncludeNode(element, options) {
751
779
  const role = getRole(element);
752
- if (options.interactive) return role === "canvas" || isInteractive(element) || isScrollable(element) || isLandmark(element);
780
+ if (options.interactive) return role === "canvas" || role === "heading" || isInteractive(element) || isScrollable(element) || isLandmark(element);
753
781
  if (isInteractive(element)) return true;
754
782
  if (isScrollable(element)) return true;
755
783
  if (isLandmark(element)) return true;
@@ -831,6 +859,7 @@
831
859
  selected: selected || void 0,
832
860
  focused: focused || void 0,
833
861
  disabled: disabled || void 0,
862
+ interactiveControl: interactivity.interactive || void 0,
834
863
  refId: nodeRefId,
835
864
  hints,
836
865
  href: href ?? void 0,
@@ -916,7 +945,8 @@
916
945
  function withoutWhitespace(text) {
917
946
  return normalizeWhitespace(text).replace(/\s+/g, "");
918
947
  }
919
- function mergeTextLeafChildren(node) {
948
+ // `liveText` maps each live-region root to the text pieces the snapshot kept from inside it.
949
+ function mergeTextLeafChildren(node, liveText) {
920
950
  const textLeafRoles = /* @__PURE__ */ new Set([
921
951
  "generic",
922
952
  "heading",
@@ -945,11 +975,26 @@
945
975
  if (!merged) return;
946
976
  if (!current.name) {
947
977
  current.name = merged;
948
- current.children = [];
978
+ // The name is cut at 100 characters. When the cut drops the text of a live region nested inside
979
+ // this node (a toast in a scrollable or clickable container), that text stays as a child, capped
980
+ // once per live-region root; the container's own text keeps only the cut name.
981
+ const full = texts.join(" ");
982
+ current.children = merged.length < normalizeWhitespace(full).length && current.element && !getLiveRegionRoot(current.element) ? nestedLiveTexts(current.element, withoutWhitespace(full), withoutWhitespace(merged)) : [];
949
983
  return;
950
984
  }
951
985
  if (withoutWhitespace(current.name) === withoutWhitespace(merged)) current.children = [];
952
986
  };
987
+ // Capped text of the live regions inside `element` that appears in the node's text but not in its cut name.
988
+ const nestedLiveTexts = (element, fullText, nameText) => {
989
+ const kept = [];
990
+ for (const [root, pieces] of liveText) {
991
+ if (root === element || !isSelfOrAncestor(element, root)) continue;
992
+ const text = normalizeName(mergeStringBuffer(pieces));
993
+ const bare = withoutWhitespace(text);
994
+ if (bare && fullText.includes(bare) && !nameText.includes(bare)) kept.push(text);
995
+ }
996
+ return kept;
997
+ };
953
998
  visit(node);
954
999
  }
955
1000
  function snapshotNodeToString(node) {
@@ -1036,6 +1081,14 @@
1036
1081
  children: []
1037
1082
  };
1038
1083
  const visited = /* @__PURE__ */ new Set();
1084
+ // Characters of live-region text an interactive read has kept so far, per live-region root.
1085
+ const liveTextLength = /* @__PURE__ */ new Map();
1086
+ // Text pieces kept from inside each live-region root, in either mode; see mergeTextLeafChildren.
1087
+ const liveText = /* @__PURE__ */ new Map();
1088
+ const keepLiveText = (root, text) => {
1089
+ if (!liveText.has(root)) liveText.set(root, []);
1090
+ liveText.get(root).push(text);
1091
+ };
1039
1092
  function traverse(element, currentDepth, parentNode) {
1040
1093
  if (currentDepth > options.maxDepth) return;
1041
1094
  if (!element?.tagName) return;
@@ -1066,6 +1119,34 @@
1066
1119
  for (const child of getLightAndShadowChildNodes(element)) {
1067
1120
  if (child.nodeType === Node.TEXT_NODE) {
1068
1121
  if (!child.nodeValue || targetNode.role === "textbox") continue;
1122
+ // Interactive reads keep the text of a node that is itself clickable or scrollable, and
1123
+ // text inside a live region (live roles or aria-live polite/assertive, such as toasts),
1124
+ // capped like an accessible name so a card wrapping a whole article stays short;
1125
+ // free-standing prose under landmarks and generics is dropped. A clickable or scrollable
1126
+ // node caps its own text; live-region text is capped once per live-region root, whichever
1127
+ // kept node it lands on, so two toasts in a row each keep their text and a log of many
1128
+ // entries stays bounded. A live region nested inside the clickable or scrollable node (a
1129
+ // toast in a scrollable app shell) uses its live-region budget, not the node's own.
1130
+ if (options.interactive && targetNode.role !== "heading" && !INTERACTIVE_REF_ROLES.has(targetNode.role)) {
1131
+ const liveRoot = getLiveRegionRoot(element);
1132
+ const ownText = (targetNode.interactiveControl || targetNode.scrollable) && !(liveRoot && !isSelfOrAncestor(liveRoot, targetNode.element));
1133
+ if (!ownText && !liveRoot) continue;
1134
+ const used = ownText ? targetNode.labelLength ?? 0 : liveTextLength.get(liveRoot) ?? 0;
1135
+ const room = INTERACTIVE_LABEL_MAX - used;
1136
+ if (room <= 0) continue;
1137
+ const collapsed = child.nodeValue.replace(/\s+/g, " ");
1138
+ const kept = used + Math.min(collapsed.length, room);
1139
+ if (ownText) targetNode.labelLength = kept;
1140
+ else liveTextLength.set(liveRoot, kept);
1141
+ const piece = collapsed.length > room ? collapsed.substring(0, room) : child.nodeValue;
1142
+ if (liveRoot) keepLiveText(liveRoot, piece);
1143
+ targetNode.children.push(piece);
1144
+ continue;
1145
+ }
1146
+ // Text of a wrapper below the kept node may sit in a nested live region; text on the kept
1147
+ // node itself never does.
1148
+ const liveRoot = element !== targetNode.element && getLiveRegionRoot(element);
1149
+ if (liveRoot) keepLiveText(liveRoot, child.nodeValue);
1069
1150
  targetNode.children.push(child.nodeValue);
1070
1151
  continue;
1071
1152
  }
@@ -1095,7 +1176,7 @@
1095
1176
  } else if (document.body) traverse(document.body, 0, treeRoot);
1096
1177
  normalizeStringChildren(treeRoot);
1097
1178
  normalizeGenericRoles(treeRoot);
1098
- mergeTextLeafChildren(treeRoot);
1179
+ mergeTextLeafChildren(treeRoot, liveText);
1099
1180
  const duplicateRefs = findDuplicateRefIds(treeRoot);
1100
1181
  if (duplicateRefs.length > 0) return {
1101
1182
  error: `Snapshot produced duplicate refs: ${duplicateRefs.join(", ")}. Take a new snapshot and retry.`,
@@ -0,0 +1,45 @@
1
+ // Every event page.on / page.off / page.waitForEvent accepts. Each name is delivered by the page or by the module
2
+ // that owns it (console-events.js, network-events.js); this is the one public list.
3
+ export const PAGE_EVENT_NAMES = Object.freeze([
4
+ "close", "console", "crash", "dialog", "domcontentloaded", "download", "filechooser", "frameattached",
5
+ "framedetached", "framenavigated", "load", "pageerror", "popup", "request", "response",
6
+ ]);
7
+
8
+ // Events that need the Runtime domain. Pages can detect Runtime.enable, so the page holds it only while one of
9
+ // these has a listener.
10
+ export const RUNTIME_PAGE_EVENTS = new Set(["console", "pageerror"]);
11
+
12
+ export function assertPageEvent(name) {
13
+ if (!PAGE_EVENT_NAMES.includes(name)) {
14
+ throw new TypeError(`Unknown page event: ${String(name)}. Supported events: ${PAGE_EVENT_NAMES.join(", ")}`);
15
+ }
16
+ }
17
+
18
+ function pageError(details = {}) {
19
+ const exception = details.exception ?? {};
20
+ const description = typeof exception.description === "string" ? exception.description : "";
21
+ if (exception.subtype !== "error" || !description) {
22
+ const text = exception.value !== undefined ? String(exception.value) : description || details.text || "Uncaught exception";
23
+ return new Error(text);
24
+ }
25
+ const name = exception.className ?? "Error";
26
+ const head = description.split(/\n\s+at /)[0];
27
+ const error = new Error(head === name ? "" : head.startsWith(`${name}: `) ? head.slice(name.length + 2) : head);
28
+ error.name = name;
29
+ error.stack = description;
30
+ return error;
31
+ }
32
+
33
+ // Runtime.exceptionThrown arrives only while the page holds Runtime for a console or pageerror listener.
34
+ export function subscribePageErrors(page) {
35
+ return page.cdp.on("Runtime.exceptionThrown", (event, meta) => {
36
+ if (!meta?.sessionId || !page.frameManager.hasSession(meta.sessionId)) return;
37
+ const details = event.exceptionDetails ?? {};
38
+ // The page's own isolated world is not the page's code.
39
+ for (const frame of page.frameManager.frames.values()) {
40
+ if (frame.sessionId === meta.sessionId && frame.isolatedContextId === details.executionContextId) return;
41
+ }
42
+ page.events.emit("pageerror", pageError(details))
43
+ .catch(error => console.warn("[pageerror] page event listener failed", error));
44
+ });
45
+ }
@@ -0,0 +1,239 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { acquireNetwork } from "./network-events.js";
4
+ import { validateViewport, repinViewport } from "./viewport.js";
5
+
6
+ const states = new WeakMap();
7
+
8
+ // The same codec runs on both sides of Runtime's string-only binding transport.
9
+ function bindingValue(value, decode = false) {
10
+ if (decode) {
11
+ const [type, data] = value;
12
+ if (type === "undefined") return undefined;
13
+ if (type === "number") return data === "-0" ? -0 : Number(data);
14
+ if (type === "bigint") return BigInt(data);
15
+ if (type === "array") return data.map(item => bindingValue(item, true));
16
+ if (type === "object") return Object.fromEntries(data.map(([key, item]) => [key, bindingValue(item, true)]));
17
+ return data;
18
+ }
19
+ if (value === undefined) return ["undefined"];
20
+ if (typeof value === "number" && (!Number.isFinite(value) || Object.is(value, -0))) return ["number", Object.is(value, -0) ? "-0" : String(value)];
21
+ if (typeof value === "bigint") return ["bigint", String(value)];
22
+ if (Array.isArray(value)) return ["array", value.map(item => bindingValue(item))];
23
+ if (value !== null && typeof value === "object") return ["object", Object.entries(value).map(([key, item]) => [key, bindingValue(item)])];
24
+ return ["value", value];
25
+ }
26
+
27
+ function bindingScript(name, internalName) {
28
+ return `(() => {
29
+ const name = ${JSON.stringify(name)};
30
+ if (globalThis[name]?.__omowrightBinding) return;
31
+ const bindingValue = ${bindingValue.toString()};
32
+ const raw = globalThis[${JSON.stringify(internalName)}];
33
+ let sequence = 0;
34
+ const callbacks = new Map();
35
+ const fn = (...args) => new Promise((resolve, reject) => {
36
+ const id = ++sequence;
37
+ callbacks.set(id, { resolve, reject });
38
+ try { raw(JSON.stringify({ id, args: bindingValue(args) })); }
39
+ catch (error) { callbacks.delete(id); reject(error); }
40
+ });
41
+ fn.__omowrightBinding = { callbacks, bindingValue };
42
+ globalThis[name] = fn;
43
+ })()`;
44
+ }
45
+
46
+ export function hasPageBindings(page) {
47
+ return (states.get(page)?.bindings.size ?? 0) > 0;
48
+ }
49
+
50
+ function setupState(page) {
51
+ let state = states.get(page);
52
+ if (state) return state;
53
+ state = { scripts: [], bindings: new Map(), sessions: new Map(), headers: null, media: null };
54
+ states.set(page, state);
55
+ // FrameManager calls this before resuming a paused out-of-process child.
56
+ page.frameManager.sessionSetup = sessionId => initializeSession(page, state, sessionId);
57
+ const offBinding = page.cdp.on("Runtime.bindingCalled", (event, meta) => {
58
+ const binding = state.bindings.get(event.name);
59
+ if (!binding || !state.sessions.has(meta.sessionId)) return;
60
+ deliverBinding(page, state, binding, event, meta.sessionId).catch(() => {
61
+ // A navigation or detached frame can destroy the calling context while
62
+ // its host callback is still running. There is then no promise to settle.
63
+ });
64
+ });
65
+ const offDetached = page.cdp.on("Target.detachedFromTarget", ({ sessionId }) => {
66
+ state.sessions.get(sessionId)?.releaseNetwork?.();
67
+ state.sessions.delete(sessionId);
68
+ });
69
+ page.events.on("close", async () => {
70
+ offBinding();
71
+ offDetached();
72
+ states.delete(page);
73
+ delete page.frameManager.sessionSetup;
74
+ for (const [sessionId, session] of state.sessions) {
75
+ session.releaseNetwork?.();
76
+ for (const identifier of session.scripts.values()) {
77
+ await page.cdp.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }, sessionId).catch(() => {});
78
+ }
79
+ for (const name of session.bindings) {
80
+ await page.cdp.send("Runtime.removeBinding", { name }, sessionId).catch(() => {});
81
+ }
82
+ if (state.bindings.size) await page.cdp.send("Runtime.disable", undefined, sessionId).catch(() => {});
83
+ }
84
+ });
85
+ return state;
86
+ }
87
+
88
+ async function deliverBinding(page, state, binding, event, sessionId) {
89
+ const call = JSON.parse(event.payload);
90
+ let result;
91
+ try {
92
+ const args = bindingValue(call.args, true);
93
+ if (binding.source) {
94
+ const frameId = page.frameManager.mainWorldContexts.get(`${sessionId}:${event.executionContextId}`);
95
+ const frame = page.frames().find(frame => frame.frameId === frameId);
96
+ if (!frame) throw Error("Binding caller frame is detached");
97
+ args.unshift({ context: page.context(), page, frame });
98
+ }
99
+ result = { value: bindingValue(await binding.callback(...args)) };
100
+ } catch (error) {
101
+ result = error instanceof Error
102
+ ? { error: { name: error.name, message: error.message, stack: error.stack } }
103
+ : { thrown: bindingValue(error) };
104
+ }
105
+ if (states.get(page) !== state || !state.sessions.has(sessionId)) return;
106
+ await page.cdp.send("Runtime.evaluate", {
107
+ contextId: event.executionContextId,
108
+ expression: `(() => {
109
+ const state = globalThis[${JSON.stringify(binding.name)}].__omowrightBinding;
110
+ const callback = state.callbacks.get(${call.id});
111
+ state.callbacks.delete(${call.id});
112
+ const result = ${JSON.stringify(result)};
113
+ if (result.error) {
114
+ const error = new Error(result.error.message);
115
+ error.name = result.error.name; error.stack = result.error.stack;
116
+ callback.reject(error);
117
+ } else if (result.thrown) callback.reject(state.bindingValue(result.thrown, true));
118
+ else callback.resolve(state.bindingValue(result.value, true));
119
+ })()`,
120
+ }, sessionId);
121
+ }
122
+
123
+ async function installScripts(page, state, sessionId, session) {
124
+ for (const script of state.scripts) {
125
+ if (session.scripts.has(script)) continue;
126
+ const { identifier } = await page.cdp.send("Page.addScriptToEvaluateOnNewDocument",
127
+ { source: script.source, runImmediately: script.binding }, sessionId);
128
+ session.scripts.set(script, identifier);
129
+ }
130
+ }
131
+
132
+ function initializeSession(page, state, sessionId) {
133
+ let session = state.sessions.get(sessionId);
134
+ if (!session) {
135
+ session = { scripts: new Map(), bindings: new Set(), ready: Promise.resolve() };
136
+ state.sessions.set(sessionId, session);
137
+ }
138
+ // Explicit setup calls can overlap the automatic OOPIF attach path.
139
+ const operation = session.ready.then(async () => {
140
+ for (const [name] of state.bindings) {
141
+ if (session.bindings.has(name)) continue;
142
+ await page.cdp.send("Runtime.addBinding", { name }, sessionId);
143
+ session.bindings.add(name);
144
+ }
145
+ if (state.bindings.size && !session.runtimeEnabled) {
146
+ await page.cdp.send("Runtime.enable", undefined, sessionId);
147
+ session.runtimeEnabled = true;
148
+ }
149
+ await installScripts(page, state, sessionId, session);
150
+ if (state.headers !== null) {
151
+ session.releaseNetwork ??= acquireNetwork(page.cdp, sessionId);
152
+ await session.releaseNetwork.ready;
153
+ await page.cdp.send("Network.setExtraHTTPHeaders", { headers: state.headers }, sessionId);
154
+ }
155
+ if (state.media) await page.cdp.send("Emulation.setEmulatedMedia", state.media, sessionId);
156
+ });
157
+ session.ready = operation.catch(() => {});
158
+ return operation;
159
+ }
160
+
161
+ async function updateSessions(page, state) {
162
+ const main = await page.resolveSessionId();
163
+ const sessions = new Set([main, ...[...page.frameManager.frames.values()].map(frame => frame.sessionId)]);
164
+ for (const sessionId of sessions) {
165
+ await initializeSession(page, state, sessionId);
166
+ await page.cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, sessionId);
167
+ }
168
+ }
169
+
170
+ export async function addInitScript(script, arg) {
171
+ let source;
172
+ if (typeof script === "function") {
173
+ source = `(() => { const __name = value => value; (${script.toString()})(${JSON.stringify(arg) ?? "undefined"}); })()`;
174
+ } else if (typeof script === "string") source = script;
175
+ else if (typeof script?.content === "string") source = script.content;
176
+ else if (typeof script?.path === "string") source = await readFile(script.path, "utf8");
177
+ else throw new TypeError("addInitScript requires a function, string, or { path | content }");
178
+ const state = setupState(this);
179
+ state.scripts.push({ source, binding: false });
180
+ await updateSessions(this, state);
181
+ }
182
+
183
+ export async function exposeFunction(name, callback) {
184
+ await registerBinding(this, name, callback, false);
185
+ }
186
+
187
+ export async function exposeBinding(name, callback) {
188
+ await registerBinding(this, name, callback, true);
189
+ }
190
+
191
+ async function registerBinding(page, name, callback, source) {
192
+ if (typeof name !== "string" || typeof callback !== "function") throw new TypeError(`${source ? "exposeBinding" : "exposeFunction"} requires a name and function`);
193
+ const state = setupState(page);
194
+ if ([...state.bindings.values()].some(binding => binding.name === name)) throw Error(`Function "${name}" has already been registered`);
195
+ const internalName = `__omowright_binding_${randomUUID().replaceAll("-", "")}`;
196
+ state.bindings.set(internalName, { name, callback, source });
197
+ state.scripts.push({ source: bindingScript(name, internalName), binding: true });
198
+ await updateSessions(page, state);
199
+ }
200
+
201
+ export async function setExtraHTTPHeaders(headers) {
202
+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) throw new TypeError("headers must be an object of strings");
203
+ for (const [name, value] of Object.entries(headers)) {
204
+ if (typeof value !== "string") throw new TypeError(`Header "${name}" value must be a string`);
205
+ }
206
+ const state = setupState(this);
207
+ state.headers = { ...headers };
208
+ await updateSessions(this, state);
209
+ }
210
+
211
+ export async function setViewportSize(viewport) {
212
+ const size = validateViewport(viewport);
213
+ if (this.browser.setViewportSize) await this.browser.setViewportSize(size);
214
+ else await repinViewport(this, size);
215
+ }
216
+
217
+ const mediaFeatures = {
218
+ colorScheme: ["prefers-color-scheme", ["light", "dark", "no-preference"]],
219
+ reducedMotion: ["prefers-reduced-motion", ["reduce", "no-preference"]],
220
+ forcedColors: ["forced-colors", ["active", "none"]],
221
+ contrast: ["prefers-contrast", ["more", "no-preference"]],
222
+ };
223
+
224
+ export async function emulateMedia(options = {}) {
225
+ if (options.media !== undefined && options.media !== null && !["screen", "print"].includes(options.media)) throw new TypeError("media must be screen, print or null");
226
+ for (const [key, [, allowed]] of Object.entries(mediaFeatures)) {
227
+ if (options[key] !== undefined && options[key] !== null && !allowed.includes(options[key])) throw new TypeError(`${key} must be ${allowed.join(", ")} or null`);
228
+ }
229
+ const state = setupState(this);
230
+ const previous = new Map(state.media?.features.map(feature => [feature.name, feature.value]));
231
+ for (const [key, [name]] of Object.entries(mediaFeatures)) {
232
+ if (options[key] !== undefined) previous.set(name, options[key] ?? "");
233
+ }
234
+ state.media = {
235
+ media: options.media === undefined ? state.media?.media ?? "" : options.media ?? "",
236
+ features: [...previous].map(([name, value]) => ({ name, value })),
237
+ };
238
+ await updateSessions(this, state);
239
+ }