@vexralabs/zerodom 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.
- package/LICENSE +73 -0
- package/README.md +53 -0
- package/dist/frames.d.ts +55 -0
- package/dist/frames.js +84 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/labelLinker.d.ts +25 -0
- package/dist/labelLinker.js +233 -0
- package/dist/parser.d.ts +168 -0
- package/dist/parser.js +501 -0
- package/dist/playwright.d.ts +30 -0
- package/dist/playwright.js +130 -0
- package/package.json +41 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright 2026 Syed Husnain Khalid
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# zerodom (TypeScript)
|
|
2
|
+
|
|
3
|
+
TypeScript port of [ZeroDOM](https://github.com/DevHusnainAi/zerodom)'s core engine —
|
|
4
|
+
same interaction graph, same selector guarantees, for the Node/TS agent stack
|
|
5
|
+
(LangChain.js, the Vercel AI SDK, Playwright for Node).
|
|
6
|
+
|
|
7
|
+
This is a v1 port: the parser, label linker, and a one-line Playwright adapter.
|
|
8
|
+
The CLI, MCP server, and HTML report inspector are still Python-only — this package
|
|
9
|
+
is the piece most JS agents actually need (`ZeroDOM.fromPage(page)` →
|
|
10
|
+
`graph.toCompactText()`), not the whole toolchain. See the root
|
|
11
|
+
[README](../README.md) for the full feature set and design rationale; the logic
|
|
12
|
+
here is a line-for-line port of `../zerodom/parser.py` and `../zerodom/label_linker.py`,
|
|
13
|
+
so the same design notes (selector priority, label priority, escaping rules) apply.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @vexralabs/zerodom
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { ZeroDOM } from "@vexralabs/zerodom";
|
|
25
|
+
|
|
26
|
+
const graph = await ZeroDOM.fromPage(page); // any object with content()/url(), e.g. a Playwright Page
|
|
27
|
+
console.log(graph.toCompactText()); // what you send the model
|
|
28
|
+
const selectors = graph.selectorMap(); // { node_01: "#email-input", ... } — stays your side
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { parseHtml } from "@vexralabs/zerodom";
|
|
33
|
+
|
|
34
|
+
const graph = parseHtml(html, url); // parse HTML you already have, no browser needed
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Why linkedom, not jsdom
|
|
38
|
+
|
|
39
|
+
`linkedom` gives a real `querySelector`/`getElementById` DOM — needed so every
|
|
40
|
+
generated selector can be self-verified, the same guarantee the Python version
|
|
41
|
+
makes against a real browser — at a fraction of jsdom's footprint. One caveat this
|
|
42
|
+
port works around: unlike jsdom or a real browser, linkedom's parser doesn't
|
|
43
|
+
normalize a bare HTML fragment into a full `<html><body>` document, so
|
|
44
|
+
`ZeroDOMParser` wraps non-document input itself before handing it to linkedom
|
|
45
|
+
(`page.content()` output is unaffected — it's always a full document already).
|
|
46
|
+
|
|
47
|
+
## Development
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install
|
|
51
|
+
npm run build # tsc -> dist/
|
|
52
|
+
npm test # node's built-in test runner, against the built dist
|
|
53
|
+
```
|
package/dist/frames.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reaching into iframes. Port of zerodom/frames.py.
|
|
3
|
+
*
|
|
4
|
+
* Each frame is a separate document with its own DOM, so a CSS selector from the
|
|
5
|
+
* top page can never address something inside one. Playwright bridges that with
|
|
6
|
+
* `frameLocator()`, and this module records, per node, the chain of iframe
|
|
7
|
+
* selectors needed to get there — so `locate(page, node)` reaches any node in any
|
|
8
|
+
* frame, and callers never have to know which is which.
|
|
9
|
+
*
|
|
10
|
+
* Node's Playwright API is async-only (no sync/async split like Python's), so
|
|
11
|
+
* there's one version of each function here where the Python source has two.
|
|
12
|
+
*/
|
|
13
|
+
import type { GraphNode } from "./parser.js";
|
|
14
|
+
/** Minimal surface this module needs from a Playwright Frame. */
|
|
15
|
+
export interface FrameLike {
|
|
16
|
+
url(): string;
|
|
17
|
+
parentFrame(): FrameLike | null;
|
|
18
|
+
frameElement(): Promise<{
|
|
19
|
+
evaluate(fn: string): Promise<number>;
|
|
20
|
+
boundingBox(): Promise<{
|
|
21
|
+
width: number;
|
|
22
|
+
height: number;
|
|
23
|
+
} | null>;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Selectors from the top document down to `frame`, or null if unreachable.
|
|
28
|
+
*
|
|
29
|
+
* Indexed rather than named: `iframe >> nth=2` survives a frame with no id, no
|
|
30
|
+
* name and no stable class, which is most of them.
|
|
31
|
+
*/
|
|
32
|
+
export declare function frameChain(frame: FrameLike): Promise<string[] | null>;
|
|
33
|
+
/**
|
|
34
|
+
* Is this frame rendered, and big enough to hold something clickable?
|
|
35
|
+
*
|
|
36
|
+
* `boundingBox()` returns null for a frame that is display:none or detached,
|
|
37
|
+
* which is most of the iframes on an ad-supported page. A visible frame below
|
|
38
|
+
* MIN_FRAME_PX is a tracking pixel.
|
|
39
|
+
*/
|
|
40
|
+
export declare function isWorthReading(frame: FrameLike): Promise<boolean>;
|
|
41
|
+
/** Minimal surface this module needs from a Playwright Page or FrameLocator. */
|
|
42
|
+
export interface LocatableLike {
|
|
43
|
+
frameLocator(selector: string): LocatableLike;
|
|
44
|
+
locator(selector: string): unknown;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A Playwright locator for `node`, descending into its frame if it has one.
|
|
48
|
+
*
|
|
49
|
+
* The single place that knows how a node's `frame` chain turns into something
|
|
50
|
+
* clickable — click, fill and the report measurer all route through it, so they
|
|
51
|
+
* cannot disagree about where a node lives.
|
|
52
|
+
*/
|
|
53
|
+
export declare function locate(page: LocatableLike, node: GraphNode): unknown;
|
|
54
|
+
/** Re-id a merged node list so ids stay dense and in document order. */
|
|
55
|
+
export declare function renumber(nodes: GraphNode[]): GraphNode[];
|
package/dist/frames.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reaching into iframes. Port of zerodom/frames.py.
|
|
3
|
+
*
|
|
4
|
+
* Each frame is a separate document with its own DOM, so a CSS selector from the
|
|
5
|
+
* top page can never address something inside one. Playwright bridges that with
|
|
6
|
+
* `frameLocator()`, and this module records, per node, the chain of iframe
|
|
7
|
+
* selectors needed to get there — so `locate(page, node)` reaches any node in any
|
|
8
|
+
* frame, and callers never have to know which is which.
|
|
9
|
+
*
|
|
10
|
+
* Node's Playwright API is async-only (no sync/async split like Python's), so
|
|
11
|
+
* there's one version of each function here where the Python source has two.
|
|
12
|
+
*/
|
|
13
|
+
/** `about:blank` is deliberately NOT here — a frame written by srcdoc or
|
|
14
|
+
* document.write keeps that URL and holds the embedded preview an agent came
|
|
15
|
+
* for. Size and content decide whether a frame is worth reading, not its URL. */
|
|
16
|
+
const SKIP_URL_PREFIXES = ["javascript:", "data:"];
|
|
17
|
+
// An iframe smaller than this is a tracking pixel or a consent beacon.
|
|
18
|
+
const MIN_FRAME_PX = 40;
|
|
19
|
+
/**
|
|
20
|
+
* Selectors from the top document down to `frame`, or null if unreachable.
|
|
21
|
+
*
|
|
22
|
+
* Indexed rather than named: `iframe >> nth=2` survives a frame with no id, no
|
|
23
|
+
* name and no stable class, which is most of them.
|
|
24
|
+
*/
|
|
25
|
+
export async function frameChain(frame) {
|
|
26
|
+
const chain = [];
|
|
27
|
+
let current = frame;
|
|
28
|
+
let parent = current.parentFrame();
|
|
29
|
+
while (parent !== null) {
|
|
30
|
+
let index;
|
|
31
|
+
try {
|
|
32
|
+
const element = await current.frameElement();
|
|
33
|
+
index = await element.evaluate("e => [...e.ownerDocument.querySelectorAll('iframe')].indexOf(e)");
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (index < 0)
|
|
39
|
+
return null;
|
|
40
|
+
chain.push(`iframe >> nth=${index}`);
|
|
41
|
+
current = parent;
|
|
42
|
+
parent = current.parentFrame();
|
|
43
|
+
}
|
|
44
|
+
return chain.reverse();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Is this frame rendered, and big enough to hold something clickable?
|
|
48
|
+
*
|
|
49
|
+
* `boundingBox()` returns null for a frame that is display:none or detached,
|
|
50
|
+
* which is most of the iframes on an ad-supported page. A visible frame below
|
|
51
|
+
* MIN_FRAME_PX is a tracking pixel.
|
|
52
|
+
*/
|
|
53
|
+
export async function isWorthReading(frame) {
|
|
54
|
+
if (SKIP_URL_PREFIXES.some((p) => (frame.url() || "").toLowerCase().startsWith(p)))
|
|
55
|
+
return false;
|
|
56
|
+
try {
|
|
57
|
+
const element = await frame.frameElement();
|
|
58
|
+
const box = await element.boundingBox();
|
|
59
|
+
return !!box && box.width >= MIN_FRAME_PX && box.height >= MIN_FRAME_PX;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* A Playwright locator for `node`, descending into its frame if it has one.
|
|
67
|
+
*
|
|
68
|
+
* The single place that knows how a node's `frame` chain turns into something
|
|
69
|
+
* clickable — click, fill and the report measurer all route through it, so they
|
|
70
|
+
* cannot disagree about where a node lives.
|
|
71
|
+
*/
|
|
72
|
+
export function locate(page, node) {
|
|
73
|
+
let target = page;
|
|
74
|
+
for (const selector of node.frame ?? [])
|
|
75
|
+
target = target.frameLocator(selector);
|
|
76
|
+
return target.locator(node.selector);
|
|
77
|
+
}
|
|
78
|
+
/** Re-id a merged node list so ids stay dense and in document order. */
|
|
79
|
+
export function renumber(nodes) {
|
|
80
|
+
nodes.forEach((node, i) => {
|
|
81
|
+
node.id = `node_${String(i + 1).padStart(2, "0")}`;
|
|
82
|
+
});
|
|
83
|
+
return nodes;
|
|
84
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { InteractionGraph, ZeroDOMParser, parseHtml, cssId, cssString, classToken, isShadowRoot, compactLine, findNodes, } from "./parser.js";
|
|
2
|
+
export type { GraphNode, GraphMetadata } from "./parser.js";
|
|
3
|
+
export { LabelLinker, textOf, getLabel } from "./labelLinker.js";
|
|
4
|
+
export { frameChain, isWorthReading, locate, renumber } from "./frames.js";
|
|
5
|
+
export type { FrameLike, LocatableLike } from "./frames.js";
|
|
6
|
+
export { ZeroDOM, serialize, SERIALIZE } from "./playwright.js";
|
|
7
|
+
export type { PageLike } from "./playwright.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { InteractionGraph, ZeroDOMParser, parseHtml, cssId, cssString, classToken, isShadowRoot, compactLine, findNodes, } from "./parser.js";
|
|
2
|
+
export { LabelLinker, textOf, getLabel } from "./labelLinker.js";
|
|
3
|
+
export { frameChain, isWorthReading, locate, renumber } from "./frames.js";
|
|
4
|
+
export { ZeroDOM, serialize, SERIALIZE } from "./playwright.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Work out what a control is called, the way a person reading the page would. Port of zerodom/label_linker.py. */
|
|
2
|
+
export declare function textOf(el: Element): string;
|
|
3
|
+
/**
|
|
4
|
+
* Caption sitting immediately before an input, as in `Search: <input>`.
|
|
5
|
+
*
|
|
6
|
+
* Reads the text between the previous element sibling and this element (or the
|
|
7
|
+
* parent's leading text when this is the first child). Only the last few words are
|
|
8
|
+
* kept — the text run before an input is often a whole sentence of surrounding
|
|
9
|
+
* copy, not a caption.
|
|
10
|
+
*/
|
|
11
|
+
export declare function adjacentText(el: Element): string;
|
|
12
|
+
/**
|
|
13
|
+
* Resolves labels against a pre-indexed set of <label> tags.
|
|
14
|
+
*
|
|
15
|
+
* The parser walks the DOM once and hands over what it saw, so label lookup stays
|
|
16
|
+
* O(1) per node instead of re-searching the tree for every input.
|
|
17
|
+
*/
|
|
18
|
+
export declare class LabelLinker {
|
|
19
|
+
private readonly root;
|
|
20
|
+
private readonly labelsByFor;
|
|
21
|
+
constructor(root: Document, labelsByFor?: Map<string, Element>);
|
|
22
|
+
label(element: Element, ancestorLabel?: Element | null): string;
|
|
23
|
+
}
|
|
24
|
+
/** Standalone label lookup for a single element. */
|
|
25
|
+
export declare function getLabel(root: Document, element: Element): string;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/** Work out what a control is called, the way a person reading the page would. Port of zerodom/label_linker.py. */
|
|
2
|
+
// Attribute fallbacks, most explicit first. Split around the adjacent-text scan:
|
|
3
|
+
// authored attributes beat scraped text, but scraped text beats name/value, which
|
|
4
|
+
// are developer identifiers ("q") rather than anything a user reads.
|
|
5
|
+
const AUTHORED_ATTRS = ["aria-label", "placeholder", "alt", "title"];
|
|
6
|
+
const IDENTIFIER_ATTRS = ["value", "name"];
|
|
7
|
+
// Icon buttons routinely put their only human-readable caption in a tooltip
|
|
8
|
+
// library's data attribute. These four cover Tippy, Bootstrap and the
|
|
9
|
+
// conventional hand-rolled spelling, which between them are most of the web.
|
|
10
|
+
const TOOLTIP_ATTRS = ["data-tooltip", "data-original-title", "data-tippy-content", "data-tippy-simple-content"];
|
|
11
|
+
// Controls that sit next to their caption. Buttons and links carry their own text.
|
|
12
|
+
const CAPTIONED_TAGS = new Set(["input", "select", "textarea"]);
|
|
13
|
+
// Inputs whose `value` is a button caption rather than user data.
|
|
14
|
+
const BUTTON_INPUT_TYPES = new Set(["submit", "button", "reset", "image"]);
|
|
15
|
+
const MAX_LABEL_LEN = 80;
|
|
16
|
+
// Trailing punctuation on a caption: "Search:" -> "Search".
|
|
17
|
+
const CAPTION_STRIP = /[ \t\n :*>\-–—]+$/;
|
|
18
|
+
export function textOf(el) {
|
|
19
|
+
return collapse(el.textContent ?? "").slice(0, MAX_LABEL_LEN);
|
|
20
|
+
}
|
|
21
|
+
function collapse(text) {
|
|
22
|
+
return text.split(/\s+/).filter(Boolean).join(" ");
|
|
23
|
+
}
|
|
24
|
+
/** Raw text between `afterEl` (exclusive) and `stopEl` — the DOM analogue of lxml's `.tail`. */
|
|
25
|
+
function textBetween(afterEl, parent, stopEl) {
|
|
26
|
+
let node = afterEl ? afterEl.nextSibling : parent.firstChild;
|
|
27
|
+
let text = "";
|
|
28
|
+
while (node && node !== stopEl) {
|
|
29
|
+
if (node.nodeType === 3 /* TEXT_NODE */)
|
|
30
|
+
text += node.data;
|
|
31
|
+
node = node.nextSibling;
|
|
32
|
+
}
|
|
33
|
+
return text;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Caption sitting immediately before an input, as in `Search: <input>`.
|
|
37
|
+
*
|
|
38
|
+
* Reads the text between the previous element sibling and this element (or the
|
|
39
|
+
* parent's leading text when this is the first child). Only the last few words are
|
|
40
|
+
* kept — the text run before an input is often a whole sentence of surrounding
|
|
41
|
+
* copy, not a caption.
|
|
42
|
+
*/
|
|
43
|
+
export function adjacentText(el) {
|
|
44
|
+
const parent = el.parentElement;
|
|
45
|
+
if (!parent)
|
|
46
|
+
return "";
|
|
47
|
+
const previous = el.previousElementSibling;
|
|
48
|
+
const source = textBetween(previous, parent, el);
|
|
49
|
+
const caption = collapse(source).replace(CAPTION_STRIP, "");
|
|
50
|
+
if (!caption)
|
|
51
|
+
return "";
|
|
52
|
+
return caption.split(" ").slice(-6).join(" ").slice(0, MAX_LABEL_LEN);
|
|
53
|
+
}
|
|
54
|
+
// Handler names that describe the plumbing rather than the action.
|
|
55
|
+
const HANDLER_NOISE = new Set([
|
|
56
|
+
"return", "function", "void", "this", "event", "typeof", "new", "if",
|
|
57
|
+
"settimeout", "requestanimationframe", "preventdefault", "stoppropagation",
|
|
58
|
+
]);
|
|
59
|
+
const HANDLER_CALL = /([A-Za-z_$][\w$]*)\s*\(/g;
|
|
60
|
+
const WORD_BREAK = /(?<=[a-z0-9])(?=[A-Z])/g;
|
|
61
|
+
/**
|
|
62
|
+
* The action an inline handler names, as words. `_bsa.close(…)` -> "close".
|
|
63
|
+
*
|
|
64
|
+
* Only ever reached when an element has no text, no icon and no attribute of its
|
|
65
|
+
* own, which in practice means an icon `<div onclick>` built out of an SVG path.
|
|
66
|
+
* Conservative on purpose: a name that describes the wiring instead of the intent
|
|
67
|
+
* is worse than admitting the control is unlabelled.
|
|
68
|
+
*/
|
|
69
|
+
function handlerLabel(onclick) {
|
|
70
|
+
const names = Array.from((onclick || "").matchAll(HANDLER_CALL), (m) => m[1]).reverse();
|
|
71
|
+
for (const name of names) {
|
|
72
|
+
if (name.length < 3 || HANDLER_NOISE.has(name.toLowerCase().replace(/^_+/, "")))
|
|
73
|
+
continue;
|
|
74
|
+
const words = name.replace(/^[_$]+|[_$]+$/g, "").replace(WORD_BREAK, " ").replace(/[_-]/g, " ");
|
|
75
|
+
const cleaned = collapse(words).toLowerCase();
|
|
76
|
+
if (cleaned)
|
|
77
|
+
return cleaned.slice(0, MAX_LABEL_LEN);
|
|
78
|
+
}
|
|
79
|
+
return "";
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A link's destination, trimmed to the part a person would read aloud.
|
|
83
|
+
*
|
|
84
|
+
* Last resort only — a real caption always wins. `javascript:` and bare fragments
|
|
85
|
+
* say nothing about where the link goes, so they stay unlabelled.
|
|
86
|
+
*/
|
|
87
|
+
function hrefLabel(href) {
|
|
88
|
+
const trimmed0 = href.trim();
|
|
89
|
+
if (trimmed0.startsWith("javascript:") || trimmed0.startsWith("#") || !trimmed0)
|
|
90
|
+
return "";
|
|
91
|
+
// Drop scheme and www so "https://news.ycombinator.com/" reads as the site.
|
|
92
|
+
const trimmed = trimmed0.replace(/^[a-z][a-z0-9+.-]*:\/\/(www\.)?/i, "");
|
|
93
|
+
return trimmed.replace(/\/+$/, "").slice(0, MAX_LABEL_LEN);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Resolves labels against a pre-indexed set of <label> tags.
|
|
97
|
+
*
|
|
98
|
+
* The parser walks the DOM once and hands over what it saw, so label lookup stays
|
|
99
|
+
* O(1) per node instead of re-searching the tree for every input.
|
|
100
|
+
*/
|
|
101
|
+
export class LabelLinker {
|
|
102
|
+
root;
|
|
103
|
+
labelsByFor;
|
|
104
|
+
constructor(root, labelsByFor) {
|
|
105
|
+
this.root = root;
|
|
106
|
+
if (labelsByFor) {
|
|
107
|
+
this.labelsByFor = labelsByFor;
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
this.labelsByFor = new Map();
|
|
111
|
+
for (const tag of Array.from(root.querySelectorAll("label"))) {
|
|
112
|
+
const forId = tag.getAttribute("for");
|
|
113
|
+
if (forId && !this.labelsByFor.has(forId))
|
|
114
|
+
this.labelsByFor.set(forId, tag);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
label(element, ancestorLabel = null) {
|
|
119
|
+
// explicit <label for="...">
|
|
120
|
+
const elemId = element.getAttribute("id");
|
|
121
|
+
if (elemId) {
|
|
122
|
+
const tag = this.labelsByFor.get(elemId);
|
|
123
|
+
if (tag) {
|
|
124
|
+
const text = textOf(tag);
|
|
125
|
+
if (text)
|
|
126
|
+
return text;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// wrapping <label>
|
|
130
|
+
let ancestor = ancestorLabel;
|
|
131
|
+
if (!ancestor) {
|
|
132
|
+
let node = element.parentElement;
|
|
133
|
+
while (node) {
|
|
134
|
+
if (node.localName === "label") {
|
|
135
|
+
ancestor = node;
|
|
136
|
+
break;
|
|
137
|
+
}
|
|
138
|
+
node = node.parentElement;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (ancestor) {
|
|
142
|
+
const text = textOf(ancestor);
|
|
143
|
+
if (text)
|
|
144
|
+
return text;
|
|
145
|
+
}
|
|
146
|
+
// aria-labelledby -> referenced element's text
|
|
147
|
+
for (const refId of (element.getAttribute("aria-labelledby") ?? "").split(/\s+/).filter(Boolean)) {
|
|
148
|
+
const ref = this.root.getElementById(refId);
|
|
149
|
+
if (ref) {
|
|
150
|
+
const text = textOf(ref);
|
|
151
|
+
if (text)
|
|
152
|
+
return text;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// authored attribute fallbacks
|
|
156
|
+
for (const attr of AUTHORED_ATTRS) {
|
|
157
|
+
const val = element.getAttribute(attr);
|
|
158
|
+
if (val && val.trim())
|
|
159
|
+
return val.trim().slice(0, MAX_LABEL_LEN);
|
|
160
|
+
}
|
|
161
|
+
// On a submit/button input, `value` is the visible caption, not an identifier.
|
|
162
|
+
if (element.localName === "input" && BUTTON_INPUT_TYPES.has(element.getAttribute("type") ?? "")) {
|
|
163
|
+
const val = element.getAttribute("value");
|
|
164
|
+
if (val && val.trim())
|
|
165
|
+
return val.trim().slice(0, MAX_LABEL_LEN);
|
|
166
|
+
}
|
|
167
|
+
// Caption text next to the control, before falling back to identifiers
|
|
168
|
+
if (CAPTIONED_TAGS.has(element.localName)) {
|
|
169
|
+
const caption = adjacentText(element);
|
|
170
|
+
if (caption)
|
|
171
|
+
return caption;
|
|
172
|
+
}
|
|
173
|
+
// Inner text (buttons, links). Skipped for captioned controls, whose contents
|
|
174
|
+
// are their value or options — a <select>'s first <option> is not its label.
|
|
175
|
+
if (!CAPTIONED_TAGS.has(element.localName)) {
|
|
176
|
+
const text = textOf(element);
|
|
177
|
+
if (text)
|
|
178
|
+
return text;
|
|
179
|
+
}
|
|
180
|
+
for (const attr of IDENTIFIER_ATTRS) {
|
|
181
|
+
const val = element.getAttribute(attr);
|
|
182
|
+
if (val && val.trim())
|
|
183
|
+
return val.trim().slice(0, MAX_LABEL_LEN);
|
|
184
|
+
}
|
|
185
|
+
// Icon-only controls carry their label on a descendant, not on themselves: an
|
|
186
|
+
// <img alt>, but just as often a styled <div title> or <i aria-label>. Hacker
|
|
187
|
+
// News' vote arrows are <a><div class="votearrow" title="upvote"></div></a>,
|
|
188
|
+
// and they are the most-clicked control on the page.
|
|
189
|
+
for (const descendant of Array.from(element.querySelectorAll("*"))) {
|
|
190
|
+
for (const attr of AUTHORED_ATTRS) {
|
|
191
|
+
const val = descendant.getAttribute(attr);
|
|
192
|
+
if (val && val.trim())
|
|
193
|
+
return val.trim().slice(0, MAX_LABEL_LEN);
|
|
194
|
+
}
|
|
195
|
+
// <svg><title>Save</title></svg> is the standards-defined accessible name
|
|
196
|
+
// for an inline icon. The walk prunes <svg>, but the label lookup reads it
|
|
197
|
+
// directly.
|
|
198
|
+
if ((descendant.localName === "title" || descendant.localName === "desc")) {
|
|
199
|
+
const text = textOf(descendant);
|
|
200
|
+
if (text)
|
|
201
|
+
return text;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
// Tooltip libraries, checked after real markup and before giving up.
|
|
205
|
+
for (const attr of TOOLTIP_ATTRS) {
|
|
206
|
+
const val = element.getAttribute(attr);
|
|
207
|
+
if (val && val.trim())
|
|
208
|
+
return val.trim().slice(0, MAX_LABEL_LEN);
|
|
209
|
+
}
|
|
210
|
+
// A link with no text and no icon label still has somewhere to go, and the
|
|
211
|
+
// destination is the only thing left that tells an agent them apart.
|
|
212
|
+
if (element.localName === "a") {
|
|
213
|
+
const href = (element.getAttribute("href") ?? "").trim();
|
|
214
|
+
if (href) {
|
|
215
|
+
const label = hrefLabel(href);
|
|
216
|
+
if (label)
|
|
217
|
+
return label;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// Last resort: the handler's own name. A bare `<div onclick="_bsa.close(…)">`
|
|
221
|
+
// wrapping an SVG path has no text, no alt, no title and no tooltip — but
|
|
222
|
+
// somebody named the function, and "close" is worth more to an agent than
|
|
223
|
+
// "Unlabelled Element".
|
|
224
|
+
const handler = handlerLabel(element.getAttribute("onclick") ?? "");
|
|
225
|
+
if (handler)
|
|
226
|
+
return handler;
|
|
227
|
+
return "Unlabelled Element";
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** Standalone label lookup for a single element. */
|
|
231
|
+
export function getLabel(root, element) {
|
|
232
|
+
return new LabelLinker(root).label(element);
|
|
233
|
+
}
|