@jini-ai/diagnostics 0.5.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/web-evidence/browser-port.d.ts +1 -0
- package/dist/web-evidence/collect-page-evidence.js +3 -0
- package/dist/web-evidence/lazy-browser.d.ts +52 -0
- package/dist/web-evidence/lazy-browser.js +115 -0
- package/dist/web-evidence/page-work-budget.d.ts +3 -0
- package/dist/web-evidence/page-work-budget.js +17 -4
- package/dist/web-evidence/playwright-browser.d.ts +14 -129
- package/dist/web-evidence/playwright-browser.js +67 -126
- package/dist/web-evidence/playwright-runtime.d.ts +100 -0
- package/dist/web-evidence/playwright-runtime.js +39 -0
- package/dist/web-evidence/public-page.d.ts +97 -0
- package/dist/web-evidence/public-page.js +209 -0
- package/dist/web-evidence/render-page.d.ts +135 -0
- package/dist/web-evidence/render-page.js +192 -0
- package/dist/web-evidence/request-guard.d.ts +166 -0
- package/dist/web-evidence/request-guard.js +239 -0
- package/package.json +3 -3
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The one and only module in this repository that touches a real headless browser.
|
|
3
|
+
* Implements `SiteEvidenceBrowserPort` (`browser-port.ts`) on Playwright's Chromium.
|
|
4
|
+
*
|
|
5
|
+
* ---------------------------------------------------------------------------
|
|
6
|
+
* Why the import is dynamic, and why the module's types are declared here
|
|
7
|
+
* ---------------------------------------------------------------------------
|
|
8
|
+
* The host may optionally install `playwright`; this package adds no browser dependency. The BROWSER
|
|
9
|
+
* BINARY it drives needs a separate `playwright install chromium` step in the host deployment.
|
|
10
|
+
* Installing the module alone does not supply that binary. So both halves can
|
|
11
|
+
* legitimately be missing at runtime, independently:
|
|
12
|
+
*
|
|
13
|
+
* - the module itself, on a deployment that pruned it;
|
|
14
|
+
* - the Chromium binary, on a deployment that installed the module but not the browser.
|
|
15
|
+
*
|
|
16
|
+
* Both are caught here and converted into `{ available: false, reason }`, never a thrown error and
|
|
17
|
+
* never a boot failure. The tool then reports "no browser in this deployment" and the compliance
|
|
18
|
+
* skill is required by its own output contract to downgrade every rendered-truth finding to
|
|
19
|
+
* `cannot-determine`. That is the entire reason this adapter must not be a static import: a static
|
|
20
|
+
* one would make an optional capability a hard boot dependency for every host install.
|
|
21
|
+
*
|
|
22
|
+
* {@link PlaywrightLike} and render-page.ts declare, structurally, the browser members this adapter uses.
|
|
23
|
+
* That is deliberate rather than importing Playwright's own (very large) `.d.ts`: typechecking this
|
|
24
|
+
* repository must not depend on a browser automation library's type surface being resolvable, and
|
|
25
|
+
* naming the members used makes the actual coupling one short, reviewable block instead of an
|
|
26
|
+
* open-ended import.
|
|
27
|
+
*
|
|
28
|
+
* ---------------------------------------------------------------------------
|
|
29
|
+
* Privacy properties, enforced here rather than promised
|
|
30
|
+
* ---------------------------------------------------------------------------
|
|
31
|
+
* - **Ephemeral context.** `browser.newContext()` with no `storageState` and no user-data
|
|
32
|
+
* directory. Cookies, storage, and cache exist only in memory and die with `close()`. Nothing is
|
|
33
|
+
* written to disk by this module.
|
|
34
|
+
* - **One context per page.** Each `observe()` call gets a fresh context, so a cookie set by page A
|
|
35
|
+
* can never be reported as though page B set it — which would be an outright false citation in a
|
|
36
|
+
* pre-consent cookie finding.
|
|
37
|
+
* - **No non-GET request ever leaves the process.** Every request is intercepted; anything that is
|
|
38
|
+
* not GET or HEAD is aborted and recorded as blocked. This is what makes "never submits forms" a
|
|
39
|
+
* structural property instead of a policy: even if a page auto-submits, or a consent widget POSTs
|
|
40
|
+
* preferences, the attempt is observed and the bytes do not go out.
|
|
41
|
+
* These evidence privacy rules describe SiteEvidenceBrowserPort; public-page.ts separately
|
|
42
|
+
* captures explicitly requested, bounded JSON response bodies, without cookies/credentials.
|
|
43
|
+
* - **Values are never read.** Cookie values, request bodies, and form-field values are not
|
|
44
|
+
* extracted anywhere below, because `browser-port.ts`'s shapes have nowhere to put them.
|
|
45
|
+
*/
|
|
46
|
+
import type { RenderBrowser } from "./render-page.js";
|
|
47
|
+
import type { RequestRouter } from "./request-guard.js";
|
|
48
|
+
export interface PlaywrightLike {
|
|
49
|
+
chromium: {
|
|
50
|
+
launch(options?: {
|
|
51
|
+
headless?: boolean;
|
|
52
|
+
args?: readonly string[];
|
|
53
|
+
chromiumSandbox?: boolean;
|
|
54
|
+
}): Promise<RenderBrowser>;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Opens a real Chromium for the shared render/evidence adapters, or explains why this
|
|
59
|
+
* deployment cannot.
|
|
60
|
+
*
|
|
61
|
+
* @returns `{ available: true, browser }` on success; `{ available: false, reason }` when the
|
|
62
|
+
* `playwright` module or its Chromium binary is not present. Never throws for either case — see
|
|
63
|
+
* this file's header for why an absent browser must be a reportable state rather than an error.
|
|
64
|
+
* @complexity One process launch. The caller is responsible for calling `close()`, which
|
|
65
|
+
* `collectPageEvidence` does in a `finally`.
|
|
66
|
+
*/
|
|
67
|
+
export interface PlaywrightAdapterOptions {
|
|
68
|
+
/** Host pinned HTTP router. Own-origin captures alone may preserve fresh visitor cookies. */
|
|
69
|
+
readonly routerFactory?: (required: {
|
|
70
|
+
originBaseUrl: string;
|
|
71
|
+
signal: AbortSignal;
|
|
72
|
+
}) => RequestRouter;
|
|
73
|
+
readonly moduleLoader?: {
|
|
74
|
+
load(required: {
|
|
75
|
+
moduleName: string;
|
|
76
|
+
}): Promise<PlaywrightLike>;
|
|
77
|
+
};
|
|
78
|
+
readonly launchOptions?: {
|
|
79
|
+
headless?: boolean;
|
|
80
|
+
args?: string[];
|
|
81
|
+
chromiumSandbox?: boolean;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** Opens the optional browser capability; import and launch failures become availability results. */
|
|
85
|
+
export declare function openPlaywrightRenderBrowser(_required: Record<string, never>, options?: PlaywrightAdapterOptions): Promise<{
|
|
86
|
+
available: true;
|
|
87
|
+
browser: RenderBrowser;
|
|
88
|
+
} | {
|
|
89
|
+
available: false;
|
|
90
|
+
reason: string;
|
|
91
|
+
}>;
|
|
92
|
+
/** Sandboxed public rendering: no unrouted network, including implicit loopback and WebRTC.
|
|
93
|
+
* Port 9 (discard) on loopback: nothing listens, so an unrouted request fails instead of escaping.
|
|
94
|
+
* Chromium implicitly bypasses proxies for loopback; `<-loopback>` removes that bypass. */
|
|
95
|
+
export declare const PUBLIC_RENDER_LAUNCH_OPTIONS: {
|
|
96
|
+
headless: boolean;
|
|
97
|
+
chromiumSandbox: boolean;
|
|
98
|
+
args: string[];
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=playwright-runtime.d.ts.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Opens the optional browser capability; import and launch failures become availability results. */
|
|
2
|
+
// A successful launch transfers process ownership to the caller; close the browser in a finally
|
|
3
|
+
// block so an unreachable or unstable page cannot leak the browser process.
|
|
4
|
+
export async function openPlaywrightRenderBrowser(_required, options = {}) {
|
|
5
|
+
let playwright;
|
|
6
|
+
try {
|
|
7
|
+
const moduleName = "playwright";
|
|
8
|
+
playwright = options.moduleLoader
|
|
9
|
+
? await options.moduleLoader.load({ moduleName })
|
|
10
|
+
: (await import(moduleName));
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
return {
|
|
14
|
+
available: false,
|
|
15
|
+
reason: "the 'playwright' package is not installed in this deployment, so rendered-page behaviour " +
|
|
16
|
+
`cannot be observed here (${error instanceof Error ? error.message : String(error)})`,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
let browser;
|
|
20
|
+
try {
|
|
21
|
+
browser = await playwright.chromium.launch({ headless: true, ...options.launchOptions });
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
return {
|
|
25
|
+
available: false,
|
|
26
|
+
reason: "Chromium could not be launched in this deployment — the 'playwright' package is present but its " +
|
|
27
|
+
`browser binary may be missing or the host may not support the configured sandbox (run 'npx playwright install --with-deps chromium'). Underlying error: ${error instanceof Error ? error.message : String(error)}`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return { available: true, browser };
|
|
31
|
+
}
|
|
32
|
+
/** Sandboxed public rendering: no unrouted network, including implicit loopback and WebRTC.
|
|
33
|
+
* Port 9 (discard) on loopback: nothing listens, so an unrouted request fails instead of escaping.
|
|
34
|
+
* Chromium implicitly bypasses proxies for loopback; `<-loopback>` removes that bypass. */
|
|
35
|
+
export const PUBLIC_RENDER_LAUNCH_OPTIONS = {
|
|
36
|
+
headless: true, chromiumSandbox: true,
|
|
37
|
+
args: ["--disable-dev-shm-usage", "--proxy-server=http://127.0.0.1:9", "--proxy-bypass-list=<-loopback>", "--force-webrtc-ip-handling-policy=disable_non_proxied_udp"],
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=playwright-runtime.js.map
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import type { HttpClientPort } from "@jini-ai/core/primitives";
|
|
2
|
+
import { type FetchedResource, type AbortReason } from "./request-guard.js";
|
|
3
|
+
import { type PlaywrightAdapterOptions } from "./playwright-runtime.js";
|
|
4
|
+
import type { RenderBrowserPool } from "./lazy-browser.js";
|
|
5
|
+
export interface CapturedJsonResponse {
|
|
6
|
+
url: string;
|
|
7
|
+
status: number;
|
|
8
|
+
body: string;
|
|
9
|
+
truncated: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** A deliberately omitted JSON body; size is the byte count observed by the bounded transport. */
|
|
12
|
+
export interface UnmatchedJsonResponse {
|
|
13
|
+
url: string;
|
|
14
|
+
status: number;
|
|
15
|
+
size: number;
|
|
16
|
+
}
|
|
17
|
+
export interface PublicPageInput {
|
|
18
|
+
url: string;
|
|
19
|
+
maxChars: number;
|
|
20
|
+
waitFor?: string | number;
|
|
21
|
+
dismissCookieBanners?: boolean;
|
|
22
|
+
captureData?: boolean;
|
|
23
|
+
screenshot?: boolean;
|
|
24
|
+
/** URL substrings, or full-URL globs with `*` matching any characters; alternatives are ORed. */
|
|
25
|
+
captureDataMatch?: string | string[];
|
|
26
|
+
/** Full text by default, no text, or a leading visible-text excerpt of at most 1000 characters. */
|
|
27
|
+
textMode?: "full" | "none" | "summary";
|
|
28
|
+
}
|
|
29
|
+
export interface PublicPageCapture {
|
|
30
|
+
finalUrl: string;
|
|
31
|
+
status: number;
|
|
32
|
+
title: string;
|
|
33
|
+
html: string;
|
|
34
|
+
text: string;
|
|
35
|
+
truncated: boolean;
|
|
36
|
+
images: Array<{
|
|
37
|
+
src: string;
|
|
38
|
+
alt: string;
|
|
39
|
+
}>;
|
|
40
|
+
imagesTruncated: boolean;
|
|
41
|
+
data: CapturedJsonResponse[];
|
|
42
|
+
dataTruncated: boolean;
|
|
43
|
+
dataUnmatched?: UnmatchedJsonResponse[];
|
|
44
|
+
blockedDataRequests: Partial<Record<AbortReason, number>>;
|
|
45
|
+
screenshot?: {
|
|
46
|
+
mimeType: "image/jpeg";
|
|
47
|
+
data: string;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** Bounded synchronous collector over responses already read by the pinned request router.
|
|
51
|
+
* No response.body() listener: it would read whole untrusted bodies before applying the cap.
|
|
52
|
+
* Filters affect output only: unmatched data still reaches the page so hydration can complete.
|
|
53
|
+
* Matched and unmatched lists each cap their count; both charge URLs to the shared character budget.
|
|
54
|
+
* @example createJsonCapture({}, { captureDataMatch: "/v1/datasource/" })
|
|
55
|
+
* @complexity URL matching plus O(min(body, perBodyChars)) per JSON answer; O(totalChars + count) retained space. */
|
|
56
|
+
export declare function createJsonCapture(_required: Record<string, never>, { maxResponses, perBodyChars, totalChars, captureDataMatch }?: {
|
|
57
|
+
maxResponses?: number;
|
|
58
|
+
perBodyChars?: number;
|
|
59
|
+
totalChars?: number;
|
|
60
|
+
captureDataMatch?: string | string[];
|
|
61
|
+
}): {
|
|
62
|
+
record({ url, resourceType, resource }: {
|
|
63
|
+
url: string;
|
|
64
|
+
resourceType: string;
|
|
65
|
+
resource: FetchedResource;
|
|
66
|
+
}, _options?: {}): void;
|
|
67
|
+
markTruncated({ resourceType }: {
|
|
68
|
+
resourceType: string;
|
|
69
|
+
}, _options?: {}): void;
|
|
70
|
+
result: (_required?: {}, _options?: {}) => {
|
|
71
|
+
dataUnmatched?: UnmatchedJsonResponse[];
|
|
72
|
+
data: CapturedJsonResponse[];
|
|
73
|
+
dataTruncated: boolean;
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
/** Self-contained browser script: DOM and computed styles are native browser capabilities.
|
|
77
|
+
* Ships as a string to avoid esbuild's module-scoped __name helper leaking into evaluation.
|
|
78
|
+
* Scans at most 5000 nodes, caps images and every emitted string before crossing the browser port. */
|
|
79
|
+
export declare function publicPageExpression({ maxChars, textMode }: {
|
|
80
|
+
maxChars: number;
|
|
81
|
+
textMode?: PublicPageInput["textMode"];
|
|
82
|
+
}, _options?: {}): string;
|
|
83
|
+
/** Anonymous public render using the shared lifecycle and the existing pinned HTTP transport.
|
|
84
|
+
* Import/launch, navigation, selector, extraction and screenshot all share one hard deadline.
|
|
85
|
+
* Owned processes close, shared leases release; late launches are handled without owner storage.
|
|
86
|
+
* @throws Error for unavailable Chromium, refused navigation or deadline exhaustion.
|
|
87
|
+
* @complexity Bounded requests/bytes plus at most 5000 DOM nodes and one viewport screenshot. */
|
|
88
|
+
export declare function renderPublicPage({ input, httpClient }: {
|
|
89
|
+
input: PublicPageInput;
|
|
90
|
+
httpClient: HttpClientPort;
|
|
91
|
+
}, { signal, timeoutMs, moduleLoader, browserPool }?: {
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
timeoutMs?: number;
|
|
94
|
+
moduleLoader?: PlaywrightAdapterOptions["moduleLoader"];
|
|
95
|
+
browserPool?: RenderBrowserPool;
|
|
96
|
+
}): Promise<PublicPageCapture>;
|
|
97
|
+
//# sourceMappingURL=public-page.d.ts.map
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { createRequestRouter, fetchOwnSiteResource } from "./request-guard.js";
|
|
2
|
+
import { renderPage } from "./render-page.js";
|
|
3
|
+
import { openPlaywrightRenderBrowser, PUBLIC_RENDER_LAUNCH_OPTIONS } from "./playwright-runtime.js";
|
|
4
|
+
import { PageWorkBudget, PageWorkTimeout } from "./page-work-budget.js";
|
|
5
|
+
/** Match a literal substring or an anchored `*` glob using native string searches.
|
|
6
|
+
* Other characters (including URL query `?`) are literal. No regex backtracking on untrusted URLs.
|
|
7
|
+
* @complexity O(s × u), s is the pattern's segment count and u the URL length; O(pattern length) space. */
|
|
8
|
+
function matchesCaptureUrl({ url, pattern }, _options = {}) {
|
|
9
|
+
const parts = pattern.split("*");
|
|
10
|
+
if (parts.length === 1)
|
|
11
|
+
return url.includes(pattern);
|
|
12
|
+
const prefix = parts[0];
|
|
13
|
+
const suffix = parts[parts.length - 1];
|
|
14
|
+
if (!url.startsWith(prefix) || !url.endsWith(suffix))
|
|
15
|
+
return false;
|
|
16
|
+
let offset = prefix.length;
|
|
17
|
+
const end = url.length - suffix.length;
|
|
18
|
+
for (const part of parts.slice(1, -1)) {
|
|
19
|
+
const found = url.indexOf(part, offset);
|
|
20
|
+
if (found < 0 || found + part.length > end)
|
|
21
|
+
return false;
|
|
22
|
+
offset = found + part.length;
|
|
23
|
+
}
|
|
24
|
+
return offset <= end;
|
|
25
|
+
}
|
|
26
|
+
/** Bounded synchronous collector over responses already read by the pinned request router.
|
|
27
|
+
* No response.body() listener: it would read whole untrusted bodies before applying the cap.
|
|
28
|
+
* Filters affect output only: unmatched data still reaches the page so hydration can complete.
|
|
29
|
+
* Matched and unmatched lists each cap their count; both charge URLs to the shared character budget.
|
|
30
|
+
* @example createJsonCapture({}, { captureDataMatch: "/v1/datasource/" })
|
|
31
|
+
* @complexity URL matching plus O(min(body, perBodyChars)) per JSON answer; O(totalChars + count) retained space. */
|
|
32
|
+
export function createJsonCapture(_required, { maxResponses = 20, perBodyChars = 8000, totalChars = 60_000, captureDataMatch } = {}) {
|
|
33
|
+
const data = [];
|
|
34
|
+
const dataUnmatched = [];
|
|
35
|
+
const patterns = typeof captureDataMatch === "string" ? [captureDataMatch] : captureDataMatch;
|
|
36
|
+
let used = 0;
|
|
37
|
+
let truncated = false;
|
|
38
|
+
return {
|
|
39
|
+
record({ url, resourceType, resource }, _options = {}) {
|
|
40
|
+
if (resourceType !== "xhr" && resourceType !== "fetch")
|
|
41
|
+
return;
|
|
42
|
+
const contentType = Object.entries(resource.headers).find(([key]) => key.toLowerCase() === "content-type")?.[1]?.split(";")[0]?.trim() ?? "";
|
|
43
|
+
if (!/^(?:application|text)\/(?:json|[\w.+-]+\+json)$/i.test(contentType))
|
|
44
|
+
return;
|
|
45
|
+
const capturedUrl = url.slice(0, 2048);
|
|
46
|
+
if (patterns && !patterns.some(pattern => matchesCaptureUrl({ url, pattern }))) {
|
|
47
|
+
if (dataUnmatched.length >= maxResponses || used + capturedUrl.length > totalChars) {
|
|
48
|
+
truncated = true;
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
// Do not decode or charge omitted bodies: noisy providers must not consume the useful body window.
|
|
52
|
+
dataUnmatched.push({ url: capturedUrl, status: resource.status, size: resource.body.length });
|
|
53
|
+
used += capturedUrl.length;
|
|
54
|
+
truncated ||= resource.truncated || url.length > 2048;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (data.length >= maxResponses || used >= totalChars) {
|
|
58
|
+
truncated = true;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (used + capturedUrl.length >= totalChars) {
|
|
62
|
+
truncated = true;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const limit = Math.min(perBodyChars, totalChars - used - capturedUrl.length);
|
|
66
|
+
// At most four UTF-8 bytes per output character; never decode a multi-megabyte body here.
|
|
67
|
+
const decoded = resource.body.subarray(0, limit * 4).toString("utf8");
|
|
68
|
+
const body = decoded.slice(0, limit);
|
|
69
|
+
const cut = resource.truncated || resource.body.length > limit * 4 || decoded.length > limit || url.length > 2048;
|
|
70
|
+
used += capturedUrl.length + body.length;
|
|
71
|
+
data.push({ url: capturedUrl, status: resource.status, body, truncated: cut });
|
|
72
|
+
truncated ||= cut;
|
|
73
|
+
},
|
|
74
|
+
markTruncated({ resourceType }, _options = {}) {
|
|
75
|
+
if (resourceType === "xhr" || resourceType === "fetch")
|
|
76
|
+
truncated = true;
|
|
77
|
+
},
|
|
78
|
+
result: (_required = {}, _options = {}) => ({ data: [...data], dataTruncated: truncated, ...(patterns ? { dataUnmatched: [...dataUnmatched] } : {}) }),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Self-contained browser script: DOM and computed styles are native browser capabilities.
|
|
82
|
+
* Ships as a string to avoid esbuild's module-scoped __name helper leaking into evaluation.
|
|
83
|
+
* Scans at most 5000 nodes, caps images and every emitted string before crossing the browser port. */
|
|
84
|
+
export function publicPageExpression({ maxChars, textMode = "full" }, _options = {}) {
|
|
85
|
+
return `(() => {
|
|
86
|
+
const cap = ${maxChars}; const htmlCap = Math.max(4096, cap * 4);
|
|
87
|
+
const mode = ${JSON.stringify(textMode)}; const textCap = mode === 'summary' ? Math.min(1000, cap) : cap;
|
|
88
|
+
const images = []; const seen = new Set(); let imagesTruncated = false;
|
|
89
|
+
const add = (raw, alt) => {
|
|
90
|
+
if (!raw) return;
|
|
91
|
+
let u; try { u = new URL(raw, document.baseURI); } catch { return; }
|
|
92
|
+
if (!['http:', 'https:'].includes(u.protocol) || seen.has(u.href)) return;
|
|
93
|
+
seen.add(u.href);
|
|
94
|
+
if (images.length >= 300 || u.href.length > 2048) { imagesTruncated = true; return; }
|
|
95
|
+
images.push({src: u.href, alt: (alt || '').slice(0, 300)});
|
|
96
|
+
};
|
|
97
|
+
const copy = document.documentElement.cloneNode(true);
|
|
98
|
+
const originals = document.documentElement.querySelectorAll('*');
|
|
99
|
+
const clones = copy.querySelectorAll('*');
|
|
100
|
+
let scanTruncated = originals.length > 5000;
|
|
101
|
+
for (let i = 0; i < Math.min(originals.length, 5000); i++) {
|
|
102
|
+
const node = originals[i]; const clone = clones[i];
|
|
103
|
+
if (['SCRIPT','NOSCRIPT','TEMPLATE'].includes(node.tagName)) { clone.remove(); continue; }
|
|
104
|
+
const style = getComputedStyle(node);
|
|
105
|
+
if (style.display === 'none' || style.visibility === 'hidden') {
|
|
106
|
+
if (!node.closest('head')) clone.remove();
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (node.tagName === 'IMG') { add(node.currentSrc, node.alt); add(node.src, node.alt); add(node.getAttribute('data-src'), node.alt); }
|
|
110
|
+
if (node.tagName === 'IMG' || node.tagName === 'SOURCE') {
|
|
111
|
+
for (const candidate of (node.getAttribute('srcset') || '').split(',')) add(candidate.trim().split(/\\s+/)[0], node.alt);
|
|
112
|
+
}
|
|
113
|
+
for (const match of style.backgroundImage.matchAll(/url\\(['"]?([^'"\\)]+)['"]?\\)/g)) add(match[1], '');
|
|
114
|
+
}
|
|
115
|
+
copy.querySelectorAll('script,noscript,template').forEach(node => node.remove());
|
|
116
|
+
const html = copy.outerHTML; const text = mode !== 'none' && document.body ? document.body.innerText : '';
|
|
117
|
+
const split = text.charCodeAt(textCap);
|
|
118
|
+
const textEnd = mode === 'summary' && split >= 0xDC00 && split <= 0xDFFF ? textCap - 1 : textCap;
|
|
119
|
+
return {html: html.slice(0, htmlCap), text: text.slice(0, textEnd), title: document.title.slice(0, 300),
|
|
120
|
+
images, imagesTruncated: imagesTruncated || scanTruncated,
|
|
121
|
+
truncated: scanTruncated || html.length > htmlCap || text.length > textCap};
|
|
122
|
+
})()`;
|
|
123
|
+
}
|
|
124
|
+
/** Anonymous public render using the shared lifecycle and the existing pinned HTTP transport.
|
|
125
|
+
* Import/launch, navigation, selector, extraction and screenshot all share one hard deadline.
|
|
126
|
+
* Owned processes close, shared leases release; late launches are handled without owner storage.
|
|
127
|
+
* @throws Error for unavailable Chromium, refused navigation or deadline exhaustion.
|
|
128
|
+
* @complexity Bounded requests/bytes plus at most 5000 DOM nodes and one viewport screenshot. */
|
|
129
|
+
export async function renderPublicPage({ input, httpClient }, { signal, timeoutMs = 30_000, moduleLoader, browserPool } = {}) {
|
|
130
|
+
timeoutMs = Math.min(timeoutMs, 30_000);
|
|
131
|
+
const abort = new AbortController();
|
|
132
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
133
|
+
const combined = AbortSignal.any([abort.signal, deadline, ...(signal ? [signal] : [])]);
|
|
134
|
+
const budget = new PageWorkBudget({ timeoutMs }, { signal: combined });
|
|
135
|
+
let lease;
|
|
136
|
+
const opened = await budget.run({ work: async () => {
|
|
137
|
+
if (browserPool) {
|
|
138
|
+
let acquired;
|
|
139
|
+
try {
|
|
140
|
+
acquired = await browserPool.acquire({}, { signal: combined });
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (combined.aborted || error?.code === "WEB_RENDER_BUSY")
|
|
144
|
+
throw error;
|
|
145
|
+
throw Object.assign(new Error("Headless browser is unavailable in this deployment"), { code: "WEB_RENDER_UNAVAILABLE" });
|
|
146
|
+
}
|
|
147
|
+
if (combined.aborted || budget.remainingMs() <= 0) {
|
|
148
|
+
acquired.release();
|
|
149
|
+
combined.throwIfAborted();
|
|
150
|
+
throw new PageWorkTimeout({ timeoutMs });
|
|
151
|
+
}
|
|
152
|
+
lease = acquired;
|
|
153
|
+
return { available: true, browser: acquired.browser };
|
|
154
|
+
}
|
|
155
|
+
const result = await openPlaywrightRenderBrowser({}, { ...(moduleLoader ? { moduleLoader } : {}), launchOptions: PUBLIC_RENDER_LAUNCH_OPTIONS });
|
|
156
|
+
if (result.available && (budget.remainingMs() <= 0 || combined.aborted)) {
|
|
157
|
+
void result.browser.close().catch(() => { });
|
|
158
|
+
combined.throwIfAborted();
|
|
159
|
+
throw new PageWorkTimeout({ timeoutMs });
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
} });
|
|
163
|
+
if (!opened.available)
|
|
164
|
+
throw Object.assign(new Error("Headless browser is unavailable in this deployment"), { code: "WEB_RENDER_UNAVAILABLE" });
|
|
165
|
+
// Small/batched reads keep their JSON window small too; a batch must not multiply 60k by default.
|
|
166
|
+
const json = createJsonCapture({}, { perBodyChars: Math.min(8000, input.maxChars), totalChars: Math.min(60_000, input.maxChars),
|
|
167
|
+
...(input.captureDataMatch === undefined ? {} : { captureDataMatch: input.captureDataMatch }),
|
|
168
|
+
});
|
|
169
|
+
const blockedDataRequests = {};
|
|
170
|
+
const router = createRequestRouter({ httpClient, ownSiteFetch: fetchOwnSiteResource, allowedOrigins: [], signal: combined }, {
|
|
171
|
+
maxResourceBytes: 5 * 1024 * 1024, maxTotalBytes: 30 * 1024 * 1024, maxRequests: 200,
|
|
172
|
+
allowDataRequests: true,
|
|
173
|
+
...(input.captureData === false ? {} : { onResponse: json.record }),
|
|
174
|
+
onBlocked: ({ resourceType, reason }) => {
|
|
175
|
+
if (resourceType !== "xhr" && resourceType !== "fetch")
|
|
176
|
+
return;
|
|
177
|
+
blockedDataRequests[reason] = (blockedDataRequests[reason] ?? 0) + 1;
|
|
178
|
+
json.markTruncated({ resourceType });
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
try {
|
|
182
|
+
return await renderPage({ browser: opened.browser, url: input.url, consume: async ({ page, finalUrl, response, budget: pageBudget }) => {
|
|
183
|
+
const snapshot = await pageBudget.run({ work: async () => await page.evaluate(publicPageExpression({ maxChars: input.maxChars, ...(input.textMode ? { textMode: input.textMode } : {}) })) });
|
|
184
|
+
let screenshot;
|
|
185
|
+
if (input.screenshot) {
|
|
186
|
+
if (!page.screenshot)
|
|
187
|
+
throw new Error("Browser cannot take screenshots");
|
|
188
|
+
const jpeg = await pageBudget.run({ work: () => page.screenshot({ type: "jpeg", quality: 72, fullPage: false, timeout: pageBudget.remainingMs(), animations: "disabled" }) });
|
|
189
|
+
if (jpeg.length <= 2 * 1024 * 1024)
|
|
190
|
+
screenshot = { mimeType: "image/jpeg", data: jpeg.toString("base64") };
|
|
191
|
+
else
|
|
192
|
+
snapshot.truncated = true;
|
|
193
|
+
}
|
|
194
|
+
return { ...snapshot, truncated: snapshot.truncated || finalUrl.length > 2048, finalUrl: finalUrl.slice(0, 2048), status: response?.status() ?? 0, ...json.result(), blockedDataRequests: { ...blockedDataRequests }, ...(screenshot ? { screenshot } : {}) };
|
|
195
|
+
} }, {
|
|
196
|
+
originPolicy: "public", router, timeoutMs: budget.remainingMs(), signal: combined,
|
|
197
|
+
...(input.waitFor === undefined ? {} : { waitFor: input.waitFor }), dismissCookieBanners: input.dismissCookieBanners !== false,
|
|
198
|
+
contextOptions: { viewport: { width: 1280, height: 800 } },
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
abort.abort();
|
|
203
|
+
if (lease)
|
|
204
|
+
lease.release();
|
|
205
|
+
else
|
|
206
|
+
await budget.release({ close: () => opened.browser.close().catch(() => { }) });
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=public-page.js.map
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { PageWorkBudget } from "./page-work-budget.js";
|
|
2
|
+
import { type RequestRouter, type RouteLike } from "./request-guard.js";
|
|
3
|
+
/** Structural browser ports shared by evidence, public reading and screenshots. No vendor SDK. */
|
|
4
|
+
export interface RenderResponse {
|
|
5
|
+
status(): number;
|
|
6
|
+
url?(): string;
|
|
7
|
+
headers?(): Record<string, string>;
|
|
8
|
+
}
|
|
9
|
+
export interface RenderLocator {
|
|
10
|
+
first(): RenderLocator;
|
|
11
|
+
count(): Promise<number>;
|
|
12
|
+
click(options?: {
|
|
13
|
+
timeout?: number;
|
|
14
|
+
}): Promise<void>;
|
|
15
|
+
isVisible?(): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
export interface RenderPage {
|
|
18
|
+
goto(url: string, options: {
|
|
19
|
+
waitUntil: "domcontentloaded";
|
|
20
|
+
timeout: number;
|
|
21
|
+
}): Promise<RenderResponse | null>;
|
|
22
|
+
evaluate(expression: string): Promise<unknown>;
|
|
23
|
+
waitForTimeout(ms: number): Promise<void>;
|
|
24
|
+
waitForLoadState?(state: "load", options: {
|
|
25
|
+
timeout: number;
|
|
26
|
+
}): Promise<void>;
|
|
27
|
+
waitForSelector?(selector: string, options: {
|
|
28
|
+
state: "visible";
|
|
29
|
+
timeout: number;
|
|
30
|
+
}): Promise<unknown>;
|
|
31
|
+
locator?(selector: string): RenderLocator;
|
|
32
|
+
title(): Promise<string>;
|
|
33
|
+
url?(): string;
|
|
34
|
+
screenshot?(options: {
|
|
35
|
+
type: "png" | "jpeg";
|
|
36
|
+
quality?: number;
|
|
37
|
+
fullPage: boolean;
|
|
38
|
+
clip?: {
|
|
39
|
+
x: number;
|
|
40
|
+
y: number;
|
|
41
|
+
width: number;
|
|
42
|
+
height: number;
|
|
43
|
+
};
|
|
44
|
+
timeout: number;
|
|
45
|
+
animations: "disabled";
|
|
46
|
+
}): Promise<Buffer>;
|
|
47
|
+
}
|
|
48
|
+
export interface RenderCookie {
|
|
49
|
+
name: string;
|
|
50
|
+
value: string;
|
|
51
|
+
domain: string;
|
|
52
|
+
path: string;
|
|
53
|
+
expires: number;
|
|
54
|
+
httpOnly: boolean;
|
|
55
|
+
secure: boolean;
|
|
56
|
+
sameSite: string;
|
|
57
|
+
}
|
|
58
|
+
export interface RenderContext {
|
|
59
|
+
newPage(): Promise<RenderPage>;
|
|
60
|
+
route(pattern: string, handler: (route: RouteLike & {
|
|
61
|
+
continue?(): Promise<void>;
|
|
62
|
+
}) => Promise<void>): Promise<unknown>;
|
|
63
|
+
routeWebSocket?(pattern: RegExp, handler: (socket: {
|
|
64
|
+
close(): Promise<void>;
|
|
65
|
+
}) => unknown): Promise<unknown>;
|
|
66
|
+
cookies?(): Promise<RenderCookie[]>;
|
|
67
|
+
close(): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
export interface RenderBrowser {
|
|
70
|
+
newContext(options?: Record<string, unknown>): Promise<RenderContext>;
|
|
71
|
+
close(): Promise<void>;
|
|
72
|
+
}
|
|
73
|
+
export interface RenderSession {
|
|
74
|
+
page: RenderPage;
|
|
75
|
+
context: RenderContext;
|
|
76
|
+
response: RenderResponse | null;
|
|
77
|
+
finalUrl: string;
|
|
78
|
+
budget: PageWorkBudget;
|
|
79
|
+
}
|
|
80
|
+
export interface RenderPageOptions {
|
|
81
|
+
timeoutMs?: number;
|
|
82
|
+
signal?: AbortSignal;
|
|
83
|
+
/** CSS selector, or settle seconds (0–10). DOM content loaded always precedes this. */
|
|
84
|
+
waitFor?: string | number;
|
|
85
|
+
dismissCookieBanners?: boolean;
|
|
86
|
+
/** Best-effort load wait after the settle/selector strategy, capped within the total deadline. */
|
|
87
|
+
loadWaitMs?: number;
|
|
88
|
+
/** Same-origin navigation is the default. Public mode requires a pinned-transport router. */
|
|
89
|
+
originPolicy?: "same-origin" | "public";
|
|
90
|
+
originBaseUrl?: string;
|
|
91
|
+
/** Only viewport/device settings cross this boundary; saved storage/credentials are discarded. */
|
|
92
|
+
contextOptions?: Record<string, unknown>;
|
|
93
|
+
router?: RequestRouter;
|
|
94
|
+
/** Observe the attempt immediately; an optional returned hook records a later guard refusal. */
|
|
95
|
+
onRequest?: (required: {
|
|
96
|
+
route: RouteLike;
|
|
97
|
+
blocked: boolean;
|
|
98
|
+
}) => void | ((required: {
|
|
99
|
+
reason: string;
|
|
100
|
+
}) => void);
|
|
101
|
+
}
|
|
102
|
+
/** Stable safe code for a renderer behind a port; no resolved peer or target path is exposed. */
|
|
103
|
+
export declare class RenderRequestRefused extends Error {
|
|
104
|
+
readonly code = "WEB_RENDER_REFUSED";
|
|
105
|
+
constructor(_required: Record<string, never>, _options?: {});
|
|
106
|
+
}
|
|
107
|
+
/** Origin-only refusal metadata lets collectors retain their existing off-origin skip result. */
|
|
108
|
+
export declare class OffOriginNavigationError extends Error {
|
|
109
|
+
readonly origin: string;
|
|
110
|
+
constructor({ url }: {
|
|
111
|
+
url: string;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/** Narrow known consent controls: never click a generic page-wide 'close' or 'accept' button. */
|
|
115
|
+
export declare const COOKIE_DISMISS_SELECTORS: readonly ["#onetrust-accept-btn-handler", "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll", "button#cookie-accept", "button[aria-label='Accept cookies']", "button[aria-label='Accept all cookies']", "[role='dialog']:has-text('cookie') button:has-text('Accept all')", "[role='dialog']:has-text('cookie') button[aria-label='Close']", "[id*='cookie'] button:has-text('Accept')", "[class*='cookie'] button:has-text('Accept all')", "#onetrust-close-btn-container button", "[id*='cookie'] button[aria-label='Close']", "[class*='cookie'] button[aria-label='Close']"];
|
|
116
|
+
/** Click the first visible known cookie control; absence or a disappearing banner is harmless.
|
|
117
|
+
* @complexity O(k), k is the fixed selector list; clicks use the same total page budget. */
|
|
118
|
+
export declare function dismissCookieBanners({ page, budget }: {
|
|
119
|
+
page: RenderPage;
|
|
120
|
+
budget: PageWorkBudget;
|
|
121
|
+
}, _options?: {}): Promise<boolean>;
|
|
122
|
+
/** Open, guard, wait and consume ONE ephemeral page, always releasing the context.
|
|
123
|
+
* No network-idle wait: SPAs and polling sites can stay busy forever. DNS decisions are not followed
|
|
124
|
+
* by Chromium `continue()` in public mode: the router fetches on pinned vetted peers and fulfills
|
|
125
|
+
* responses; a dead proxy at launch prevents unrouted protocols from escaping.
|
|
126
|
+
* A fulfilled 3xx is never handed to Chromium: Playwright does not route its next hop. The router
|
|
127
|
+
* aborts a main-frame redirect and records its target, so each explicit goto is vetted again.
|
|
128
|
+
* @throws Browser errors, cancellation, PageWorkTimeout, or a refused origin/transport boundary.
|
|
129
|
+
* @complexity Bounded page I/O plus the consumer; at most six explicit navigation hops. */
|
|
130
|
+
export declare function renderPage<T>({ browser, url, consume }: {
|
|
131
|
+
browser: RenderBrowser;
|
|
132
|
+
url: string;
|
|
133
|
+
consume: (session: RenderSession) => Promise<T>;
|
|
134
|
+
}, options?: RenderPageOptions): Promise<T>;
|
|
135
|
+
//# sourceMappingURL=render-page.d.ts.map
|