@botiverse/porthole 0.9.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/annotate/types.d.ts +21 -7
  2. package/dist/annotate/validate.d.ts +18 -3
  3. package/dist/annotate/validate.js +29 -5
  4. package/dist/bridge/bridge.js +1 -51
  5. package/dist/bridge/unseen.d.ts +18 -0
  6. package/dist/bridge/unseen.js +71 -0
  7. package/dist/check/files.d.ts +2 -0
  8. package/dist/check/files.js +67 -50
  9. package/dist/check/lint.d.ts +8 -1
  10. package/dist/check/lint.js +18 -0
  11. package/dist/check/markup.d.ts +7 -0
  12. package/dist/check/markup.js +49 -0
  13. package/dist/check/page-source.js +1 -1
  14. package/dist/check/scroll.d.ts +100 -0
  15. package/dist/check/scroll.js +1429 -0
  16. package/dist/conformance/behavior.js +107 -68
  17. package/dist/conformance/clipboard.js +16 -14
  18. package/dist/conformance/harness-source.js +1 -1
  19. package/dist/conformance/limits.js +117 -64
  20. package/dist/conformance/probes.js +66 -49
  21. package/dist/conformance/runtime.js +6 -0
  22. package/dist/conformance/served.js +66 -63
  23. package/dist/guide/guide.js +1 -1
  24. package/dist/guide/runtime.js +2 -2
  25. package/dist/host/create-host.js +46 -4
  26. package/dist/index.d.ts +1 -1
  27. package/dist/platform/types.d.ts +4 -2
  28. package/dist/react/frame.d.ts +2 -1
  29. package/dist/runtime/requests.d.ts +5 -0
  30. package/dist/runtime/requests.js +16 -1
  31. package/dist/runtime/types.generated.js +1 -1
  32. package/dist/shell/annotate.d.ts +6 -3
  33. package/dist/shell/annotate.js +474 -104
  34. package/dist/shell/use.js +9 -1
  35. package/docs/ADOPTING.md +99 -1
  36. package/docs/ARCHITECTURE.md +2 -1
  37. package/docs/DECISIONS.md +764 -14
  38. package/docs/DESIGN.md +192 -42
  39. package/docs/THREAT_MODEL.md +109 -27
  40. package/package.json +1 -1
  41. package/src/annotate/types.ts +22 -7
  42. package/src/annotate/validate.ts +32 -6
  43. package/src/bridge/bridge.ts +1 -60
  44. package/src/bridge/unseen.ts +82 -0
  45. package/src/check/files.ts +68 -54
  46. package/src/check/lint.ts +24 -0
  47. package/src/check/markup.ts +53 -0
  48. package/src/check/scroll.ts +1757 -0
  49. package/src/conformance/behavior.ts +221 -69
  50. package/src/conformance/clipboard.ts +44 -14
  51. package/src/conformance/limits.ts +169 -76
  52. package/src/conformance/probes.ts +97 -49
  53. package/src/conformance/runtime.ts +9 -0
  54. package/src/conformance/served.ts +112 -63
  55. package/src/guide/guide.ts +1 -0
  56. package/src/guide/runtime.ts +2 -2
  57. package/src/host/create-host.ts +50 -4
  58. package/src/index.ts +1 -0
  59. package/src/platform/types.ts +4 -2
  60. package/src/react/frame.tsx +2 -1
  61. package/src/runtime/requests.ts +23 -1
  62. package/src/runtime/types.generated.ts +1 -1
  63. package/src/shell/annotate.ts +474 -104
  64. package/src/shell/use.ts +9 -1
  65. package/types/runtime/v1/comments.d.ts +14 -4
@@ -0,0 +1,1429 @@
1
+ import { attributesOf } from "./markup.js";
2
+ /** How much of one stylesheet is read: its first 2 MiB. */
3
+ const SCANNED = 2 * 1024 * 1024;
4
+ /** How deep `@import` and `@layer` are followed. */
5
+ const DEEPEST = 8;
6
+ /** The most layers a page's sheets name: past that, a new layer's rules aren't read. */
7
+ const MOST_LAYERS = 1_024;
8
+ /**
9
+ * The longest layer name, with the layers it is in (`a.b.c`): a longer one isn't declared, nor
10
+ * its rules or the layers in it read (each would copy its name).
11
+ */
12
+ const LONGEST_LAYER = 256;
13
+ /** The most parts of a layer's name (`a.b.c`, with the layers it is in): deeper isn't read. */
14
+ const LAYER_PARTS = 16;
15
+ /** The most stylesheets read for one page, each once. */
16
+ export const SHEETS = 32;
17
+ /** The most bytes of stylesheets read for one page, in all. */
18
+ export const READ = 4 * 1024 * 1024;
19
+ /**
20
+ * A version's pages share one budget (`lintFiles`, which checks the entry and at most 7 more):
21
+ * every byte of stylesheet read for any of them, its own `<style>` included (a sheet two pages
22
+ * link is read for each), and every step matching scroll rules against markup. A page that would
23
+ * spend more than is left isn't checked, nor are the pages after it.
24
+ */
25
+ export const VERSION_READ = 8 * 1024 * 1024;
26
+ export const VERSION_STEPS = 2_000_000;
27
+ /** A version's budget, for one `lintFiles`. */
28
+ export const scrollBudget = () => ({
29
+ bytes: VERSION_READ,
30
+ steps: VERSION_STEPS,
31
+ spent: false,
32
+ });
33
+ /** The most elements below body, and how deep, that scroll rules are matched against. */
34
+ const MOST_ELEMENTS = 2_000;
35
+ const DEEPEST_ELEMENT = 32;
36
+ /** The most ids and classes in one compound selector: one with more matches nothing here. */
37
+ const MOST_IN_COMPOUND = 32;
38
+ /** The most scroll rules' selectors kept, and steps spent matching them. */
39
+ const MOST_SCROLL_SELECTORS = 256;
40
+ const MATCH_STEPS = 1_000_000;
41
+ /** The longest declaration or selector told back to the agent. */
42
+ const ECHOED = 60;
43
+ const VOID = new Set([
44
+ "area",
45
+ "base",
46
+ "br",
47
+ "col",
48
+ "embed",
49
+ "hr",
50
+ "img",
51
+ "input",
52
+ "link",
53
+ "meta",
54
+ "param",
55
+ "source",
56
+ "track",
57
+ "wbr",
58
+ ]);
59
+ /** Elements whose text isn't markup (or never shown): read past, to their end tag. */
60
+ const RAW = new Set([
61
+ "script",
62
+ "style",
63
+ "textarea",
64
+ "title",
65
+ "noscript",
66
+ "template",
67
+ "iframe",
68
+ "xmp",
69
+ "noembed",
70
+ "noframes",
71
+ ]);
72
+ /** HTML's own elements: a tag's name the agent may be told (another is page text). */
73
+ const HTML_TAGS = new Set(("a abbr address area article aside audio b bdi bdo blockquote br button canvas center cite " +
74
+ "code data datalist del details dfn dialog div dl em embed fieldset figure font footer form " +
75
+ "h1 h2 h3 h4 h5 h6 header hgroup hr i iframe img input ins kbd label main map mark math menu " +
76
+ "meter nav object ol output p picture pre progress q s samp search section select slot small " +
77
+ "span strong sub sup svg table textarea time u ul var video").split(" "));
78
+ /** A body's children that hold no content. */
79
+ const NOT_CONTENT = new Set(["script", "style", "link", "meta", "noscript", "template", "base"]);
80
+ const TAG_AT = /<(\/?)([a-z][a-z0-9-]{0,30})\b([^<>]{0,8192})>/iuy;
81
+ const closers = new Map();
82
+ const closer = (name) => {
83
+ let found = closers.get(name);
84
+ if (found === undefined) {
85
+ found = new RegExp(`</${name}\\s*>`, "giu");
86
+ closers.set(name, found);
87
+ }
88
+ return found;
89
+ };
90
+ const attribute = (tag, name) => tag?.attributes.find((each) => each.name === name);
91
+ /** What a page's markup says of its top: html's and body's tags, body's children, its sheets. */
92
+ function scanPage(page) {
93
+ let html = null;
94
+ let body = null;
95
+ const children = [];
96
+ let childCount = 0;
97
+ const content = [];
98
+ let contentCount = 0;
99
+ const sheets = [];
100
+ let tailwind = false;
101
+ /** Whether body's children, and the elements below them, scroll themselves by style or class. */
102
+ const top = { style: false, classes: false };
103
+ const inner = { style: false, classes: false };
104
+ const below = [];
105
+ let contentBelow = 0;
106
+ let scripted = false;
107
+ /** Body has text of its own (outside scripts and styles). */
108
+ let texted = false;
109
+ /** The open elements below body, each with how many children it has had. */
110
+ const open = [];
111
+ const bodyFrame = { children: 0 };
112
+ let opened = null;
113
+ let inBody = false;
114
+ let depth = 0;
115
+ let at = page.indexOf("<");
116
+ while (at >= 0 && at < page.length) {
117
+ if (page.startsWith("<!--", at)) {
118
+ const end = page.indexOf("-->", at + 4);
119
+ at = end < 0 ? page.length : page.indexOf("<", end + 3);
120
+ continue;
121
+ }
122
+ TAG_AT.lastIndex = at;
123
+ const match = TAG_AT.exec(page);
124
+ if (match === null) {
125
+ at = page.indexOf("<", at + 1);
126
+ continue;
127
+ }
128
+ const closing = match[1] === "/";
129
+ const name = (match[2] ?? "").toLowerCase();
130
+ const attributesAt = at + 1 + (match[1] ?? "").length + name.length;
131
+ let next = at + match[0].length;
132
+ if (closing) {
133
+ if (inBody) {
134
+ if (depth === 0 && (name === "body" || name === "html")) {
135
+ inBody = false;
136
+ }
137
+ else if (depth > 0) {
138
+ depth -= 1;
139
+ open.pop();
140
+ }
141
+ }
142
+ at = page.indexOf("<", next);
143
+ texted ||= inBody && hasText(page, next, at);
144
+ continue;
145
+ }
146
+ const tag = { name, attributes: attributesOf(match[3] ?? ""), at: attributesAt };
147
+ if (name === "html" && html === null) {
148
+ html = tag;
149
+ }
150
+ else if (name === "body" && body === null) {
151
+ body = tag;
152
+ inBody = true;
153
+ depth = 0;
154
+ }
155
+ else if (inBody) {
156
+ // An element below body that scrolls itself, as its markup says. Body's own children apart:
157
+ // where one is the root, its values are in the cascade, and they decide.
158
+ const own = depth === 0 ? top : inner;
159
+ own.style ||= declaresScroll(attribute(tag, "style")?.value ?? "");
160
+ own.classes ||= SCROLL_UTILITY.test(attribute(tag, "class")?.value ?? "");
161
+ const parent = open.at(-1) ?? bodyFrame;
162
+ const element = {
163
+ tag: name,
164
+ id: attribute(tag, "id")?.value ?? "",
165
+ classes: classesOf(attribute(tag, "class")?.value ?? ""),
166
+ onlyChild: false,
167
+ firstChild: parent.children === 0,
168
+ };
169
+ parent.children += 1;
170
+ opened = element;
171
+ if (!NOT_CONTENT.has(name)) {
172
+ contentBelow += 1;
173
+ if (below.length < MOST_ELEMENTS && open.length < DEEPEST_ELEMENT) {
174
+ below.push([...open.map((each) => each.element), element]);
175
+ }
176
+ }
177
+ }
178
+ if (name === "script") {
179
+ scripted = true;
180
+ }
181
+ if (inBody && depth === 0 && name !== "body") {
182
+ childCount += 1;
183
+ if (children.length < 2) {
184
+ children.push(tag);
185
+ }
186
+ if (!NOT_CONTENT.has(name)) {
187
+ contentCount += 1;
188
+ if (content.length < 2) {
189
+ content.push(tag);
190
+ }
191
+ }
192
+ }
193
+ if (name === "link") {
194
+ const href = attribute(tag, "href")?.value ?? "";
195
+ if (/tailwindcss/iu.test(href)) {
196
+ tailwind = true;
197
+ }
198
+ sheets.push({ kind: "link", tag });
199
+ }
200
+ else if (name === "script" && /tailwindcss/iu.test(attribute(tag, "src")?.value ?? "")) {
201
+ tailwind = true;
202
+ }
203
+ if (RAW.has(name)) {
204
+ const end = closer(name);
205
+ end.lastIndex = next;
206
+ const found = end.exec(page);
207
+ if (name === "style") {
208
+ sheets.push({
209
+ kind: "style",
210
+ start: next,
211
+ end: found === null ? page.length : found.index,
212
+ tag,
213
+ });
214
+ }
215
+ next = found === null ? page.length : found.index + found[0].length;
216
+ }
217
+ else if (inBody && name !== "body" && !VOID.has(name)) {
218
+ depth += 1;
219
+ if (opened !== null) {
220
+ open.push({ element: opened, children: 0 });
221
+ }
222
+ }
223
+ opened = null;
224
+ at = page.indexOf("<", next);
225
+ texted ||= inBody && hasText(page, next, at);
226
+ }
227
+ return {
228
+ html,
229
+ body,
230
+ children,
231
+ childCount,
232
+ content,
233
+ contentCount,
234
+ sheets,
235
+ tailwind,
236
+ // Body's children count where there is no root (it has two of content, or none).
237
+ styleScrolls: inner.style || (contentCount !== 1 && top.style),
238
+ classScrolls: inner.classes || (contentCount !== 1 && top.classes),
239
+ below,
240
+ contentBelow,
241
+ scripted,
242
+ texted,
243
+ };
244
+ }
245
+ /** A class attribute's names. */
246
+ const classesOf = (value) => new Set(value.split(/\s+/u).filter((each) => each !== ""));
247
+ /** Whether `page` has text other than spaces from `from` to `to` (the end where `to` is -1). */
248
+ const hasText = (page, from, to) => /\S/u.test(page.slice(from, to < 0 ? page.length : to));
249
+ /** Tailwind's utilities that make a box scroll itself. */
250
+ const SCROLL_UTILITY = /(?:^|\s)overflow-(?:y-)?(?:auto|scroll)(?:\s|$)/u;
251
+ /** Whether declarations (a block's, or style="") give overflow-y auto or scroll. */
252
+ function declaresScroll(text) {
253
+ for (const match of text.matchAll(/(?:^|[\s;{])overflow(-y)?\s{0,64}:\s{0,64}([^;{}!]{0,256})/giu)) {
254
+ const parts = (match[2] ?? "").trim().toLowerCase().split(/\s+/u);
255
+ const y = match[1] === undefined ? (parts[1] ?? parts[0]) : parts[0];
256
+ if (y !== undefined && SCROLLS.has(y)) {
257
+ return true;
258
+ }
259
+ }
260
+ return false;
261
+ }
262
+ /** A text with its comments blanked (same length, same lines), strings kept. */
263
+ function withoutComments(text) {
264
+ let out = "";
265
+ let from = 0;
266
+ let at = 0;
267
+ while (at < text.length) {
268
+ const code = text[at];
269
+ if (code === '"' || code === "'") {
270
+ at = stringEnd(text, at, text.length);
271
+ }
272
+ else if (code === "/" && text[at + 1] === "*") {
273
+ const close = text.indexOf("*/", at + 2);
274
+ const end = close < 0 ? text.length : close + 2;
275
+ out += text.slice(from, at) + text.slice(at, end).replace(/[^\n]/gu, " ");
276
+ from = end;
277
+ at = end;
278
+ }
279
+ else {
280
+ at += 1;
281
+ }
282
+ }
283
+ return out + text.slice(from);
284
+ }
285
+ /** Past the string that starts at `at` (its quote): its end quote, a newline, or `to`. */
286
+ function stringEnd(text, at, to) {
287
+ const quote = text[at];
288
+ let index = at + 1;
289
+ while (index < to) {
290
+ const code = text[index];
291
+ if (code === "\\") {
292
+ index += 2;
293
+ }
294
+ else if (code === quote || code === "\n") {
295
+ return index + 1;
296
+ }
297
+ else {
298
+ index += 1;
299
+ }
300
+ }
301
+ return to;
302
+ }
303
+ /** Past the block whose `{` is at `at`: after its `}`, or `to`. */
304
+ function blockEnd(text, at, to) {
305
+ let depth = 0;
306
+ let index = at;
307
+ while (index < to) {
308
+ const code = text[index];
309
+ if (code === '"' || code === "'") {
310
+ index = stringEnd(text, index, to);
311
+ continue;
312
+ }
313
+ if (code === "{") {
314
+ depth += 1;
315
+ }
316
+ else if (code === "}") {
317
+ depth -= 1;
318
+ if (depth === 0) {
319
+ return index + 1;
320
+ }
321
+ }
322
+ index += 1;
323
+ }
324
+ return to;
325
+ }
326
+ /** The next rule or statement from `at`: its prelude, and its block's bounds if it has one. */
327
+ function nextItem(text, at, to) {
328
+ let start = at;
329
+ while (start < to && /\s/u.test(text[start] ?? "")) {
330
+ start += 1;
331
+ }
332
+ if (start >= to) {
333
+ return null;
334
+ }
335
+ let parens = 0;
336
+ let index = start;
337
+ while (index < to) {
338
+ const code = text[index];
339
+ if (code === '"' || code === "'") {
340
+ index = stringEnd(text, index, to);
341
+ continue;
342
+ }
343
+ if (code === "(") {
344
+ parens += 1;
345
+ }
346
+ else if (code === ")") {
347
+ parens = Math.max(0, parens - 1);
348
+ }
349
+ else if (parens === 0 && code === "{") {
350
+ const end = blockEnd(text, index, to);
351
+ return {
352
+ prelude: text.slice(start, index).trim(),
353
+ block: [index + 1, Math.max(index + 1, end - 1)],
354
+ end,
355
+ };
356
+ }
357
+ else if (parens === 0 && (code === ";" || code === "}")) {
358
+ return { prelude: text.slice(start, index).trim(), block: null, end: index + 1 };
359
+ }
360
+ index += 1;
361
+ }
362
+ return { prelude: text.slice(start, to).trim(), block: null, end: to };
363
+ }
364
+ /** Each item of a list at its top-level commas (not inside parentheses or strings), in turn. */
365
+ function* listOf(text) {
366
+ let parens = 0;
367
+ let from = 0;
368
+ for (let index = 0; index <= text.length; index += 1) {
369
+ const code = text[index];
370
+ if (code === '"' || code === "'") {
371
+ index = stringEnd(text, index, text.length) - 1;
372
+ }
373
+ else if (code === "(") {
374
+ parens += 1;
375
+ }
376
+ else if (code === ")") {
377
+ parens = Math.max(0, parens - 1);
378
+ }
379
+ else if ((code === "," && parens === 0) || index === text.length) {
380
+ const item = text.slice(from, index).trim();
381
+ if (item !== "") {
382
+ yield item;
383
+ }
384
+ from = index + 1;
385
+ }
386
+ }
387
+ }
388
+ /** An identifier at `at`, its escapes read; null where there is none. */
389
+ function identAt(text, at) {
390
+ let value = "";
391
+ let index = at;
392
+ while (index < text.length) {
393
+ const code = text[index] ?? "";
394
+ if (code === "\\") {
395
+ const hex = /^[0-9a-f]{1,6}\s?/iu.exec(text.slice(index + 1, index + 8));
396
+ if (hex !== null) {
397
+ value += String.fromCodePoint(Number.parseInt(hex[0].trim(), 16) || 0xfffd);
398
+ index += 1 + hex[0].length;
399
+ }
400
+ else if (index + 1 < text.length) {
401
+ value += text[index + 1];
402
+ index += 2;
403
+ }
404
+ else {
405
+ break;
406
+ }
407
+ }
408
+ else if (/[\w-]/u.test(code) || code.charCodeAt(0) > 0x7f) {
409
+ value += code;
410
+ index += 1;
411
+ }
412
+ else {
413
+ break;
414
+ }
415
+ }
416
+ return value === "" ? null : { value, end: index };
417
+ }
418
+ /** A selector this check can match, or null (it then matches nothing here). */
419
+ function parseSelector(text) {
420
+ const compounds = [];
421
+ const combinators = [];
422
+ let ids = 0;
423
+ let classLike = 0;
424
+ let tags = 0;
425
+ let index = 0;
426
+ let pending = null;
427
+ while (index < text.length) {
428
+ const code = text[index] ?? "";
429
+ if (/\s/u.test(code)) {
430
+ pending ??= " ";
431
+ index += 1;
432
+ continue;
433
+ }
434
+ if (code === ">") {
435
+ pending = ">";
436
+ index += 1;
437
+ continue;
438
+ }
439
+ if (compounds.length > 0) {
440
+ if (pending === null) {
441
+ return null;
442
+ }
443
+ combinators.push(pending);
444
+ }
445
+ else if (pending === ">") {
446
+ return null;
447
+ }
448
+ pending = null;
449
+ let tag = null;
450
+ const compoundIds = [];
451
+ const compoundClasses = [];
452
+ let root = false;
453
+ let onlyChild = false;
454
+ let firstChild = false;
455
+ if (text[index] === "*") {
456
+ index += 1;
457
+ }
458
+ else {
459
+ const name = identAt(text, index);
460
+ if (name !== null) {
461
+ tag = name.value.toLowerCase();
462
+ tags += 1;
463
+ index = name.end;
464
+ }
465
+ }
466
+ let read = tag !== null || text[index - 1] === "*";
467
+ while (index < text.length) {
468
+ const mark = text[index];
469
+ if (mark === "#" || mark === ".") {
470
+ const name = identAt(text, index + 1);
471
+ if (name === null) {
472
+ return null;
473
+ }
474
+ if (compoundIds.length + compoundClasses.length >= MOST_IN_COMPOUND) {
475
+ return null;
476
+ }
477
+ if (mark === "#") {
478
+ compoundIds.push(name.value);
479
+ ids += 1;
480
+ }
481
+ else {
482
+ compoundClasses.push(name.value);
483
+ classLike += 1;
484
+ }
485
+ index = name.end;
486
+ }
487
+ else if (mark === ":") {
488
+ if (text[index + 1] === ":") {
489
+ return null;
490
+ }
491
+ const name = identAt(text, index + 1);
492
+ const pseudo = name?.value.toLowerCase();
493
+ if (name === null || text[name.end] === "(") {
494
+ return null;
495
+ }
496
+ if (pseudo === "root") {
497
+ root = true;
498
+ }
499
+ else if (pseudo === "only-child") {
500
+ onlyChild = true;
501
+ }
502
+ else if (pseudo === "first-child") {
503
+ firstChild = true;
504
+ }
505
+ else {
506
+ return null;
507
+ }
508
+ classLike += 1;
509
+ index = name.end;
510
+ }
511
+ else {
512
+ break;
513
+ }
514
+ read = true;
515
+ }
516
+ if (!read) {
517
+ return null;
518
+ }
519
+ compounds.push({
520
+ tag,
521
+ ids: compoundIds,
522
+ classes: compoundClasses,
523
+ root,
524
+ onlyChild,
525
+ firstChild,
526
+ });
527
+ }
528
+ if (compounds.length === 0 || pending === ">") {
529
+ return null;
530
+ }
531
+ return { compounds, combinators, specificity: [ids, classLike, tags] };
532
+ }
533
+ const compoundMatches = (compound, node, index) => (compound.tag === null || compound.tag === node.tag) &&
534
+ compound.ids.every((id) => id === node.id) &&
535
+ compound.classes.every((name) => node.classes.has(name)) &&
536
+ (!compound.root || index === 0) &&
537
+ (!compound.onlyChild || node.onlyChild) &&
538
+ (!compound.firstChild || node.firstChild);
539
+ /**
540
+ * Whether `selector` matches `chain[index]` (each element's parent is the one before it). Each
541
+ * (compound, element) pair is tried once; `budget.steps` bounds the work across calls (none left:
542
+ * no match).
543
+ */
544
+ function matches(selector, chain, index, budget = { steps: Infinity }) {
545
+ // One compound (`div`, `.list`): the element alone, no walk (a step all the same).
546
+ if (selector.compounds.length === 1) {
547
+ budget.steps -= 1;
548
+ const only = selector.compounds[0];
549
+ const node = chain[index];
550
+ return (budget.steps > 0 &&
551
+ only !== undefined &&
552
+ node !== undefined &&
553
+ compoundMatches(only, node, index));
554
+ }
555
+ const tried = new Map();
556
+ const at = (k, i) => {
557
+ const key = k * (chain.length + 1) + i;
558
+ const known = tried.get(key);
559
+ if (known !== undefined) {
560
+ return known;
561
+ }
562
+ budget.steps -= 1;
563
+ const result = budget.steps > 0 && pair(k, i);
564
+ tried.set(key, result);
565
+ return result;
566
+ };
567
+ const pair = (k, i) => {
568
+ const compound = selector.compounds[k];
569
+ const node = chain[i];
570
+ if (compound === undefined || node === undefined || !compoundMatches(compound, node, i)) {
571
+ return false;
572
+ }
573
+ if (k === 0) {
574
+ return true;
575
+ }
576
+ if (selector.combinators[k - 1] === ">") {
577
+ return at(k - 1, i - 1);
578
+ }
579
+ for (let j = i - 1; j >= 0; j -= 1) {
580
+ if (at(k - 1, j)) {
581
+ return true;
582
+ }
583
+ }
584
+ return false;
585
+ };
586
+ return at(selector.compounds.length - 1, index);
587
+ }
588
+ /** The longhands this check reads, from the properties that set them. */
589
+ function longhands(property, value) {
590
+ const parts = value.split(/\s+/u).filter((each) => each !== "");
591
+ switch (property) {
592
+ case "overflow":
593
+ return [
594
+ ["overflow-x", parts[0] ?? ""],
595
+ ["overflow-y", parts[1] ?? parts[0] ?? ""],
596
+ ];
597
+ case "inset":
598
+ return [
599
+ ["top", parts[0] ?? ""],
600
+ ["bottom", parts[2] ?? parts[0] ?? ""],
601
+ ];
602
+ case "inset-block":
603
+ return [
604
+ ["top", parts[0] ?? ""],
605
+ ["bottom", parts[1] ?? parts[0] ?? ""],
606
+ ];
607
+ case "block-size":
608
+ return [["height", value]];
609
+ case "max-block-size":
610
+ return [["max-height", value]];
611
+ case "overflow-x":
612
+ case "overflow-y":
613
+ case "height":
614
+ case "max-height":
615
+ case "display":
616
+ case "position":
617
+ case "top":
618
+ case "bottom":
619
+ return [[property, value]];
620
+ default:
621
+ return [];
622
+ }
623
+ }
624
+ /** Tailwind's utilities that hold a page, as the CSS they are. */
625
+ const UTILITIES = {
626
+ "h-screen": ["height", "100vh"],
627
+ "h-dvh": ["height", "100dvh"],
628
+ "h-svh": ["height", "100svh"],
629
+ "h-lvh": ["height", "100lvh"],
630
+ "h-full": ["height", "100%"],
631
+ "h-auto": ["height", "auto"],
632
+ "max-h-screen": ["max-height", "100vh"],
633
+ "max-h-dvh": ["max-height", "100dvh"],
634
+ "max-h-svh": ["max-height", "100svh"],
635
+ "max-h-full": ["max-height", "100%"],
636
+ "overflow-hidden": ["overflow", "hidden"],
637
+ "overflow-clip": ["overflow", "clip"],
638
+ "overflow-auto": ["overflow", "auto"],
639
+ "overflow-scroll": ["overflow", "scroll"],
640
+ "overflow-visible": ["overflow", "visible"],
641
+ "overflow-y-hidden": ["overflow-y", "hidden"],
642
+ "overflow-y-clip": ["overflow-y", "clip"],
643
+ "overflow-y-auto": ["overflow-y", "auto"],
644
+ "overflow-y-scroll": ["overflow-y", "scroll"],
645
+ "overflow-y-visible": ["overflow-y", "visible"],
646
+ fixed: ["position", "fixed"],
647
+ absolute: ["position", "absolute"],
648
+ relative: ["position", "relative"],
649
+ static: ["position", "static"],
650
+ sticky: ["position", "sticky"],
651
+ "inset-0": ["inset", "0"],
652
+ "inset-y-0": ["inset-block", "0"],
653
+ "top-0": ["top", "0"],
654
+ "bottom-0": ["bottom", "0"],
655
+ flex: ["display", "flex"],
656
+ "inline-flex": ["display", "inline-flex"],
657
+ grid: ["display", "grid"],
658
+ "inline-grid": ["display", "inline-grid"],
659
+ block: ["display", "block"],
660
+ };
661
+ /** Tailwind's arbitrary heights: `h-[calc(100vh-4rem)]` (`calc(100vh - 4rem)`), `max-h-[80vh]`. */
662
+ const ARBITRARY_HEIGHT = /^(max-)?h-\[([^\]]{1,64})\]$/u;
663
+ const compare = (a, b) => {
664
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
665
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
666
+ if (difference !== 0) {
667
+ return difference;
668
+ }
669
+ }
670
+ return 0;
671
+ };
672
+ /**
673
+ * A layer's name cut to its first `LAYER_PARTS` parts where it has more (its rules then aren't
674
+ * read, but its parents are declared where it comes, as a browser does); null where it doesn't.
675
+ */
676
+ const tooDeep = (name) => {
677
+ let parts = 1;
678
+ for (let dot = name.indexOf(".", 1); dot > 0; dot = name.indexOf(".", dot + 1)) {
679
+ parts += 1;
680
+ if (parts > LAYER_PARTS) {
681
+ return name.slice(0, dot);
682
+ }
683
+ }
684
+ return null;
685
+ };
686
+ /** The cascade over the chain: each declaration that matches, then the one that wins. */
687
+ class Cascade {
688
+ chain;
689
+ /** Layer names, in the order they were first declared or opened (`a`, `a.b`). */
690
+ layers = [];
691
+ known = new Set();
692
+ /** The selectors of rules that give something below body overflow-y auto or scroll. */
693
+ scrollSelectors = [];
694
+ order = 0;
695
+ anonymous = 0;
696
+ /** The stylesheets read for this page, by path: each once, within the budget. */
697
+ read = new Set();
698
+ bytes = 0;
699
+ find;
700
+ budget;
701
+ constructor(chain, find, budget) {
702
+ this.chain = chain;
703
+ this.find = find;
704
+ this.budget = budget;
705
+ }
706
+ /** Spends `bytes` of the version's budget; false (and spent: no page more) past what's left. */
707
+ spend(bytes) {
708
+ if (this.budget.spent || bytes > this.budget.bytes) {
709
+ this.budget.spent = true;
710
+ return false;
711
+ }
712
+ this.budget.bytes -= bytes;
713
+ return true;
714
+ }
715
+ /** A layer, declared (its parents first): its place is where it first comes. */
716
+ declare(name) {
717
+ if (this.known.has(name)) {
718
+ return true;
719
+ }
720
+ const add = (layer) => {
721
+ if (this.known.has(layer)) {
722
+ return true;
723
+ }
724
+ // Past MOST_LAYERS a page's layers aren't kept: the new one's rules aren't read.
725
+ if (this.known.size >= MOST_LAYERS) {
726
+ return false;
727
+ }
728
+ this.known.add(layer);
729
+ this.layers.push(layer);
730
+ return true;
731
+ };
732
+ for (let dot = name.indexOf(".", 1); dot > 0; dot = name.indexOf(".", dot + 1)) {
733
+ if (!add(name.slice(0, dot))) {
734
+ return false;
735
+ }
736
+ }
737
+ return add(name);
738
+ }
739
+ /**
740
+ * Each layer's rank, low to high: a layer's sub-layers before its own rules, layers in the order
741
+ * they were first declared, unlayered rules (the document's own) above them all.
742
+ */
743
+ ranks() {
744
+ const children = new Map();
745
+ for (const name of this.layers) {
746
+ const dot = name.lastIndexOf(".");
747
+ const parent = dot > 0 ? name.slice(0, dot) : null;
748
+ const siblings = children.get(parent);
749
+ if (siblings === undefined) {
750
+ children.set(parent, [name]);
751
+ }
752
+ else {
753
+ siblings.push(name);
754
+ }
755
+ }
756
+ const out = new Map();
757
+ const visit = (name) => {
758
+ for (const child of children.get(name) ?? []) {
759
+ visit(child);
760
+ }
761
+ out.set(name, out.size);
762
+ };
763
+ visit(null);
764
+ return out;
765
+ }
766
+ /**
767
+ * Whether the page's own `<style>` of `size` may be read: within `READ` for the page (else it
768
+ * isn't, as a linked sheet past it isn't), and within the version's budget (else nothing more
769
+ * is, and `spent` says so).
770
+ */
771
+ inline(size) {
772
+ if (this.bytes + size > READ || !this.spend(size)) {
773
+ return false;
774
+ }
775
+ this.bytes += size;
776
+ return true;
777
+ }
778
+ /** Whether a stylesheet may still be read for this page (once, within the budget). */
779
+ take(found) {
780
+ if (found === null || this.read.has(found.path) || this.read.size >= SHEETS) {
781
+ return false;
782
+ }
783
+ const size = Math.min(found.text.length, SCANNED);
784
+ if (this.bytes + size > READ || !this.spend(size)) {
785
+ return false;
786
+ }
787
+ this.read.add(found.path);
788
+ this.bytes += size;
789
+ return true;
790
+ }
791
+ /**
792
+ * A declaration for `node`, kept where it wins so far within its layer (and !important,
793
+ * style=""): there, specificity and then order decide, as the layer's rank is the same for all.
794
+ */
795
+ set(node, property, value, rank, where) {
796
+ if (rank.layer !== null) {
797
+ this.declare(rank.layer);
798
+ }
799
+ this.order += 1;
800
+ for (const [longhand, longValue] of longhands(property, value)) {
801
+ const each = {
802
+ value: longValue,
803
+ written: where.written ?? echoed(property, value, rank.important),
804
+ kind: where.kind ?? (rank.inline ? "inline" : "rule"),
805
+ selector: where.selector,
806
+ important: rank.important,
807
+ layer: rank.layer,
808
+ inline: rank.inline,
809
+ specificity: rank.specificity,
810
+ order: this.order,
811
+ source: where.source,
812
+ at: where.at,
813
+ };
814
+ let kept = node.candidates.get(longhand);
815
+ if (kept === undefined) {
816
+ kept = new Map();
817
+ node.candidates.set(longhand, kept);
818
+ }
819
+ const layer = each.layer === null ? "" : `@${each.layer}`;
820
+ const key = `${each.important ? "!" : ""}${each.inline ? "=" : ""}${layer}`;
821
+ const best = kept.get(key);
822
+ // Later, as specific or more: it wins within its layer.
823
+ if (best === undefined || compare(each.specificity, best.specificity) >= 0) {
824
+ kept.set(key, each);
825
+ }
826
+ }
827
+ }
828
+ /** Picks each longhand's winner, once every rule is read and the layers' order is known. */
829
+ resolve() {
830
+ const ranks = this.ranks();
831
+ const top = ranks.get(null) ?? 0;
832
+ const priority = (each) => {
833
+ const rank = ranks.get(each.layer) ?? top;
834
+ // Normal: later layers win, unlayered most. !important: reversed. style="" above both.
835
+ const score = each.inline ? (each.important ? 1 : top + 1) : each.important ? -rank : rank;
836
+ return [each.important ? 1 : 0, score, ...each.specificity, each.order];
837
+ };
838
+ for (const node of this.chain) {
839
+ for (const [property, candidates] of node.candidates) {
840
+ let best;
841
+ let bestPriority = [];
842
+ for (const each of candidates.values()) {
843
+ const mine = priority(each);
844
+ if (best === undefined || compare(mine, bestPriority) > 0) {
845
+ best = each;
846
+ bestPriority = mine;
847
+ }
848
+ }
849
+ if (best !== undefined) {
850
+ node.values.set(property, best);
851
+ }
852
+ }
853
+ }
854
+ }
855
+ /** The declarations of a block (`from`..`to` of `text`), for the nodes given. */
856
+ declarations(text, from, to, targets, rank, source, base) {
857
+ let start = from;
858
+ let index = from;
859
+ let parens = 0;
860
+ const take = (end) => {
861
+ const segment = text.slice(start, end);
862
+ const colon = segment.indexOf(":");
863
+ if (colon > 0) {
864
+ const property = segment.slice(0, colon).trim().toLowerCase();
865
+ let value = segment
866
+ .slice(colon + 1)
867
+ .trim()
868
+ .toLowerCase()
869
+ .replace(/\s+/gu, " ");
870
+ const important = /!\s*important$/u.test(value);
871
+ if (important) {
872
+ value = value.replace(/\s*!\s*important$/u, "");
873
+ }
874
+ if (!property.startsWith("--") && longhands(property, value).length > 0) {
875
+ const offset = start + (segment.length - segment.trimStart().length);
876
+ for (const target of targets) {
877
+ this.set(target.node, property, value, {
878
+ important,
879
+ layer: rank.layer,
880
+ inline: rank.inline,
881
+ specificity: target.specificity,
882
+ }, { source, at: base + offset, selector: target.selector });
883
+ }
884
+ }
885
+ }
886
+ };
887
+ while (index < to) {
888
+ const code = text[index];
889
+ if (code === '"' || code === "'") {
890
+ index = stringEnd(text, index, to);
891
+ continue;
892
+ }
893
+ if (code === "(") {
894
+ parens += 1;
895
+ }
896
+ else if (code === ")") {
897
+ parens = Math.max(0, parens - 1);
898
+ }
899
+ else if (parens === 0 && code === ";") {
900
+ take(index);
901
+ start = index + 1;
902
+ }
903
+ else if (parens === 0 && code === "{") {
904
+ // A nested rule: not read (its prelude is dropped with it).
905
+ index = blockEnd(text, index, to);
906
+ start = index;
907
+ continue;
908
+ }
909
+ index += 1;
910
+ }
911
+ take(to);
912
+ }
913
+ /** A stylesheet the page links or a sheet imports, if it may still be read. */
914
+ file(found, layer) {
915
+ if (!this.take(found)) {
916
+ return;
917
+ }
918
+ const text = found.text.slice(0, SCANNED);
919
+ this.sheet(withoutComments(text), 0, text.length, {
920
+ source: { path: found.path, text },
921
+ base: 0,
922
+ layer,
923
+ // A file starts again at the top: it is read once, within the budget, however it's reached.
924
+ depth: 0,
925
+ from: found.path,
926
+ });
927
+ }
928
+ /** A stylesheet's rules (`text` is comment-free; offsets are `base` + its own). */
929
+ sheet(text, from, to, context) {
930
+ if (context.depth > DEEPEST) {
931
+ return;
932
+ }
933
+ let ruled = false;
934
+ let at = from;
935
+ for (let item = nextItem(text, at, to); item !== null; item = nextItem(text, at, to)) {
936
+ at = item.end;
937
+ const { prelude, block } = item;
938
+ const within = (name) => (context.layer === null ? name : `${context.layer}.${name}`);
939
+ if (prelude.startsWith("@")) {
940
+ const name = /^@([\w-]+)/u.exec(prelude)?.[1]?.toLowerCase() ?? "";
941
+ const rest = prelude.slice(name.length + 1).trim();
942
+ if (name === "import" && block === null && !ruled) {
943
+ this.import(rest, context, within);
944
+ }
945
+ else if (name === "layer") {
946
+ if (block === null) {
947
+ for (const each of listOf(rest)) {
948
+ const layer = within(each);
949
+ if (layer.length <= LONGEST_LAYER) {
950
+ this.declare(tooDeep(layer) ?? layer);
951
+ }
952
+ }
953
+ }
954
+ else {
955
+ this.anonymous += 1;
956
+ const first = listOf(rest).next();
957
+ const layer = within(first.done === true ? `\u0000${this.anonymous}` : first.value);
958
+ if (layer.length > LONGEST_LAYER) {
959
+ continue;
960
+ }
961
+ const cut = tooDeep(layer);
962
+ if (cut !== null) {
963
+ this.declare(cut);
964
+ continue;
965
+ }
966
+ // Its place is where its block opens, whatever it holds; past MOST_LAYERS, not read.
967
+ if (!this.declare(layer)) {
968
+ continue;
969
+ }
970
+ this.sheet(text, block[0], block[1], { ...context, layer, depth: context.depth + 1 });
971
+ }
972
+ }
973
+ else if (name === "media" &&
974
+ block !== null &&
975
+ /^(?:only\s+)?(?:all|screen)$/iu.test(rest)) {
976
+ this.sheet(text, block[0], block[1], { ...context, depth: context.depth + 1 });
977
+ }
978
+ continue;
979
+ }
980
+ ruled = true;
981
+ if (block === null) {
982
+ continue;
983
+ }
984
+ const targets = [];
985
+ // A scroll rule's selectors are kept as they come, while there is room for them.
986
+ const scrolls = this.scrollSelectors.length < MOST_SCROLL_SELECTORS &&
987
+ declaresScroll(text.slice(block[0], block[1]));
988
+ for (const each of listOf(prelude)) {
989
+ const selector = parseSelector(each);
990
+ let top = false;
991
+ if (selector !== null) {
992
+ this.chain.forEach((node, index) => {
993
+ if (!matches(selector, this.chain, index)) {
994
+ return;
995
+ }
996
+ top ||= index < 2;
997
+ const found = targets.find((target) => target.node === node);
998
+ if (found === undefined) {
999
+ targets.push({ node, specificity: selector.specificity, selector: each });
1000
+ }
1001
+ else if (compare(selector.specificity, found.specificity) > 0) {
1002
+ targets.splice(targets.indexOf(found), 1, {
1003
+ node,
1004
+ specificity: selector.specificity,
1005
+ selector: each,
1006
+ });
1007
+ }
1008
+ });
1009
+ }
1010
+ // A selector for anything but html or body may name an element below body; one the
1011
+ // check can't read names nothing it can see.
1012
+ if (scrolls &&
1013
+ selector !== null &&
1014
+ !top &&
1015
+ this.scrollSelectors.length < MOST_SCROLL_SELECTORS) {
1016
+ this.scrollSelectors.push(selector);
1017
+ }
1018
+ }
1019
+ if (targets.length > 0) {
1020
+ this.declarations(text, block[0], block[1], targets, { layer: context.layer, inline: false }, context.source, context.base);
1021
+ }
1022
+ }
1023
+ }
1024
+ import(rest, context, within) {
1025
+ const parsed = /^(?:url\(\s*(["']?)([^"'()\s]+)\1\s*\)|(["'])([^"']+)\3)\s*([\s\S]*)$/iu.exec(rest);
1026
+ if (parsed === null) {
1027
+ return;
1028
+ }
1029
+ const href = parsed[2] ?? parsed[4] ?? "";
1030
+ let tail = parsed[5]?.trim() ?? "";
1031
+ let layer = context.layer;
1032
+ const named = /^layer\(\s*([\w.-]+)\s*\)\s*/iu.exec(tail);
1033
+ if (named !== null) {
1034
+ layer = within(named[1] ?? "");
1035
+ tail = tail.slice(named[0].length);
1036
+ }
1037
+ else if (/^layer\b\s*/iu.test(tail)) {
1038
+ this.anonymous += 1;
1039
+ layer = within(`\u0000${this.anonymous}`);
1040
+ tail = tail.replace(/^layer\b\s*/iu, "");
1041
+ }
1042
+ if (tail !== "" && !/^(?:only\s+)?(?:all|screen)$/iu.test(tail)) {
1043
+ return;
1044
+ }
1045
+ if (layer !== null) {
1046
+ if (layer.length > LONGEST_LAYER) {
1047
+ return;
1048
+ }
1049
+ const cut = tooDeep(layer);
1050
+ if (!this.declare(cut ?? layer) || cut !== null) {
1051
+ return;
1052
+ }
1053
+ }
1054
+ this.file(this.find(href, context.from), layer);
1055
+ }
1056
+ }
1057
+ /** A value of a shape the check knows, as the agent may be told it; else its property alone. */
1058
+ const KNOWN = /^(?:(?:-?(?:\d{1,6}(?:\.\d{1,4})?|\.\d{1,4})(?:px|%|d?vh|svh|lvh|vw|em|rem)?|auto|hidden|clip|visible|scroll|overlay|fixed|absolute|static|relative|sticky|none)(?: |$)){1,4}$/u;
1059
+ const echoed = (property, value, important) => {
1060
+ const said = `${property}: ${KNOWN.test(value) ? value : "…"}`;
1061
+ const flag = important ? " !important" : "";
1062
+ const room = ECHOED - flag.length;
1063
+ return `${said.length > room ? `${said.slice(0, room - 1)}…` : said}${flag}`;
1064
+ };
1065
+ /** An element's own name's specificity: `#root`, `body > div`, `body > *`, `html`, `body`. */
1066
+ const specificityOf = (label) => label.startsWith("#")
1067
+ ? [1, 0, 0]
1068
+ : label.startsWith("body > ") && !label.endsWith("*")
1069
+ ? [0, 0, 2]
1070
+ : [0, 0, 1];
1071
+ /** A selector the agent may be told: plain characters, short. */
1072
+ const PLAIN_SELECTOR = new RegExp(`^[\\w#.:>* ()-]{1,${ECHOED}}$`, "u");
1073
+ /** One positive length taken from a whole: `calc(100vh - 4rem)`, `calc(100% - 56px)`. */
1074
+ const LESS = String.raw ` - (?:\d{1,6}(?:\.\d{1,4})?|\.\d{1,4})(?:px|rem|em|%|[dsl]?vh)\s?\)`;
1075
+ const SCREEN = new RegExp(String.raw `^(?:100[dsl]?vh|calc\(\s?100[dsl]?vh${LESS})$`, "u");
1076
+ /** 100% of the parent, less something: one screen where the parent is. */
1077
+ const PARENT = new RegExp(String.raw `^(?:100%|calc\(\s?100%${LESS})$`, "u");
1078
+ /** Heights that are the content's (the box grows with what it holds). */
1079
+ const CONTENT_HEIGHT = /^(?:auto|none|fit-content|min-content|max-content)$/u;
1080
+ /** A display that lays its children out by flex or grid: their heights are its to give. */
1081
+ const FLEX_OR_GRID = /^(?:(?:block|inline) )?(?:inline-)?(?:flex|grid)$/u;
1082
+ const CLIPS = new Set(["hidden", "clip"]);
1083
+ const SCROLLS = new Set(["auto", "scroll", "overlay"]);
1084
+ const RESET = new Set(["initial", "unset", "revert", "revert-layer"]);
1085
+ const lineOf = (text, index) => {
1086
+ let line = 1;
1087
+ for (let at = text.indexOf("\n"); at >= 0 && at < index; at = text.indexOf("\n", at + 1)) {
1088
+ line += 1;
1089
+ }
1090
+ return line;
1091
+ };
1092
+ /**
1093
+ * Whether `page`'s own styles hold it to one screen, and what to tell the agent; null where they
1094
+ * don't (or where it can't tell). `sheet` finds what the page links (a version's own files).
1095
+ */
1096
+ export function scrollLock(page, options) {
1097
+ const shared = options.budget ?? { bytes: Infinity, steps: Infinity, spent: false };
1098
+ if (shared.spent) {
1099
+ return null;
1100
+ }
1101
+ const scanned = scanPage(page);
1102
+ const pageSource = { path: options.path, text: page };
1103
+ const nodeOf = (tag, name, label, child) => {
1104
+ const style = attribute(tag, "style");
1105
+ const classes = attribute(tag, "class");
1106
+ return {
1107
+ label,
1108
+ tag: name,
1109
+ id: attribute(tag, "id")?.value ?? "",
1110
+ classes: classesOf(classes?.value ?? ""),
1111
+ onlyChild: child && scanned.childCount === 1,
1112
+ firstChild: child && scanned.children[0] === tag,
1113
+ style: style === undefined || tag === null ? null : { text: style.value, at: tag.at + style.at },
1114
+ classAt: tag === null || classes === undefined ? 0 : tag.at + classes.at,
1115
+ candidates: new Map(),
1116
+ values: new Map(),
1117
+ };
1118
+ };
1119
+ const chain = [
1120
+ nodeOf(scanned.html, "html", "html", false),
1121
+ nodeOf(scanned.body, "body", "body", false),
1122
+ ];
1123
+ const rootTag = scanned.body !== null && scanned.contentCount === 1 ? scanned.content[0] : undefined;
1124
+ if (rootTag !== undefined) {
1125
+ const id = attribute(rootTag, "id")?.value ?? "";
1126
+ // Page text told to the agent: `#id` for a plain id, at most ECHOED characters; else its tag
1127
+ // where HTML has it (a custom element's name is the page's own).
1128
+ const named = /^[a-z_][\w-]*$/iu.test(id) && id.length < ECHOED;
1129
+ const tag = HTML_TAGS.has(rootTag.name) ? rootTag.name : "*";
1130
+ chain.push(nodeOf(rootTag, rootTag.name, named ? `#${id}` : `body > ${tag}`, true));
1131
+ }
1132
+ // Each stylesheet is asked for once per place it is named from, and read once (`take`).
1133
+ const linked = options.sheet;
1134
+ const asked = new Map();
1135
+ const find = (href, from) => {
1136
+ if (linked === undefined) {
1137
+ return null;
1138
+ }
1139
+ const key = `${from}\n${href}`;
1140
+ if (!asked.has(key)) {
1141
+ asked.set(key, linked(href, from));
1142
+ }
1143
+ return asked.get(key) ?? null;
1144
+ };
1145
+ const cascade = new Cascade(chain, find, shared);
1146
+ const from = options.path ?? "";
1147
+ for (const sheet of scanned.sheets) {
1148
+ const media = attribute(sheet.tag, "media")?.value.trim() ?? "";
1149
+ if (media !== "" && !/^(?:only\s+)?(?:all|screen)$/iu.test(media)) {
1150
+ continue;
1151
+ }
1152
+ if (sheet.kind === "style") {
1153
+ if (!cascade.inline(sheet.end - sheet.start)) {
1154
+ if (shared.spent) {
1155
+ return null;
1156
+ }
1157
+ continue;
1158
+ }
1159
+ const text = withoutComments(page.slice(sheet.start, sheet.end));
1160
+ cascade.sheet(text, 0, text.length, {
1161
+ source: pageSource,
1162
+ base: sheet.start,
1163
+ layer: null,
1164
+ depth: 0,
1165
+ from,
1166
+ });
1167
+ continue;
1168
+ }
1169
+ const rel = (attribute(sheet.tag, "rel")?.value ?? "").toLowerCase().split(/\s+/u);
1170
+ const href = attribute(sheet.tag, "href")?.value ?? "";
1171
+ if (!rel.includes("stylesheet") ||
1172
+ rel.includes("alternate") ||
1173
+ attribute(sheet.tag, "disabled") !== undefined ||
1174
+ href === "") {
1175
+ continue;
1176
+ }
1177
+ cascade.file(find(href, from), null);
1178
+ }
1179
+ for (const node of chain) {
1180
+ if (node.style !== null) {
1181
+ cascade.declarations(node.style.text, 0, node.style.text.length, [{ node, specificity: [0, 0, 0], selector: "" }], { layer: null, inline: true }, pageSource, node.style.at);
1182
+ }
1183
+ }
1184
+ if (scanned.tailwind) {
1185
+ for (const node of chain) {
1186
+ for (const name of node.classes) {
1187
+ const arbitrary = ARBITRARY_HEIGHT.exec(name);
1188
+ // As Tailwind writes it: `_` is a space, and calc() has spaces around - and + (its CSS
1189
+ // needs them): `h-[calc(100vh-4rem)]` is `calc(100vh - 4rem)`.
1190
+ const raw = (arbitrary?.[2] ?? "").replaceAll("_", " ").toLowerCase();
1191
+ const height = raw.startsWith("calc(")
1192
+ ? raw.replace(/\s*([+-])\s*/gu, " $1 ").replace(/\(\s+/gu, "(")
1193
+ : raw;
1194
+ const utility = Object.hasOwn(UTILITIES, name)
1195
+ ? UTILITIES[name]
1196
+ : arbitrary === null
1197
+ ? undefined
1198
+ : [arbitrary[1] === undefined ? "height" : "max-height", height];
1199
+ // An arbitrary class is page text: told as it is only where its value is of a known shape.
1200
+ const written = arbitrary === null || SCREEN.test(height) || PARENT.test(height)
1201
+ ? name
1202
+ : `${arbitrary[1] ?? ""}h-[…]`;
1203
+ if (utility !== undefined) {
1204
+ cascade.set(node, utility[0], utility[1], { important: false, layer: null, inline: false, specificity: [0, 1, 0] }, { source: pageSource, at: node.classAt, selector: "", written, kind: "utility" });
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ if (shared.spent) {
1210
+ // Past the version's budget: this page can't be told, nor the ones after it.
1211
+ return null;
1212
+ }
1213
+ cascade.resolve();
1214
+ // Something in the page's own markup below body scrolls itself: the page may scroll in it (the
1215
+ // manual's line on the wheel says the rest). Not a hold the check can be sure of. A scroll rule
1216
+ // counts only where it matches an element the markup has: an app's stylesheet has many for
1217
+ // boxes a page never draws. Not the root's own rules: it is in the cascade, and its computed
1218
+ // values say whether it scrolls the page (one screen tall) or grows with it (`scrollBox`).
1219
+ const outer = chain.slice(0, 2);
1220
+ const rooted = chain.length > 2;
1221
+ // Each page's steps, within what the version has left.
1222
+ const allowed = Math.min(MATCH_STEPS, shared.steps);
1223
+ const budget = { steps: allowed };
1224
+ const scrollsInside = scanned.styleScrolls ||
1225
+ (scanned.tailwind && scanned.classScrolls) ||
1226
+ cascade.scrollSelectors.some((selector) => scanned.below.some((path) => {
1227
+ if (rooted && path.length === 1) {
1228
+ return false;
1229
+ }
1230
+ const elements = [...outer, ...path];
1231
+ return matches(selector, elements, elements.length - 1, budget);
1232
+ }));
1233
+ shared.steps -= allowed - Math.max(0, budget.steps);
1234
+ if (allowed < MATCH_STEPS && budget.steps < allowed && budget.steps <= 0) {
1235
+ // The version's steps ran out on this page: it can't be told, nor the ones after it.
1236
+ shared.spent = true;
1237
+ return null;
1238
+ }
1239
+ if (scrollsInside) {
1240
+ return null;
1241
+ }
1242
+ // Drawn by its script (body holds an empty root at most): a box it draws may scroll the content.
1243
+ const drawn = scanned.scripted && scanned.contentBelow <= 1 && !scanned.texted;
1244
+ // Each element's computed values, from the outside in.
1245
+ const value = (node, property) => {
1246
+ const found = node.values.get(property);
1247
+ return found === undefined || RESET.has(found.value) ? undefined : found;
1248
+ };
1249
+ const overflowY = (node) => {
1250
+ const y = value(node, "overflow-y")?.value ?? "visible";
1251
+ const x = value(node, "overflow-x")?.value ?? "visible";
1252
+ // One axis that isn't visible or clip makes the other's visible auto (and its clip hidden).
1253
+ if (y === "visible" && (CLIPS.has(x) || SCROLLS.has(x)) && x !== "clip") {
1254
+ return "auto";
1255
+ }
1256
+ return y;
1257
+ };
1258
+ const htmlVisible = (() => {
1259
+ const html = chain[0];
1260
+ return (html !== undefined &&
1261
+ (value(html, "overflow-x")?.value ?? "visible") === "visible" &&
1262
+ (value(html, "overflow-y")?.value ?? "visible") === "visible");
1263
+ })();
1264
+ const states = [];
1265
+ for (const [index, node] of chain.entries()) {
1266
+ const parent = index === 0 ? true : (states[index - 1]?.screen ?? false);
1267
+ const position = value(node, "position");
1268
+ const positioned = position?.value === "fixed" || position?.value === "absolute";
1269
+ const shown = [];
1270
+ const tall = (property) => {
1271
+ const found = value(node, property);
1272
+ const is = found !== undefined &&
1273
+ (SCREEN.test(found.value) || (PARENT.test(found.value) && (parent || positioned)));
1274
+ if (is && found !== undefined) {
1275
+ shown.push(found);
1276
+ }
1277
+ return is;
1278
+ };
1279
+ const top = value(node, "top");
1280
+ const bottom = value(node, "bottom");
1281
+ const spanned = positioned &&
1282
+ top !== undefined &&
1283
+ bottom !== undefined &&
1284
+ top.value !== "auto" &&
1285
+ bottom.value !== "auto";
1286
+ if (spanned) {
1287
+ shown.unshift(top, bottom);
1288
+ }
1289
+ const height = tall("height");
1290
+ const maxHeight = tall("max-height");
1291
+ if (positioned && position !== undefined && (spanned || height || maxHeight)) {
1292
+ shown.unshift(position);
1293
+ }
1294
+ states.push({ screen: height || maxHeight || spanned, shown, position: position?.value ?? "" });
1295
+ }
1296
+ // The root scrolling in a height the check can't read, in a body one screen tall: its own box,
1297
+ // as an inner one is (no warning). Under a flex or grid body (its height is the layout's), or a
1298
+ // height of a shape it doesn't know (a length, calc(), min(), var(), an arbitrary class). Not a
1299
+ // height that is the content's, or 100% of a body that is, nor under a body that grows with the
1300
+ // page: then it grows too.
1301
+ const unread = (index) => {
1302
+ const node = chain[index];
1303
+ const parent = chain[index - 1];
1304
+ if (index !== 2 || node === undefined || parent === undefined || !states[index - 1]?.screen) {
1305
+ return false;
1306
+ }
1307
+ if (FLEX_OR_GRID.test(value(parent, "display")?.value ?? "")) {
1308
+ return true;
1309
+ }
1310
+ return ["height", "max-height"].some((property) => {
1311
+ const found = value(node, property)?.value;
1312
+ return found !== undefined && !CONTENT_HEIGHT.test(found) && !PARENT.test(found);
1313
+ });
1314
+ };
1315
+ const scrollBox = (index) => {
1316
+ const node = chain[index];
1317
+ return (node !== undefined &&
1318
+ SCROLLS.has(overflowY(node)) &&
1319
+ ((states[index]?.screen ?? false) || unread(index)));
1320
+ };
1321
+ const holds = [];
1322
+ for (const [index, node] of chain.entries()) {
1323
+ const state = states[index];
1324
+ if (state === undefined) {
1325
+ continue;
1326
+ }
1327
+ if (chain.slice(index + 1).some((_, deeper) => scrollBox(index + 1 + deeper))) {
1328
+ continue;
1329
+ }
1330
+ const clips = CLIPS.has(overflowY(node));
1331
+ const overflow = value(node, "overflow-y");
1332
+ const clipped = clips && (index === 0 ? true : index === 1 ? state.screen || htmlVisible : state.screen);
1333
+ const fixed = state.position === "fixed" && state.screen && !SCROLLS.has(overflowY(node));
1334
+ if (!clipped && !fixed) {
1335
+ continue;
1336
+ }
1337
+ const shown = [...state.shown, ...(clips && overflow !== undefined ? [overflow] : [])];
1338
+ const at = clipped && overflow !== undefined ? overflow : (shown[0] ?? overflow);
1339
+ if (at !== undefined) {
1340
+ holds.push({ node, shown: [...new Set(shown)], at });
1341
+ }
1342
+ }
1343
+ const first = holds[0];
1344
+ if (first === undefined) {
1345
+ return null;
1346
+ }
1347
+ // What holds it, as the agent wrote it: "html and body (height: 100%; overflow: hidden)".
1348
+ const written = (hold, kind) => [
1349
+ ...new Set(hold.shown.filter((each) => each.kind === kind).map((each) => each.written)),
1350
+ ];
1351
+ const described = (hold) => {
1352
+ const inline = written(hold, "inline");
1353
+ const utilities = written(hold, "utility");
1354
+ return [
1355
+ written(hold, "rule").join("; "),
1356
+ inline.length === 0 ? "" : `style="${inline.join("; ")}"`,
1357
+ utilities.length === 0 ? "" : `class ${utilities.join(" ")}`,
1358
+ ]
1359
+ .filter((each) => each !== "")
1360
+ .join("; ");
1361
+ };
1362
+ const groups = [];
1363
+ for (const hold of holds) {
1364
+ const what = described(hold);
1365
+ const last = groups.at(-1);
1366
+ if (last !== undefined && last.what === what) {
1367
+ last.labels.push(hold.node.label);
1368
+ }
1369
+ else {
1370
+ groups.push({ labels: [hold.node.label], what });
1371
+ }
1372
+ }
1373
+ const and = (items) => items.length <= 1
1374
+ ? (items[0] ?? "")
1375
+ : `${items.slice(0, -1).join(", ")} and ${items.at(-1) ?? ""}`;
1376
+ const what = and(groups.map((group) => `${and(group.labels)} (${group.what})`));
1377
+ // The fix: a later rule that undoes the rules' values, under their own selectors (so it wins
1378
+ // by coming later); what style="" and utility classes say is taken out where it is.
1379
+ const rules = holds.flatMap((hold) => hold.shown.filter((each) => each.kind === "rule"));
1380
+ // Where an element's own name stands for a rule's selector, the rule may outrank it: then the
1381
+ // fix is !important, or it couldn't win.
1382
+ let outranked = false;
1383
+ const selectors = [
1384
+ ...new Set(holds.flatMap((hold) => {
1385
+ const own = hold.shown.filter((each) => each.kind === "rule");
1386
+ const strongest = own.reduce((best, each) => best === undefined || compare(each.specificity, best.specificity) > 0 ? each : best, undefined);
1387
+ // A selector the agent may be told as it is; else the element's own name.
1388
+ if (strongest === undefined) {
1389
+ return [];
1390
+ }
1391
+ if (PLAIN_SELECTOR.test(strongest.selector)) {
1392
+ return [strongest.selector];
1393
+ }
1394
+ outranked ||= compare(strongest.specificity, specificityOf(hold.node.label)) > 0;
1395
+ return [hold.node.label];
1396
+ })),
1397
+ ];
1398
+ const says = (prefixes) => rules.some((each) => prefixes.some((prefix) => each.written.startsWith(prefix)));
1399
+ const important = outranked || rules.some((each) => each.important) ? " !important" : "";
1400
+ const reset = [
1401
+ says(["height", "inset", "top", "bottom", "block-size"]) ? "height: auto" : null,
1402
+ says(["max-height", "max-block-size"]) ? "max-height: none" : null,
1403
+ says(["overflow"]) ? "overflow: visible" : null,
1404
+ says(["position"]) ? "position: static" : null,
1405
+ ]
1406
+ .filter((each) => each !== null)
1407
+ .map((each) => `${each}${important}`);
1408
+ const fixes = [];
1409
+ if (selectors.length > 0 && reset.length > 0) {
1410
+ fixes.push(`add ${selectors.join(", ")} { ${reset.join("; ")} } after those rules`);
1411
+ }
1412
+ for (const hold of holds) {
1413
+ const inline = written(hold, "inline");
1414
+ if (inline.length > 0) {
1415
+ fixes.push(`take ${inline.join("; ")} out of ${hold.node.label}'s style attribute`);
1416
+ }
1417
+ const utilities = written(hold, "utility");
1418
+ if (utilities.length > 0) {
1419
+ fixes.push(`take ${utilities.join(" ")} off ${hold.node.label}'s class`);
1420
+ }
1421
+ }
1422
+ return {
1423
+ message: drawn
1424
+ ? `The ${options.noun} looks held to one screen in its frame: ${what} hold${holds.length === 1 ? "s" : ""} it there, and what's below can't be reached. If it is meant to fit one screen, or a box its script draws scrolls the content, ignore this; otherwise let it scroll as a document: ${and(fixes)}.`
1425
+ : `The ${options.noun} won't scroll in its frame: ${what} hold${holds.length === 1 ? "s" : ""} it to one screen, and what's below can't be reached. Unless it is meant to fit one screen, let it scroll as a document: ${and(fixes)}.`,
1426
+ ...(first.at.source.path === undefined ? {} : { path: first.at.source.path }),
1427
+ line: lineOf(first.at.source.text, first.at.at),
1428
+ };
1429
+ }