@jini-ai/diagnostics 0.1.2 → 0.5.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 (69) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +114 -0
  3. package/dist/agent-logs.d.ts +9 -4
  4. package/dist/agent-logs.js +14 -15
  5. package/dist/domain-dns/index.d.ts +136 -0
  6. package/dist/domain-dns/index.js +117 -0
  7. package/dist/index.d.ts +41 -3
  8. package/dist/index.js +38 -1
  9. package/dist/manifest.d.ts +22 -16
  10. package/dist/manifest.js +9 -19
  11. package/dist/node-ports.d.ts +6 -0
  12. package/dist/node-ports.js +57 -0
  13. package/dist/observability/config.d.ts +24 -0
  14. package/dist/observability/config.js +21 -0
  15. package/dist/observability/hooks.d.ts +19 -0
  16. package/dist/observability/hooks.js +32 -0
  17. package/dist/observability/index.d.ts +17 -0
  18. package/dist/observability/index.js +16 -0
  19. package/dist/observability/instrumentation.d.ts +61 -0
  20. package/dist/observability/instrumentation.js +139 -0
  21. package/dist/observability/node.d.ts +12 -0
  22. package/dist/observability/node.js +15 -0
  23. package/dist/observability/noop.d.ts +7 -0
  24. package/dist/observability/noop.js +22 -0
  25. package/dist/observability/otel.d.ts +28 -0
  26. package/dist/observability/otel.js +120 -0
  27. package/dist/observability/ports.d.ts +150 -0
  28. package/dist/observability/ports.js +2 -0
  29. package/dist/ports.d.ts +45 -0
  30. package/dist/ports.js +2 -0
  31. package/dist/redaction/secrets-only.d.ts +44 -0
  32. package/dist/redaction/secrets-only.js +179 -0
  33. package/dist/redaction.d.ts +12 -3
  34. package/dist/redaction.js +18 -8
  35. package/dist/sources.d.ts +22 -12
  36. package/dist/sources.js +22 -42
  37. package/dist/types.d.ts +24 -0
  38. package/dist/types.js +2 -0
  39. package/dist/web-evidence/browser-port.d.ts +166 -0
  40. package/dist/web-evidence/browser-port.js +6 -0
  41. package/dist/web-evidence/collect-page-evidence.d.ts +160 -0
  42. package/dist/web-evidence/collect-page-evidence.js +215 -0
  43. package/dist/web-evidence/index.d.ts +5 -0
  44. package/dist/web-evidence/index.js +5 -0
  45. package/dist/web-evidence/page-structure-script.d.ts +53 -0
  46. package/dist/web-evidence/page-structure-script.js +338 -0
  47. package/dist/web-evidence/page-work-budget.d.ts +27 -0
  48. package/dist/web-evidence/page-work-budget.js +53 -0
  49. package/dist/web-evidence/playwright-browser.d.ts +131 -0
  50. package/dist/web-evidence/playwright-browser.js +349 -0
  51. package/dist/web-evidence/same-origin.d.ts +126 -0
  52. package/dist/web-evidence/same-origin.js +141 -0
  53. package/dist/zip.d.ts +8 -3
  54. package/dist/zip.js +23 -16
  55. package/package.json +50 -5
  56. package/dist/agent-logs.d.ts.map +0 -1
  57. package/dist/agent-logs.js.map +0 -1
  58. package/dist/contract.d.ts.map +0 -1
  59. package/dist/contract.js.map +0 -1
  60. package/dist/index.d.ts.map +0 -1
  61. package/dist/index.js.map +0 -1
  62. package/dist/manifest.d.ts.map +0 -1
  63. package/dist/manifest.js.map +0 -1
  64. package/dist/redaction.d.ts.map +0 -1
  65. package/dist/redaction.js.map +0 -1
  66. package/dist/sources.d.ts.map +0 -1
  67. package/dist/sources.js.map +0 -1
  68. package/dist/zip.d.ts.map +0 -1
  69. package/dist/zip.js.map +0 -1
@@ -0,0 +1,215 @@
1
+ import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
2
+ import { isSameOriginUrl, normalizeSitePath, resolveSameOriginUrl, verifiedOriginToBaseUrl } from "./same-origin.js";
3
+ /**
4
+ * Every bound this tool operates under, in one place so the values reported to the caller and the
5
+ * values actually enforced cannot drift apart (they are the same constant).
6
+ *
7
+ * The numbers are deliberately small. This is an interactive tool an agent calls mid-conversation,
8
+ * not a crawler: five pages is enough to screen a home page, a form page, and the policy pages,
9
+ * and a caller who needs more can call again with the next five and say so in its report.
10
+ */
11
+ export const SITE_EVIDENCE_LIMITS = {
12
+ /** Hard cap on pages per call. Excess requested paths are returned as `skipped`. */
13
+ maxPagesPerCall: 5,
14
+ /** Per-page navigation + settle budget, including evaluation and cookie capture. */
15
+ maxPageLoadMs: 15_000,
16
+ /** Whole-call deadline. Once passed, remaining pages are `skipped` with `deadline`. */
17
+ maxTotalMs: 60_000,
18
+ /** Cap on the visible-text excerpt returned per page. */
19
+ maxTextExcerptChars: 2_000,
20
+ maxCookies: 100,
21
+ maxRequests: 200,
22
+ /** Cap per accessibility category (landmarks, headings, images, form controls). */
23
+ maxAccessibilityNodesPerCategory: 200,
24
+ maxContrastSamples: 40,
25
+ };
26
+ /** Stated in every result. Not decoration: it is the tool half of the no-verdict contract, and it
27
+ * travels with the data into whatever context the model is reasoning in. */
28
+ export const SITE_EVIDENCE_DISCLAIMER = "Observed evidence only. This tool reports what was rendered, requested, and set when these pages " +
29
+ "were loaded. It does not evaluate, score, or determine compliance with GDPR, CCPA/CPRA, WCAG, or " +
30
+ "any other law or standard, and the absence of an observation is not evidence that something is " +
31
+ "absent — it may mean it was not inspected.";
32
+ /**
33
+ * Collects observed evidence for up to {@link SITE_EVIDENCE_LIMITS.maxPagesPerCall} pages of this
34
+ * workspace's own published site.
35
+ *
36
+ * @param deps - Requested paths, verified-origin resolver, browser factory, and observation policy.
37
+ * @param input - Optional clock, accessibility capture and consent selector.
38
+ * @returns Observed evidence plus an explicit account of everything that was not observed and why.
39
+ * @throws The origin port's error if the workspace has no verified
40
+ * canonical origin. Deliberately propagated rather than converted into a per-page skip: with no
41
+ * origin there is no same-origin boundary to enforce, and guessing one from a request host is
42
+ * precisely what F2 forbids. The tool handler turns it into an actionable message.
43
+ * @complexity O(p) page loads bounded by `maxPagesPerCall`, each bounded by `maxPageLoadMs`, the
44
+ * whole call bounded by `maxTotalMs`. Space is bounded by the per-category caps above.
45
+ * See docs/decisions/DR-001-trusted-evidence-addresses.md.
46
+ */
47
+ export async function collectPageEvidence(deps, input = {}) {
48
+ const clock = input.clock;
49
+ const now = clock ? () => clock.nowMs() : Date.now;
50
+ const startedAt = now();
51
+ const origin = await deps.originRegistry.canonicalOrigin({ workspaceId: deps.workspaceId });
52
+ const originBaseUrl = verifiedOriginToBaseUrl({ origin });
53
+ const { accepted, skipped } = partitionRequestedPaths(deps.paths);
54
+ const availability = await deps.openBrowser({});
55
+ if (!availability.available) {
56
+ const reason = deps.observationPolicy.redactMessage({ message: availability.reason });
57
+ return {
58
+ schemaVersion: "1",
59
+ collectedAt: new Date(startedAt).toISOString(),
60
+ origin: originBaseUrl,
61
+ browser: { status: "unavailable", reason },
62
+ consentTransition: consentTransitionReport(input.consentAcceptSelector),
63
+ limits: SITE_EVIDENCE_LIMITS,
64
+ pages: [],
65
+ skipped: [
66
+ ...skipped,
67
+ ...accepted.map((path) => skip(path, "browser-unavailable", reason)),
68
+ ],
69
+ disclaimer: SITE_EVIDENCE_DISCLAIMER,
70
+ };
71
+ }
72
+ const pages = [];
73
+ const runtimeSkipped = [];
74
+ try {
75
+ for (const path of accepted) {
76
+ const remainingMs = SITE_EVIDENCE_LIMITS.maxTotalMs - (now() - startedAt);
77
+ if (remainingMs <= 0) {
78
+ runtimeSkipped.push(skip(path, "deadline", `the ${SITE_EVIDENCE_LIMITS.maxTotalMs}ms whole-call budget was exhausted before this page was loaded`));
79
+ continue;
80
+ }
81
+ // A THROWING `observe()` (a port implementation that does not honor the `{ ok: false, reason }`
82
+ // contract for every failure — e.g. the page navigating away between the load and the read
83
+ // that follows it) must not end the whole run any more than an ordinary `ok: false` does. One
84
+ // bad page is recorded as skipped; every OTHER requested page still gets its own attempt.
85
+ try {
86
+ // The port's timeout is advisory for custom adapters; bound our own await as well.
87
+ const timeoutMs = Math.min(SITE_EVIDENCE_LIMITS.maxPageLoadMs, remainingMs);
88
+ const outcome = await new PageWorkBudget({ timeoutMs }).run({
89
+ work: () => observeOnePage(availability.browser, originBaseUrl, path, input, timeoutMs),
90
+ });
91
+ if (outcome.kind === "skipped") {
92
+ runtimeSkipped.push({ ...outcome.skipped, message: deps.observationPolicy.redactMessage({ message: outcome.skipped.message }) });
93
+ }
94
+ else {
95
+ pages.push({ ...outcome.page, observation: deps.observationPolicy.redactObservation({ observation: outcome.page.observation }) });
96
+ }
97
+ }
98
+ catch (error) {
99
+ const reason = error instanceof PageWorkTimeout && remainingMs <= SITE_EVIDENCE_LIMITS.maxPageLoadMs ? "deadline" : "navigation-failed";
100
+ runtimeSkipped.push(skip(path, reason, deps.observationPolicy.redactMessage({ message: messageOf(error) })));
101
+ }
102
+ }
103
+ }
104
+ finally {
105
+ // Release is still attempted after expiry; cleanup cannot add an unbounded wait to the call.
106
+ await new PageWorkBudget({ timeoutMs: Math.max(0, SITE_EVIDENCE_LIMITS.maxTotalMs - (now() - startedAt)) })
107
+ .release({ close: () => availability.browser.close({}) });
108
+ }
109
+ return {
110
+ schemaVersion: "1",
111
+ collectedAt: new Date(startedAt).toISOString(),
112
+ origin: originBaseUrl,
113
+ browser: { status: "available" },
114
+ consentTransition: consentTransitionReport(input.consentAcceptSelector),
115
+ limits: SITE_EVIDENCE_LIMITS,
116
+ pages,
117
+ skipped: [...skipped, ...runtimeSkipped],
118
+ disclaimer: SITE_EVIDENCE_DISCLAIMER,
119
+ };
120
+ }
121
+ /**
122
+ * Resolves, loads, and validates exactly one requested page. Split out of
123
+ * {@link collectPageEvidence} purely to keep that function's own cognitive complexity below the
124
+ * repo's gate — the request shape, the failure handling, and the second same-origin check
125
+ * (`same-origin.ts`'s header, layer 2) are unchanged.
126
+ *
127
+ * @complexity O(1) plus one browser page load.
128
+ */
129
+ async function observeOnePage(browser, originBaseUrl, path, input, timeoutMs) {
130
+ const url = resolveSameOriginUrl({ baseUrl: originBaseUrl, path });
131
+ const result = await browser.observe({
132
+ url,
133
+ originBaseUrl,
134
+ collectAccessibility: input.collectAccessibility ?? true,
135
+ timeoutMs,
136
+ maxTextExcerptChars: SITE_EVIDENCE_LIMITS.maxTextExcerptChars,
137
+ maxCookies: SITE_EVIDENCE_LIMITS.maxCookies,
138
+ maxRequests: SITE_EVIDENCE_LIMITS.maxRequests,
139
+ maxAccessibilityNodesPerCategory: SITE_EVIDENCE_LIMITS.maxAccessibilityNodesPerCategory,
140
+ maxContrastSamples: SITE_EVIDENCE_LIMITS.maxContrastSamples,
141
+ }, input.consentAcceptSelector === undefined ? {} : { consentAcceptSelector: input.consentAcceptSelector });
142
+ if (!result.ok) {
143
+ return { kind: "skipped", skipped: skip(path, "navigation-failed", result.reason) };
144
+ }
145
+ // Second same-origin layer (`same-origin.ts`'s header, layer 2): the path could not name
146
+ // another origin, but the SERVER can redirect to one. A page that left the origin is reported
147
+ // as evidence of the redirect and its content is discarded — this tool does not inspect
148
+ // anybody else's site, including one the inspected origin chose to point at.
149
+ const finalUrl = result.observation.document.finalUrl;
150
+ if (!isSameOriginUrl({ baseUrl: originBaseUrl, candidateUrl: finalUrl })) {
151
+ return {
152
+ kind: "skipped",
153
+ skipped: skip(path, "off-origin-redirect", `redirected off the inspected origin to '${redactToOrigin(finalUrl)}' — not inspected; this tool only observes ${originBaseUrl}`),
154
+ };
155
+ }
156
+ return { kind: "observed", page: { path, url, observation: result.observation } };
157
+ }
158
+ /**
159
+ * Splits the requested paths into the ones this call will attempt and the ones it will not,
160
+ * applying the syntactic guard first and the page cap second.
161
+ *
162
+ * Order matters and is not arbitrary: validating before capping means five valid paths followed by
163
+ * an absolute URL still reports the absolute URL as `invalid-path` rather than hiding it behind
164
+ * `page-cap`, so a caller that is doing something the tool refuses always learns that it was
165
+ * refused rather than that it was merely truncated.
166
+ *
167
+ * @complexity O(n) in the requested-path count.
168
+ */
169
+ function partitionRequestedPaths(paths) {
170
+ const accepted = [];
171
+ const skipped = [];
172
+ for (const raw of paths) {
173
+ const normalized = normalizeSitePath({ raw });
174
+ if (!normalized.ok) {
175
+ skipped.push(skip(raw, "invalid-path", `${normalized.message} (${normalized.reason})`));
176
+ continue;
177
+ }
178
+ if (accepted.length >= SITE_EVIDENCE_LIMITS.maxPagesPerCall) {
179
+ skipped.push(skip(normalized.path, "page-cap", `this call already accepted the maximum of ${SITE_EVIDENCE_LIMITS.maxPagesPerCall} pages — request the remaining paths in a follow-up call`));
180
+ continue;
181
+ }
182
+ accepted.push(normalized.path);
183
+ }
184
+ return { accepted, skipped };
185
+ }
186
+ function consentTransitionReport(selector) {
187
+ if (selector === undefined) {
188
+ return {
189
+ attempted: false,
190
+ reason: "no consentAcceptSelector was supplied, so no consent interaction was performed. Every cookie and " +
191
+ "request below was observed in the pre-consent phase; nothing here shows what changes after a visitor accepts.",
192
+ };
193
+ }
194
+ return { attempted: true, selector };
195
+ }
196
+ /** Reduces an off-origin URL to its origin before it appears in a skip reason. The redirect target
197
+ * is the evidence; its path and query are somebody else's data and may carry identifiers this tool
198
+ * has no business echoing back into a model's context. */
199
+ function redactToOrigin(url) {
200
+ try {
201
+ return new URL(url).origin;
202
+ }
203
+ catch {
204
+ return "(unparseable URL)";
205
+ }
206
+ }
207
+ function skip(path, reason, message) {
208
+ return { path, reason, message };
209
+ }
210
+ /** Same tiny helper as `playwright-browser.ts`'s own — duplicated rather than imported, matching
211
+ * this feature's existing convention for a helper this small. */
212
+ function messageOf(error) {
213
+ return error instanceof Error ? error.message : String(error);
214
+ }
215
+ //# sourceMappingURL=collect-page-evidence.js.map
@@ -0,0 +1,5 @@
1
+ export * from "./browser-port.js";
2
+ export * from "./collect-page-evidence.js";
3
+ export * from "./same-origin.js";
4
+ export { collectPageStructure, type PageStructureCapture, type PageStructureLimits } from "./page-structure-script.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ export * from "./browser-port.js";
2
+ export * from "./collect-page-evidence.js";
3
+ export * from "./same-origin.js";
4
+ export { collectPageStructure } from "./page-structure-script.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @file `collectPageStructure` — the function that runs INSIDE the page, serialized across to
3
+ * Chromium by `page.evaluate` in `playwright-browser.ts`.
4
+ *
5
+ * ---------------------------------------------------------------------------
6
+ * Read this before editing: this function has no scope
7
+ * ---------------------------------------------------------------------------
8
+ * Playwright serializes the function source and evaluates it in the browser. It therefore CANNOT
9
+ * reference anything outside its own body — no import, no module-level constant, no helper declared
10
+ * beside it in this file. Every helper it uses is nested inside it. That is not a style choice and
11
+ * a "cleanup" that hoists a helper out will fail at runtime, in the browser, with a
12
+ * `ReferenceError` no typechecker can see.
13
+ *
14
+ * Its return value crosses a structured-clone boundary, so it may only contain JSON-ish values:
15
+ * no DOM nodes, no functions, no `undefined` in object positions.
16
+ *
17
+ * ---------------------------------------------------------------------------
18
+ * What it does and does not read
19
+ * ---------------------------------------------------------------------------
20
+ * It reads structure: landmarks, heading levels, image alt text, how form controls are labelled,
21
+ * and colour pairs. It never reads a form control's `.value`, and it never reads
22
+ * `document.cookie` — cookies come from the browser context's own jar in the adapter, where the
23
+ * value can be dropped rather than copied.
24
+ *
25
+ * The contrast numbers are SAMPLES over a bounded set of text-bearing elements, not a full-page
26
+ * audit. `AccessibilityEvidence.truncated` names every category that hit its cap so a report can
27
+ * never read a sample as a census.
28
+ */
29
+ import type { AccessibilityEvidence } from "./browser-port.js";
30
+ export interface PageStructureLimits {
31
+ readonly maxTextExcerptChars: number;
32
+ readonly maxNodesPerCategory: number;
33
+ readonly maxContrastSamples: number;
34
+ readonly collectAccessibility: boolean;
35
+ }
36
+ export interface PageStructureCapture {
37
+ readonly title: string;
38
+ readonly lang: string | null;
39
+ readonly textExcerpt: string;
40
+ readonly textTruncated: boolean;
41
+ readonly accessibility: AccessibilityEvidence;
42
+ }
43
+ /**
44
+ * Walks the rendered document and returns the structural evidence the compliance skill cites.
45
+ *
46
+ * Runs in the browser. See this file's header for the constraints that implies.
47
+ *
48
+ * @param limits - Per-category caps, passed in rather than hardcoded so the collector's single
49
+ * `SITE_EVIDENCE_LIMITS` constant is the only place any bound is defined.
50
+ * @complexity O(n) in rendered element count, with every output list capped by `limits`.
51
+ */
52
+ export declare function collectPageStructure(limits: PageStructureLimits): PageStructureCapture;
53
+ //# sourceMappingURL=page-structure-script.d.ts.map
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Walks the rendered document and returns the structural evidence the compliance skill cites.
3
+ *
4
+ * Runs in the browser. See this file's header for the constraints that implies.
5
+ *
6
+ * @param limits - Per-category caps, passed in rather than hardcoded so the collector's single
7
+ * `SITE_EVIDENCE_LIMITS` constant is the only place any bound is defined.
8
+ * @complexity O(n) in rendered element count, with every output list capped by `limits`.
9
+ */
10
+ export function collectPageStructure(limits) {
11
+ const truncated = [];
12
+ /** Whether `current` should end the selector walk, and if so, the segment to use: `html`/`body`
13
+ * by tag, or any ancestor's own `id`. Nested (not module-scope) alongside every other helper here
14
+ * — see this file's header for why that is not optional. */
15
+ function terminalSegment(current) {
16
+ const tag = current.tagName.toLowerCase();
17
+ if (tag === "html" || tag === "body")
18
+ return tag;
19
+ if (current.id)
20
+ return `#${CSS.escape(current.id)}`;
21
+ return null;
22
+ }
23
+ /** The `tag` or `tag:nth-of-type(n)` segment for `current` among its siblings under `parent`. */
24
+ function siblingSegment(current, parent) {
25
+ const tag = current.tagName.toLowerCase();
26
+ const siblings = Array.from(parent.children).filter((child) => child.tagName === current.tagName);
27
+ return siblings.length > 1 ? `${tag}:nth-of-type(${siblings.indexOf(current) + 1})` : tag;
28
+ }
29
+ /** A short, re-checkable CSS path for one element. Prefers an `id` (stable and readable), then a
30
+ * bounded `nth-of-type` chain. The path is a CITATION — a human must be able to paste it into
31
+ * devtools and land on the same element — so readability beats theoretical uniqueness. */
32
+ function selectorFor(element) {
33
+ if (element.id)
34
+ return `#${CSS.escape(element.id)}`;
35
+ const parts = [];
36
+ let current = element;
37
+ let depth = 0;
38
+ while (current && current.nodeType === 1 && depth < 5) {
39
+ const terminal = terminalSegment(current);
40
+ if (terminal !== null) {
41
+ parts.unshift(terminal);
42
+ break;
43
+ }
44
+ const parent = current.parentElement;
45
+ if (!parent) {
46
+ parts.unshift(current.tagName.toLowerCase());
47
+ break;
48
+ }
49
+ parts.unshift(siblingSegment(current, parent));
50
+ current = parent;
51
+ depth += 1;
52
+ }
53
+ return parts.join(" > ");
54
+ }
55
+ function textOf(element, max) {
56
+ const raw = (element.textContent ?? "").replace(/\s+/g, " ").trim();
57
+ return raw.length > max ? `${raw.slice(0, max)}…` : raw;
58
+ }
59
+ // Each of the following is one accessible-name STRATEGY, tried in the order the accessible-name
60
+ // computation spec prefers: `aria-label`, then `aria-labelledby`, then an explicit `<label for>`,
61
+ // then a wrapping `<label>`, then `title`. Each returns `null` to fall through to the next; the
62
+ // order and every reject/accept condition are unchanged from the pre-split function.
63
+ function accessibleNameFromAriaLabel(element) {
64
+ const ariaLabel = element.getAttribute("aria-label");
65
+ return ariaLabel?.trim() ? { name: ariaLabel.trim(), source: "aria-label" } : null;
66
+ }
67
+ function accessibleNameFromAriaLabelledBy(element) {
68
+ const labelledBy = element.getAttribute("aria-labelledby");
69
+ if (!labelledBy)
70
+ return null;
71
+ const names = labelledBy
72
+ .split(/\s+/)
73
+ .map((id) => document.getElementById(id))
74
+ .filter((node) => node !== null)
75
+ .map((node) => textOf(node, 120))
76
+ .filter((value) => value.length > 0);
77
+ return names.length > 0 ? { name: names.join(" "), source: "aria-labelledby" } : null;
78
+ }
79
+ function accessibleNameFromLabelFor(element) {
80
+ if (!element.id)
81
+ return null;
82
+ const forLabel = document.querySelector(`label[for="${CSS.escape(element.id)}"]`);
83
+ if (!forLabel)
84
+ return null;
85
+ const value = textOf(forLabel, 120);
86
+ return value ? { name: value, source: "label-for" } : null;
87
+ }
88
+ function accessibleNameFromLabelWrap(element) {
89
+ const wrapping = element.closest("label");
90
+ if (!wrapping)
91
+ return null;
92
+ const value = textOf(wrapping, 120);
93
+ return value ? { name: value, source: "label-wrap" } : null;
94
+ }
95
+ function accessibleNameFromTitle(element) {
96
+ const title = element.getAttribute("title");
97
+ return title?.trim() ? { name: title.trim(), source: "title" } : null;
98
+ }
99
+ function accessibleNameOf(element) {
100
+ const strategies = [
101
+ accessibleNameFromAriaLabel,
102
+ accessibleNameFromAriaLabelledBy,
103
+ accessibleNameFromLabelFor,
104
+ accessibleNameFromLabelWrap,
105
+ accessibleNameFromTitle,
106
+ ];
107
+ for (const strategy of strategies) {
108
+ const found = strategy(element);
109
+ if (found)
110
+ return found;
111
+ }
112
+ return { name: null, source: "none" };
113
+ }
114
+ function capped(items, category) {
115
+ if (items.length > limits.maxNodesPerCategory) {
116
+ truncated.push(category);
117
+ return items.slice(0, limits.maxNodesPerCategory);
118
+ }
119
+ return items;
120
+ }
121
+ // --- landmarks -----------------------------------------------------------
122
+ const LANDMARK_SELECTOR = "header,nav,main,aside,footer,form,section,[role]";
123
+ const IMPLICIT_ROLES = {
124
+ HEADER: "banner",
125
+ NAV: "navigation",
126
+ MAIN: "main",
127
+ ASIDE: "complementary",
128
+ FOOTER: "contentinfo",
129
+ FORM: "form",
130
+ SECTION: "region",
131
+ };
132
+ function collectLandmarks() {
133
+ const out = [];
134
+ for (const element of Array.from(document.querySelectorAll(LANDMARK_SELECTOR))) {
135
+ const explicit = element.getAttribute("role");
136
+ const role = explicit?.trim() ? explicit.trim() : (IMPLICIT_ROLES[element.tagName] ?? "");
137
+ if (!role)
138
+ continue;
139
+ out.push({ role, selector: selectorFor(element), accessibleName: accessibleNameOf(element).name });
140
+ }
141
+ return capped(out, "landmarks");
142
+ }
143
+ // --- headings ------------------------------------------------------------
144
+ function collectHeadings() {
145
+ const out = [];
146
+ for (const element of Array.from(document.querySelectorAll("h1,h2,h3,h4,h5,h6,[role='heading']"))) {
147
+ const tagLevel = /^H([1-6])$/.exec(element.tagName);
148
+ const ariaLevel = element.getAttribute("aria-level");
149
+ const level = tagLevel ? Number(tagLevel[1]) : ariaLevel ? Number(ariaLevel) : 0;
150
+ if (!Number.isFinite(level) || level === 0)
151
+ continue;
152
+ out.push({ level, selector: selectorFor(element), text: textOf(element, 160) });
153
+ }
154
+ return capped(out, "headings");
155
+ }
156
+ // --- images --------------------------------------------------------------
157
+ function collectImages() {
158
+ const out = [];
159
+ for (const element of Array.from(document.querySelectorAll("img"))) {
160
+ const image = element;
161
+ out.push({
162
+ selector: selectorFor(image),
163
+ // `getAttribute` rather than `.src`: the authored value is what a reviewer will look for in
164
+ // the template, and `.src` would resolve it against the document, changing the citation.
165
+ src: image.getAttribute("src") ?? "",
166
+ alt: image.hasAttribute("alt") ? image.getAttribute("alt") : null,
167
+ ariaHidden: image.getAttribute("aria-hidden") === "true",
168
+ });
169
+ }
170
+ return capped(out, "images");
171
+ }
172
+ // --- form controls -------------------------------------------------------
173
+ function collectFormControls() {
174
+ const out = [];
175
+ for (const element of Array.from(document.querySelectorAll("input,select,textarea"))) {
176
+ const type = element.getAttribute("type");
177
+ // A hidden input has no rendered presence and no labelling obligation; including it would pad
178
+ // every finding list with noise a reviewer then has to filter out by hand.
179
+ if (element.tagName === "INPUT" && type === "hidden")
180
+ continue;
181
+ const { name, source } = accessibleNameOf(element);
182
+ out.push({
183
+ selector: selectorFor(element),
184
+ tag: element.tagName.toLowerCase(),
185
+ type,
186
+ name: element.getAttribute("name"),
187
+ accessibleName: name,
188
+ labelSource: source,
189
+ required: element.hasAttribute("required") || element.getAttribute("aria-required") === "true",
190
+ });
191
+ }
192
+ return capped(out, "formControls");
193
+ }
194
+ // --- contrast ------------------------------------------------------------
195
+ function parseColor(value) {
196
+ const match = /^rgba?\(([^)]+)\)$/.exec(value.trim());
197
+ if (!match)
198
+ return null;
199
+ const parts = match[1].split(/[,\s/]+/).filter((part) => part.length > 0).map(Number);
200
+ const [r, g, b] = parts;
201
+ if (r === undefined || g === undefined || b === undefined)
202
+ return null;
203
+ const alpha = parts.length > 3 ? parts[3] : 1;
204
+ return [r, g, b, alpha];
205
+ }
206
+ function relativeLuminance([r, g, b]) {
207
+ const channel = (raw) => {
208
+ const c = raw / 255;
209
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
210
+ };
211
+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
212
+ }
213
+ function composite(fg, bg) {
214
+ const alpha = fg[3];
215
+ return [fg[0] * alpha + bg[0] * (1 - alpha), fg[1] * alpha + bg[1] * (1 - alpha), fg[2] * alpha + bg[2] * (1 - alpha), 1];
216
+ }
217
+ /** Composite translucent backgrounds from the outermost ancestor onto a white fallback.
218
+ * Images and gradients remain outside this bounded colour-pair sample. */
219
+ function effectiveBackground(element) {
220
+ const layers = [];
221
+ let current = element;
222
+ while (current) {
223
+ const parsed = parseColor(getComputedStyle(current).backgroundColor);
224
+ if (parsed && parsed[3] > 0) {
225
+ layers.push(parsed);
226
+ if (parsed[3] === 1)
227
+ break;
228
+ }
229
+ current = current.parentElement;
230
+ }
231
+ let background = [255, 255, 255, 1];
232
+ for (const layer of layers.reverse())
233
+ background = composite(layer, background);
234
+ return `rgb(${background[0]}, ${background[1]}, ${background[2]})`;
235
+ }
236
+ const CONTRAST_CANDIDATE_SELECTOR = "p,li,a,button,h1,h2,h3,h4,h5,h6,label,span,td,th";
237
+ /** Only leaf-ish text with real content: a wrapper repeats its children's colours and would crowd
238
+ * the sample set with duplicates of the same real pair. */
239
+ function hasOwnSampleableText(element) {
240
+ const text = (element.textContent ?? "").trim();
241
+ if (text.length === 0)
242
+ return false;
243
+ return !element.querySelector(CONTRAST_CANDIDATE_SELECTOR);
244
+ }
245
+ function isRenderedVisible(element, style) {
246
+ if (style.visibility === "hidden" || style.display === "none")
247
+ return false;
248
+ // display is not inherited: a hidden subtree's child can still compute display:block.
249
+ let ancestor = element.parentElement;
250
+ while (ancestor) {
251
+ if (getComputedStyle(ancestor).display === "none")
252
+ return false;
253
+ ancestor = ancestor.parentElement;
254
+ }
255
+ return true;
256
+ }
257
+ /** Computes one contrast sample for an element already known to be sampleable and visible, or
258
+ * `null` when its colours cannot be parsed.
259
+ *
260
+ * INVARIANT: `bg` can never actually be null, only `fg` can. `background` comes from
261
+ * `effectiveBackground`, which has exactly two return paths: an ancestor's `backgroundColor`
262
+ * that `parseColor` has ALREADY parsed successfully (that is what `parsed[3] > 0` requires), or
263
+ * the hardcoded fallback literal `"rgb(255, 255, 255)"`, which trivially matches `parseColor`'s
264
+ * own regex. So `parseColor(effectiveBackground(element))` is guaranteed non-null. `fg`, by
265
+ * contrast, comes straight from the browser's own `style.color` serialization, which is not
266
+ * guaranteed to be `rgb()`/`rgba()` syntax (e.g. newer CSS Color 4 syntaxes some engines may
267
+ * report) — that is the one this guard exists to catch.
268
+ *
269
+ * Kept as `!fg || !bg` (not narrowed to `!fg`) deliberately: this file's header forbids hoisting
270
+ * helpers out of `collectPageStructure`'s closure for serialization across the Playwright
271
+ * `page.evaluate` boundary (see file header), so there is no seam here that would let a test
272
+ * inject an unparseable `effectiveBackground` result without changing `effectiveBackground`'s own
273
+ * behavior. Removing the `!bg` half would encode "we are certain this never happens" as an
274
+ * assumption baked into the return type instead of a runtime check — if `effectiveBackground`'s
275
+ * fallback literal is ever changed to something not always parseable, this guard is what keeps a
276
+ * malformed sample from reaching `relativeLuminance` instead of failing loudly. */
277
+ function contrastSampleFor(element, style) {
278
+ const foreground = style.color;
279
+ const background = effectiveBackground(element);
280
+ const fg = parseColor(foreground);
281
+ const bg = parseColor(background);
282
+ if (!fg || !bg) {
283
+ truncated.push("contrastSamples:unparsed-colour");
284
+ return null;
285
+ }
286
+ const l1 = relativeLuminance(composite(fg, bg));
287
+ const l2 = relativeLuminance(bg);
288
+ const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
289
+ return {
290
+ selector: selectorFor(element),
291
+ foreground,
292
+ background,
293
+ ratio: Math.round(ratio * 100) / 100,
294
+ fontSizePx: Math.round(parseFloat(style.fontSize) * 10) / 10,
295
+ fontWeight: Number(style.fontWeight) || 400,
296
+ };
297
+ }
298
+ function collectContrastSamples() {
299
+ const out = [];
300
+ const candidates = Array.from(document.querySelectorAll(CONTRAST_CANDIDATE_SELECTOR));
301
+ for (const element of candidates) {
302
+ if (out.length >= limits.maxContrastSamples) {
303
+ truncated.push("contrastSamples");
304
+ break;
305
+ }
306
+ if (!hasOwnSampleableText(element))
307
+ continue;
308
+ const style = getComputedStyle(element);
309
+ if (!isRenderedVisible(element, style))
310
+ continue;
311
+ const sample = contrastSampleFor(element, style);
312
+ if (sample)
313
+ out.push(sample);
314
+ }
315
+ return out;
316
+ }
317
+ // --- document ------------------------------------------------------------
318
+ const bodyText = (document.body?.innerText ?? "").replace(/[ \t]+/g, " ").replace(/\n{3,}/g, "\n\n").trim();
319
+ const textTruncated = bodyText.length > limits.maxTextExcerptChars;
320
+ const accessibility = limits.collectAccessibility
321
+ ? {
322
+ landmarks: collectLandmarks(),
323
+ headings: collectHeadings(),
324
+ images: collectImages(),
325
+ formControls: collectFormControls(),
326
+ contrastSamples: collectContrastSamples(),
327
+ truncated: Array.from(new Set(truncated)),
328
+ }
329
+ : { landmarks: [], headings: [], images: [], formControls: [], contrastSamples: [], truncated: ["not-collected"] };
330
+ return {
331
+ title: document.title,
332
+ lang: document.documentElement.getAttribute("lang"),
333
+ textExcerpt: textTruncated ? bodyText.slice(0, limits.maxTextExcerptChars) : bodyText,
334
+ textTruncated,
335
+ accessibility,
336
+ };
337
+ }
338
+ //# sourceMappingURL=page-structure-script.js.map
@@ -0,0 +1,27 @@
1
+ /** Internal deadline shared by every asynchronous step of one page observation. */
2
+ export declare class PageWorkTimeout extends Error {
3
+ constructor({ timeoutMs }: {
4
+ timeoutMs: number;
5
+ });
6
+ }
7
+ /** A timeout is a budget for the whole page, not a fresh allowance for each browser operation. */
8
+ export declare class PageWorkBudget {
9
+ private readonly expiresAt;
10
+ private readonly timeoutMs;
11
+ constructor({ timeoutMs }: {
12
+ timeoutMs: number;
13
+ });
14
+ remainingMs(): number;
15
+ /** Races even APIs without native timeouts (evaluation/cookies) and never starts expired work.
16
+ * @complexity O(1) time and space apart from the injected operation. */
17
+ run<T>({ work }: {
18
+ work: () => Promise<T>;
19
+ }): Promise<T>;
20
+ /** Always initiate resource release, but a stalled close must not extend an exhausted budget.
21
+ * Pending Playwright operations are interrupted by context/browser close; late rejections are handled.
22
+ * @complexity O(1) aside from resource release. */
23
+ release({ close }: {
24
+ close: () => Promise<void>;
25
+ }): Promise<void>;
26
+ }
27
+ //# sourceMappingURL=page-work-budget.d.ts.map