@artis-lab/cli 0.9.0 → 0.10.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.
package/README.md CHANGED
@@ -54,6 +54,20 @@ artis annotate artifact-slug --comment "Tighten this heading" --quote "Checkout
54
54
  artis reply annotation-123 --comment "Fixed in revision 2."
55
55
  ```
56
56
 
57
+ ## Check a page before publishing
58
+
59
+ ```bash
60
+ artis verify artifact.html # or a published artifact: artis verify artifact-slug
61
+ ```
62
+
63
+ `verify` renders the page in your system Chrome (or Edge) at 1280 and 390 px
64
+ in light and dark themes, served with the same Content-Security-Policy as
65
+ Artis, and reports horizontal overflow, clipped SVG, console errors and CSP
66
+ violations. It exits 8 when it finds any. It needs the optional
67
+ `playwright-core` dependency (installed with the CLI by default, about
68
+ 10 MB and no browser binaries) and a
69
+ Chromium-based browser; set `ARTIS_CHROME_PATH` to use a specific one.
70
+
57
71
  Run `artis help` for the full command and flag reference.
58
72
 
59
73
  ## Install the agent skill
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@artis-lab/cli",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Agent-first CLI for publishing, reviewing, and revising self-contained HTML artifacts on an Artis server.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -45,6 +45,9 @@
45
45
  "dependencies": {
46
46
  "tslib": "^2.3.0"
47
47
  },
48
+ "optionalDependencies": {
49
+ "playwright-core": "^1.64.1"
50
+ },
48
51
  "devDependencies": {
49
52
  "@artis/sdk": "0.0.1"
50
53
  },
package/src/bin.js CHANGED
@@ -5,7 +5,12 @@
5
5
  import { runArtisCli } from './lib/cli.js';
6
6
  import { exitCodeFor } from './lib/exit-codes.js';
7
7
  runArtisCli().catch((error) => {
8
- console.error(error instanceof Error ? error.message : String(error));
8
+ const message = error instanceof Error ? error.message : String(error);
9
+ // An outcome already reported on stdout (verify's findings) carries no
10
+ // message; only the exit code is left to set.
11
+ if (message) {
12
+ console.error(message);
13
+ }
9
14
  process.exitCode = exitCodeFor(error);
10
15
  });
11
16
  //# sourceMappingURL=bin.js.map
package/src/lib/cli.d.ts CHANGED
@@ -47,6 +47,18 @@ export declare function getArtifactFromCli(args: string[]): Promise<void>;
47
47
  * `artis artifact html <id> --output report.html`, edit, then `artis revise`.
48
48
  */
49
49
  export declare function getArtifactHtmlFromCli(args: string[]): Promise<void>;
50
+ /**
51
+ * Render a local HTML file, or a published artifact's stored HTML, in the
52
+ * system Chrome at 1280 and 390 px in light and dark themes, and report
53
+ * horizontal overflow, clipped SVG, console errors and CSP violations.
54
+ * Exits 8 when it finds any.
55
+ */
56
+ export declare function verifyFromCli(args: string[]): Promise<void>;
57
+ /**
58
+ * List your own artifacts, newest first, optionally searched by title and
59
+ * description and filtered by kind and tag.
60
+ */
61
+ export declare function listArtifactsFromCli(args: string[]): Promise<void>;
50
62
  export declare function getArtifactFeedbackFromCli(args: string[]): Promise<void>;
51
63
  export declare function shareArtifactFromCli(args: string[]): Promise<void>;
52
64
  export declare function reviseArtifactFromCli(args: string[]): Promise<void>;
package/src/lib/cli.js CHANGED
@@ -9,6 +9,24 @@ function annotationIdFromIri(iri) {
9
9
  var _a;
10
10
  return (_a = iri.replace(/\/+$/, '').split('/').pop()) !== null && _a !== void 0 ? _a : iri;
11
11
  }
12
+ // Mirrors the sdk's formatRevisionConflictMessage.
13
+ function formatRevisionConflictMessage(message, details) {
14
+ var _a;
15
+ if (!(details === null || details === void 0 ? void 0 : details.currentRevisionId)) {
16
+ return message;
17
+ }
18
+ let text = `${message} Current revision: ${details.currentRevisionId}.`;
19
+ if (typeof details.currentVersion === 'number') {
20
+ const firstLine = ((_a = details.currentSummary) !== null && _a !== void 0 ? _a : '')
21
+ .split(/\r?\n/)
22
+ .map((line) => line.replace(/^\s*(?:[-*•]\s+)?/, '').trim())
23
+ .find(Boolean);
24
+ text += firstLine
25
+ ? ` Version ${details.currentVersion}: ${firstLine}`
26
+ : ` Version ${details.currentVersion}.`;
27
+ }
28
+ return text;
29
+ }
12
30
  function isRootAnnotation(annotation) {
13
31
  return annotation.motivation === 'commenting';
14
32
  }
@@ -17,6 +35,7 @@ import { getRememberedBase, rememberBase } from './revision-bases.js';
17
35
  import { installSkillFromCli } from './skill-install.js';
18
36
  import { artisCliVersion } from './version.js';
19
37
  import { collectFlagValues, hasFlag, parseFlagValue } from './args.js';
38
+ import { formatVerifyReport, verifyHtml, VerifyUnavailableError, } from './verify.js';
20
39
  import { CliError, exitCodeForResponse, exitCodes, usageError, } from './exit-codes.js';
21
40
  export { artisCliVersion };
22
41
  export { installSkillFromCli };
@@ -79,6 +98,7 @@ const valueFlags = new Set([
79
98
  '--quote',
80
99
  '--quote-prefix',
81
100
  '--quote-suffix',
101
+ '--query',
82
102
  '--rect',
83
103
  '--requested-change',
84
104
  '--resolve',
@@ -88,6 +108,7 @@ const valueFlags = new Set([
88
108
  '--status',
89
109
  '--base',
90
110
  '--summary',
111
+ '--tag',
91
112
  '--text-end',
92
113
  '--text-start',
93
114
  '--timeout',
@@ -295,9 +316,7 @@ function apiFetch(credentials_1, path_1) {
295
316
  if (!response.ok) {
296
317
  const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${response.status}.`;
297
318
  // A revise conflict is only recoverable with the current revision id.
298
- throw new CliError((payload === null || payload === void 0 ? void 0 : payload.currentRevisionId)
299
- ? `${message} Current revision: ${payload.currentRevisionId}.`
300
- : message, exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
319
+ throw new CliError(formatRevisionConflictMessage(message, payload), exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
301
320
  }
302
321
  return payload;
303
322
  });
@@ -403,6 +422,8 @@ Usage:
403
422
  artis artifact get <artifact-id-or-slug> [--json]
404
423
  artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>] [--json]
405
424
  artis artifact feedback <artifact-id-or-slug> [--json] [--revision <revision-id>]
425
+ artis artifact list [--query <text>] [--kind <value>] [--tag <tag>] [--json]
426
+ artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]
406
427
  artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]
407
428
  artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>] [--resolve <annotation-id>]
408
429
  artis annotate <artifact-id-or-slug> --comment <text> [anchor options]
@@ -435,6 +456,8 @@ Options:
435
456
  --pin-label <text> Short label shown on the artifact canvas pin (annotate).
436
457
  --output <path> Write the artifact HTML to this file (artifact html). Without it, the document goes to stdout.
437
458
  --revision <revision-id> Revision to read (artifact html, artifact feedback). Defaults to the current revision.
459
+ --query <text> Text to find in your artifacts' titles and descriptions (artifact list).
460
+ --tag <tag> Only your artifacts carrying this tag (artifact list). --kind filters by kind.
438
461
  --email <email> Email address for artis share.
439
462
  --role <role> Share role: viewer or commenter. Defaults to viewer.
440
463
  --remove Remove the email from an artifact share list.
@@ -450,7 +473,7 @@ Options:
450
473
  --json Print machine-readable JSON for supported commands.
451
474
 
452
475
  Exit codes:
453
- 0 success, 1 error, 2 usage, 3 auth, 4 not found, 5 revision conflict, 6 watch timeout, 7 rate limited.
476
+ 0 success, 1 error, 2 usage, 3 auth, 4 not found, 5 revision conflict, 6 watch timeout, 7 rate limited, 8 verify found problems.
454
477
 
455
478
  Examples (--host is optional; without it commands target https://artis.xiispace.eu.org):
456
479
  artis publish report.html
@@ -459,6 +482,7 @@ Examples (--host is optional; without it commands target https://artis.xiispace.
459
482
  artis share artifact-slug --host https://artis.example.com --email reviewer@example.com --role commenter
460
483
  artis artifact get artifact-slug --host https://artis.example.com --json
461
484
  artis artifact html artifact-slug --output report.html
485
+ artis verify report.html
462
486
  artis artifact feedback artifact-slug --host https://artis.example.com --json
463
487
  artis annotate artifact-slug --host https://artis.example.com --comment "Tighten this heading" --quote "Checkout latency" --requested-change "Add the affected checkout count"
464
488
  artis reply annotation-123 --host https://artis.example.com --comment "Addressed in the latest revision"
@@ -611,6 +635,11 @@ export function getArtifactHtmlFromCli(args) {
611
635
  if (result === null || result === void 0 ? void 0 : result.revisionId) {
612
636
  yield rememberBase(target.baseUrl, [artifactId, result.artifactId], result.revisionId);
613
637
  }
638
+ // Stderr, so piped HTML or JSON on stdout is unaffected. Strictly false:
639
+ // an older server omits the field and must not trigger the hint.
640
+ if ((result === null || result === void 0 ? void 0 : result.isLatest) === false) {
641
+ console.error(`Note: version ${result.version} is not the latest. The latest is version ${result.latestVersion} (revision ${result.latestRevisionId}); a revise based on this one will be refused.`);
642
+ }
614
643
  if (hasFlag(args, '--json')) {
615
644
  console.log(JSON.stringify(result, null, 2));
616
645
  return;
@@ -631,6 +660,113 @@ export function getArtifactHtmlFromCli(args) {
631
660
  console.log(`Version: ${result.version}`);
632
661
  });
633
662
  }
663
+ /**
664
+ * Render a local HTML file, or a published artifact's stored HTML, in the
665
+ * system Chrome at 1280 and 390 px in light and dark themes, and report
666
+ * horizontal overflow, clipped SVG, console errors and CSP violations.
667
+ * Exits 8 when it finds any.
668
+ */
669
+ export function verifyFromCli(args) {
670
+ return __awaiter(this, void 0, void 0, function* () {
671
+ const [target] = getPositionals(args);
672
+ if (!target) {
673
+ throw usageError('Usage: artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]');
674
+ }
675
+ // Anything that looks like a path (a separator, or an .html/.htm name) is
676
+ // a local file, and a missing one is reported as such rather than sent to
677
+ // the API as an artifact id. A bare name that exists on disk is a file
678
+ // too; any other bare name is an artifact id or slug.
679
+ let html;
680
+ let label;
681
+ const looksLikePath = /[\\/]/.test(target) || /\.html?$/i.test(target);
682
+ const local = yield readFile(target, 'utf8').catch((error) => error);
683
+ if (typeof local === 'string' || looksLikePath) {
684
+ if (typeof local !== 'string') {
685
+ throw local.code === 'ENOENT'
686
+ ? new CliError(`File not found: ${target}`, exitCodes.notFound)
687
+ : usageError(`Cannot read ${target}: ${local.message}`);
688
+ }
689
+ if (parseFlagValue(args, '--revision')) {
690
+ throw usageError('--revision applies to a published artifact, not a local file.');
691
+ }
692
+ html = local;
693
+ label = target;
694
+ }
695
+ else {
696
+ const remote = yield resolveOptionalTarget(args);
697
+ const revisionId = parseFlagValue(args, '--revision');
698
+ const query = revisionId
699
+ ? `?revisionId=${encodeURIComponent(revisionId)}`
700
+ : '';
701
+ const result = yield apiFetchOptional(remote, `/api/artifacts/${encodeURIComponent(target)}/html${query}`);
702
+ if (!(result === null || result === void 0 ? void 0 : result.html)) {
703
+ throw new Error('Artifact response did not include revision HTML.');
704
+ }
705
+ html = result.html;
706
+ label = `${target} v${result.version}`;
707
+ }
708
+ let report;
709
+ try {
710
+ report = yield verifyHtml(html);
711
+ }
712
+ catch (error) {
713
+ if (error instanceof VerifyUnavailableError) {
714
+ throw new CliError(error.message, exitCodes.error);
715
+ }
716
+ throw error;
717
+ }
718
+ if (hasFlag(args, '--json')) {
719
+ console.log(JSON.stringify(report, null, 2));
720
+ }
721
+ else {
722
+ console.log(`Verified ${label}`);
723
+ for (const line of formatVerifyReport(report)) {
724
+ console.log(line);
725
+ }
726
+ }
727
+ if (!report.ok) {
728
+ throw new CliError('', exitCodes.verifyFailed);
729
+ }
730
+ });
731
+ }
732
+ /**
733
+ * List your own artifacts, newest first, optionally searched by title and
734
+ * description and filtered by kind and tag.
735
+ */
736
+ export function listArtifactsFromCli(args) {
737
+ return __awaiter(this, void 0, void 0, function* () {
738
+ var _a, _b;
739
+ const credentials = yield resolveCredentials(args);
740
+ const params = new URLSearchParams({ owner: 'me' });
741
+ const query = parseFlagValue(args, '--query');
742
+ const kind = parseFlagValue(args, '--kind');
743
+ const tag = parseFlagValue(args, '--tag');
744
+ if (query)
745
+ params.set('q', query);
746
+ if (kind)
747
+ params.set('kind', parseKind(kind));
748
+ if (tag)
749
+ params.set('tag', tag);
750
+ const result = yield apiFetch(credentials, `/api/artifacts?${params}`);
751
+ if (hasFlag(args, '--json')) {
752
+ console.log(JSON.stringify(result, null, 2));
753
+ return;
754
+ }
755
+ const artifacts = (_a = result === null || result === void 0 ? void 0 : result.artifacts) !== null && _a !== void 0 ? _a : [];
756
+ if (!artifacts.length) {
757
+ console.log(query || kind || tag
758
+ ? 'No artifacts match.'
759
+ : 'You have no artifacts yet.');
760
+ return;
761
+ }
762
+ for (const artifact of artifacts) {
763
+ const tags = ((_b = artifact.metadata.tags) === null || _b === void 0 ? void 0 : _b.length)
764
+ ? ` #${artifact.metadata.tags.join(' #')}`
765
+ : '';
766
+ console.log(`${artifact.slug} ${artifact.metadata.visibility} ${artifact.metadata.kind} ${artifact.metadata.title}${tags}`);
767
+ }
768
+ });
769
+ }
634
770
  export function getArtifactFeedbackFromCli(args) {
635
771
  return __awaiter(this, void 0, void 0, function* () {
636
772
  const [artifactId] = getPositionals(args);
@@ -707,7 +843,7 @@ export function shareArtifactFromCli(args) {
707
843
  }
708
844
  export function reviseArtifactFromCli(args) {
709
845
  return __awaiter(this, void 0, void 0, function* () {
710
- var _a;
846
+ var _a, _b;
711
847
  const [artifactId, filePath] = getPositionals(args);
712
848
  const summary = parseFlagValue(args, '--summary');
713
849
  if (!artifactId || !filePath) {
@@ -746,6 +882,18 @@ export function reviseArtifactFromCli(args) {
746
882
  }
747
883
  console.log(`Revision ${result.revision.id}`);
748
884
  console.log(`Version ${result.revision.version}`);
885
+ // The anchored text of these is gone: the agent should check whether the
886
+ // feedback was addressed or the text was lost by accident.
887
+ const orphaned = (_b = result.orphanedAnnotationIds) !== null && _b !== void 0 ? _b : [];
888
+ if (result.anchorStatusComputed === false) {
889
+ console.log('Anchor status: could not be computed for this revision; check open annotations by hand.');
890
+ }
891
+ else if (orphaned.length) {
892
+ console.log(`Orphaned annotations (anchored text removed): ${orphaned.length}`);
893
+ for (const id of orphaned) {
894
+ console.log(` ${id}`);
895
+ }
896
+ }
749
897
  if (baseRevisionId && !explicitBase) {
750
898
  console.log(`Base ${baseRevisionId} (remembered from this machine)`);
751
899
  }
@@ -1012,6 +1160,14 @@ export function runArtisCli() {
1012
1160
  yield getArtifactHtmlFromCli(rest.slice(1));
1013
1161
  return;
1014
1162
  }
1163
+ if (command === 'verify') {
1164
+ yield verifyFromCli(rest);
1165
+ return;
1166
+ }
1167
+ if (command === 'artifact' && rest[0] === 'list') {
1168
+ yield listArtifactsFromCli(rest.slice(1));
1169
+ return;
1170
+ }
1015
1171
  if (command === 'artifact' && rest[0] === 'feedback') {
1016
1172
  yield getArtifactFeedbackFromCli(rest.slice(1));
1017
1173
  return;
@@ -12,6 +12,8 @@ export declare const exitCodes: {
12
12
  readonly revisionConflict: 5;
13
13
  readonly watchTimeout: 6;
14
14
  readonly rateLimited: 7;
15
+ /** `artis verify` found problems in the rendered page. */
16
+ readonly verifyFailed: 8;
15
17
  };
16
18
  export type ExitCode = (typeof exitCodes)[keyof typeof exitCodes];
17
19
  /** An error that knows which exit code it should end the process with. */
@@ -12,6 +12,8 @@ export const exitCodes = {
12
12
  revisionConflict: 5,
13
13
  watchTimeout: 6,
14
14
  rateLimited: 7,
15
+ /** `artis verify` found problems in the rendered page. */
16
+ verifyFailed: 8,
15
17
  };
16
18
  /** An error that knows which exit code it should end the process with. */
17
19
  export class CliError extends Error {
@@ -0,0 +1,56 @@
1
+ export declare const verifyWidths: readonly [1280, 390];
2
+ export declare const verifyThemes: readonly ["light", "dark"];
3
+ export type VerifyTheme = (typeof verifyThemes)[number];
4
+ /** A copy of usercontent's artifact CSP (apps/usercontent/src/worker/csp.ts);
5
+ * scripts/verify-unit.mjs keeps the two identical. */
6
+ export declare function artifactContentSecurityPolicy(origin: string): string;
7
+ export interface OverflowFinding {
8
+ scrollWidth: number;
9
+ clientWidth: number;
10
+ /** `overflow-x: hidden` on <html>/<body>: no scrollbar, but the content
11
+ * past the edge is still cut off. */
12
+ hiddenByPage: boolean;
13
+ /** Elements reaching past the right edge, widest first (at most 5). */
14
+ offenders: Array<{
15
+ element: string;
16
+ right: number;
17
+ }>;
18
+ }
19
+ export interface ClippedSvgFinding {
20
+ element: string;
21
+ /** How far drawn content extends past the SVG viewport, per side. */
22
+ overflow: {
23
+ top: number;
24
+ right: number;
25
+ bottom: number;
26
+ left: number;
27
+ };
28
+ }
29
+ export interface CspViolation {
30
+ directive: string;
31
+ blocked: string;
32
+ }
33
+ export interface VerifyRun {
34
+ width: number;
35
+ theme: VerifyTheme;
36
+ overflow: OverflowFinding | null;
37
+ clippedSvgs: ClippedSvgFinding[];
38
+ consoleErrors: string[];
39
+ cspViolations: CspViolation[];
40
+ }
41
+ export interface VerifyReport {
42
+ ok: boolean;
43
+ runs: VerifyRun[];
44
+ }
45
+ export declare class VerifyUnavailableError extends Error {
46
+ }
47
+ /** Insert the theme boot as the first child of <head> — the same stamp
48
+ * usercontent's inline boot script applies for an explicit theme. Like
49
+ * usercontent (which injects through an HTMLRewriter `head` handler), a
50
+ * document without a `<head>` tag gets no stamp, only the matching
51
+ * `prefers-color-scheme`; prepending would also push the doctype out of
52
+ * first place and render in quirks mode. */
53
+ export declare function stampTheme(html: string, theme: VerifyTheme): string;
54
+ export declare function verifyHtml(html: string): Promise<VerifyReport>;
55
+ /** Human-readable report: one block per problem, listing the runs it hit. */
56
+ export declare function formatVerifyReport(report: VerifyReport): string[];
@@ -0,0 +1,395 @@
1
+ import { __awaiter } from "tslib";
2
+ import { createServer } from 'node:http';
3
+ /*
4
+ * `artis verify`: render an artifact the way viewers get it and report what
5
+ * an agent cannot see from the source. Runs locally in a headless browser
6
+ * (the system Chrome through the optional `playwright-core` dependency), so
7
+ * it needs no server or bridge support.
8
+ *
9
+ * The page is served from a local origin with the same Content-Security-
10
+ * Policy usercontent sends, and each theme is applied the way the bridge's
11
+ * theme boot does it (`data-theme` + `color-scheme` on <html>, plus the
12
+ * matching `prefers-color-scheme`).
13
+ */
14
+ export const verifyWidths = [1280, 390];
15
+ export const verifyThemes = ['light', 'dark'];
16
+ /** A copy of usercontent's artifact CSP (apps/usercontent/src/worker/csp.ts);
17
+ * scripts/verify-unit.mjs keeps the two identical. */
18
+ export function artifactContentSecurityPolicy(origin) {
19
+ return (`sandbox allow-scripts allow-forms; default-src 'none'; ` +
20
+ `script-src 'unsafe-inline' ${origin}; style-src 'unsafe-inline'; ` +
21
+ 'img-src data: blob:; font-src data:');
22
+ }
23
+ export class VerifyUnavailableError extends Error {
24
+ }
25
+ function launchBrowser() {
26
+ return __awaiter(this, void 0, void 0, function* () {
27
+ let chromium;
28
+ try {
29
+ // A variable specifier keeps bundlers and tsc from requiring the
30
+ // optional dependency at build time.
31
+ const specifier = 'playwright-core';
32
+ ({ chromium } = yield import(specifier));
33
+ }
34
+ catch (_a) {
35
+ throw new VerifyUnavailableError('artis verify needs playwright-core. Install it next to the CLI: npm install -g playwright-core');
36
+ }
37
+ const executablePath = process.env['ARTIS_CHROME_PATH'];
38
+ const attempts = executablePath
39
+ ? [{ executablePath }]
40
+ : [{ channel: 'chrome' }, { channel: 'msedge' }, { channel: 'chromium' }];
41
+ for (const attempt of attempts) {
42
+ try {
43
+ return yield chromium.launch(Object.assign({ headless: true }, attempt));
44
+ }
45
+ catch (_b) {
46
+ // Try the next browser.
47
+ }
48
+ }
49
+ throw new VerifyUnavailableError(executablePath
50
+ ? `Could not launch the browser at ARTIS_CHROME_PATH (${executablePath}).`
51
+ : 'artis verify uses the system Google Chrome (or Edge). Install one, or set ARTIS_CHROME_PATH to a Chromium-based browser.');
52
+ });
53
+ }
54
+ /** Serve one document at `/` with the artifact CSP, the theme stamped the
55
+ * way usercontent's theme boot does it. */
56
+ function serveDocument(html) {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const server = createServer((request, response) => {
59
+ var _a;
60
+ const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://localhost');
61
+ const theme = url.searchParams.get('theme') === 'dark' ? 'dark' : 'light';
62
+ if (url.pathname !== '/') {
63
+ response.writeHead(404).end();
64
+ return;
65
+ }
66
+ const origin = `http://${request.headers.host}`;
67
+ response.writeHead(200, {
68
+ 'content-type': 'text/html; charset=utf-8',
69
+ 'content-security-policy': artifactContentSecurityPolicy(origin),
70
+ });
71
+ response.end(stampTheme(html, theme));
72
+ });
73
+ yield new Promise((resolve, reject) => {
74
+ server.once('error', reject);
75
+ server.listen(0, '127.0.0.1', () => {
76
+ server.off('error', reject);
77
+ resolve();
78
+ });
79
+ });
80
+ const { port } = server.address();
81
+ return {
82
+ server,
83
+ url: (theme) => `http://127.0.0.1:${port}/?theme=${theme}`,
84
+ };
85
+ });
86
+ }
87
+ /** Insert the theme boot as the first child of <head> — the same stamp
88
+ * usercontent's inline boot script applies for an explicit theme. Like
89
+ * usercontent (which injects through an HTMLRewriter `head` handler), a
90
+ * document without a `<head>` tag gets no stamp, only the matching
91
+ * `prefers-color-scheme`; prepending would also push the doctype out of
92
+ * first place and render in quirks mode. */
93
+ export function stampTheme(html, theme) {
94
+ const boot = `<script>document.documentElement.setAttribute('data-theme','${theme}');document.documentElement.style.colorScheme='${theme}';</script>`;
95
+ const head = /<head\b[^>]*>/i.exec(html);
96
+ if (!head) {
97
+ return html;
98
+ }
99
+ const at = head.index + head[0].length;
100
+ return html.slice(0, at) + boot + html.slice(at);
101
+ }
102
+ /** Records CSP violations the page itself observes. */
103
+ const RECORD_CSP_VIOLATIONS = `
104
+ window.__artisCsp = [];
105
+ document.addEventListener('securitypolicyviolation', (event) => {
106
+ window.__artisCsp.push({
107
+ directive: event.effectiveDirective || event.violatedDirective,
108
+ blocked: event.blockedURI || 'inline',
109
+ });
110
+ });`;
111
+ /** In-page checks, run after load. Kept as a string so it executes in the
112
+ * page untouched by the CLI's TypeScript build. */
113
+ const INSPECT_PAGE = `(() => {
114
+ const describe = (el) => {
115
+ let text = el.tagName.toLowerCase();
116
+ if (el.id) text += '#' + el.id;
117
+ const cls = typeof el.className === 'string' ? el.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2) : [];
118
+ if (cls.length) text += '.' + cls.join('.');
119
+ return text;
120
+ };
121
+ const root = document.documentElement;
122
+ const clientWidth = root.clientWidth;
123
+ const scrollWidth = Math.max(root.scrollWidth, document.body ? document.body.scrollWidth : 0);
124
+ let overflow = null;
125
+ if (scrollWidth > clientWidth + 1) {
126
+ // Elements past either edge whose own scroll container is the page:
127
+ // an element inside overflow-x: auto/hidden is contained, not the cause.
128
+ const scrolls = (el) => {
129
+ const ox = getComputedStyle(el).overflowX;
130
+ return ox === 'auto' || ox === 'scroll' || ox === 'hidden' || ox === 'clip';
131
+ };
132
+ const contained = (el) => {
133
+ for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
134
+ if (scrolls(p)) return true;
135
+ }
136
+ return false;
137
+ };
138
+ const rtl = getComputedStyle(root).direction === 'rtl';
139
+ const offenders = [];
140
+ for (const el of document.body ? document.body.querySelectorAll('*') : []) {
141
+ const rect = el.getBoundingClientRect();
142
+ const left = rect.left + window.scrollX;
143
+ const right = rect.right + window.scrollX;
144
+ // Past the left edge only counts in a right-to-left document: in LTR
145
+ // it is the usual off-screen pattern (skip links, visually-hidden
146
+ // text), which the page cannot scroll to anyway.
147
+ const past = rtl ? Math.max(right - clientWidth, -left) : right - clientWidth;
148
+ if (past > 1 && !contained(el)) offenders.push({ element: describe(el), right: Math.round(right), past });
149
+ }
150
+ offenders.sort((a, b) => b.past - a.past);
151
+ // overflow-x: hidden on <html>/<body> hides the scrollbar but still cuts
152
+ // the content off, so it is reported, flagged as hidden.
153
+ const hiddenBy = [root, document.body].find((el) => {
154
+ if (!el) return false;
155
+ const ox = getComputedStyle(el).overflowX;
156
+ return ox === 'hidden' || ox === 'clip';
157
+ });
158
+ overflow = {
159
+ scrollWidth,
160
+ clientWidth,
161
+ hiddenByPage: Boolean(hiddenBy),
162
+ offenders: offenders.slice(0, 5).map(({ element, right }) => ({ element, right })),
163
+ };
164
+ }
165
+
166
+ // Drawn content of an <svg>, in its user units: the union of its visible
167
+ // leaf shapes (with half their stroke), skipping anything under a
168
+ // clip-path or mask (clipped on purpose) and anything not painted.
169
+ const LEAVES = 'path, rect, circle, ellipse, line, polyline, polygon, text, image, use, foreignObject';
170
+ const drawnBox = (svg) => {
171
+ const toUser = svg.getScreenCTM();
172
+ if (!toUser) return null;
173
+ const inverse = toUser.inverse();
174
+ let box = null;
175
+ for (const leaf of svg.querySelectorAll(LEAVES)) {
176
+ if (leaf.closest('defs, clipPath, mask, marker, pattern, symbol, linearGradient, radialGradient')) continue;
177
+ // A nested <svg> clips its own content; it is checked on its own terms
178
+ // only when it is the outermost one.
179
+ if (leaf.parentElement && leaf.parentElement.closest('svg') !== svg) continue;
180
+ let hidden = false;
181
+ for (let el = leaf; el && el !== svg; el = el.parentElement) {
182
+ const cs = getComputedStyle(el);
183
+ if (el.hasAttribute('clip-path') || el.hasAttribute('mask') || (cs.clipPath && cs.clipPath !== 'none') || (cs.mask && cs.mask !== 'none') || cs.display === 'none' || Number(cs.opacity) === 0) {
184
+ hidden = true;
185
+ break;
186
+ }
187
+ }
188
+ const leafStyle = getComputedStyle(leaf);
189
+ if (hidden || leafStyle.visibility !== 'visible') continue;
190
+ // Paints nothing (a transparent hover overlay): not visible content.
191
+ const paints = (paint) => Boolean(paint) && paint !== 'none' && paint !== 'transparent' && !(paint.startsWith('rgba(') && paint.replace(/ /g, '').endsWith(',0)'));
192
+ if (leaf.tagName !== 'image' && leaf.tagName !== 'use' && leaf.tagName !== 'foreignObject' && !paints(leafStyle.fill) && !paints(leafStyle.stroke)) continue;
193
+ let b;
194
+ try { b = leaf.getBBox(); } catch { continue; }
195
+ if (b.width === 0 && b.height === 0) continue;
196
+ const half = leafStyle.stroke && leafStyle.stroke !== 'none' ? (parseFloat(leafStyle.strokeWidth) || 0) / 2 : 0;
197
+ const matrix = leaf.getScreenCTM();
198
+ if (!matrix) continue;
199
+ const m = inverse.multiply(matrix);
200
+ for (const [x, y] of [[b.x - half, b.y - half], [b.x + b.width + half, b.y - half], [b.x - half, b.y + b.height + half], [b.x + b.width + half, b.y + b.height + half]]) {
201
+ const px = m.a * x + m.c * y + m.e;
202
+ const py = m.b * x + m.d * y + m.f;
203
+ box = box
204
+ ? { x1: Math.min(box.x1, px), y1: Math.min(box.y1, py), x2: Math.max(box.x2, px), y2: Math.max(box.y2, py) }
205
+ : { x1: px, y1: py, x2: px, y2: py };
206
+ }
207
+ }
208
+ return box;
209
+ };
210
+
211
+ // The region of user space the SVG actually shows: the viewBox scaled into
212
+ // the element's box under preserveAspectRatio (meet shows more than the
213
+ // viewBox, slice less), or the box itself without a viewBox.
214
+ const visibleRegion = (svg) => {
215
+ const width = svg.clientWidth || svg.getBoundingClientRect().width;
216
+ const height = svg.clientHeight || svg.getBoundingClientRect().height;
217
+ if (!width || !height) return null;
218
+ const vb = svg.viewBox && svg.viewBox.baseVal;
219
+ if (!vb || !(vb.width > 0) || !(vb.height > 0)) return { x1: 0, y1: 0, x2: width, y2: height };
220
+ const par = svg.preserveAspectRatio.baseVal;
221
+ if (par.align === 1) return { x1: vb.x, y1: vb.y, x2: vb.x + vb.width, y2: vb.y + vb.height };
222
+ const scale = par.meetOrSlice === 2
223
+ ? Math.max(width / vb.width, height / vb.height)
224
+ : Math.min(width / vb.width, height / vb.height);
225
+ const shownWidth = width / scale;
226
+ const shownHeight = height / scale;
227
+ const xAlign = (par.align - 2) % 3;
228
+ const yAlign = Math.floor((par.align - 2) / 3);
229
+ const x1 = vb.x - ((shownWidth - vb.width) * xAlign) / 2;
230
+ const y1 = vb.y - ((shownHeight - vb.height) * yAlign) / 2;
231
+ return { x1, y1, x2: x1 + shownWidth, y2: y1 + shownHeight };
232
+ };
233
+
234
+ const clippedSvgs = [];
235
+ for (const svg of document.querySelectorAll('svg')) {
236
+ if (svg.parentElement && svg.parentElement.closest('svg')) continue;
237
+ const style = getComputedStyle(svg);
238
+ if (style.overflow === 'visible' || style.display === 'none') continue;
239
+ const shown = visibleRegion(svg);
240
+ const drawn = shown && drawnBox(svg);
241
+ if (!drawn) continue;
242
+ const tolerance = Math.max(1, (shown.x2 - shown.x1) / 500);
243
+ const over = {
244
+ top: Math.max(0, shown.y1 - drawn.y1),
245
+ right: Math.max(0, drawn.x2 - shown.x2),
246
+ bottom: Math.max(0, drawn.y2 - shown.y2),
247
+ left: Math.max(0, shown.x1 - drawn.x1),
248
+ };
249
+ if (Object.values(over).some((v) => v > tolerance)) {
250
+ const round = (v) => Math.round(v * 10) / 10;
251
+ clippedSvgs.push({
252
+ element: describe(svg),
253
+ overflow: { top: round(over.top), right: round(over.right), bottom: round(over.bottom), left: round(over.left) },
254
+ });
255
+ }
256
+ }
257
+
258
+ return { overflow, clippedSvgs, cspViolations: window.__artisCsp || [] };
259
+ })()`;
260
+ /** Chrome reports CSP blocks as console errors too; those are counted as
261
+ * CSP violations, not as script errors. */
262
+ function isCspConsoleMessage(text) {
263
+ return /Content Security Policy/i.test(text);
264
+ }
265
+ export function verifyHtml(html) {
266
+ return __awaiter(this, void 0, void 0, function* () {
267
+ // Server first, then the browser, each released in its own finally: a
268
+ // failed launch or close must never leave a listening server behind (it
269
+ // would keep the CLI process alive).
270
+ const { server, url } = yield serveDocument(html);
271
+ try {
272
+ const browser = yield launchBrowser();
273
+ try {
274
+ return yield runChecks(browser, url);
275
+ }
276
+ finally {
277
+ yield browser.close().catch(() => undefined);
278
+ }
279
+ }
280
+ finally {
281
+ yield new Promise((resolve) => server.close(resolve));
282
+ }
283
+ });
284
+ }
285
+ function runChecks(browser, url) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ const runs = [];
288
+ for (const width of verifyWidths) {
289
+ for (const theme of verifyThemes) {
290
+ const context = yield browser.newContext({
291
+ viewport: { width, height: 900 },
292
+ colorScheme: theme,
293
+ });
294
+ try {
295
+ const page = yield context.newPage();
296
+ const consoleErrors = [];
297
+ page.on('console', (message) => {
298
+ if (message.type() === 'error' &&
299
+ !isCspConsoleMessage(message.text())) {
300
+ consoleErrors.push(message.text());
301
+ }
302
+ });
303
+ page.on('pageerror', (error) => {
304
+ // eval / new Function blocked by the CSP throws an EvalError;
305
+ // the securitypolicyviolation event already records it.
306
+ if (!isCspConsoleMessage(error.message)) {
307
+ consoleErrors.push(error.message);
308
+ }
309
+ });
310
+ yield page.addInitScript(RECORD_CSP_VIOLATIONS);
311
+ yield page.goto(url(theme), { waitUntil: 'load', timeout: 15000 });
312
+ // Let late renders and web fonts settle.
313
+ yield page.waitForTimeout(400);
314
+ const findings = yield page.evaluate(INSPECT_PAGE);
315
+ runs.push({
316
+ width,
317
+ theme,
318
+ overflow: findings.overflow,
319
+ clippedSvgs: findings.clippedSvgs,
320
+ consoleErrors: [...new Set(consoleErrors)],
321
+ cspViolations: dedupe(findings.cspViolations),
322
+ });
323
+ }
324
+ finally {
325
+ yield context.close();
326
+ }
327
+ }
328
+ }
329
+ return {
330
+ ok: runs.every((run) => !run.overflow &&
331
+ !run.clippedSvgs.length &&
332
+ !run.consoleErrors.length &&
333
+ !run.cspViolations.length),
334
+ runs,
335
+ };
336
+ });
337
+ }
338
+ function dedupe(violations) {
339
+ const seen = new Set();
340
+ return violations.filter((violation) => {
341
+ const key = `${violation.directive} ${violation.blocked}`;
342
+ if (seen.has(key))
343
+ return false;
344
+ seen.add(key);
345
+ return true;
346
+ });
347
+ }
348
+ /** Human-readable report: one block per problem, listing the runs it hit. */
349
+ export function formatVerifyReport(report) {
350
+ if (report.ok) {
351
+ return [
352
+ `No problems found at ${verifyWidths.join(' and ')} px in light and dark themes.`,
353
+ ];
354
+ }
355
+ const lines = [];
356
+ const label = (run) => `${run.width}px ${run.theme}`;
357
+ const group = (pick, key) => {
358
+ var _a;
359
+ const byKey = new Map();
360
+ for (const run of report.runs) {
361
+ for (const item of pick(run)) {
362
+ const entry = (_a = byKey.get(key(item))) !== null && _a !== void 0 ? _a : { item, runs: [] };
363
+ entry.runs.push(label(run));
364
+ byKey.set(key(item), entry);
365
+ }
366
+ }
367
+ return [...byKey.values()];
368
+ };
369
+ for (const run of report.runs) {
370
+ if (run.overflow) {
371
+ const offenders = run.overflow.offenders
372
+ .map((o) => `${o.element} (to ${o.right}px)`)
373
+ .join(', ');
374
+ const hidden = run.overflow.hiddenByPage
375
+ ? ' (hidden by overflow-x on the page, so the content past the edge is cut off)'
376
+ : '';
377
+ lines.push(`Horizontal overflow at ${label(run)}: page is ${run.overflow.scrollWidth}px wide in a ${run.overflow.clientWidth}px viewport${hidden}${offenders ? `; widest: ${offenders}` : ''}.`);
378
+ }
379
+ }
380
+ for (const { item, runs } of group((run) => run.clippedSvgs, (svg) => `${svg.element} ${JSON.stringify(svg.overflow)}`)) {
381
+ const sides = Object.entries(item.overflow)
382
+ .filter(([, value]) => value > 0)
383
+ .map(([side, value]) => `${side} ${value}`)
384
+ .join(', ');
385
+ lines.push(`Clipped SVG ${item.element} (content past its viewport: ${sides}) at ${runs.join(', ')}.`);
386
+ }
387
+ for (const { item, runs } of group((run) => run.consoleErrors, (text) => text)) {
388
+ lines.push(`Console error at ${runs.join(', ')}: ${item}`);
389
+ }
390
+ for (const { item, runs } of group((run) => run.cspViolations, (violation) => `${violation.directive} ${violation.blocked}`)) {
391
+ lines.push(`CSP violation (${item.directive}) blocking ${item.blocked} at ${runs.join(', ')}. Artifacts may load nothing external: inline it or use a data: URL.`);
392
+ }
393
+ return lines;
394
+ }
395
+ //# sourceMappingURL=verify.js.map