omowright 0.0.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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +290 -2
  3. package/TOOLS.md +487 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +88 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +195 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +109 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +179 -0
  20. package/src/aria-hidden.js +47 -0
  21. package/src/bridge-schemas.js +44 -0
  22. package/src/bridge-transport.js +83 -0
  23. package/src/browser-context.js +105 -0
  24. package/src/browser-process.js +127 -0
  25. package/src/bsk/browser-signals.js +90 -0
  26. package/src/bsk/browsers.js +114 -0
  27. package/src/bsk/connect.js +75 -0
  28. package/src/bsk/daemon-info.js +100 -0
  29. package/src/bsk/external-extension.js +110 -0
  30. package/src/bsk/identify-browser.js +88 -0
  31. package/src/bsk/install-cli.js +81 -0
  32. package/src/bsk/ipc-client.js +236 -0
  33. package/src/bsk/onboard.js +140 -0
  34. package/src/bsk/screenshot.js +49 -0
  35. package/src/bsk/session.js +131 -0
  36. package/src/bsk/snapshot.js +56 -0
  37. package/src/bsk/targets.js +25 -0
  38. package/src/captcha-wait.js +79 -0
  39. package/src/captcha.js +142 -0
  40. package/src/cdp-errors.js +23 -0
  41. package/src/cdp-methods.js +69 -0
  42. package/src/chrome-profile.js +176 -0
  43. package/src/chrome.js +194 -0
  44. package/src/cloak-profile.js +266 -0
  45. package/src/connection.js +234 -0
  46. package/src/console-events.js +12 -0
  47. package/src/cookies.js +39 -0
  48. package/src/core.js +1702 -0
  49. package/src/cua.js +74 -0
  50. package/src/dialog-policy.js +80 -0
  51. package/src/emulate.js +127 -0
  52. package/src/events.js +111 -0
  53. package/src/frames-snapshot.js +138 -0
  54. package/src/har.js +103 -0
  55. package/src/human-handoff.js +124 -0
  56. package/src/index.js +89 -0
  57. package/src/injected.js +3 -0
  58. package/src/instance-lock.js +74 -0
  59. package/src/instances.js +490 -0
  60. package/src/internal-capability.js +1 -0
  61. package/src/launch-endpoint.js +185 -0
  62. package/src/layers.js +138 -0
  63. package/src/llm.js +201 -0
  64. package/src/lock-backend-win32.js +54 -0
  65. package/src/lock-backend.js +81 -0
  66. package/src/native-host-win32.js +201 -0
  67. package/src/network-events.js +223 -0
  68. package/src/network-snoop.js +229 -0
  69. package/src/nul-frames.js +28 -0
  70. package/src/open-shadow-query.js +101 -0
  71. package/src/owner-only.js +196 -0
  72. package/src/page-bundle.js +1478 -0
  73. package/src/page-events.js +45 -0
  74. package/src/page-routes.js +94 -0
  75. package/src/page-setup.js +239 -0
  76. package/src/pipe.js +418 -0
  77. package/src/process-start-time.js +64 -0
  78. package/src/routes.js +256 -0
  79. package/src/running-browser.js +85 -0
  80. package/src/scroll-collect.js +73 -0
  81. package/src/serial-emitter.js +17 -0
  82. package/src/shared-connections.js +285 -0
  83. package/src/snapshot-diff.js +75 -0
  84. package/src/text-matching.js +101 -0
  85. package/src/trace.js +183 -0
  86. package/src/url-match.js +148 -0
  87. package/src/viewport.js +12 -0
@@ -0,0 +1,285 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ // One CDP connection per browser per process (#68). Chrome asks the user to
4
+ // allow remote debugging once per WebSocket connection to their own profile,
5
+ // so an attach that opens a fresh socket on every call prompts on every call.
6
+ // Entries are keyed by the browser's webSocketDebuggerUrl: it carries the
7
+ // browser GUID, so a restarted or different browser never gets a cached
8
+ // connection. Each caller gets a lease whose close() is a release; the last
9
+ // release disconnects, because an open socket keeps the process alive.
10
+ const shared = new Map();
11
+
12
+ function withinTimeout(pending, timeoutMs, message) {
13
+ let timer;
14
+ return Promise.race([
15
+ pending,
16
+ new Promise((_, reject) => {
17
+ timer = setTimeout(() => reject(new Error(message)), timeoutMs);
18
+ }),
19
+ ]).finally(() => clearTimeout(timer));
20
+ }
21
+
22
+ function release(key, entry) {
23
+ entry.refs -= 1;
24
+ if (entry.refs > 0) return Promise.resolve();
25
+ if (shared.get(key) === entry) shared.delete(key);
26
+ return entry.ready.then(
27
+ (connection) => connection.close(),
28
+ () => {},
29
+ );
30
+ }
31
+
32
+ function bindTo(target, value) {
33
+ return typeof value === "function" ? value.bind(target) : value;
34
+ }
35
+
36
+ // Thrown when a holder tries to change a setting every other holder of the
37
+ // connection shares. Opening with that setting gives the holder its own.
38
+ export class SharedConnectionError extends Error {
39
+ constructor() {
40
+ super("this browser connection is shared; pass dialogPolicy to connect()/connectNamed() so this holder gets its own connection");
41
+ this.name = "SharedConnectionError";
42
+ this.code = "shared_connection";
43
+ }
44
+ }
45
+
46
+ // Members the lease itself provides; a handle can't replace them.
47
+ const RESERVED = new Set(["cdp", "close", "setDialogPolicy"]);
48
+
49
+ function refuse(what) {
50
+ return (_target, property) => {
51
+ throw new TypeError(`cannot change ${String(property)} on ${what} through a handle: every holder of this connection uses it`);
52
+ };
53
+ }
54
+
55
+ // A lease is one holder's view of the shared connection, and a holder never
56
+ // changes what another holder gets (#72 review):
57
+ // - setDialogPolicy works for a sole holder and makes the connection
58
+ // unshareable from then on; while others hold it, it throws
59
+ // SharedConnectionError instead (pages are shared, so a policy can't be
60
+ // scoped to one holder, and moving the holder would orphan its pages).
61
+ // - Properties set or defined on the lease stay on the lease; shared ones can't
62
+ // be deleted through it, and the shared client can't be written through it.
63
+ // - Listeners added through lease.cdp are removed when the lease closes, and
64
+ // lease.cdp.close() releases only this lease.
65
+ // - After close() the lease refuses every use, so a stale handle can never
66
+ // reopen a connection nobody owns.
67
+ function lease(key, entry, connection) {
68
+ let closed;
69
+ const overlay = Object.create(null);
70
+ const subscriptions = new Set();
71
+ const transportSubscriptions = new Set();
72
+ const unsubscribeAll = (set) => {
73
+ for (const unsubscribe of [...set]) unsubscribe();
74
+ };
75
+ // Symbols and `then` stay readable, so inspecting or resolving a closed
76
+ // handle doesn't throw; every named member does.
77
+ const ensureOpen = (property) => {
78
+ if (closed && typeof property === "string" && property !== "then") {
79
+ throw new Error("this browser connection handle was closed");
80
+ }
81
+ };
82
+ const close = () => {
83
+ if (!closed) {
84
+ unsubscribeAll(subscriptions);
85
+ closed = release(key, entry);
86
+ }
87
+ return closed;
88
+ };
89
+ const setDialogPolicy = (policy) => {
90
+ ensureOpen("setDialogPolicy");
91
+ if (entry.refs > 1) throw new SharedConnectionError();
92
+ if (shared.get(key) === entry) shared.delete(key);
93
+ return connection.setDialogPolicy(policy);
94
+ };
95
+ // An unsubscribe forgets itself, so a handle that subscribes and
96
+ // unsubscribes keeps nothing, and close() or clearListeners() never runs a
97
+ // spent unsubscribe that would remove the same function registered since by
98
+ // another holder (#82).
99
+ const tracked = (subscribe, ...sets) => (...args) => {
100
+ const remove = subscribe(...args);
101
+ let removed = false;
102
+ const unsubscribe = () => {
103
+ if (removed) return;
104
+ removed = true;
105
+ for (const set of sets) set.delete(unsubscribe);
106
+ remove();
107
+ };
108
+ for (const set of sets) set.add(unsubscribe);
109
+ return unsubscribe;
110
+ };
111
+ const readOnly = (what, get) => ({
112
+ get,
113
+ set: refuse(what),
114
+ defineProperty: refuse(what),
115
+ deleteProperty: refuse(what),
116
+ });
117
+ const client = connection.cdp;
118
+ // Transport events reach every holder: through a handle, clearListeners
119
+ // removes only that handle's listeners and emit is refused. The emitter keys
120
+ // listeners by function, so each registration gets a function of its own:
121
+ // two holders adding the same function never share one entry that either
122
+ // could remove (#140).
123
+ const transportEvents = new Proxy(client.transportEvents, readOnly("the shared transport events", (target, property) => {
124
+ ensureOpen(property);
125
+ if (property === "on") {
126
+ const on = (name, listener) => target.on(name, (event) => listener(event));
127
+ return tracked(on, subscriptions, transportSubscriptions);
128
+ }
129
+ if (property === "clearListeners") return () => unsubscribeAll(transportSubscriptions);
130
+ if (property === "emit") {
131
+ return () => {
132
+ throw new TypeError("cannot emit transport events through a handle: every holder of this connection hears them");
133
+ };
134
+ }
135
+ return bindTo(target, Reflect.get(target, property, target));
136
+ }));
137
+ const clientView = new Proxy(client, readOnly("the shared CDP client", (target, property) => {
138
+ ensureOpen(property);
139
+ if (property === "setDialogPolicy") return setDialogPolicy;
140
+ if (property === "close") return close;
141
+ if (property === "on") return tracked(target.on.bind(target), subscriptions);
142
+ if (property === "transportEvents") return transportEvents;
143
+ return bindTo(target, Reflect.get(target, property, target));
144
+ }));
145
+ return new Proxy(connection, {
146
+ get(target, property) {
147
+ // Disposing a lease releases only this holder, like close() (#244).
148
+ if (property === "close" || property === Symbol.asyncDispose) return close;
149
+ ensureOpen(property);
150
+ if (property === "setDialogPolicy") return setDialogPolicy;
151
+ if (property === "cdp") return clientView;
152
+ if (Object.hasOwn(overlay, property)) return overlay[property];
153
+ return bindTo(target, Reflect.get(target, property, target));
154
+ },
155
+ set(target, property, value) {
156
+ ensureOpen(property);
157
+ if (RESERVED.has(property)) return refuse("a handle")(target, property);
158
+ return Reflect.set(overlay, property, value);
159
+ },
160
+ defineProperty(target, property, descriptor) {
161
+ ensureOpen(property);
162
+ if (RESERVED.has(property)) return refuse("a handle")(target, property);
163
+ // A non-configurable property can't live on the lease alone.
164
+ if (descriptor.configurable !== true) return false;
165
+ return Reflect.defineProperty(overlay, property, descriptor);
166
+ },
167
+ deleteProperty(target, property) {
168
+ ensureOpen(property);
169
+ if (Object.hasOwn(overlay, property)) return Reflect.deleteProperty(overlay, property);
170
+ return refuse("the shared connection")(target, property);
171
+ },
172
+ has(target, property) {
173
+ return Object.hasOwn(overlay, property) || Reflect.has(target, property);
174
+ },
175
+ ownKeys(target) {
176
+ return [...new Set([...Reflect.ownKeys(target), ...Reflect.ownKeys(overlay)])];
177
+ },
178
+ getOwnPropertyDescriptor(target, property) {
179
+ return Object.hasOwn(overlay, property)
180
+ ? Reflect.getOwnPropertyDescriptor(overlay, property)
181
+ : Reflect.getOwnPropertyDescriptor(target, property);
182
+ },
183
+ });
184
+ }
185
+
186
+ // Only plain data is compared structurally, and isDeepStrictEqual sees only
187
+ // enumerable values. So options are shared only when every own key is an
188
+ // enumerable, string-keyed data property and nothing refers back to itself;
189
+ // a class instance (an authorizer keeping its token in a private field), a
190
+ // symbol or non-enumerable key, an accessor or a cycle makes them unshareable.
191
+ // Functions compare by identity, which is exact.
192
+ function isPlainData(value, path = new Set()) {
193
+ if (typeof value === "function" || value === null || typeof value !== "object") return true;
194
+ if (path.has(value)) return false;
195
+ const prototype = Object.getPrototypeOf(value);
196
+ const isArray = Array.isArray(value);
197
+ if (isArray ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
198
+ return false;
199
+ }
200
+ path.add(value);
201
+ try {
202
+ for (const key of Reflect.ownKeys(value)) {
203
+ if (isArray && key === "length") continue;
204
+ if (typeof key === "symbol") return false;
205
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
206
+ if (!descriptor.enumerable || !("value" in descriptor)) return false;
207
+ if (!isPlainData(descriptor.value, path)) return false;
208
+ }
209
+ return true;
210
+ } finally {
211
+ path.delete(value);
212
+ }
213
+ }
214
+
215
+ // A frozen deep copy of shareable options (plain data, so only arrays and
216
+ // objects need copying; functions keep their identity). The shared connection
217
+ // is opened with and compared against this copy, so a caller mutating its
218
+ // options object after attaching changes neither the live connection nor which
219
+ // later attaches share it, and a handle can't change the policy in place (#81).
220
+ function frozenCopy(value) {
221
+ if (value === null || typeof value !== "object") return value;
222
+ const copy = Array.isArray(value)
223
+ ? new Array(value.length)
224
+ : Object.create(Object.getPrototypeOf(value));
225
+ for (const key of Object.keys(value)) {
226
+ Object.defineProperty(copy, key, { value: frozenCopy(value[key]), enumerable: true });
227
+ }
228
+ return Object.freeze(copy);
229
+ }
230
+
231
+ // The options a shared connection is opened with: the snapshot, plus a frozen
232
+ // default dialog policy of its own when the caller passed none, so no holder
233
+ // can change the live policy in place through handle.cdp.dialogPolicy (#81).
234
+ // The snapshot itself stays the sharing key, so an attach that names no policy
235
+ // still differs from one that asks for { accept: true }.
236
+ function openingOptions(snapshot) {
237
+ if (snapshot?.dialogPolicy != null || snapshot?.client?.dialogPolicy != null) return snapshot;
238
+ return Object.freeze({ ...snapshot, dialogPolicy: Object.freeze({ accept: true }) });
239
+ }
240
+
241
+ // An authorizer is a credential: two callers never share one connection
242
+ // through it, even with the same authorizer object (#79 review).
243
+ export function canShareConnection(options) {
244
+ return options?.client?.authorizer === undefined && isPlainData(options);
245
+ }
246
+
247
+ // `open(options)` makes the real connection; it runs once per browser while a
248
+ // lease is held. A caller whose connection options differ from the shared
249
+ // connection's (dialogPolicy included) gets a connection of its own rather
250
+ // than someone else's storage root or dialog policy.
251
+ export async function acquireSharedConnection(
252
+ webSocketDebuggerUrl,
253
+ options,
254
+ { open, timeoutMs },
255
+ ) {
256
+ if (!canShareConnection(options)) return open(options);
257
+ const snapshot = frozenCopy(options);
258
+ let entry = shared.get(webSocketDebuggerUrl);
259
+ if (entry && !isDeepStrictEqual(entry.options, snapshot)) return open(openingOptions(snapshot));
260
+ if (!entry) {
261
+ entry = { options: snapshot, refs: 0, ready: open(openingOptions(snapshot)) };
262
+ shared.set(webSocketDebuggerUrl, entry);
263
+ }
264
+ entry.refs += 1;
265
+ try {
266
+ const connection = await entry.ready;
267
+ // A dropped socket is already being reconnected by the client; join that
268
+ // attempt (or start one) instead of opening a second connection.
269
+ const reconnected = connection.cdp.ensureConnected();
270
+ await (timeoutMs === undefined
271
+ ? reconnected
272
+ : withinTimeout(
273
+ reconnected,
274
+ timeoutMs,
275
+ `timed out after ${timeoutMs}ms reconnecting the CDP session on ${webSocketDebuggerUrl}`,
276
+ ));
277
+ return lease(webSocketDebuggerUrl, entry, connection);
278
+ } catch (error) {
279
+ // The browser behind this key is gone or unreachable: evict the entry so
280
+ // the next attach resolves and opens anew instead of joining a dead one.
281
+ if (shared.get(webSocketDebuggerUrl) === entry) shared.delete(webSocketDebuggerUrl);
282
+ await release(webSocketDebuggerUrl, entry);
283
+ throw error;
284
+ }
285
+ }
@@ -0,0 +1,75 @@
1
+ const baselines = new WeakMap();
2
+ const REF_LINE = /^(\s*)- [^\s"]+(?: "(?:\\.|[^"\\])*")? \[ref=((?:f\d+)?e\d+)\]/;
3
+
4
+ // Compare the final, frame-inlined tree so values, selected options and text children use
5
+ // exactly the same escaping and password redaction as a full snapshot.
6
+ function indexTree(tree) {
7
+ const nodes = new Map();
8
+ const unreferenced = [];
9
+ const parents = [];
10
+ let focused = null;
11
+ for (const line of tree.split("\n")) {
12
+ if (!line) continue;
13
+ const depth = line.search(/\S/);
14
+ while (parents.length && parents.at(-1).depth >= depth) parents.pop();
15
+ const match = REF_LINE.exec(line);
16
+ if (match) {
17
+ const ref = match[2];
18
+ const node = { ref, tree: line.trim().slice(2) };
19
+ nodes.set(ref, node);
20
+ parents.push({ depth, node });
21
+ // Strip the quoted name before looking at state, not user-supplied name text.
22
+ const state = line.slice(match[0].length).match(/"(?:\\.|[^"\\])*"|\[focused\]/g) ?? [];
23
+ if (state.includes("[focused]")) focused = ref;
24
+ } else if (parents.length) {
25
+ parents.at(-1).node.tree += ` | ${line.trim().slice(2)}`;
26
+ } else if (!/^\s*- [\w-]+:?$/.test(line)) {
27
+ unreferenced.push(line);
28
+ }
29
+ }
30
+ return { nodes, focused, unreferenced: unreferenced.join("\n") };
31
+ }
32
+
33
+ export function snapshotResult(frameManager, options, snapshot) {
34
+ const { diff, ...scope } = options;
35
+ const document = frameManager.getFrame(frameManager.mainFrameId);
36
+ const contexts = JSON.stringify(frameManager.collectDescendantFrames(frameManager.mainFrameId)
37
+ .map(({ frameId }) => [frameId, frameManager.getFrame(frameId)?.isolatedContextId]));
38
+ const scopeKey = JSON.stringify(scope);
39
+ const current = indexTree(snapshot.tree);
40
+ const previous = baselines.get(frameManager);
41
+ // Store private, derived data, not the caller-mutable refs map or returned delta entries.
42
+ baselines.set(frameManager, { ...current, document, contexts, scopeKey });
43
+ if (diff !== true) return snapshot;
44
+ let reason;
45
+ if (!previous) reason = "no-baseline";
46
+ else if (previous.document !== document || previous.contexts !== contexts) reason = "navigation";
47
+ else if (previous.scopeKey !== scopeKey) reason = "options-changed";
48
+ else if (previous.unreferenced !== current.unreferenced) reason = "unreferenced-content";
49
+ if (reason) return { ...snapshot, full: true, reason };
50
+
51
+ const added = [];
52
+ const changed = [];
53
+ const removed = [];
54
+ for (const [ref, node] of current.nodes) {
55
+ const before = previous.nodes.get(ref);
56
+ if (!before) added.push({ ...node });
57
+ else if (before.tree !== node.tree) {
58
+ // A stable ref already identifies the role and name. Do not resend its unchanged
59
+ // label or placeholder on every keystroke; the remaining text is current state/value.
60
+ const label = /^[^\s"]+(?: "(?:\\.|[^"\\])*")? /;
61
+ let tree = node.tree;
62
+ const heading = label.exec(tree)?.[0];
63
+ if (heading && heading === label.exec(before.tree)?.[0]) tree = tree.slice(heading.length);
64
+ const placeholder = / \[placeholder="(?:\\.|[^"\\])*"\]/.exec(tree)?.[0];
65
+ if (placeholder && before.tree.includes(placeholder)) tree = tree.replace(placeholder, "");
66
+ changed.push({ ref, tree });
67
+ }
68
+ }
69
+ for (const ref of previous.nodes.keys()) if (!current.nodes.has(ref)) removed.push(ref);
70
+ const result = { diff: { added, changed, removed, focused: current.focused }, full: false };
71
+ if (Buffer.byteLength(JSON.stringify(result), "utf8") > Buffer.byteLength(snapshot.tree, "utf8")) {
72
+ return { ...snapshot, full: true, reason: "diff-larger-than-full" };
73
+ }
74
+ return result;
75
+ }
@@ -0,0 +1,101 @@
1
+ // Self-contained: locator queries serialize this factory into the document's world.
2
+ // Playwright's selectorUtils/createTextMatcher and roleUtils define the matching and naming rules.
3
+ export function createTextMatching(isHidden = () => false, getRole = () => "", includeHidden = false) {
4
+ const normalize = value => String(value ?? "").replace(/[\u200b\u00ad]/g, "").trim().replace(/\s+/g, " ");
5
+ const matches = (value, matcher) => {
6
+ if (matcher instanceof RegExp) {
7
+ matcher.lastIndex = 0;
8
+ return matcher.test(value);
9
+ }
10
+ const text = normalize(value);
11
+ return "exact" in matcher
12
+ ? text === normalize(matcher.exact)
13
+ : text.toLowerCase().includes(normalize(matcher.contains).toLowerCase());
14
+ };
15
+ const skipped = node => ["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT"].includes(node.nodeName) ||
16
+ !!node.ownerDocument?.head?.contains(node);
17
+ const textCache = new Map();
18
+ const text = node => {
19
+ if (textCache.has(node)) return textCache.get(node);
20
+ let value = "";
21
+ if (!skipped(node)) {
22
+ if (node.nodeName === "INPUT" && ["submit", "button", "reset"].includes(node.type)) value = node.value;
23
+ else {
24
+ for (const child of node.childNodes) {
25
+ if (child.nodeType === 3) value += child.nodeValue;
26
+ else if (child.nodeType === 1) value += text(child);
27
+ }
28
+ if (node.shadowRoot) value += text(node.shadowRoot);
29
+ }
30
+ }
31
+ textCache.set(node, value);
32
+ return value;
33
+ };
34
+ const matchesText = (node, matcher) => !skipped(node) && matches(text(node), matcher);
35
+ const labelledBy = node => {
36
+ const refs = node.ariaLabelledByElements ?? (node.getAttribute("aria-labelledby") ?? "")
37
+ .trim().split(/\s+/).filter(Boolean).map(id => node.getRootNode().getElementById?.(id)).filter(Boolean);
38
+ return refs.length ? [...new Set(refs)] : null;
39
+ };
40
+ const labels = node => {
41
+ const refs = labelledBy(node);
42
+ if (refs) return refs.map(text);
43
+ const ariaLabel = node.getAttribute("aria-label");
44
+ if (ariaLabel?.trim()) return [ariaLabel];
45
+ return Array.from(node.labels ?? [], text);
46
+ };
47
+ const contentRoles = new Set(["button", "cell", "checkbox", "columnheader", "gridcell", "heading", "link",
48
+ "menuitem", "menuitemcheckbox", "menuitemradio", "option", "radio", "row", "rowheader", "switch",
49
+ "tab", "tooltip", "treeitem"]);
50
+ const prohibitedRoles = new Set(["caption", "code", "definition", "deletion", "emphasis", "generic",
51
+ "insertion", "mark", "paragraph", "presentation", "strong", "subscript", "suggestion", "superscript", "term", "time"]);
52
+ const accessibleName = node => {
53
+ const visited = new Set();
54
+ const alternative = (element, referenced = false, hiddenReference = false, descendant = false, inLabelledBy = false) => {
55
+ if (visited.has(element) || skipped(element)) return "";
56
+ if (!includeHidden && !hiddenReference && isHidden(element)) return "";
57
+ visited.add(element);
58
+ const refs = labelledBy(element);
59
+ if (refs && !inLabelledBy) {
60
+ const value = refs.map(ref => alternative(ref, true, isHidden(ref), false, true)).join(" ");
61
+ if (value) return value;
62
+ }
63
+ const ariaLabel = element.getAttribute("aria-label");
64
+ if (ariaLabel?.trim()) return ariaLabel;
65
+ const tag = element.nodeName;
66
+ if (tag === "INPUT" && ["button", "submit", "reset"].includes(element.type))
67
+ return element.value || ({ submit: "Submit", reset: "Reset" }[element.type]) || element.getAttribute("title") || "";
68
+ if (element.labels?.length && !inLabelledBy)
69
+ return Array.from(element.labels, label => alternative(label, true, isHidden(label))).join(" ");
70
+ if (tag === "IMG" || tag === "AREA" || (tag === "INPUT" && element.type === "image"))
71
+ return element.getAttribute("alt") || element.getAttribute("title") || (tag === "INPUT" ? "Submit" : "");
72
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
73
+ if (descendant && ["INPUT", "TEXTAREA"].includes(tag)) return element.value;
74
+ if (tag === "INPUT" && element.type === "file") return "Choose File";
75
+ const usePlaceholder = tag === "TEXTAREA" || ["text", "password", "number", "search", "tel", "email", "url"].includes(element.type);
76
+ return element.getAttribute("title") || (usePlaceholder ? element.getAttribute("placeholder") : "") || "";
77
+ }
78
+ const nativeChild = { FIELDSET: "LEGEND", FIGURE: "FIGCAPTION", TABLE: "CAPTION", SVG: "title" }[tag];
79
+ const child = nativeChild && Array.from(element.children).find(child => child.nodeName === nativeChild);
80
+ if (child) return alternative(child, true, isHidden(child));
81
+ if (referenced || descendant || tag === "SUMMARY" || contentRoles.has(getRole(element))) {
82
+ let value = "";
83
+ const assigned = tag === "SLOT" ? element.assignedNodes() : [];
84
+ const children = assigned.length ? assigned : [...element.childNodes, ...(element.shadowRoot?.childNodes ?? [])];
85
+ for (const child of children) {
86
+ if (!assigned.length && child.assignedSlot) continue;
87
+ if (child.nodeType === 3) value += child.nodeValue;
88
+ else if (child.nodeType === 1) {
89
+ const token = alternative(child, referenced, hiddenReference, true, inLabelledBy);
90
+ const display = child.ownerDocument.defaultView.getComputedStyle(child).display;
91
+ value += display !== "inline" || child.nodeName === "BR" ? ` ${token} ` : token;
92
+ }
93
+ }
94
+ if (normalize(value)) return value;
95
+ }
96
+ return element.getAttribute("title") || "";
97
+ };
98
+ return prohibitedRoles.has(getRole(node)) ? "" : normalize(alternative(node));
99
+ };
100
+ return { normalize, matches, skipped, text, matchesText, labels, accessibleName };
101
+ }
package/src/trace.js ADDED
@@ -0,0 +1,183 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createNetworkSnoop } from "./network-snoop.js";
4
+ import { toHar } from "./har.js";
5
+
6
+ const SLUG_MAX = 48;
7
+ const SNOOP_MAX_ENTRIES = 5000;
8
+
9
+ function slug(name) {
10
+ const value = String(name ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
11
+ return (value || "step").slice(0, SLUG_MAX);
12
+ }
13
+
14
+ function messageOf(error) {
15
+ return error instanceof Error ? error.message : String(error);
16
+ }
17
+
18
+ async function readConsole(page) {
19
+ // core.js exposes `page.console` as a PageConsole getter with logs(); simpler pages
20
+ // expose it as a method. Both hand back the buffered in-page entries.
21
+ const api = page.console;
22
+ const entries = typeof api === "function" ? await api.call(page) : await api?.logs?.();
23
+ return Array.isArray(entries) ? entries : [];
24
+ }
25
+
26
+ /**
27
+ * Records a flight recorder trace for one page: steps, screenshots, network, console,
28
+ * dialogs, navigations and downloads, flushed to `dir` as trace.jsonl, trace.har and
29
+ * summary.json when {@link stop} runs.
30
+ */
31
+ export function createTrace(page, options = {}) {
32
+ if (!page?.cdp || typeof page.resolveSessionId !== "function") {
33
+ throw new TypeError("createTrace requires a page with cdp and resolveSessionId");
34
+ }
35
+ const {
36
+ dir,
37
+ screenshots = true,
38
+ network = true,
39
+ console: consoleLogs = true,
40
+ maxBodyBytes = 1_000_000,
41
+ events,
42
+ } = options;
43
+ if (typeof dir !== "string" || dir.length === 0) throw new TypeError("createTrace requires a dir");
44
+
45
+ const shotDir = path.join(dir, "screenshots");
46
+ const ready = mkdir(shotDir, { recursive: true });
47
+ const startedAt = Date.now();
48
+ const records = [];
49
+ const netEntries = [];
50
+ const unsubscribers = [];
51
+ const snoop = network
52
+ ? createNetworkSnoop(page, { bodies: true, maxBodyBytes, maxEntries: SNOOP_MAX_ENTRIES })
53
+ : null;
54
+ let seq = 0;
55
+ let consoleSeen = 0;
56
+ let sessionId = null;
57
+ let stopped = false;
58
+ let stopping = null;
59
+
60
+ function record(event) {
61
+ const entry = { ...event, ts: Date.now(), seq: seq++ };
62
+ records.push(entry);
63
+ return entry;
64
+ }
65
+
66
+ const sessionReady = Promise.resolve(page.resolveSessionId()).then(id => { sessionId = id; });
67
+ sessionReady.catch(error => record({ kind: "warning", scope: "session", message: messageOf(error) }));
68
+
69
+ unsubscribers.push(page.cdp.on("Page.frameNavigated", (params, meta) => {
70
+ if (stopped || params?.frame?.parentId) return;
71
+ const add = () => record({ kind: "navigation", url: params?.frame?.url ?? "", frameId: params?.frame?.id ?? null });
72
+ if (sessionId === null) {
73
+ // The session id resolves asynchronously; hold early events until it is known.
74
+ sessionReady.then(() => { if (!stopped && meta?.sessionId === sessionId) add(); }).catch(() => {});
75
+ return;
76
+ }
77
+ if (meta?.sessionId === sessionId) add();
78
+ }));
79
+
80
+ unsubscribers.push(page.on("dialog", dialog => record({
81
+ kind: "dialog",
82
+ type: dialog.type() ?? null,
83
+ message: dialog.message() ?? "",
84
+ defaultPrompt: dialog.defaultValue(),
85
+ url: dialog.url ?? null,
86
+ })));
87
+
88
+ if (events) {
89
+ unsubscribers.push(events.on("downloadStarted", payload => record({ kind: "download", phase: "started", ...payload })));
90
+ unsubscribers.push(events.on("downloadFinished", payload => record({ kind: "download", phase: "finished", ...payload })));
91
+ }
92
+
93
+ async function capture(step, phase) {
94
+ const file = path.join(shotDir, `${step.seq}-${slug(step.name)}-${phase}.png`);
95
+ try {
96
+ // The buffer is written here rather than through screenshot({ path }) so the file
97
+ // always lands in the trace directory, whatever the page's path resolution does.
98
+ await writeFile(file, await page.screenshot({ type: "png" }));
99
+ step.screenshots[phase] = file;
100
+ } catch (error) {
101
+ record({ kind: "warning", scope: `screenshot:${phase}`, step: step.seq, message: messageOf(error) });
102
+ }
103
+ }
104
+
105
+ function drainNetwork() {
106
+ for (const entry of snoop?.pop() ?? []) {
107
+ if (typeof entry.body === "string" && Buffer.byteLength(entry.body) > maxBodyBytes) {
108
+ entry.body = null;
109
+ entry.bodySkipped = true;
110
+ }
111
+ netEntries.push(entry);
112
+ record({ kind: "network", ...entry });
113
+ }
114
+ }
115
+
116
+ async function drainConsole() {
117
+ if (!consoleLogs) return;
118
+ let entries;
119
+ try {
120
+ entries = await readConsole(page);
121
+ } catch {
122
+ // A closed or navigating page cannot report its console; keep the rest of the trace.
123
+ return;
124
+ }
125
+ if (entries.length < consoleSeen) consoleSeen = 0;
126
+ for (const entry of entries.slice(consoleSeen)) record({ kind: "console", ...entry });
127
+ consoleSeen = entries.length;
128
+ }
129
+
130
+ async function drain() {
131
+ drainNetwork();
132
+ await drainConsole();
133
+ }
134
+
135
+ async function step(name, fn) {
136
+ if (typeof fn !== "function") throw new TypeError("trace.step requires a function");
137
+ await ready;
138
+ const entry = record({ kind: "step", name: String(name), startedAt: Date.now(), screenshots: {} });
139
+ if (screenshots) await capture(entry, "before");
140
+ try {
141
+ return await fn();
142
+ } catch (error) {
143
+ entry.error = messageOf(error);
144
+ throw error;
145
+ } finally {
146
+ entry.endedAt = Date.now();
147
+ entry.durationMs = entry.endedAt - entry.startedAt;
148
+ if (screenshots) await capture(entry, "after");
149
+ await drain();
150
+ }
151
+ }
152
+
153
+ function mark(name, data) {
154
+ return record({ kind: "mark", name: String(name), data: data ?? null });
155
+ }
156
+
157
+ async function finish() {
158
+ await ready;
159
+ await drain();
160
+ stopped = true;
161
+ for (const off of unsubscribers.splice(0, unsubscribers.length)) off();
162
+ snoop?.dispose();
163
+ const ordered = [...records].sort((a, b) => a.seq - b.seq);
164
+ const summary = {
165
+ steps: ordered.filter(entry => entry.kind === "step").length,
166
+ events: ordered.length,
167
+ network: netEntries.length,
168
+ startedAt,
169
+ endedAt: Date.now(),
170
+ url: page.url(),
171
+ };
172
+ await writeFile(path.join(dir, "trace.jsonl"), ordered.map(entry => `${JSON.stringify(entry)}\n`).join(""));
173
+ await writeFile(path.join(dir, "trace.har"), `${JSON.stringify(toHar(netEntries), null, 2)}\n`);
174
+ await writeFile(path.join(dir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`);
175
+ return summary;
176
+ }
177
+
178
+ function stop() {
179
+ return stopping ??= finish();
180
+ }
181
+
182
+ return { step, mark, stop, get dir() { return dir; } };
183
+ }