@ac-kit/format-xpath 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +28 -0
  3. package/README.md +223 -2
  4. package/dist/_axes.d.ts +18 -0
  5. package/dist/_axes.d.ts.map +1 -0
  6. package/dist/_axes.js +124 -0
  7. package/dist/_axes.js.map +1 -0
  8. package/dist/_code-points.d.ts +13 -0
  9. package/dist/_code-points.d.ts.map +1 -0
  10. package/dist/_code-points.js +40 -0
  11. package/dist/_code-points.js.map +1 -0
  12. package/dist/_compare.d.ts +14 -0
  13. package/dist/_compare.d.ts.map +1 -0
  14. package/dist/_compare.js +160 -0
  15. package/dist/_compare.js.map +1 -0
  16. package/dist/_compile.d.ts +87 -0
  17. package/dist/_compile.d.ts.map +1 -0
  18. package/dist/_compile.js +262 -0
  19. package/dist/_compile.js.map +1 -0
  20. package/dist/_convert.d.ts +16 -0
  21. package/dist/_convert.d.ts.map +1 -0
  22. package/dist/_convert.js +46 -0
  23. package/dist/_convert.js.map +1 -0
  24. package/dist/_evaluate.d.ts +15 -0
  25. package/dist/_evaluate.d.ts.map +1 -0
  26. package/dist/_evaluate.js +160 -0
  27. package/dist/_evaluate.js.map +1 -0
  28. package/dist/_foreign-functions.d.ts +7 -0
  29. package/dist/_foreign-functions.d.ts.map +1 -0
  30. package/dist/_foreign-functions.js +54 -0
  31. package/dist/_foreign-functions.js.map +1 -0
  32. package/dist/_functions.d.ts +24 -0
  33. package/dist/_functions.d.ts.map +1 -0
  34. package/dist/_functions.js +312 -0
  35. package/dist/_functions.js.map +1 -0
  36. package/dist/_lexer.d.ts +23 -0
  37. package/dist/_lexer.d.ts.map +1 -0
  38. package/dist/_lexer.js +211 -0
  39. package/dist/_lexer.js.map +1 -0
  40. package/dist/_node-test.d.ts +15 -0
  41. package/dist/_node-test.d.ts.map +1 -0
  42. package/dist/_node-test.js +123 -0
  43. package/dist/_node-test.js.map +1 -0
  44. package/dist/_number.d.ts +15 -0
  45. package/dist/_number.d.ts.map +1 -0
  46. package/dist/_number.js +31 -0
  47. package/dist/_number.js.map +1 -0
  48. package/dist/_parse-bounded.d.ts +17 -0
  49. package/dist/_parse-bounded.d.ts.map +1 -0
  50. package/dist/_parse-bounded.js +107 -0
  51. package/dist/_parse-bounded.js.map +1 -0
  52. package/dist/_parser.d.ts +15 -0
  53. package/dist/_parser.d.ts.map +1 -0
  54. package/dist/_parser.js +391 -0
  55. package/dist/_parser.js.map +1 -0
  56. package/dist/_run.d.ts +169 -0
  57. package/dist/_run.d.ts.map +1 -0
  58. package/dist/_run.js +646 -0
  59. package/dist/_run.js.map +1 -0
  60. package/dist/_walk-expression.d.ts +8 -0
  61. package/dist/_walk-expression.d.ts.map +1 -0
  62. package/dist/_walk-expression.js +54 -0
  63. package/dist/_walk-expression.js.map +1 -0
  64. package/dist/ast.d.ts +110 -0
  65. package/dist/ast.d.ts.map +1 -0
  66. package/dist/ast.js +2 -0
  67. package/dist/ast.js.map +1 -0
  68. package/dist/compile-xpath.d.ts +97 -0
  69. package/dist/compile-xpath.d.ts.map +1 -0
  70. package/dist/compile-xpath.js +105 -0
  71. package/dist/compile-xpath.js.map +1 -0
  72. package/dist/errors.d.ts +52 -0
  73. package/dist/errors.d.ts.map +1 -0
  74. package/dist/errors.js +68 -0
  75. package/dist/errors.js.map +1 -0
  76. package/dist/evaluate-xpath.d.ts +11 -0
  77. package/dist/evaluate-xpath.d.ts.map +1 -0
  78. package/dist/evaluate-xpath.js +11 -0
  79. package/dist/evaluate-xpath.js.map +1 -0
  80. package/dist/index.d.ts +8 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +8 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/limits.d.ts +77 -0
  85. package/dist/limits.d.ts.map +1 -0
  86. package/dist/limits.js +74 -0
  87. package/dist/limits.js.map +1 -0
  88. package/dist/parse-xpath.d.ts +27 -0
  89. package/dist/parse-xpath.d.ts.map +1 -0
  90. package/dist/parse-xpath.js +41 -0
  91. package/dist/parse-xpath.js.map +1 -0
  92. package/dist/values.d.ts +68 -0
  93. package/dist/values.d.ts.map +1 -0
  94. package/dist/values.js +28 -0
  95. package/dist/values.js.map +1 -0
  96. package/package.json +68 -3
package/CHANGELOG.md ADDED
@@ -0,0 +1,91 @@
1
+ # @ac-kit/format-xpath
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [065cf8d]
8
+ - Updated dependencies [065cf8d]
9
+ - Updated dependencies [065cf8d]
10
+ - @ac-kit/core@0.11.0
11
+ - @ac-kit/algo@0.4.1
12
+ - @ac-kit/format-xml@0.2.1
13
+ - @ac-kit/math-numbers@0.2.8
14
+ - @ac-kit/model-markup@0.1.1
15
+
16
+ ## 0.1.0
17
+
18
+ ### Minor Changes
19
+
20
+ - 5152230: New package: XPath 1.0 over any `MarkupTreeShape` (`@ac-kit/model-markup`) —
21
+ parse5 HTML trees, XML trees, your own.
22
+
23
+ - `compileXPath(expression, { namespaces, limits })` parses (or takes an
24
+ `XPathExpression`), resolves names and checks arities and node-set requirements
25
+ once; the `CompiledXPath` offers `evaluate`, `selectNodes`, `selectFirst` and
26
+ `evaluateString` over any shape and context node, with `variables`,
27
+ `documentMode` and a shared `budget` per evaluation. `evaluateXPath`
28
+ compiles and evaluates in one call; `parseXPath` and `tryParseXPath` give
29
+ the syntax tree with abbreviations expanded and spans.
30
+ - The whole of XPath 1.0: the 13 axes, every node test, predicates, unions,
31
+ filters, the operators with node-set semantics, the 27 core functions,
32
+ `$QName` variables and prefix bindings. String functions count code points
33
+ and never split a surrogate pair; `number()` accepts only XPath's lexical
34
+ form; `normalize-space()` uses XML whitespace; `string()` writes an
35
+ integer exactly and a fraction with its shortest round-trip digits, never
36
+ with an exponent.
37
+ - HTML documents follow the HTML Standard's XPath amendment as WPT
38
+ `domxpath` asserts: unprefixed element names select HTML elements only,
39
+ ASCII case-insensitively (`//svg` misses inline SVG; use
40
+ `//*[local-name()='svg']` or a prefix), and so do unprefixed attribute
41
+ names on HTML elements; a prefixed name such as `html:div` compares exactly.
42
+ - Nodes: tree nodes (a text node stands for its run, as its first node),
43
+ `XPathAttributeNode` and `XPathNamespaceNode` (`isXPathAttributeNode`,
44
+ `isXPathNamespaceNode`, `createXPathAttributeNode`,
45
+ `createXPathNamespaceNode`), deduplicated by owner and attribute or prefix.
46
+ - Untrusted input: one `WorkBudget` per evaluation charged by expressions
47
+ evaluated, axis steps, node visits and ancestor climbs, characters scanned,
48
+ compared or built (including namespace URI comparisons in name tests),
49
+ values compared, namespace bindings and calls
50
+ (`maxSteps`, 2²¹ by default, or the caller's budget, shared across calls
51
+ and handed to the shape's `namespacesInScopeWithin`); `maxLength` (also
52
+ bounding a hand-built syntax tree), `maxNestingDepth`
53
+ (≤ `XPATH_MAX_NESTING_DEPTH`) and `maxStringLength` (every string the
54
+ evaluation produces) limits. Parsing, compiling and evaluating run on
55
+ explicit stacks: no stack overflow on any expression, tree or caller stack.
56
+ Empty paths skip remaining steps and fallback `id()` charges only the
57
+ attributes its lookup inspects.
58
+ - Errors: `XPathSyntaxError`, `XPathStaticError` (names the XPath 2.0/3.x or
59
+ XSLT function called, e.g. `matches()`), `XPathTypeError`,
60
+ `XPathUnboundVariableError`, `XPathLimitExceededError`.
61
+
62
+ ### Patch Changes
63
+
64
+ - Updated dependencies [2a0fe74]
65
+ - Updated dependencies [5152230]
66
+ - Updated dependencies [5152230]
67
+ - Updated dependencies [2a0fe74]
68
+ - Updated dependencies [5152230]
69
+ - Updated dependencies [2a0fe74]
70
+ - Updated dependencies [5152230]
71
+ - Updated dependencies [5152230]
72
+ - Updated dependencies [2a0fe74]
73
+ - Updated dependencies [2a0fe74]
74
+ - Updated dependencies [5152230]
75
+ - Updated dependencies [5152230]
76
+ - Updated dependencies [5152230]
77
+ - Updated dependencies [5152230]
78
+ - Updated dependencies [5152230]
79
+ - Updated dependencies [5152230]
80
+ - Updated dependencies [5152230]
81
+ - Updated dependencies [5152230]
82
+ - Updated dependencies [5152230]
83
+ - Updated dependencies [5152230]
84
+ - Updated dependencies [5152230]
85
+ - Updated dependencies [5152230]
86
+ - Updated dependencies [5152230]
87
+ - @ac-kit/algo@0.4.0
88
+ - @ac-kit/core@0.10.0
89
+ - @ac-kit/format-xml@0.2.0
90
+ - @ac-kit/model-markup@0.1.0
91
+ - @ac-kit/math-numbers@0.2.7
package/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2024-2026 Anthony Champagne and contributors
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,224 @@
1
- # Temporary Holding Version
1
+ # @ac-kit/format-xpath
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ XPath 1.0 — parse, compile and evaluate — over any markup tree: HTML parsed by
4
+ parse5, an XML tree, or your own, read through `@ac-kit/model-markup`'s
5
+ `MarkupTreeShape`.
6
+
7
+ An extractor written as data needs a query language its authors already know,
8
+ and XPath 1.0 is the one that works on both HTML and XML. This package
9
+ implements all of it — the 13 axes, every node test, predicates, unions, the
10
+ operators with their node-set semantics, the 27 core functions, variables and
11
+ namespace prefixes — against a shape, so the tree you already hold is queried
12
+ as it is, without converting it. Expressions and documents are treated as
13
+ untrusted: every evaluation runs on a work budget, strings are bounded, and no
14
+ expression or tree, however deep, reaches a stack overflow.
15
+
16
+ It is portable (no host APIs). API reference:
17
+ <https://anthochamp.pages.grenadine.io/node-essentials/api/format-xpath/>.
18
+
19
+ ## Querying an HTML page
20
+
21
+ ```ts
22
+ import { compileXPath } from "@ac-kit/format-xpath";
23
+ import { indexMarkupTree } from "@ac-kit/model-markup";
24
+ import { parse5MarkupShape } from "@ac-kit/model-markup/parse5";
25
+ import { parse } from "parse5";
26
+
27
+ const document = parse(
28
+ '<ul><li><a href="/one">One</a></li><li><a href="/two">Two</a></li></ul>',
29
+ );
30
+ // Index once per page: parents, positions, document order and ids in O(1).
31
+ const shape = indexMarkupTree(parse5MarkupShape, document);
32
+
33
+ const second = compileXPath("string(//li[2]/a)");
34
+ second.evaluateString(shape, document); // "Two"
35
+
36
+ const links = compileXPath("//a/@href").selectNodes(shape, document);
37
+ links.length; // 2
38
+
39
+ const count = compileXPath("count(//li)").evaluate(shape, document);
40
+ // { type: "number", value: 2 }
41
+ ```
42
+
43
+ `compileXPath` parses, resolves every name and checks every arity once; the
44
+ result is evaluated over any shape and context node, as often as you like.
45
+ `evaluateXPath(shape, contextNode, expression, options)` compiles and
46
+ evaluates in one call. `parseXPath` gives the syntax tree, abbreviations
47
+ expanded, and `compileXPath` accepts one.
48
+
49
+ ### Results
50
+
51
+ `evaluate` returns one of the four XPath types: `{ type: "nodeSet", nodes }`
52
+ (in document order, without duplicates), `"string"`, `"number"` or
53
+ `"boolean"`. `selectNodes` and `selectFirst` require a node-set,
54
+ `evaluateString` converts as `string()` does.
55
+
56
+ A node is one of three things:
57
+
58
+ - **a tree node** — never a doctype; a text node always stands for its whole
59
+ run of adjacent text siblings (text and CDATA side by side, a parser's split
60
+ text) and is that run's first node, as `markupTextRunStart` returns it. A run
61
+ holding only empty text is not a node at all. Its string-value is
62
+ `markupStringValue(shape, node)` from `@ac-kit/model-markup`, the one
63
+ definition both packages share;
64
+ - **an attribute node** (`isXPathAttributeNode`), `{ owner, attribute }`: read
65
+ its value with `shape.attributeValueOf(node.attribute)`. Two attribute nodes
66
+ with the same owner and attribute are the same node, whichever objects hold
67
+ them — results deduplicate and order them by that pair;
68
+ - **a namespace node** (`isXPathNamespaceNode`), `{ owner, prefix, uri }`.
69
+
70
+ Attributes declaring namespaces (`xmlns`, `xmlns:p`) are on the namespace axis,
71
+ not the attribute axis. Nodes of different trees (from variables) are ordered
72
+ stably within an evaluation; which tree comes first is unspecified.
73
+
74
+ ## HTML documents
75
+
76
+ In a document whose mode is `"html"` or `"html-quirks"` (parse5 reports it;
77
+ `documentMode` in the evaluation context overrides it), names follow the HTML
78
+ Standard's amendment to XPath 1.0 (§2.1.11) as browsers implement it and as
79
+ WPT `domxpath` asserts:
80
+
81
+ - an unprefixed element name selects **HTML elements only**, compared ASCII
82
+ case-insensitively: `//DIV` finds `<div>`. A prefixed name compares
83
+ exactly, as §2.1.11 changes only the default namespace: `//html:div` finds
84
+ it, `//html:DIV` does not;
85
+ - so **`//svg` misses inline SVG**, whose elements are in the SVG namespace.
86
+ Bind a prefix (`//svg:path` with `namespaces: new Map([["svg",
87
+ SVG_NAMESPACE]])`) or match the local name:
88
+ `//*[local-name()='svg']`;
89
+ - an unprefixed attribute name compares ASCII case-insensitively on an HTML
90
+ element (`@ID` finds `id`) and exactly elsewhere (`@refX` on SVG).
91
+
92
+ `lang()` reads `xml:lang`, as XPath 1.0 specifies; HTML's `lang` attribute is
93
+ an ordinary attribute (`ancestor-or-self::*[@lang][1]/@lang`). `id()` reads the
94
+ no-namespace `id` attribute of any element, the first in document order when
95
+ several share it.
96
+
97
+ ```ts
98
+ import { compileXPath } from "@ac-kit/format-xpath";
99
+ import { SVG_NAMESPACE } from "@ac-kit/model-markup";
100
+ import { parse5MarkupShape } from "@ac-kit/model-markup/parse5";
101
+ import { parse } from "parse5";
102
+
103
+ const page = parse("<DIV><svg><path/></svg></DIV>");
104
+ compileXPath("//div").selectNodes(parse5MarkupShape, page).length; // 1
105
+ compileXPath("//svg").selectNodes(parse5MarkupShape, page).length; // 0
106
+ compileXPath("//*[local-name()='svg']").selectNodes(parse5MarkupShape, page)
107
+ .length; // 1
108
+ compileXPath("//s:path", { namespaces: new Map([["s", SVG_NAMESPACE]]) })
109
+ .selectNodes(parse5MarkupShape, page).length; // 1
110
+ ```
111
+
112
+ ## Variables and namespaces
113
+
114
+ ```ts
115
+ import { compileXPath } from "@ac-kit/format-xpath";
116
+ import { parse5MarkupShape } from "@ac-kit/model-markup/parse5";
117
+ import { parse } from "parse5";
118
+
119
+ const page = parse('<p class="price">12</p><p class="price">30</p>');
120
+ const total = compileXPath("sum(//p[@class = $class])");
121
+ total.evaluate(parse5MarkupShape, page, {
122
+ variables: new Map([["class", "price"]]),
123
+ }); // { type: "number", value: 42 }
124
+ ```
125
+
126
+ A variable holds a string, a number, a boolean or an array of nodes (any
127
+ order, duplicates allowed). `$p:name` is keyed `{uri}name`, the prefix bound
128
+ through `namespaces`; `xml` is always bound. An unbound variable throws
129
+ `XPathUnboundVariableError`.
130
+
131
+ ## Strings and numbers
132
+
133
+ - String functions count **code points**: `string-length("😀")` is 1,
134
+ `substring()` positions and `translate()` maps code points, and
135
+ `contains()`, `starts-with()`, `substring-before()` and `substring-after()`
136
+ never match half of a surrogate pair.
137
+ - `number()` accepts exactly XPath's lexical form — optional XML whitespace,
138
+ an optional `-`, digits with an optional fraction — so `""`, `"0x10"`,
139
+ `"1e3"` and `"Infinity"` are NaN. Number literals have no exponent either.
140
+ - `string()` of a number never uses an exponent: an integer is written
141
+ exactly (`12345678901234567890` is the double `"12345678901234567168"`), a
142
+ fraction with the shortest digits that round-trip (`0.0000001`), and NaN,
143
+ `Infinity` and `-Infinity` are spelled out.
144
+ - `normalize-space()` strips and collapses XML whitespace (space, tab, CR, LF)
145
+ only.
146
+
147
+ ## Limits and the work budget
148
+
149
+ Every evaluation charges a `WorkBudget` (`@ac-kit/core`), before the work it
150
+ pays for:
151
+
152
+ - one unit per expression evaluated, per axis step taken from each node, per
153
+ node an axis visits or ancestor it climbs, per node a predicate or a
154
+ comparison examines, per function call, and `k log k` per sort of `k` nodes;
155
+ - one unit per character read or built — string-values, string functions,
156
+ numeric conversions (`number()`, arithmetic on strings), string comparisons,
157
+ the names and equal-length namespace URIs a name test compares, and `id()`
158
+ tokens; the `id()` fallback charges only the attributes it actually inspects
159
+ and the names it compares;
160
+ - one unit per namespace binding the namespace axis discovers or revisits,
161
+ through the shape's `namespacesInScopeWithin` with this very budget when it
162
+ has one.
163
+
164
+ A path stops when its current node-set is empty, without visiting the remaining
165
+ steps or evaluating more predicates on that set.
166
+
167
+ Node-set comparisons look values up instead of comparing every pair, so
168
+ `//* = //*` costs O(n), not O(n²).
169
+
170
+ - Without a budget, each evaluation gets `limits.maxSteps` units (2²¹ by
171
+ default, about 100 ms of node visits) and reports exhaustion as
172
+ `XPathLimitExceededError` of kind `"steps"`.
173
+ - Pass `budget` in the evaluation context to cap many evaluations together —
174
+ every expression run over one page, say; its exhaustion throws whatever its
175
+ `spend` throws (`FixedWorkBudget` throws `WorkBudgetExceededError`).
176
+
177
+ ```ts
178
+ import { FixedWorkBudget } from "@ac-kit/core";
179
+ import { compileXPath } from "@ac-kit/format-xpath";
180
+ import { parse5MarkupShape } from "@ac-kit/model-markup/parse5";
181
+ import { parse } from "parse5";
182
+
183
+ const page = parse("<h1>Title</h1><p>Body</p>");
184
+ const budget = new FixedWorkBudget(1_000_000);
185
+ for (const expression of ["string(//h1)", "string(//p)"]) {
186
+ compileXPath(expression).evaluateString(parse5MarkupShape, page, { budget });
187
+ }
188
+ ```
189
+
190
+ `XPathLimits` also bounds the expression (`maxLength`, 16 Ki characters;
191
+ `maxNestingDepth`, 256 levels of syntax tree, at most
192
+ `XPATH_MAX_NESTING_DEPTH`) and the strings an evaluation builds
193
+ (`maxStringLength`, 2²⁴ code units, kind `"stringLength"`: every string the
194
+ evaluation produces or reads from the tree; a string passed in a variable is
195
+ input and is not checked). A syntax tree built by hand is measured against
196
+ `maxLength` as nodes, steps and the characters of its names and literals. The
197
+ parser, the compiler and the evaluator keep their nesting on explicit stacks
198
+ and every walk over the document is iterative, so neither a deep expression
199
+ nor a deep caller stack can overflow the native stack.
200
+
201
+ A shape without `compareDocumentOrder` is numbered once per evaluation the
202
+ first time two nodes must be ordered, and one without `elementByIdOf` is
203
+ scanned once by the first `id()`; `indexMarkupTree` answers both, with parents
204
+ and sibling positions, once per page. An indexed shape reads only the tree it
205
+ indexed.
206
+
207
+ ## Errors
208
+
209
+ - `XPathSyntaxError` (a `SyntaxError`, with `source` and `offset`) — not
210
+ XPath 1.0 syntax; `tryParseXPath` answers `null` instead.
211
+ - `XPathStaticError` (`code`: `"unknownFunction"`, `"arity"`,
212
+ `"unboundPrefix"`; `subject`; `span`) — a function outside the core library,
213
+ named when it belongs to XPath 2.0, 3.0, 3.1 or XSLT (`matches()`,
214
+ `lower-case()`, `tokenize()`, `generate-id()`…), a wrong argument count, an
215
+ unbound prefix.
216
+ - `XPathTypeError` (a `TypeError`, with `span`) — a non-node-set where one is
217
+ required, at compile time when decidable without the variables; also a
218
+ variable bound to something that is not an XPath value.
219
+ - `XPathUnboundVariableError`, `XPathLimitExceededError` (`kind`, `limit`).
220
+
221
+ ## Not supported
222
+
223
+ XPath 2.0 and later (a different data model of sequences and atomic types),
224
+ extension functions and EXSLT.
@@ -0,0 +1,18 @@
1
+ import type { EvaluationRun } from "./_run.js";
2
+ import type { XPathAxis } from "./ast.js";
3
+ /** A compiled node test: whether a node the axis yields is kept. */
4
+ export type NodeMatcher = (run: AnyRun, node: unknown) => boolean;
5
+ /**
6
+ * The run as the evaluator sees it: the compiled expression is independent of
7
+ * the node types, which only the shape knows.
8
+ */
9
+ export type AnyRun = EvaluationRun<unknown, unknown>;
10
+ /** The axes whose proximity order is reverse document order. */
11
+ export declare const REVERSE_AXES_: ReadonlySet<XPathAxis>;
12
+ /**
13
+ * The nodes `axis` yields from `node` that `matches` keeps, in proximity order:
14
+ * document order for a forward axis, reverse document order for a reverse one.
15
+ * Every node considered is charged to the run's budget.
16
+ */
17
+ export declare function axisNodes(run: AnyRun, node: unknown, axis: XPathAxis, matches: NodeMatcher): unknown[];
18
+ //# sourceMappingURL=_axes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_axes.d.ts","sourceRoot":"","sources":["../src/_axes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAG1C,oEAAoE;AACpE,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,KAAK,OAAO,CAAC;AAElE;;;GAGG;AACH,MAAM,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAErD,gEAAgE;AAChE,eAAO,MAAM,aAAa,EAAE,WAAW,CAAC,SAAS,CAK/C,CAAC;AAEH;;;;GAIG;AACH,wBAAgB,SAAS,CACxB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,WAAW,GAClB,OAAO,EAAE,CA4GX"}
package/dist/_axes.js ADDED
@@ -0,0 +1,124 @@
1
+ import { isXPathAttributeNode, isXPathNamespaceNode } from "./values.js";
2
+ /** The axes whose proximity order is reverse document order. */
3
+ export const REVERSE_AXES_ = new Set([
4
+ "ancestor",
5
+ "ancestor-or-self",
6
+ "preceding",
7
+ "preceding-sibling",
8
+ ]);
9
+ /**
10
+ * The nodes `axis` yields from `node` that `matches` keeps, in proximity order:
11
+ * document order for a forward axis, reverse document order for a reverse one.
12
+ * Every node considered is charged to the run's budget.
13
+ */
14
+ export function axisNodes(run, node, axis, matches) {
15
+ const result = [];
16
+ const keep = (candidate) => {
17
+ if (matches(run, candidate)) {
18
+ result.push(candidate);
19
+ }
20
+ };
21
+ // One unit for the dispatch itself, so even `self::node()` costs something.
22
+ run.budget.spend(1);
23
+ const isWrapper = isXPathAttributeNode(node) || isXPathNamespaceNode(node);
24
+ const tree = run.treeNodeOf(node);
25
+ switch (axis) {
26
+ case "self":
27
+ keep(node);
28
+ break;
29
+ case "child":
30
+ if (!isWrapper) {
31
+ run.forEachChild(tree, keep);
32
+ }
33
+ break;
34
+ case "descendant":
35
+ case "descendant-or-self":
36
+ if (isWrapper) {
37
+ if (axis === "descendant-or-self") {
38
+ keep(node);
39
+ }
40
+ }
41
+ else {
42
+ run.forEachDescendant(tree, axis === "descendant-or-self", keep);
43
+ }
44
+ break;
45
+ case "parent":
46
+ if (isWrapper) {
47
+ keep(tree);
48
+ }
49
+ else {
50
+ run.budget.spend(1);
51
+ const parent = run.parentOf(tree);
52
+ if (parent !== null) {
53
+ keep(parent);
54
+ }
55
+ }
56
+ break;
57
+ case "ancestor":
58
+ case "ancestor-or-self": {
59
+ if (axis === "ancestor-or-self") {
60
+ keep(node);
61
+ }
62
+ run.budget.spend(1);
63
+ let current = isWrapper ? tree : run.parentOf(tree);
64
+ while (current !== null) {
65
+ run.budget.spend(1);
66
+ keep(current);
67
+ current = run.parentOf(current);
68
+ }
69
+ break;
70
+ }
71
+ case "following-sibling":
72
+ case "preceding-sibling":
73
+ if (!isWrapper) {
74
+ run.forEachSibling(tree, axis === "following-sibling" ? 1 : -1, keep);
75
+ }
76
+ break;
77
+ case "following": {
78
+ if (isWrapper) {
79
+ run.forEachDescendant(tree, false, keep);
80
+ }
81
+ let current = tree;
82
+ while (current !== null) {
83
+ run.forEachSibling(current, 1, (sibling) => {
84
+ run.forEachDescendant(sibling, true, keep);
85
+ });
86
+ run.budget.spend(1);
87
+ current = run.parentOf(current);
88
+ }
89
+ break;
90
+ }
91
+ case "preceding": {
92
+ let current = tree;
93
+ const subtree = [];
94
+ while (current !== null) {
95
+ run.forEachSibling(current, -1, (sibling) => {
96
+ subtree.length = 0;
97
+ run.forEachDescendant(sibling, true, (descendant) => {
98
+ subtree.push(descendant);
99
+ });
100
+ for (let index = subtree.length - 1; index >= 0; index--) {
101
+ keep(subtree[index]);
102
+ }
103
+ });
104
+ run.budget.spend(1);
105
+ current = run.parentOf(current);
106
+ }
107
+ break;
108
+ }
109
+ case "attribute":
110
+ if (!isWrapper && run.kindOf(tree) === "element") {
111
+ run.forEachAttribute(tree, keep);
112
+ }
113
+ break;
114
+ case "namespace":
115
+ if (!isWrapper && run.kindOf(tree) === "element") {
116
+ for (const namespace of run.namespaceNodesOf(tree)) {
117
+ keep(namespace);
118
+ }
119
+ }
120
+ break;
121
+ }
122
+ return result;
123
+ }
124
+ //# sourceMappingURL=_axes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_axes.js","sourceRoot":"","sources":["../src/_axes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAWzE,gEAAgE;AAChE,MAAM,CAAC,MAAM,aAAa,GAA2B,IAAI,GAAG,CAAY;IACvE,UAAU;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IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAClD,GAAG,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAClC,CAAC;YACD,MAAM;QACP,KAAK,WAAW;YACf,IAAI,CAAC,SAAS,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBAClD,KAAK,MAAM,SAAS,IAAI,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC;oBACpD,IAAI,CAAC,SAAS,CAAC,CAAC;gBACjB,CAAC;YACF,CAAC;YACD,MAAM;IACR,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `substring(text, start, length)` (XPath 1.0 §4.2): the code points at 1-based
3
+ * positions `p` with `round(start) ≤ p < round(start) + round(length)`, NaN and
4
+ * infinities following IEEE 754 comparison. A surrogate pair is one position, a
5
+ * lone surrogate too. O(length).
6
+ */
7
+ export declare function xpathSubstring(text: string, start: number, length?: number): string;
8
+ /**
9
+ * `normalize-space(text)` (XPath 1.0 §4.2): XML whitespace stripped at both
10
+ * ends and every inner run of it replaced by one space. O(length).
11
+ */
12
+ export declare function normalizeSpace(text: string): string;
13
+ //# sourceMappingURL=_code-points.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_code-points.d.ts","sourceRoot":"","sources":["../src/_code-points.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AACH,wBAAgB,cAAc,CAC7B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,MAAM,GAAE,MAAiC,GACvC,MAAM,CAOR;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAkBnD"}
@@ -0,0 +1,40 @@
1
+ import { substringCodePoints } from "@ac-kit/core";
2
+ import { isXmlWhitespace } from "@ac-kit/format-xml";
3
+ /**
4
+ * `substring(text, start, length)` (XPath 1.0 §4.2): the code points at 1-based
5
+ * positions `p` with `round(start) ≤ p < round(start) + round(length)`, NaN and
6
+ * infinities following IEEE 754 comparison. A surrogate pair is one position, a
7
+ * lone surrogate too. O(length).
8
+ */
9
+ export function xpathSubstring(text, start, length = Number.POSITIVE_INFINITY) {
10
+ const first = Math.round(start);
11
+ const end = first + Math.round(length);
12
+ if (!(first < end)) {
13
+ return "";
14
+ }
15
+ return substringCodePoints(text, first - 1, end - 1);
16
+ }
17
+ /**
18
+ * `normalize-space(text)` (XPath 1.0 §4.2): XML whitespace stripped at both
19
+ * ends and every inner run of it replaced by one space. O(length).
20
+ */
21
+ export function normalizeSpace(text) {
22
+ let result = "";
23
+ let pendingSpace = false;
24
+ let segmentStart = -1;
25
+ for (let offset = 0; offset <= text.length; offset++) {
26
+ const isSpace = offset === text.length || isXmlWhitespace(text.charCodeAt(offset));
27
+ if (isSpace) {
28
+ if (segmentStart >= 0) {
29
+ result += (pendingSpace ? " " : "") + text.slice(segmentStart, offset);
30
+ pendingSpace = true;
31
+ segmentStart = -1;
32
+ }
33
+ }
34
+ else if (segmentStart < 0) {
35
+ segmentStart = offset;
36
+ }
37
+ }
38
+ return result;
39
+ }
40
+ //# sourceMappingURL=_code-points.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_code-points.js","sourceRoot":"","sources":["../src/_code-points.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAErD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAC7B,IAAY,EACZ,KAAa,EACb,MAAM,GAAW,MAAM,CAAC,iBAAiB;IAEzC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAChC,MAAM,GAAG,GAAG,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACvC,IAAI,CAAC,CAAC,KAAK,GAAG,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,EAAE,CAAC;IACX,CAAC;IACD,OAAO,mBAAmB,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC;AACtD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IAC1C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,IAAI,YAAY,GAAG,KAAK,CAAC;IACzB,IAAI,YAAY,GAAG,CAAC,CAAC,CAAC;IACtB,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,IAAI,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,CAAC;QACtD,MAAM,OAAO,GACZ,MAAM,KAAK,IAAI,CAAC,MAAM,IAAI,eAAe,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,IAAI,OAAO,EAAE,CAAC;YACb,IAAI,YAAY,IAAI,CAAC,EAAE,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;gBACvE,YAAY,GAAG,IAAI,CAAC;gBACpB,YAAY,GAAG,CAAC,CAAC,CAAC;YACnB,CAAC;QACF,CAAC;aAAM,IAAI,YAAY,GAAG,CAAC,EAAE,CAAC;YAC7B,YAAY,GAAG,MAAM,CAAC;QACvB,CAAC;IACF,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { AnyRun } from "./_axes.js";
2
+ import { type Value } from "./_convert.js";
3
+ export type ComparisonOperator = "=" | "!=" | "<" | "<=" | ">" | ">=";
4
+ /**
5
+ * A comparison (XPath 1.0 §3.4), node-sets compared existentially.
6
+ *
7
+ * Node-set against node-set never compares every pair: `=` looks the right
8
+ * side's string-values up in a set of the left side's, `!=` only needs two
9
+ * distinct values, and the relational operators compare the extreme numbers.
10
+ * The cost is therefore one unit per node plus its string-value and the
11
+ * characters hashed, compared or scanned for a number: O(n + m) values.
12
+ */
13
+ export declare function compareValues(run: AnyRun, operator: ComparisonOperator, left: Value, right: Value): boolean;
14
+ //# sourceMappingURL=_compare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"_compare.d.ts","sourceRoot":"","sources":["../src/_compare.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAIN,KAAK,KAAK,EACV,MAAM,eAAe,CAAC;AAEvB,MAAM,MAAM,kBAAkB,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,CAAC;AAyDtE;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC5B,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,kBAAkB,EAC5B,IAAI,EAAE,KAAK,EACX,KAAK,EAAE,KAAK,GACV,OAAO,CAuBT"}