@grafctory/mime-xml 0.0.0-stage → 0.5.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 (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +56 -2
  3. package/dist/denoise.core.d.ts +12 -0
  4. package/dist/denoise.core.d.ts.map +1 -0
  5. package/dist/denoise.core.js +78 -0
  6. package/dist/denoise.core.js.map +1 -0
  7. package/dist/denoise.d.ts +45 -0
  8. package/dist/denoise.d.ts.map +1 -0
  9. package/dist/denoise.js +63 -0
  10. package/dist/denoise.js.map +1 -0
  11. package/dist/focus.core.d.ts +9 -0
  12. package/dist/focus.core.d.ts.map +1 -0
  13. package/dist/focus.core.js +305 -0
  14. package/dist/focus.core.js.map +1 -0
  15. package/dist/focus.d.ts +64 -0
  16. package/dist/focus.d.ts.map +1 -0
  17. package/dist/focus.js +88 -0
  18. package/dist/focus.js.map +1 -0
  19. package/dist/html.core.d.ts +9 -0
  20. package/dist/html.core.d.ts.map +1 -0
  21. package/dist/html.core.js +229 -0
  22. package/dist/html.core.js.map +1 -0
  23. package/dist/html.d.ts +76 -0
  24. package/dist/html.d.ts.map +1 -0
  25. package/dist/html.js +104 -0
  26. package/dist/html.js.map +1 -0
  27. package/dist/index.core.d.ts +74 -0
  28. package/dist/index.core.d.ts.map +1 -0
  29. package/dist/index.core.js +117 -0
  30. package/dist/index.core.js.map +1 -0
  31. package/dist/index.d.ts +67 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +116 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/untag.core.d.ts +9 -0
  36. package/dist/untag.core.d.ts.map +1 -0
  37. package/dist/untag.core.js +216 -0
  38. package/dist/untag.core.js.map +1 -0
  39. package/dist/untag.d.ts +86 -0
  40. package/dist/untag.d.ts.map +1 -0
  41. package/dist/untag.js +102 -0
  42. package/dist/untag.js.map +1 -0
  43. package/dist/unwrap.d.ts +37 -0
  44. package/dist/unwrap.d.ts.map +1 -0
  45. package/dist/unwrap.js +69 -0
  46. package/dist/unwrap.js.map +1 -0
  47. package/dist/xml.core.d.ts +9 -0
  48. package/dist/xml.core.d.ts.map +1 -0
  49. package/dist/xml.core.js +86 -0
  50. package/dist/xml.core.js.map +1 -0
  51. package/dist/xml.d.ts +69 -0
  52. package/dist/xml.d.ts.map +1 -0
  53. package/dist/xml.js +97 -0
  54. package/dist/xml.js.map +1 -0
  55. package/dist/xpath.core.d.ts +100 -0
  56. package/dist/xpath.core.d.ts.map +1 -0
  57. package/dist/xpath.core.js +279 -0
  58. package/dist/xpath.core.js.map +1 -0
  59. package/dist/xpath.d.ts +128 -0
  60. package/dist/xpath.d.ts.map +1 -0
  61. package/dist/xpath.js +33 -0
  62. package/dist/xpath.js.map +1 -0
  63. package/package.json +62 -4
@@ -0,0 +1,305 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { cloneNode, Document, Element, hasChildren, isTag, isText } from "domhandler";
17
+ import { DomUtils } from "htmlparser2";
18
+ import { Ignored, name, normalize, text, title } from "./index.core.js";
19
+ /**
20
+ * The elements carrying text a reader is after.
21
+ *
22
+ * Lists the markup a page states its content with, headings, paragraphs, lists, tables and inline emphasis among them,
23
+ * so that a container is weighed by how much of it is content rather than framing.
24
+ */
25
+ const Textual = new Set([
26
+ "h1", "h2", "h3", "h4", "h5", "h6",
27
+ "p", "blockquote", "pre",
28
+ "ul", "ol", "dl", "li", "dt", "dd",
29
+ "table", "th", "td",
30
+ "article", "section", "div", "span",
31
+ "em", "strong", "b", "i", "u", "mark",
32
+ "a", "time", "address", "cite", "q",
33
+ "code", "kbd", "samp", "var",
34
+ "small", "sub", "sup", "del", "ins"
35
+ ]);
36
+ /**
37
+ * The elements whose text an article doesn't state as content of its own.
38
+ *
39
+ * Framing and nested articles carry text about other things, and headings name what follows rather than stating it, so
40
+ * that an article holding nothing else is read as wrapping a listing rather than as stating content of its own.
41
+ */
42
+ const Foreign = new Set([...Ignored, "article", "h1", "h2", "h3", "h4", "h5", "h6"]);
43
+ /**
44
+ * The scan of a subtree holding no text.
45
+ */
46
+ const Empty = {
47
+ xchars: 0,
48
+ echars: 0,
49
+ densest: undefined,
50
+ density: 0
51
+ };
52
+ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
53
+ /**
54
+ * Extracts the main content of a markup tree.
55
+ *
56
+ * Helper backing the `focus()` task, which states the extraction contract.
57
+ */
58
+ export function process(node) {
59
+ const nodes = hasChildren(node) ? node.children : [];
60
+ const regions = marked(nodes) ?? articles(nodes) ?? dense(nodes);
61
+ return regions === undefined ? undefined : extract(regions, framed(nodes), title(node));
62
+ /**
63
+ * Draws the region a page marks as its own.
64
+ *
65
+ * The region is taken as stated, however dense the text it holds.
66
+ *
67
+ * @param nodes The nodes to search
68
+ *
69
+ * @returns A singleton holding the region marked by `nodes`; `undefined` if none is marked
70
+ */
71
+ function marked(nodes) {
72
+ const element = first(element => name(element) === "main")
73
+ ?? first(element => element.attribs["role"]?.toLowerCase() === "main");
74
+ return element === undefined ? undefined : [element];
75
+ function first(test) {
76
+ return DomUtils.findOne(test, [...nodes], true) ?? undefined; // searched as stated, in document order
77
+ }
78
+ }
79
+ /**
80
+ * Draws the regions a page states as articles.
81
+ *
82
+ * A page states as many articles as it lists, so they are taken together rather than one standing for the rest.
83
+ * Articles carrying no text are widgets rather than content, and leave the page to be scored.
84
+ *
85
+ * @param nodes The nodes to search
86
+ *
87
+ * @returns The outermost articles stated by `nodes`; `undefined` if none is stated or none carries text
88
+ */
89
+ function articles(nodes) {
90
+ const stated = outermost(nodes);
91
+ return stated.length > 0 && scan(stated).density > 0 ? stated : undefined;
92
+ function outermost(nodes) {
93
+ return nodes.filter(isTag).flatMap(element => name(element) === "article" ? [element] // holds its own
94
+ : Ignored.has(name(element)) ? [] // framing lists articles a reader is not after
95
+ : outermost(element.children));
96
+ }
97
+ }
98
+ function dense(nodes) {
99
+ const { densest } = scan(nodes);
100
+ return densest === undefined ? undefined : [densest];
101
+ }
102
+ /**
103
+ * Weighs the text held by a sequence of nodes.
104
+ *
105
+ * Text weighs by the square of its length, so that a long run outweighs the same amount of text scattered around.
106
+ *
107
+ * @param nodes The nodes to weigh
108
+ *
109
+ * @returns The weight of the text held by `nodes`, alongside the densest element among them
110
+ */
111
+ function scan(nodes) {
112
+ return fold(nodes.map(weigh));
113
+ /**
114
+ * Totals a set of weights.
115
+ *
116
+ * @param scans The weights to total
117
+ *
118
+ * @returns The weight of the subtrees `scans` were taken from, taken together
119
+ */
120
+ function fold(scans) {
121
+ return scans.reduce((total, item) => ({
122
+ xchars: total.xchars + item.xchars,
123
+ echars: total.echars + item.echars,
124
+ densest: item.density > total.density ? item.densest : total.densest, // ties keep the outermost
125
+ density: Math.max(total.density, item.density)
126
+ }), Empty);
127
+ }
128
+ function weigh(node) {
129
+ return isTag(node) ? (Ignored.has(name(node)) ? Empty : weighElement(node))
130
+ : isText(node) ? { ...Empty, xchars: normalize(node.data.trim()).length ** 2 }
131
+ : hasChildren(node) ? scan(node.children)
132
+ : Empty;
133
+ /**
134
+ * Weighs the text held by an element.
135
+ *
136
+ * A leaf carrying text is weighed by the text itself, a container by how much of it is content. An element
137
+ * carrying no text neither carries nor dilutes, the line breaks, rules, images and metadata a page is laid
138
+ * out with among them; framing dilutes whatever it holds, so that a page is not read as its own content.
139
+ *
140
+ * @param element The element to weigh
141
+ *
142
+ * @returns The weight of the text held by `element`, alongside the densest element it holds
143
+ */
144
+ function weighElement(element) {
145
+ const weighed = element.children.map(node => ({ node, scanned: weigh(node) }));
146
+ const { xchars, echars, densest, density } = fold(weighed.map(({ scanned }) => scanned));
147
+ const children = weighed.flatMap(({ node, scanned }) => // framing tells a container apart from content
148
+ isTag(node) && (scanned.xchars > 0 || Ignored.has(name(node))) ? [node] : []);
149
+ const diluting = children.length;
150
+ const carrying = children.filter(child => Textual.has(name(child))).length;
151
+ const weight = Textual.has(name(element)) && echars === 0 ? xchars
152
+ : echars * (carrying + 1) / (diluting + 1);
153
+ return {
154
+ xchars,
155
+ echars: weight,
156
+ densest: weight > 0 && weight >= density ? element : densest, // an element outweighs its content
157
+ density: Math.max(weight, density)
158
+ };
159
+ }
160
+ }
161
+ }
162
+ /**
163
+ * Tests whether a tree states the frame of a page.
164
+ *
165
+ * @param nodes The nodes to search
166
+ *
167
+ * @returns true if `nodes` state an `html` or a `body` element; false otherwise
168
+ */
169
+ function framed(nodes) {
170
+ return DomUtils.findOne(element => name(element) === "html" || name(element) === "body", [...nodes], true) !== null;
171
+ }
172
+ /**
173
+ * Roots a set of regions in a document of their own.
174
+ *
175
+ * Regions are copied into a document, so that expressions apply to them as to a parsed page. Where the tree drawn
176
+ * from is a page, that is where it is framed or states a title, the copies are held by the `body` of an `html`
177
+ * element, stating a `head` with a copy of the title where the tree states one.
178
+ *
179
+ * @param regions The regions to root
180
+ * @param frame Whether the tree drawn from states the frame of a page
181
+ * @param title The title the tree drawn from states, if any
182
+ *
183
+ * @returns A document holding a copy of the content of each region in `regions`
184
+ */
185
+ function extract(regions, frame, title) {
186
+ const roots = regions.map(rebased);
187
+ const children = frame || title !== undefined ? [paged(title, roots)] : roots;
188
+ const document = new Document([...children]);
189
+ children.forEach(root => { root.parent = document; }); // a document owns the roots it is handed over rooted at
190
+ return document;
191
+ /**
192
+ * Assembles a page holding a title and a set of regions.
193
+ *
194
+ * The URL the tree drawn from resolved against travels with the page, so that a consumer reads the URL the
195
+ * content belongs to alongside the content itself.
196
+ *
197
+ * @param title The title the page states, if any
198
+ * @param roots The regions the page holds
199
+ *
200
+ * @returns An `html` element holding `roots` in its `body`, stating a `head` with a copy of `title` where one
201
+ * is stated and as `xml:base` the URL the tree drawn from resolved against, where it states one
202
+ */
203
+ function paged(title, roots) {
204
+ const target = located(node);
205
+ return holding("html", [
206
+ ...(title === undefined ? [] : [holding("head", [cloneNode(title, true)])]),
207
+ holding("body", roots)
208
+ ], target === undefined ? {} : { "xml:base": target });
209
+ }
210
+ /**
211
+ * Draws the URL the tree drawn from resolves against.
212
+ *
213
+ * @param node The root of the tree drawn from
214
+ *
215
+ * @returns The URL `node` resolves against, taken from the root element of the tree where `node` is a
216
+ * document; `undefined` if the tree states none
217
+ */
218
+ function located(node) {
219
+ return isTag(node) ? based(node)
220
+ : nodes.filter(isTag).map(based).find(target => target !== undefined);
221
+ }
222
+ /**
223
+ * Assembles an element around a set of children.
224
+ *
225
+ * @param name The name of the element to assemble
226
+ * @param children The nodes the element holds
227
+ * @param attribs The attributes the element states
228
+ *
229
+ * @returns An element named `name` owning `children` and stating `attribs`
230
+ */
231
+ function holding(name, children, attribs = {}) {
232
+ const element = new Element(name, { ...attribs }, [...children]);
233
+ children.forEach(child => { child.parent = element; }); // an element owns the nodes it is handed over
234
+ return element;
235
+ }
236
+ /**
237
+ * Copies the content of a region, recording the URL its references resolve against.
238
+ *
239
+ * The copy leaves out the articles nested inside the articles of the region, which belong to separate pieces. The
240
+ * URL the region resolved against in the page travels with the copy, so that its references still resolve.
241
+ *
242
+ * @param region The region to copy
243
+ *
244
+ * @returns A copy of the content of `region` stating as `xml:base` the URL it resolved against in the page, if
245
+ * the page states a base URL for its references at the original position of the region
246
+ */
247
+ function rebased(region) {
248
+ const clone = detached(region);
249
+ const target = based(region);
250
+ clone.attribs = target === undefined ? clone.attribs : { ...clone.attribs, "xml:base": target };
251
+ return clone;
252
+ }
253
+ /**
254
+ * Copies a region, leaving out the articles nested inside the articles it holds.
255
+ *
256
+ * An article nested inside another is a separate piece related to it, such as a teaser or a comment, rather than
257
+ * part of its content. Nesting is reckoned within the region alone, so that the content a page marks as its own
258
+ * is never lost to what surrounds it. An article stating no text of its own beyond headings wraps a listing rather
259
+ * than stating content, so the articles it holds are kept as the items of the listing rather than dropped.
260
+ *
261
+ * @param region The region to copy
262
+ *
263
+ * @returns A copy of `region` leaving out every article nested inside an article stating content of its own
264
+ */
265
+ function detached(region) {
266
+ const clone = cloneNode(region, true);
267
+ nested([clone], false).forEach(article => DomUtils.removeElement(article)); // pruned off a private copy
268
+ return clone;
269
+ function nested(nodes, held) {
270
+ return nodes.filter(isTag).flatMap(element => name(element) !== "article" ? nested(element.children, held)
271
+ : held ? [element]
272
+ : nested(element.children, voiced(element)));
273
+ }
274
+ function voiced(article) {
275
+ return normalize(text(article, Foreign)).trim() !== "";
276
+ }
277
+ }
278
+ /**
279
+ * Draws the URL the references held by an element resolve against.
280
+ *
281
+ * @param element The element whose base URL is to be drawn
282
+ *
283
+ * @returns The URL `element` resolves against, each `xml:base` in scope resolved against the ones stated
284
+ * further up and one resolving to no absolute URL kept as stated; `undefined` if none is in scope
285
+ */
286
+ function based(element) {
287
+ return scoped(element).reduce((base, href) => absolute(href, base) ?? href, undefined);
288
+ function scoped(element) {
289
+ const parent = element.parent;
290
+ const inherited = parent !== null && isTag(parent) ? scoped(parent) : [];
291
+ const href = element.attribs["xml:base"];
292
+ return href === undefined ? inherited : [...inherited, href];
293
+ }
294
+ function absolute(href, base) {
295
+ try {
296
+ return new URL(href, base).href;
297
+ }
298
+ catch { // a malformed or unresolvable reference leaves the base as it stands
299
+ return undefined;
300
+ }
301
+ }
302
+ }
303
+ }
304
+ }
305
+ //# sourceMappingURL=focus.core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.core.js","sourceRoot":"","sources":["../src/focus.core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,MAA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handler";
3
+ /**
4
+ * Creates a content extractor.
5
+ *
6
+ * The task converts a feed of parsed X/HTML trees into a feed of documents holding their main content, one document per
7
+ * tree, so that downstream tasks work on the content of a page without its navigation, headers, footers, sidebars and
8
+ * controls.
9
+ *
10
+ * Trees without content produce no document, so the output feed is not aligned one to one with the input feed.
11
+ *
12
+ * The main content of a tree is the first of the following regions the tree contains:
13
+ *
14
+ * 1. the first `main` element or, if there is none, the first element with `role="main"`
15
+ * 2. all `article` elements, taken together, so that listing pages are kept whole; articles inside page framing
16
+ * (navigation, headers, footers, sidebars and the like), articles nested inside other articles, and articles
17
+ * without any text are ignored
18
+ * 3. the element with the densest text, as described below
19
+ *
20
+ * Regions are searched below the root of the tree, so a tree rooted at a `main` element is searched for a region
21
+ * inside it. Element names are matched case-insensitively.
22
+ *
23
+ * Articles nested inside an article of the content, such as teasers for related items or comment threads, are left
24
+ * out of the document: they are separate pieces related to the article holding them, and they often rotate while the
25
+ * content itself stays the same. Nesting is reckoned within the selected region alone. An article stating nothing
26
+ * of its own beyond headings, framing and nested articles is taken to wrap a listing, so its articles are all kept.
27
+ *
28
+ * Text density favours long runs of text over the same amount of text split into short fragments, and penalises
29
+ * containers holding a large share of framing. Scripts, styles, navigation, headers, footers, sidebars, controls and
30
+ * embedded objects contribute no text, so pages with long menus are scored on their prose alone. Elements without text
31
+ * of their own, such as line breaks, rules, images and metadata, are neutral. If two elements are equally dense, the
32
+ * first one in document order is selected, which is the outermost of a chain of single children.
33
+ *
34
+ * If the tree is a page, that is if it contains an `html` or `body` element or a title, the content is wrapped in the
35
+ * `body` of a new `html` element. If the page has a title, the `html` element also includes a `head` with a copy of
36
+ * it. The title is the first `title` element outside page framing, so that captions of embedded objects are not
37
+ * mistaken for it. If the tree is a fragment, each content region becomes a document root of its own.
38
+ *
39
+ * Each content region records as `xml:base` the base URL in scope at its original position, if any, so that its
40
+ * relative references keep resolving correctly. In page output, the `html` element also records as `xml:base` the base
41
+ * URL of the source tree, so that the page URL travels with its content. Source trees are not modified.
42
+ *
43
+ * > [!NOTE]
44
+ * >
45
+ * > - **Incremental**: each document is emitted as soon as its tree is drawn, so endless sources are processed for as
46
+ * > long as the feed is consumed.
47
+ * > - **Streaming**: trees are processed one at a time and released once their content is copied, so memory use
48
+ * > doesn't grow with the length of the feed.
49
+ * > - **Stateless**: each tree is processed independently, so the result doesn't depend on how the feed is split
50
+ * > across nested feeds or runs.
51
+ *
52
+ * @returns A task converting a feed of parsed X/HTML trees into a feed of documents holding their main content
53
+ *
54
+ * @throws {@link !Error Error} While the feed is consumed, if the source feed fails
55
+ *
56
+ * @see {@link https://html.spec.whatwg.org/multipage/sections.html#the-main-element WHATWG HTML - The main element}
57
+ * @see {@link https://html.spec.whatwg.org/multipage/sections.html#the-article-element WHATWG HTML - The article
58
+ * element}
59
+ * @see {@link https://www.w3.org/TR/wai-aria-1.2/#main WAI-ARIA - main role}
60
+ *
61
+ * @group Factories
62
+ */
63
+ export declare function focus(): Task<AnyNode, Document>;
64
+ //# sourceMappingURL=focus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.d.ts","sourceRoot":"","sources":["../src/focus.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAIpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,wBAAgB,KAAK,IAAI,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC,CAkB/C"}
package/dist/focus.js ADDED
@@ -0,0 +1,88 @@
1
+ /*
2
+ * Copyright © 2026 Metreeca srl
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { items } from "@grafctory/flow/feeds";
17
+ import { process } from "./focus.core.js";
18
+ /**
19
+ * Creates a content extractor.
20
+ *
21
+ * The task converts a feed of parsed X/HTML trees into a feed of documents holding their main content, one document per
22
+ * tree, so that downstream tasks work on the content of a page without its navigation, headers, footers, sidebars and
23
+ * controls.
24
+ *
25
+ * Trees without content produce no document, so the output feed is not aligned one to one with the input feed.
26
+ *
27
+ * The main content of a tree is the first of the following regions the tree contains:
28
+ *
29
+ * 1. the first `main` element or, if there is none, the first element with `role="main"`
30
+ * 2. all `article` elements, taken together, so that listing pages are kept whole; articles inside page framing
31
+ * (navigation, headers, footers, sidebars and the like), articles nested inside other articles, and articles
32
+ * without any text are ignored
33
+ * 3. the element with the densest text, as described below
34
+ *
35
+ * Regions are searched below the root of the tree, so a tree rooted at a `main` element is searched for a region
36
+ * inside it. Element names are matched case-insensitively.
37
+ *
38
+ * Articles nested inside an article of the content, such as teasers for related items or comment threads, are left
39
+ * out of the document: they are separate pieces related to the article holding them, and they often rotate while the
40
+ * content itself stays the same. Nesting is reckoned within the selected region alone. An article stating nothing
41
+ * of its own beyond headings, framing and nested articles is taken to wrap a listing, so its articles are all kept.
42
+ *
43
+ * Text density favours long runs of text over the same amount of text split into short fragments, and penalises
44
+ * containers holding a large share of framing. Scripts, styles, navigation, headers, footers, sidebars, controls and
45
+ * embedded objects contribute no text, so pages with long menus are scored on their prose alone. Elements without text
46
+ * of their own, such as line breaks, rules, images and metadata, are neutral. If two elements are equally dense, the
47
+ * first one in document order is selected, which is the outermost of a chain of single children.
48
+ *
49
+ * If the tree is a page, that is if it contains an `html` or `body` element or a title, the content is wrapped in the
50
+ * `body` of a new `html` element. If the page has a title, the `html` element also includes a `head` with a copy of
51
+ * it. The title is the first `title` element outside page framing, so that captions of embedded objects are not
52
+ * mistaken for it. If the tree is a fragment, each content region becomes a document root of its own.
53
+ *
54
+ * Each content region records as `xml:base` the base URL in scope at its original position, if any, so that its
55
+ * relative references keep resolving correctly. In page output, the `html` element also records as `xml:base` the base
56
+ * URL of the source tree, so that the page URL travels with its content. Source trees are not modified.
57
+ *
58
+ * > [!NOTE]
59
+ * >
60
+ * > - **Incremental**: each document is emitted as soon as its tree is drawn, so endless sources are processed for as
61
+ * > long as the feed is consumed.
62
+ * > - **Streaming**: trees are processed one at a time and released once their content is copied, so memory use
63
+ * > doesn't grow with the length of the feed.
64
+ * > - **Stateless**: each tree is processed independently, so the result doesn't depend on how the feed is split
65
+ * > across nested feeds or runs.
66
+ *
67
+ * @returns A task converting a feed of parsed X/HTML trees into a feed of documents holding their main content
68
+ *
69
+ * @throws {@link !Error Error} While the feed is consumed, if the source feed fails
70
+ *
71
+ * @see {@link https://html.spec.whatwg.org/multipage/sections.html#the-main-element WHATWG HTML - The main element}
72
+ * @see {@link https://html.spec.whatwg.org/multipage/sections.html#the-article-element WHATWG HTML - The article
73
+ * element}
74
+ * @see {@link https://www.w3.org/TR/wai-aria-1.2/#main WAI-ARIA - main role}
75
+ *
76
+ * @group Factories
77
+ */
78
+ export function focus() {
79
+ return trees => items((async function* () {
80
+ for await (const tree of trees) {
81
+ const main = process(tree);
82
+ if (main !== undefined) { // a tree holding no content contributes no value
83
+ yield main;
84
+ }
85
+ }
86
+ })());
87
+ }
88
+ //# sourceMappingURL=focus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"focus.js","sourceRoot":"","sources":["../src/focus.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAG1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2DG;AACH,MAAM,UAAU,KAAK;IAEpB,OAAO,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,SAAS,CAAC;QAErC,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YAEhC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;YAE3B,IAAK,IAAI,KAAK,SAAS,EAAG,CAAC,CAAC,iDAAiD;gBAE5E,MAAM,IAAI,CAAC;YAEZ,CAAC;QAEF,CAAC;IAEF,CAAC,CAAC,EAAE,CAAC,CAAC;AAEP,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { IRI } from "@grafctory/core/resource";
2
+ import type { Document } from "domhandler";
3
+ /**
4
+ * Parses an HTML document.
5
+ *
6
+ * Helper backing the `html()` task, which states the parsing contract.
7
+ */
8
+ export declare function process(document: string | Response, base?: IRI): Promise<undefined | Document>;
9
+ //# sourceMappingURL=html.core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html.core.d.ts","sourceRoot":"","sources":["../src/html.core.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAGpD,OAAO,KAAK,EAAW,QAAQ,EAAE,MAAM,YAAY,CAAC;AAoIpD;;;;GAIG;AACH,wBAAsB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,SAAS,GAAG,QAAQ,CAAC,CAgKpG"}