uiport 0.1.2 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -4,6 +4,27 @@ Notable changes are documented here. Versions follow Semantic Versioning.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.1.3] — 2026-11-28
8
+
9
+ ### Added
10
+ - `uiport diff --before DIRECTORY --after DIRECTORY` compares two exported sections: the pixels they render and the limitations they report.
11
+ - `uiport examples` serves the original examples that ship with the package, so the tool can be tried without choosing a page first.
12
+ - `uiport inspect --dir DIRECTORY` reads the limitations of an exported section without opening a browser.
13
+ - `uiport capture --dry-run` checks the selector against the page and writes nothing.
14
+ - Every failure carries a stable code and a hint, so a script can branch on it and a person knows what to do.
15
+
16
+ ### Changed
17
+ - Without `--json` the result is a readable summary on stdout; with `--json` it stays one JSON document. Progress always goes to stderr.
18
+ - The agent skill tells what to do with each failure code and each limitation.
19
+
20
+ ### Fixed
21
+ - Bind a contextual custom property to the element of the exported DOM. The identifiers are assigned by position, so an observation from another viewport could point the property at a different element.
22
+ - Keep a style element created by a script in one piece when its text holds a closing tag, and escape that sequence in the exported CSS whatever its case.
23
+ - Serve a font in the OpenType format with the type the browser expects, instead of an opaque type that the browser refuses to load.
24
+ - Publish the captured directory with a single rename, so a reader never observes it half written.
25
+ - The markers that connect a capture to the validation of its result live in one module, and the validation reports an artifact that does not carry them instead of reading it as an empty one.
26
+ - Redact the message of a failure before it reaches any channel, in the readable output as well as in the JSON document.
27
+
7
28
  ## [0.1.2] — 2026-11-28
8
29
 
9
30
  ### Fixed
package/README.md CHANGED
@@ -25,10 +25,10 @@ Requires **Node.js 22.14+**; Node 24 LTS recommended. Chromium is installed expl
25
25
  Run these commands in any directory, including an empty one. `npx` fetches UIport automatically; you do not need a `package.json` or `npm install` in that directory. `browser install` prepares Chromium in Playwright's shared browser cache.
26
26
 
27
27
  ```sh
28
- npx uiport@0.1.2 browser install
29
- npx uiport@0.1.2 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
30
- npx uiport@0.1.2 serve --dir ./my-section
31
- npx uiport@0.1.2 validate --url "https://your-site.example" --selector "#hero" --dir ./my-section
28
+ npx uiport@0.1.3 browser install
29
+ npx uiport@0.1.3 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
30
+ npx uiport@0.1.3 serve --dir ./my-section
31
+ npx uiport@0.1.3 validate --url "https://your-site.example" --selector "#hero" --dir ./my-section
32
32
  ```
33
33
 
34
34
  Choose the selector using your browser's **Inspect element** tool. It must match exactly one container, such as `main`, `section` or a `div`, and that container must render something at the captured viewport: a root that displays nothing is reported as a partial result. Use `body` to capture the whole visible page, or `html` to include original head scripts as well. This captures one page, not a multi-page crawl.
@@ -62,10 +62,13 @@ Open `http://127.0.0.1:4174`. You can move that output directory and serve it ag
62
62
  | `capture --url URL --selector CSS --out DIR` | Capture one rendered section |
63
63
  | `serve --dir DIR --port 4173` | Preview on loopback; stop with Ctrl+C |
64
64
  | `validate --url URL --selector CSS --dir DIR` | Compare screenshots and observe resource errors |
65
+ | `inspect --dir DIR` | Read the limitations of an exported section, without a browser |
66
+ | `diff --before DIR --after DIR` | Compare two exported sections: what they render and what they report |
67
+ | `examples` | Serve the original examples that ship with the package |
65
68
  | `browser install` | Install Chromium matched to the bundled Playwright version |
66
69
  | `--help` / `--version` | Inspect the CLI without starting a browser |
67
70
 
68
- `capture` and `validate` share `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` and `--json`. Defaults: four viewports (`1440x900,1024x768,768x1024,375x812`), 1200 ms settle time, 120 s whole-operation deadline and 80 scroll steps. The default locale is `pt-BR`; use the same `--locale` and `--color-scheme` in capture and validation.
71
+ `capture` and `validate` share `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` and `--json`. `capture --dry-run` checks the selector against the page and writes nothing. Defaults: four viewports (`1440x900,1024x768,768x1024,375x812`), 1200 ms settle time, 120 s whole-operation deadline and 80 scroll steps. The default locale is `pt-BR`; use the same `--locale` and `--color-scheme` in capture and validation.
69
72
 
70
73
  Capture limits copied resources to 20 MiB each and 100 MiB in total. Override with `--max-resource-mb` and `--max-total-mb`. The capture reuses responses received by its fresh browser context (including resources requiring Referer), then uses HTTP fetch as fallback. Budgets limit retained response bytes and exported downloads, not the browser's complete memory or the temporary buffer materialized by Playwright. Fallback fetching has a 15 s request deadline.
71
74
 
@@ -78,7 +81,7 @@ Set `UIPORT_BROWSER_PATH` to explicitly choose an executable. Otherwise UIport t
78
81
  - **Exit 1:** command failed, or validation failed its requested checks.
79
82
  - **Validation exit 0:** the observed visual/network checks passed. Behavior remains `not-tested`.
80
83
 
81
- `--json` produces one result on stdout for capture/validate/browser; progress goes to stderr. `serve --json` emits one readiness document and stays running until stopped. A script calling capture must handle exit 2, not treat every nonzero exit as “no files”. An existing nonempty output directory is never overwritten. Retained source code is reported as `SOURCE_RUNTIME_UNVERIFIED`: test its interactions; a screenshot match is not proof that all runtime dependencies survived.
84
+ Without `--json` the result is a readable summary on stdout; with `--json` it is one JSON document. Progress always goes to stderr. `serve --json` emits one readiness document and stays running until stopped. A script calling capture must handle exit 2, not treat every nonzero exit as “no files”. An existing nonempty output directory is never overwritten. Retained source code is reported as `SOURCE_RUNTIME_UNVERIFIED`: test its interactions; a screenshot match is not proof that all runtime dependencies survived.
82
85
 
83
86
  Validation disables animations for screenshots. It compares pixels with a default 2% difference allowance and up to 5 px height difference; this does not certify hover, clicks, scroll animation or framework state. External requests are **blocked by default** in the exported page, including another localhost port. `--allow-external` opts out of that offline check. Existing prototype exports remain usable with `validate`; its legacy root marker is recognized without rewriting the folder. New exports use UIport markers. Inspect the [support matrix](docs/support.md) before interpreting a passing result.
84
87
 
package/README.pt-BR.md CHANGED
@@ -25,10 +25,10 @@ Requer **Node.js 22.14+**; recomendamos Node 24 LTS. O Chromium é instalado exp
25
25
  Execute os comandos em uma pasta de sua escolha, que pode estar vazia. O `npx` obtém o UIport automaticamente; não é necessário criar um `package.json` nem rodar `npm install` nessa pasta. `browser install` prepara o Chromium no cache compartilhado do Playwright.
26
26
 
27
27
  ```sh
28
- npx uiport@0.1.2 browser install
29
- npx uiport@0.1.2 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
30
- npx uiport@0.1.2 serve --dir ./minha-secao
31
- npx uiport@0.1.2 validate --url "https://seu-site.example" --selector "#hero" --dir ./minha-secao
28
+ npx uiport@0.1.3 browser install
29
+ npx uiport@0.1.3 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
30
+ npx uiport@0.1.3 serve --dir ./minha-secao
31
+ npx uiport@0.1.3 validate --url "https://seu-site.example" --selector "#hero" --dir ./minha-secao
32
32
  ```
33
33
 
34
34
  Para escolher o seletor, use **Inspecionar elemento** no navegador. Ele precisa encontrar exatamente um container, como `main`, `section` ou `div`, e esse container precisa renderizar algo no tamanho de tela capturado: uma raiz que não exibe nada é relatada como resultado parcial. Use `body` para capturar a página visível completa ou `html` para incluir também scripts originais do head. Isso captura uma página, sem percorrer automaticamente outras URLs do site.
@@ -62,10 +62,13 @@ Abra `http://127.0.0.1:4174`. A pasta de saída pode ser movida e servida novame
62
62
  | `capture --url URL --selector CSS --out PASTA` | Captura uma seção renderizada |
63
63
  | `serve --dir PASTA --port 4173` | Abre servidor local; encerra com Ctrl+C |
64
64
  | `validate --url URL --selector CSS --dir PASTA` | Compara imagens e verifica erros de recursos |
65
+ | `inspect --dir PASTA` | Lê as limitações de uma seção exportada, sem abrir navegador |
66
+ | `diff --before PASTA --after PASTA` | Compara duas seções exportadas: o que renderizam e o que relatam |
67
+ | `examples` | Serve os exemplos originais que acompanham o pacote |
65
68
  | `browser install` | Instala Chromium compatível com a versão de Playwright do pacote |
66
69
  | `--help` / `--version` | Mostra ajuda ou versão sem abrir navegador |
67
70
 
68
- Capture e validate aceitam `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` e `--json`. Padrões: `1440x900,1024x768,768x1024,375x812`, espera de 1200 ms, prazo total de 120 s, 80 passos de rolagem, idioma `pt-BR` e tema `light`. Use o mesmo `--locale` nos dois comandos quando precisar de outro idioma.
71
+ Capture e validate aceitam `--viewports`, `--wait`, `--timeout`, `--max-scroll-steps`, `--locale`, `--color-scheme` e `--json`. `capture --dry-run` confere o seletor na página sem escrever nada. Padrões: `1440x900,1024x768,768x1024,375x812`, espera de 1200 ms, prazo total de 120 s, 80 passos de rolagem, idioma `pt-BR` e tema `light`. Use o mesmo `--locale` nos dois comandos quando precisar de outro idioma.
69
72
 
70
73
  A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, configuráveis por `--max-resource-mb` e `--max-total-mb`. A captura reaproveita respostas recebidas pelo navegador, incluindo recursos que exigem Referer, e usa fetch HTTP como fallback. Os orçamentos limitam bytes retidos e baixados pela exportação, não a memória completa do navegador nem o buffer temporário materializado pelo Playwright. O fetch de fallback tem prazo de até 15 s.
71
74
 
@@ -78,7 +81,7 @@ A captura limita recursos copiados a 20 MiB por arquivo e 100 MiB no total, conf
78
81
  - **Retorno 1:** falha operacional ou falha das verificações pedidas no validate.
79
82
  - **Validate retorna 0:** verificações visuais/de rede passaram nos estados observados. Comportamento continua `not-tested`.
80
83
 
81
- `--json` retorna um único resultado no stdout para capture/validate/browser; progresso vai para stderr. `serve --json` emite um único documento de início e permanece ativo até ser encerrado. Automações precisam tratar retorno 2 separadamente. A captura não sobrescreve uma pasta de saída existente com conteúdo. Código de origem preservado gera `SOURCE_RUNTIME_UNVERIFIED`: teste suas interações; igualdade de screenshots não comprova que todas as dependências foram recuperadas.
84
+ Sem `--json` o resultado é um resumo legível no stdout; com `--json` é um único documento JSON. O progresso sempre vai para stderr. `serve --json` emite um único documento de início e permanece ativo até ser encerrado. Automações precisam tratar retorno 2 separadamente. A captura não sobrescreve uma pasta de saída existente com conteúdo. Código de origem preservado gera `SOURCE_RUNTIME_UNVERIFIED`: teste suas interações; igualdade de screenshots não comprova que todas as dependências foram recuperadas.
82
85
 
83
86
  A comparação visual desativa animações, aceita por padrão 2% de diferença de pixels e até 5 px de diferença de altura. Ela não comprova cliques, hover, efeitos de scroll ou estado de framework. Requisições externas da saída são bloqueadas por padrão, inclusive outra porta de localhost. `--allow-external` permite essas requisições e desativa esse teste de funcionamento sem rede externa. O `validate` também reconhece o marcador de extrações do protótipo sem reescrever a pasta; novas extrações usam os marcadores UIport. Consulte os casos suportados em [docs/support.md](docs/support.md).
84
87
 
package/bin/cli.mjs CHANGED
@@ -5,6 +5,8 @@ import path from "node:path";
5
5
  import { allowed, parseArgs, optionsFor } from "../scripts/options.mjs";
6
6
  import { safeErrorMessage } from "../scripts/lib.mjs";
7
7
  import { guardStdout } from "../scripts/stdout.mjs";
8
+ import { describeError, UiportError } from "../scripts/errors.mjs";
9
+ import { report, reportError } from "../scripts/report.mjs";
8
10
  const require = createRequire(import.meta.url);
9
11
  const { version } = require("../package.json");
10
12
  const argv = process.argv.slice(2);
@@ -16,9 +18,12 @@ Usage:
16
18
  uiport capture --url URL --selector CSS --out DIRECTORY [options]
17
19
  uiport validate --url URL --selector CSS --dir DIRECTORY [options]
18
20
  uiport serve --dir DIRECTORY [--port 4173] [--json]
21
+ uiport inspect --dir DIRECTORY [--json]
22
+ uiport diff --before DIRECTORY --after DIRECTORY [--json]
23
+ uiport examples [--port 4173] [--json]
19
24
  uiport browser install
20
25
 
21
- Capture / validate:
26
+ Capture / validate / diff:
22
27
  --viewports 1440x900,1024x768,768x1024,375x812
23
28
  --wait 1200 Settle time per navigation (ms, 0–60000)
24
29
  --timeout 120000 Whole operation deadline (ms, 1000–600000)
@@ -28,6 +33,7 @@ Capture / validate:
28
33
  --json One JSON result on stdout; progress on stderr
29
34
  Capture:
30
35
  --omit-scripts Omit source scripts and inline event handlers
36
+ --dry-run Check the selector against the page and stop
31
37
  --max-resource-mb 20 Maximum copied resource size (0.001–100 MiB)
32
38
  --max-total-mb 100 Total resource download budget (0.001–500 MiB)
33
39
  Validate:
@@ -49,7 +55,7 @@ try {
49
55
  console.log(json ? JSON.stringify({ version }) : version);
50
56
  else {
51
57
  if (!Object.hasOwn(allowed, command))
52
- throw new Error(`Unknown command: ${command}`);
58
+ throw new UiportError("USAGE_INVALID", `Unknown command: ${command}`);
53
59
  const args = parseArgs(
54
60
  argv.slice(command === "browser" && argv[1] === "install" ? 2 : 1),
55
61
  allowed[command],
@@ -115,21 +121,30 @@ try {
115
121
  } finally {
116
122
  restore();
117
123
  }
118
- if (command !== "serve")
119
- console.log(JSON.stringify(result, null, args.json ? undefined : 2));
124
+ if (command !== "serve" && command !== "examples")
125
+ console.log(
126
+ args.json ? JSON.stringify(result, null, undefined) : report(result),
127
+ );
120
128
  process.exitCode =
121
129
  result.status === "partial" ? 2 : result.status === "failed" ? 1 : 0;
122
130
  }
123
131
  }
124
132
  } catch (error) {
133
+ const described = describeError(error);
134
+ // The message of the failure is redacted before it reaches any channel.
135
+ const message = safeErrorMessage(error);
125
136
  if (json)
126
137
  console.log(
127
138
  JSON.stringify({
128
139
  command: Object.hasOwn(allowed, command) ? command : "help",
129
140
  status: "failed",
130
- error: { code: "OPERATION_FAILED", message: safeErrorMessage(error) },
141
+ error: {
142
+ code: described.code,
143
+ message,
144
+ hint: described.hint,
145
+ },
131
146
  }),
132
147
  );
133
- else process.stderr.write(`UIport: ${safeErrorMessage(error)}\n`);
148
+ else process.stderr.write(`${reportError({ ...described, message })}\n`);
134
149
  process.exitCode = 1;
135
150
  }
package/docs/support.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # UIport support matrix
2
2
 
3
- This matrix describes the 0.1.x CLI line and was last verified against 0.1.2. It applies to every 0.1.x release unless a row says otherwise.
3
+ This matrix describes the 0.1.x CLI line and was last verified against 0.1.3. It applies to every 0.1.x release unless a row says otherwise.
4
4
 
5
5
  UIport exports a rendered section or a selected whole page. It does not reconstruct a complete application backend or crawl a site. A successful capture is not a general proof of fidelity.
6
6
 
@@ -32,6 +32,14 @@ Contextual custom-property rules that matched the source but lose structural con
32
32
 
33
33
  Existing prototype exports are accepted by their legacy root marker; validate does not rewrite them. The locale default remains pt-BR.
34
34
 
35
+ ## Output contract
36
+
37
+ Without `--json` the result is a readable summary on stdout; with `--json` it is one JSON document. Progress always goes to stderr, and a capture or a validation never writes anything else to stdout.
38
+
39
+ A failure carries a stable code and a hint: `USAGE_INVALID`, `BROWSER_NOT_FOUND`, `OUTPUT_NOT_EMPTY`, `SELECTOR_NOT_FOUND`, `SELECTOR_AMBIGUOUS`, `TIMEOUT`, `CANCELLED`, `SOURCE_UNREACHABLE`, `ARTIFACT_MISSING` and `INTERNAL`.
40
+
41
+ `uiport inspect --dir DIR` reads the limitations of an exported section without opening a browser. `uiport capture --dry-run` checks the selector against the page and writes nothing.
42
+
35
43
  ## Limits and diagnostics
36
44
 
37
45
  - One CSS selector matching one section container, body or html. Body/html export a single whole page without nesting another html/body; html also includes original head scripts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uiport",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Bring a rendered web section into your next project as editable HTML, CSS and assets.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -3,6 +3,15 @@ import path from "node:path";
3
3
  import { chromium } from "playwright-core";
4
4
  import { parseFragment, serialize } from "parse5";
5
5
  import { extractSection, measureRoot } from "./dom.mjs";
6
+ import { UiportError } from "./errors.mjs";
7
+ import {
8
+ ANIMATIONS_ID,
9
+ BEHAVIOR,
10
+ ID_ATTR,
11
+ METADATA_ID,
12
+ ROOT_ATTR,
13
+ ROOT_VALUE,
14
+ } from "./contract.mjs";
6
15
  import { parseSrcsetAttribute } from "./srcset.mjs";
7
16
  import { resources } from "./resources.mjs";
8
17
  import { browserResources } from "./browser-resources.mjs";
@@ -22,7 +31,51 @@ import {
22
31
  waitForPageStable,
23
32
  } from "./lib.mjs";
24
33
 
34
+ /** Checks the selector against the page without writing anything. */
35
+ async function dryRun(options) {
36
+ const life = lifecycle(options.timeoutMs);
37
+ try {
38
+ const { browser, selected, close } = await launchChromium(chromium, life);
39
+ const context = await browser.newContext({
40
+ viewport: options.viewports[0],
41
+ deviceScaleFactor: 1,
42
+ locale: options.locale,
43
+ colorScheme: options.colorScheme,
44
+ serviceWorkers: "block",
45
+ });
46
+ const page = await context.newPage();
47
+ await page.goto(options.sourceUrl, {
48
+ waitUntil: "domcontentloaded",
49
+ timeout: Math.min(60000, options.timeoutMs),
50
+ });
51
+ await waitForPageStable(page, options.settleMs);
52
+ const root = page.locator(options.selector);
53
+ const matches = await root.count();
54
+ const visible =
55
+ matches === 1 ? await root.isVisible().catch(() => false) : false;
56
+ const version = browser.version();
57
+ await close();
58
+ if (matches !== 1)
59
+ throw new UiportError(
60
+ matches === 0 ? "SELECTOR_NOT_FOUND" : "SELECTOR_AMBIGUOUS",
61
+ `Selector must resolve to exactly one element; found ${matches}`,
62
+ );
63
+ return {
64
+ command: "capture",
65
+ status: "complete",
66
+ dryRun: true,
67
+ selector: options.selector,
68
+ matches,
69
+ visible,
70
+ browser: { selected, version },
71
+ };
72
+ } finally {
73
+ await life.close();
74
+ }
75
+ }
76
+
25
77
  export async function capture(options) {
78
+ if (options.dryRun) return dryRun(options);
26
79
  const { sourceUrl, selector, viewports, settleMs, locale, colorScheme } =
27
80
  options;
28
81
  await inspectOutput(options.directory);
@@ -88,7 +141,8 @@ export async function capture(options) {
88
141
  const root = page.locator(selector);
89
142
  const count = await root.count();
90
143
  if (count !== 1)
91
- throw new Error(
144
+ throw new UiportError(
145
+ count === 0 ? "SELECTOR_NOT_FOUND" : "SELECTOR_AMBIGUOUS",
92
146
  `Selector must resolve to exactly one element; found ${count}`,
93
147
  );
94
148
  // A root that does not render is reported instead of waiting for a
@@ -111,6 +165,9 @@ export async function capture(options) {
111
165
  const snapshot = await page.evaluate(extractSection, {
112
166
  selector,
113
167
  omitScripts: options.omitScripts,
168
+ idAttribute: ID_ATTR,
169
+ rootAttribute: ROOT_ATTR,
170
+ rootValue: ROOT_VALUE,
114
171
  });
115
172
  captures.push(snapshot);
116
173
  await cache.settle();
@@ -138,7 +195,12 @@ export async function capture(options) {
138
195
  }
139
196
  cssContext = contextualCss(cssParts);
140
197
  }
141
- await cssContext.observe(page, snapshot);
198
+ // The contextual custom properties are adapted for the exported DOM,
199
+ // which is the first viewport. The identifiers are assigned by position,
200
+ // so an observation from another viewport only describes the same
201
+ // elements while the structure is unchanged.
202
+ if (snapshot.structure === captures[0].structure)
203
+ await cssContext.observe(page, snapshot);
142
204
  }
143
205
  await cache.settle();
144
206
  await close();
@@ -315,8 +377,10 @@ export async function capture(options) {
315
377
  "Some observed animations cannot be replayed on DocumentTimeline",
316
378
  );
317
379
  const metadata = {
380
+ elements: primary.featureCounts.elements,
381
+ assets: assets.stats().assets,
318
382
  limitations,
319
- behavior: "not-tested",
383
+ behavior: BEHAVIOR,
320
384
  source: redactedUrl(sourceUrl),
321
385
  };
322
386
  const html = `<!doctype html>
@@ -324,22 +388,22 @@ export async function capture(options) {
324
388
  <head>
325
389
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
326
390
  <title>${escapeHtml(primary.title || "UIport — extracted section")}</title>
327
- <style>${parts.join("\n").replaceAll("</style", "<\\/style")}</style>
391
+ <style>${parts.join("\n").replace(/<\/style/gi, "<\\/style")}</style>
328
392
  ${serialize(head)}
329
393
  </head>
330
394
  <body${serializeAttributes(primary.bodyAttributes)}>
331
395
  ${serialize(fragment)}
332
- <script type="application/json" id="uiport-metadata">${jsonForInlineScript(metadata)}</script>
333
- <script type="application/json" id="uiport-animations">${jsonForInlineScript(animations)}</script>
396
+ <script type="application/json" id="${METADATA_ID}">${jsonForInlineScript(metadata)}</script>
397
+ <script type="application/json" id="${ANIMATIONS_ID}">${jsonForInlineScript(animations)}</script>
334
398
  <script>
335
399
  (() => {
336
400
  const find = (id, root = document) => {
337
- const direct = root.querySelector('[data-uiport-id="' + CSS.escape(id) + '"]');
401
+ const direct = root.querySelector('[${ID_ATTR}="' + CSS.escape(id) + '"]');
338
402
  if (direct) return direct;
339
403
  for (const element of root.querySelectorAll('*')) if (element.shadowRoot) { const found = find(id, element.shadowRoot); if (found) return found; }
340
404
  return null;
341
405
  };
342
- for (const record of JSON.parse(document.getElementById('uiport-animations').textContent)) {
406
+ for (const record of JSON.parse(document.getElementById('${ANIMATIONS_ID}').textContent)) {
343
407
  const target = find(record.targetId);
344
408
  if (!target) continue;
345
409
  try {
@@ -368,7 +432,7 @@ ${serialize(fragment)}
368
432
  ...assets.stats(),
369
433
  elements: primary.featureCounts.elements,
370
434
  animationsReplayed: animations.length,
371
- behavior: "not-tested",
435
+ behavior: BEHAVIOR,
372
436
  limitations,
373
437
  };
374
438
  } finally {
@@ -0,0 +1,14 @@
1
+ // The contract between a capture and the validation of its result. The
2
+ // markers live here so that a rename cannot silently break one side: the
3
+ // validation reads the markers of the exported document, and an artifact that
4
+ // does not carry them is reported instead of being read as an empty one.
5
+ export const ROOT_ATTR = "data-uiport-root";
6
+ export const ROOT_VALUE = "true";
7
+ export const ID_ATTR = "data-uiport-id";
8
+ export const METADATA_ID = "uiport-metadata";
9
+ export const ANIMATIONS_ID = "uiport-animations";
10
+ export const BEHAVIOR = "not-tested";
11
+
12
+ // Artifacts exported before UIport used another marker. They are still
13
+ // accepted for validation, and the folder is never rewritten.
14
+ export const LEGACY_ROOT_ATTR = "data-effect-extractor-root";
@@ -1,10 +1,11 @@
1
1
  import postcss from "postcss";
2
2
  import { randomUUID } from "node:crypto";
3
+ import { ID_ATTR } from "./contract.mjs";
3
4
 
4
5
  // Inspect only selector context. No stylesheet or script is executed in this
5
6
  // detached document. Keep original declarations, specificity and enclosing
6
7
  // media/supports/container/layer rules rather than freezing computed values.
7
- function missingSelectors({ snapshot, rules }) {
8
+ function missingSelectors({ snapshot, rules, idAttribute }) {
8
9
  const copy = document.implementation.createHTMLDocument("");
9
10
  for (const { name, value } of snapshot.htmlAttributes)
10
11
  copy.documentElement.setAttribute(name, value);
@@ -20,8 +21,8 @@ function missingSelectors({ snapshot, rules }) {
20
21
  }
21
22
  container.innerHTML = snapshot.html;
22
23
  const clones = new Map(
23
- [...copy.querySelectorAll("[data-uiport-id]")].map((element) => [
24
- element.getAttribute("data-uiport-id"),
24
+ [...copy.querySelectorAll(`[${idAttribute}]`)].map((element) => [
25
+ element.getAttribute(idAttribute),
25
26
  element,
26
27
  ]),
27
28
  );
@@ -30,7 +31,7 @@ function missingSelectors({ snapshot, rules }) {
30
31
  for (const selector of rule.selectors) {
31
32
  try {
32
33
  for (const element of document.querySelectorAll(selector)) {
33
- const id = element.getAttribute("data-uiport-id");
34
+ const id = element.getAttribute(idAttribute);
34
35
  const cloned = clones.get(id);
35
36
  if (cloned && !cloned.matches(selector))
36
37
  result.push({ rule: rule.id, selector, id });
@@ -115,6 +116,7 @@ export function contextualCss(stylesheets) {
115
116
  const result = await page.evaluate(missingSelectors, {
116
117
  snapshot,
117
118
  rules: descriptors,
119
+ idAttribute: ID_ATTR,
118
120
  });
119
121
  for (const item of result) {
120
122
  missing.set(`${item.rule}|${item.selector}|${item.id}`, item);
@@ -0,0 +1,149 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import pixelmatch from "pixelmatch";
4
+ import { PNG } from "pngjs";
5
+ import { chromium } from "playwright-core";
6
+ import {
7
+ launchChromium,
8
+ lifecycle,
9
+ log,
10
+ startStaticServer,
11
+ waitForPageStable,
12
+ } from "./lib.mjs";
13
+ import {
14
+ BEHAVIOR,
15
+ LEGACY_ROOT_ATTR,
16
+ METADATA_ID,
17
+ ROOT_ATTR,
18
+ ROOT_VALUE,
19
+ } from "./contract.mjs";
20
+
21
+ async function readMetadata(directory) {
22
+ try {
23
+ const html = await fs.readFile(path.join(directory, "index.html"), "utf8");
24
+ const match = html.match(
25
+ new RegExp(
26
+ `<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
27
+ ),
28
+ );
29
+ if (!match) return null;
30
+ return JSON.parse(match[1]);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ const rootSelector = `[${ROOT_ATTR}="${ROOT_VALUE}"]`;
37
+ const legacyRootSelector = `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
38
+
39
+ /** Compares two exported sections: the pixels they render and what they report. */
40
+ export async function diff(options) {
41
+ const before = path.resolve(options.before);
42
+ const after = path.resolve(options.after);
43
+ for (const directory of [before, after])
44
+ await fs.access(path.join(directory, "index.html"));
45
+ const life = lifecycle(options.timeoutMs);
46
+ try {
47
+ const beforeServer = await startStaticServer(before);
48
+ const afterServer = await startStaticServer(after);
49
+ life.add(beforeServer.close);
50
+ life.add(afterServer.close);
51
+ const { browser, selected } = await launchChromium(chromium, life);
52
+ const results = [];
53
+ for (const viewport of options.viewports) {
54
+ life.check();
55
+ log(`Comparing ${viewport.name}…`);
56
+ const context = await browser.newContext({
57
+ viewport,
58
+ deviceScaleFactor: 1,
59
+ locale: options.locale,
60
+ colorScheme: options.colorScheme,
61
+ serviceWorkers: "block",
62
+ });
63
+ try {
64
+ const page = await context.newPage();
65
+ const shots = [];
66
+ for (const server of [beforeServer, afterServer]) {
67
+ await page.goto(`${server.url}/index.html`, {
68
+ waitUntil: "domcontentloaded",
69
+ });
70
+ await waitForPageStable(page, options.settleMs);
71
+ const root = page.locator(
72
+ (await page.locator(rootSelector).count())
73
+ ? rootSelector
74
+ : legacyRootSelector,
75
+ );
76
+ if ((await root.count()) !== 1)
77
+ throw new Error(
78
+ "An exported section is missing its extraction root",
79
+ );
80
+ shots.push(await root.screenshot({ animations: "disabled" }));
81
+ }
82
+ const left = PNG.sync.read(shots[0]);
83
+ const right = PNG.sync.read(shots[1]);
84
+ const width = Math.max(left.width, right.width);
85
+ const height = Math.max(left.height, right.height);
86
+ if (width * height > 20_000_000)
87
+ throw new Error("Comparison exceeds screenshot limit");
88
+ const sameSize =
89
+ left.width === right.width && left.height === right.height;
90
+ const buffer = (source) => {
91
+ if (sameSize) return source.data;
92
+ const target = new Uint8Array(width * height * 4);
93
+ const rowBytes = source.width * 4;
94
+ for (let y = 0; y < source.height; y += 1)
95
+ source.data.copy(
96
+ target,
97
+ y * width * 4,
98
+ y * rowBytes,
99
+ y * rowBytes + rowBytes,
100
+ );
101
+ return target;
102
+ };
103
+ const differentPixels = pixelmatch(
104
+ buffer(left),
105
+ buffer(right),
106
+ null,
107
+ width,
108
+ height,
109
+ { threshold: 0.1, includeAA: false },
110
+ );
111
+ const ratio = differentPixels / (width * height);
112
+ results.push({
113
+ viewport: viewport.name,
114
+ identical: ratio === 0,
115
+ differentPixels,
116
+ differenceRatio: ratio,
117
+ dimensionsMatch:
118
+ left.width === right.width && left.height === right.height,
119
+ });
120
+ } finally {
121
+ await context.close();
122
+ }
123
+ }
124
+ const beforeMetadata = await readMetadata(before);
125
+ const afterMetadata = await readMetadata(after);
126
+ const codes = (metadata) =>
127
+ (metadata?.limitations || []).map((entry) => entry.code).sort();
128
+ const added = codes(afterMetadata).filter(
129
+ (code) => !codes(beforeMetadata).includes(code),
130
+ );
131
+ const removed = codes(beforeMetadata).filter(
132
+ (code) => !codes(afterMetadata).includes(code),
133
+ );
134
+ const changed = results.some((entry) => !entry.identical);
135
+ return {
136
+ command: "diff",
137
+ status: changed || added.length ? "partial" : "complete",
138
+ before,
139
+ after,
140
+ browser: { selected, version: browser.version() },
141
+ identical: !changed,
142
+ results,
143
+ limitations: { added, removed },
144
+ behavior: BEHAVIOR,
145
+ };
146
+ } finally {
147
+ await life.close();
148
+ }
149
+ }
package/scripts/dom.mjs CHANGED
@@ -47,6 +47,9 @@ export function measureRoot(element) {
47
47
  export function extractSection({
48
48
  selector: targetSelector,
49
49
  omitScripts = false,
50
+ idAttribute = "data-uiport-id",
51
+ rootAttribute = "data-uiport-root",
52
+ rootValue = "true",
50
53
  }) {
51
54
  const target = document.querySelector(targetSelector);
52
55
  if (!target) throw new Error("Target disappeared before capture.");
@@ -106,13 +109,13 @@ export function extractSection({
106
109
  };
107
110
  visit(target);
108
111
  deepElements.forEach((element, index) =>
109
- element.setAttribute("data-uiport-id", `up-${index}`),
112
+ element.setAttribute(idAttribute, `up-${index}`),
110
113
  );
111
- target.setAttribute("data-uiport-root", "true");
114
+ target.setAttribute(rootAttribute, rootValue);
112
115
  let parent = target.parentElement;
113
116
  let ancestorId = 0;
114
117
  while (parent) {
115
- parent.setAttribute("data-uiport-id", `up-ancestor-${ancestorId++}`);
118
+ parent.setAttribute(idAttribute, `up-ancestor-${ancestorId++}`);
116
119
  parent = parent.parentElement;
117
120
  }
118
121
  let preservedScripts = 0;
@@ -202,7 +205,13 @@ export function extractSection({
202
205
  }
203
206
  }
204
207
  if (source.tagName === "STYLE") {
205
- clone.textContent = absolutizeCssUrls(source.textContent, source.baseURI);
208
+ // A style element created by a script can hold text that an HTML parser
209
+ // would read as the end of the element. The escape keeps the text in one
210
+ // piece and is equivalent CSS.
211
+ clone.textContent = absolutizeCssUrls(
212
+ source.textContent,
213
+ source.baseURI,
214
+ ).replace(/<\/style/gi, "<\\/style");
206
215
  return clone;
207
216
  }
208
217
  if (source.shadowRoot) {
@@ -288,7 +297,7 @@ export function extractSection({
288
297
  } catch {}
289
298
  animations.push({
290
299
  kind: animation.constructor?.name || "Animation",
291
- targetId: effect?.target?.getAttribute?.("data-uiport-id") || null,
300
+ targetId: effect?.target?.getAttribute?.(idAttribute) || null,
292
301
  pseudoElement: effect?.pseudoElement || null,
293
302
  keyframes,
294
303
  timing,
@@ -0,0 +1,53 @@
1
+ // The failures a caller can act on. Every error carries a stable code and a
2
+ // hint, so a script can branch on the code and a person knows what to do.
3
+ export const CODES = {
4
+ USAGE_INVALID: "The arguments of the command are not valid.",
5
+ BROWSER_NOT_FOUND:
6
+ "No supported browser was found. Run `uiport browser install`, or set UIPORT_BROWSER_PATH.",
7
+ OUTPUT_NOT_EMPTY:
8
+ "The output directory already has files. Choose a new directory or empty it.",
9
+ SELECTOR_NOT_FOUND:
10
+ "The selector matched no element. Inspect the page and check the selector.",
11
+ SELECTOR_AMBIGUOUS:
12
+ "The selector matched more than one element. Narrow it, or capture the whole page with `--selector body`.",
13
+ TIMEOUT:
14
+ "The operation exceeded its deadline. Raise `--timeout` or reduce `--viewports`.",
15
+ CANCELLED: "The operation was cancelled.",
16
+ SOURCE_UNREACHABLE:
17
+ "The source page could not be loaded. Check the address and that the page is reachable.",
18
+ ARTIFACT_MISSING:
19
+ "The directory has no exported section. Run `uiport capture` first.",
20
+ INTERNAL: "The operation failed for an unexpected reason.",
21
+ };
22
+
23
+ export class UiportError extends Error {
24
+ /**
25
+ * @param {keyof typeof CODES} code
26
+ * @param {string} message
27
+ * @param {{cause?: unknown, hint?: string}} [options]
28
+ */
29
+ constructor(code, message, options = {}) {
30
+ super(message, options.cause ? { cause: options.cause } : undefined);
31
+ this.name = "UiportError";
32
+ this.code = code;
33
+ this.hint = options.hint || CODES[code];
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @param {unknown} error
39
+ * @returns {{code: string, message: string, hint: string}}
40
+ */
41
+ export function describeError(error) {
42
+ if (error instanceof UiportError)
43
+ return {
44
+ code: error.code,
45
+ message: error.message,
46
+ hint: error.hint,
47
+ };
48
+ const message = String(error?.message || error || "Operation failed").split(
49
+ /[\r\n]/,
50
+ 1,
51
+ )[0];
52
+ return { code: "INTERNAL", message, hint: CODES.INTERNAL };
53
+ }
@@ -0,0 +1,37 @@
1
+ import path from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { startStaticServer } from "./lib.mjs";
4
+
5
+ // The examples travel with the package, so a person can try the tool without
6
+ // choosing a page of their own first.
7
+ const directory = path.join(
8
+ path.dirname(fileURLToPath(import.meta.url)),
9
+ "..",
10
+ "examples",
11
+ );
12
+
13
+ export async function examples(options) {
14
+ const server = await startStaticServer(directory, options.port);
15
+ const ready = {
16
+ command: "examples",
17
+ status: "ready",
18
+ directory,
19
+ url: server.url,
20
+ };
21
+ console.log(
22
+ options.json
23
+ ? JSON.stringify(ready)
24
+ : `UIport serving the original examples at ${server.url}\nTry: uiport capture --url ${server.url}/responsive-hero/ --selector "#hero" --out ./hero\nPress Ctrl+C to stop.`,
25
+ );
26
+ await new Promise((resolve) => {
27
+ const stop = async () => {
28
+ process.removeListener("SIGINT", stop);
29
+ process.removeListener("SIGTERM", stop);
30
+ await server.close();
31
+ resolve();
32
+ };
33
+ process.once("SIGINT", stop);
34
+ process.once("SIGTERM", stop);
35
+ });
36
+ return { command: "examples", status: "stopped" };
37
+ }
@@ -0,0 +1,50 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { UiportError } from "./errors.mjs";
4
+ import { BEHAVIOR, METADATA_ID } from "./contract.mjs";
5
+
6
+ /** Reads what an exported section carries, without opening a browser. */
7
+ export async function inspect(options) {
8
+ const file = path.join(options.directory, "index.html");
9
+ let html;
10
+ try {
11
+ html = await fs.readFile(file, "utf8");
12
+ } catch (error) {
13
+ throw new UiportError(
14
+ "ARTIFACT_MISSING",
15
+ `The directory has no exported section: ${file}`,
16
+ { cause: error },
17
+ );
18
+ }
19
+ const match = html.match(
20
+ new RegExp(
21
+ `<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
22
+ ),
23
+ );
24
+ let metadata = {};
25
+ if (match)
26
+ try {
27
+ metadata = JSON.parse(match[1]);
28
+ } catch {
29
+ metadata = {};
30
+ }
31
+ let assets;
32
+ try {
33
+ assets = (await fs.readdir(path.join(options.directory, "assets"))).length;
34
+ } catch {
35
+ assets = 0;
36
+ }
37
+ const limitations = Array.isArray(metadata.limitations)
38
+ ? metadata.limitations
39
+ : [];
40
+ return {
41
+ command: "inspect",
42
+ status: limitations.length ? "partial" : "complete",
43
+ outputDirectory: options.directory,
44
+ assets,
45
+ elements: metadata.elements ?? null,
46
+ source: metadata.source ?? null,
47
+ behavior: metadata.behavior ?? BEHAVIOR,
48
+ limitations,
49
+ };
50
+ }
package/scripts/lib.mjs CHANGED
@@ -5,6 +5,7 @@ import http from "node:http";
5
5
  import path from "node:path";
6
6
  import { performance } from "node:perf_hooks";
7
7
  import { startBrowser } from "./browser-process.mjs";
8
+ import { UiportError } from "./errors.mjs";
8
9
 
9
10
  export const sha256 = (buffer) =>
10
11
  crypto.createHash("sha256").update(buffer).digest("hex");
@@ -94,7 +95,8 @@ export async function inspectOutput(directory) {
94
95
  stat.isSymbolicLink() ||
95
96
  (await fs.readdir(destination)).length
96
97
  )
97
- throw new Error(
98
+ throw new UiportError(
99
+ "OUTPUT_NOT_EMPTY",
98
100
  "Output must be a new or empty directory (not a symlink)",
99
101
  );
100
102
  existing = true;
@@ -115,27 +117,17 @@ export async function stageOutput(directory) {
115
117
  return {
116
118
  directory: temporary,
117
119
  async commit() {
118
- // Recheck immediately before moving. Exclusive mkdir prevents replacing a concurrent output.
120
+ // Recheck immediately before moving. The directory is published with a
121
+ // single rename, so a reader never observes it half written.
119
122
  if (existing) await fs.rmdir(destination); // only succeeds when still empty
120
- await fs.mkdir(destination);
121
- const moved = [];
122
123
  try {
123
- for (const name of await fs.readdir(temporary)) {
124
- await fs.rename(
125
- path.join(temporary, name),
126
- path.join(destination, name),
127
- );
128
- moved.push(name);
129
- }
130
- committed = true;
124
+ await fs.rename(temporary, destination);
131
125
  } catch (error) {
132
- for (const name of moved)
133
- await fs
134
- .rename(path.join(destination, name), path.join(temporary, name))
135
- .catch(() => {});
136
- await fs.rmdir(destination).catch(() => {});
126
+ if (existing)
127
+ await fs.mkdir(destination, { recursive: true }).catch(() => {});
137
128
  throw error;
138
129
  }
130
+ committed = true;
139
131
  },
140
132
  async cleanup() {
141
133
  await fs.rm(temporary, { recursive: true, force: true });
@@ -199,6 +191,7 @@ export function mimeForFile(filePath) {
199
191
  [".woff2", "font/woff2"],
200
192
  [".woff", "font/woff"],
201
193
  [".ttf", "font/ttf"],
194
+ [".otf", "font/otf"],
202
195
  [".mp4", "video/mp4"],
203
196
  [".webm", "video/webm"],
204
197
  [".json", "application/json"],
@@ -316,7 +309,8 @@ export async function launchChromium(chromium, life) {
316
309
  /* try next installed browser */
317
310
  }
318
311
  }
319
- throw new Error(
312
+ throw new UiportError(
313
+ "BROWSER_NOT_FOUND",
320
314
  "No supported browser found. Run: uiport browser install (or set UIPORT_BROWSER_PATH).",
321
315
  );
322
316
  }
@@ -333,7 +327,10 @@ export function lifecycle(timeoutMs) {
333
327
  for (const fn of [...cleanups].reverse()) await fn().catch(() => {});
334
328
  })());
335
329
  const cancel = (message) => {
336
- reason ||= new Error(message);
330
+ reason ||= new UiportError(
331
+ message.startsWith("Operation exceeded") ? "TIMEOUT" : "CANCELLED",
332
+ message,
333
+ );
337
334
  controller.abort(reason);
338
335
  void cleanup();
339
336
  };
@@ -1,5 +1,6 @@
1
1
  // @ts-check
2
2
  import path from "node:path";
3
+ import { UiportError } from "./errors.mjs";
3
4
 
4
5
  export const common = ["json", "help", "version"];
5
6
  export const browserOptions = [
@@ -20,6 +21,7 @@ export const allowed = {
20
21
  "max-total-mb",
21
22
  "omit-scripts",
22
23
  "max-scroll-steps",
24
+ "dry-run",
23
25
  ],
24
26
  validate: [
25
27
  ...common,
@@ -30,6 +32,18 @@ export const allowed = {
30
32
  "max-scroll-steps",
31
33
  ],
32
34
  serve: [...common, "dir", "port"],
35
+ inspect: [...common, "dir"],
36
+ examples: [...common, "port"],
37
+ diff: [
38
+ ...common,
39
+ "before",
40
+ "after",
41
+ "viewports",
42
+ "wait",
43
+ "timeout",
44
+ "locale",
45
+ "color-scheme",
46
+ ],
33
47
  browser: common,
34
48
  };
35
49
  const booleans = new Set([
@@ -38,6 +52,7 @@ const booleans = new Set([
38
52
  "version",
39
53
  "allow-external",
40
54
  "omit-scripts",
55
+ "dry-run",
41
56
  ]);
42
57
 
43
58
  /** @param {string[]} argv @param {string[]} keys */
@@ -47,18 +62,23 @@ export function parseArgs(argv, keys) {
47
62
  for (let i = 0; i < argv.length; i++) {
48
63
  const token = argv[i];
49
64
  if (!token.startsWith("--"))
50
- throw new Error(`Unexpected argument: ${token}`);
65
+ throw new UiportError("USAGE_INVALID", `Unexpected argument: ${token}`);
51
66
  const [key, ...parts] = token.slice(2).split("=");
52
- if (!keys.includes(key)) throw new Error(`Unknown option: --${key}`);
67
+ if (!keys.includes(key))
68
+ throw new UiportError("USAGE_INVALID", `Unknown option: --${key}`);
53
69
  if (Object.hasOwn(result, key))
54
- throw new Error(`Repeated option: --${key}`);
70
+ throw new UiportError("USAGE_INVALID", `Repeated option: --${key}`);
55
71
  if (booleans.has(key)) {
56
- if (parts.length) throw new Error(`--${key} does not accept a value`);
72
+ if (parts.length)
73
+ throw new UiportError(
74
+ "USAGE_INVALID",
75
+ `--${key} does not accept a value`,
76
+ );
57
77
  result[key] = true;
58
78
  } else {
59
79
  const value = parts.length ? parts.join("=") : argv[++i];
60
80
  if (!value || value.startsWith("--"))
61
- throw new Error(`Missing value for --${key}`);
81
+ throw new UiportError("USAGE_INVALID", `Missing value for --${key}`);
62
82
  result[key] = value;
63
83
  }
64
84
  }
@@ -69,7 +89,7 @@ export function parseArgs(argv, keys) {
69
89
  export function required(args, key) {
70
90
  const value = args[key];
71
91
  if (typeof value !== "string" || !value.trim())
72
- throw new Error(`Missing required --${key}`);
92
+ throw new UiportError("USAGE_INVALID", `Missing required --${key}`);
73
93
  return value.trim();
74
94
  }
75
95
 
@@ -77,7 +97,8 @@ export function required(args, key) {
77
97
  export function numeric(value, key, fallback, min, max) {
78
98
  const n = value === undefined ? fallback : Number(value);
79
99
  if (typeof value === "boolean" || !Number.isFinite(n) || n < min || n > max) {
80
- throw new Error(
100
+ throw new UiportError(
101
+ "USAGE_INVALID",
81
102
  `--${key} must be a finite number between ${min} and ${max}`,
82
103
  );
83
104
  }
@@ -92,16 +113,22 @@ export function parseViewports(value = "1440x900,1024x768,768x1024,375x812") {
92
113
  .map((item) => {
93
114
  const match = /^(\d{2,4})x(\d{2,4})$/i.exec(item.trim());
94
115
  if (!match)
95
- throw new Error(`Invalid viewport '${item}'. Use WIDTHxHEIGHT.`);
116
+ throw new UiportError(
117
+ "USAGE_INVALID",
118
+ `Invalid viewport '${item}'. Use WIDTHxHEIGHT.`,
119
+ );
96
120
  const width = Number(match[1]),
97
121
  height = Number(match[2]);
98
122
  if (width < 200 || height < 200 || width > 3840 || height > 3840)
99
- throw new Error("Viewport dimensions must be between 200 and 3840");
123
+ throw new UiportError(
124
+ "USAGE_INVALID",
125
+ "Viewport dimensions must be between 200 and 3840",
126
+ );
100
127
  return { width, height, name: `${width}x${height}` };
101
128
  })
102
129
  .filter((v) => !seen.has(v.name) && seen.add(v.name));
103
130
  if (!items.length || items.length > 8)
104
- throw new Error("Use between 1 and 8 viewports");
131
+ throw new UiportError("USAGE_INVALID", "Use between 1 and 8 viewports");
105
132
  return items;
106
133
  }
107
134
 
@@ -113,7 +140,10 @@ export function httpUrl(value) {
113
140
  url.username ||
114
141
  url.password
115
142
  )
116
- throw new Error("--url must be HTTP(S) without embedded credentials");
143
+ throw new UiportError(
144
+ "USAGE_INVALID",
145
+ "--url must be HTTP(S) without embedded credentials",
146
+ );
117
147
  return url.href;
118
148
  }
119
149
 
@@ -122,6 +152,7 @@ export function optionsFor(command, args) {
122
152
  const options = {
123
153
  json: args.json === true,
124
154
  omitScripts: args["omit-scripts"] === true,
155
+ dryRun: args["dry-run"] === true,
125
156
  sourceUrl: "",
126
157
  selector: "",
127
158
  directory: "",
@@ -170,7 +201,16 @@ export function optionsFor(command, args) {
170
201
  options.sourceUrl = httpUrl(required(args, "url"));
171
202
  options.selector = required(args, "selector");
172
203
  }
173
- if (["capture", "validate", "serve"].includes(command))
204
+ if (command === "diff") {
205
+ options.before = path.resolve(required(args, "before"));
206
+ options.after = path.resolve(required(args, "after"));
207
+ }
208
+ if (command === "capture" && options.dryRun)
209
+ // A dry run writes nothing, so it needs no destination.
210
+ options.directory = path.resolve(
211
+ typeof args.out === "string" ? args.out : ".uiport-dry-run",
212
+ );
213
+ else if (["capture", "validate", "serve", "inspect"].includes(command))
174
214
  options.directory = path.resolve(
175
215
  required(args, command === "capture" ? "out" : "dir"),
176
216
  );
@@ -0,0 +1,119 @@
1
+ // The human reading of a result. The machine reading stays the JSON document;
2
+ // this is what a person sees when they did not ask for JSON.
3
+ const LIMITATION_ACTION = {
4
+ SOURCE_RUNTIME_UNVERIFIED:
5
+ "the source scripts are preserved; test the interactions before delivering",
6
+ SOURCE_RUNTIME_OMITTED:
7
+ "the source scripts were omitted; the behavior of the section is not reproduced",
8
+ RESOURCE_UNAVAILABLE:
9
+ "a resource could not be downloaded; check it in the output",
10
+ INVALID_RESOURCE_URL:
11
+ "a resource address could not be resolved; check it in the output",
12
+ STYLESHEET_UNAVAILABLE:
13
+ "a stylesheet could not be read; the section may be missing styles",
14
+ SRCSET_INVALID:
15
+ "a srcset descriptor list could not be parsed; check which image is used",
16
+ SCROLL_LIMIT: "the lazy loading was cut short; raise --max-scroll-steps",
17
+ RESPONSIVE_DOM_CHANGED:
18
+ "the structure changes across viewports; the first viewport was exported",
19
+ SECTION_NOT_VISIBLE: "the selected root is hidden; choose a visible element",
20
+ SECTION_EMPTY_AREA:
21
+ "the selected root has no size; choose an element that renders",
22
+ CANVAS_STATIC: "a canvas was exported as a still image",
23
+ CANVAS_UNREADABLE: "a canvas could not be read",
24
+ EMBED_OMITTED: "an embedded document was disabled",
25
+ ANIMATION_UNSUPPORTED: "an animation could not be replayed",
26
+ SOURCE_REQUEST_FAILED: "a request of the source failed",
27
+ SOURCE_SCRIPT_ERROR: "the source raised a JavaScript error",
28
+ CSS_IMPORT_CYCLE: "a circular stylesheet import was omitted",
29
+ CSS_IMPORT_UNSUPPORTED: "a stylesheet import could not be read",
30
+ };
31
+
32
+ const bytes = (value) => {
33
+ if (!Number.isFinite(value)) return "";
34
+ if (value < 1024) return `${value} B`;
35
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KiB`;
36
+ return `${(value / (1024 * 1024)).toFixed(1)} MiB`;
37
+ };
38
+
39
+ const limitations = (list = []) =>
40
+ list.map(
41
+ (entry) =>
42
+ ` ! ${entry.code} — ${LIMITATION_ACTION[entry.code] || entry.message}`,
43
+ );
44
+
45
+ /** @param {any} result */
46
+ export function report(result) {
47
+ if (!result) return "";
48
+ const lines = [];
49
+ if (result.command === "capture" && result.dryRun) {
50
+ lines.push(`UIport: ${result.selector} matches one element`);
51
+ lines.push(
52
+ result.visible
53
+ ? " the element renders; run the capture without --dry-run"
54
+ : " the element does not render; it would be reported as partial",
55
+ );
56
+ } else if (result.command === "capture") {
57
+ const partial = result.status === "partial";
58
+ lines.push(
59
+ `UIport: captured ${result.outputDirectory}${partial ? " (partial)" : ""}`,
60
+ );
61
+ lines.push(
62
+ ` ${result.elements} elements · ${result.assets} asset${result.assets === 1 ? "" : "s"}${result.downloadedBytes ? ` (${bytes(result.downloadedBytes)})` : ""}`,
63
+ );
64
+ lines.push(...limitations(result.limitations));
65
+ if (!partial)
66
+ lines.push(" next: uiport serve --dir <directory> to inspect it");
67
+ } else if (result.command === "validate") {
68
+ const failed = result.results.filter((entry) => !entry.pass);
69
+ lines.push(
70
+ failed.length
71
+ ? `UIport: validation failed in ${failed.length} of ${result.results.length} viewports`
72
+ : `UIport: validation passed in ${result.results.length} viewports`,
73
+ );
74
+ for (const entry of failed) {
75
+ const visual = entry.visual || {};
76
+ lines.push(
77
+ ` ! ${entry.viewport} — ${(visual.differenceRatio * 100).toFixed(1)}% of the pixels differ (limit ${(visual.maximumDifferenceRatio * 100).toFixed(0)}%)`,
78
+ );
79
+ for (const error of entry.errors || []) lines.push(` ${error}`);
80
+ for (const url of entry.network?.failedRequests || [])
81
+ lines.push(` failed request: ${url}`);
82
+ }
83
+ lines.push(...limitations(result.limitations));
84
+ lines.push(" behavior: not tested; inspect the interactions yourself");
85
+ } else if (result.command === "diff") {
86
+ const changed = result.results.filter((entry) => !entry.identical);
87
+ lines.push(
88
+ changed.length
89
+ ? `UIport: the two exports differ in ${changed.length} of ${result.results.length} viewports`
90
+ : `UIport: the two exports are identical in ${result.results.length} viewports`,
91
+ );
92
+ for (const entry of changed)
93
+ lines.push(
94
+ ` ! ${entry.viewport} — ${(entry.differenceRatio * 100).toFixed(1)}% of the pixels differ`,
95
+ );
96
+ for (const code of result.limitations.added)
97
+ lines.push(
98
+ ` + ${code} — a limitation the second export reports and the first does not`,
99
+ );
100
+ for (const code of result.limitations.removed)
101
+ lines.push(
102
+ ` - ${code} — a limitation the first export reports and the second does not`,
103
+ );
104
+ } else if (result.command === "inspect") {
105
+ lines.push(`UIport: ${result.outputDirectory}`);
106
+ lines.push(
107
+ ` ${result.elements ?? "?"} elements · ${result.assets ?? 0} asset${result.assets === 1 ? "" : "s"}`,
108
+ );
109
+ lines.push(...limitations(result.limitations));
110
+ } else if (result.command === "browser") {
111
+ lines.push("UIport: Chromium installation complete. Ready to capture.");
112
+ }
113
+ return lines.join("\n");
114
+ }
115
+
116
+ /** @param {{code:string,message:string,hint:string}} error */
117
+ export function reportError(error) {
118
+ return [`UIport: ${error.message}`, ` ${error.hint}`].join("\n");
119
+ }
@@ -3,6 +3,14 @@ import path from "node:path";
3
3
  import pixelmatch from "pixelmatch";
4
4
  import { PNG } from "pngjs";
5
5
  import { chromium } from "playwright-core";
6
+ import { UiportError } from "./errors.mjs";
7
+ import {
8
+ BEHAVIOR,
9
+ LEGACY_ROOT_ATTR,
10
+ METADATA_ID,
11
+ ROOT_ATTR,
12
+ ROOT_VALUE,
13
+ } from "./contract.mjs";
6
14
  import {
7
15
  launchChromium,
8
16
  lifecycle,
@@ -69,7 +77,10 @@ export async function validate(options) {
69
77
  await waitForPageStable(source, options.settleMs);
70
78
  const root = source.locator(options.selector);
71
79
  if ((await root.count()) !== 1)
72
- throw new Error("Source selector is missing or ambiguous");
80
+ throw new UiportError(
81
+ "SELECTOR_AMBIGUOUS",
82
+ "The source selector matched no element or more than one",
83
+ );
73
84
  const box = await root.boundingBox();
74
85
  if (!box || box.width <= 0 || box.height <= 0)
75
86
  throw new Error(
@@ -124,14 +135,24 @@ export async function validate(options) {
124
135
  });
125
136
  await waitForPageStable(local, options.settleMs);
126
137
  // Legacy root markers remain supported for existing user exports.
127
- const rootSelector = (await local
128
- .locator('[data-uiport-root="true"]')
138
+ const isCurrent = (await local
139
+ .locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`)
129
140
  .count())
130
- ? '[data-uiport-root="true"]'
131
- : '[data-effect-extractor-root="true"]';
141
+ ? true
142
+ : false;
143
+ const rootSelector = isCurrent
144
+ ? `[${ROOT_ATTR}="${ROOT_VALUE}"]`
145
+ : `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
132
146
  const localRoot = local.locator(rootSelector);
133
147
  if ((await localRoot.count()) !== 1)
134
148
  throw new Error("UIport extraction root is missing or ambiguous");
149
+ // An export of this version carries its metadata. Without it the
150
+ // artifact was changed after the capture, and the result would report
151
+ // no limitation at all.
152
+ if (isCurrent && !(await local.locator(`#${METADATA_ID}`).count()))
153
+ throw new Error(
154
+ "The exported section has no UIport metadata; it was modified after the capture",
155
+ );
135
156
  const localBox = await localRoot.boundingBox();
136
157
  if (!localBox || localBox.width <= 0 || localBox.height <= 0)
137
158
  throw new Error(
@@ -176,10 +197,10 @@ export async function validate(options) {
176
197
  failedRequests.length === 0 &&
177
198
  (options.allowExternal || externalRequests.length === 0);
178
199
  const captureLimitations = (await local
179
- .locator("#uiport-metadata")
200
+ .locator(`#${METADATA_ID}`)
180
201
  .count())
181
202
  ? await local
182
- .locator("#uiport-metadata")
203
+ .locator(`#${METADATA_ID}`)
183
204
  .evaluate((el) => JSON.parse(el.textContent).limitations)
184
205
  : [];
185
206
  results.push({
@@ -199,7 +220,7 @@ export async function validate(options) {
199
220
  failedRequests,
200
221
  externalBlocked: !options.allowExternal,
201
222
  },
202
- behavior: "not-tested",
223
+ behavior: BEHAVIOR,
203
224
  captureLimitations,
204
225
  errors,
205
226
  scrollLimited,
@@ -214,7 +235,7 @@ export async function validate(options) {
214
235
  command: "validate",
215
236
  status: results.every((r) => r.pass) ? "complete" : "failed",
216
237
  browser: { selected, version: browser.version() },
217
- behavior: "not-tested",
238
+ behavior: BEHAVIOR,
218
239
  results,
219
240
  };
220
241
  } finally {
@@ -8,13 +8,44 @@ description: Capture a rendered web section as editable HTML, original CSS and l
8
8
  Use for a request to extract an existing web section into local files. Use pages the user owns or has permission to reuse. Do not redesign or invent replacement effects.
9
9
 
10
10
  1. Inspect the requested URL and choose one CSS selector matching a section container, or body/html for a full page. Include wrappers/decorations that belong to it; html also includes original head scripts. The selected root must render something at the captured viewport: a root that displays nothing is reported as a partial result.
11
- 2. Use the installed CLI or source checkout. `npx uiport@0.1.2` is the pinned form. When testing an unpublished version, use `node bin/cli.mjs` from its checkout.
11
+ 2. Use the installed CLI or source checkout. `npx uiport@0.1.3` is the pinned form. When testing an unpublished version, use `node bin/cli.mjs` from its checkout.
12
12
  3. If needed, install the matching browser with `uiport browser install`. No browser download is hidden inside capture.
13
- 4. Run `uiport capture --url "URL" --selector "SELECTOR" --out "NEW_DIRECTORY" --json`. The default locale is pt-BR. Match locale/color scheme/viewports to the requested source. Never overwrite an existing nonempty directory.
14
- 5. Read the result. Exit 0 means no known reported limitations, not universal fidelity. Exit 2 means a partial artifact exists; inspect every limitation. Exit 1 means failure. Stdout is JSON, progress is stderr.
15
- 6. Preview with `uiport serve --dir "DIRECTORY"` and compare with `uiport validate --url "URL" --selector "SELECTOR" --dir "DIRECTORY" --json`, using the same viewport/locale/color-scheme options.
16
- 7. Inspect hover/focus, animation and relevant interactions separately. Validation disables animation for screenshots and reports behavior as not tested. Source scripts inside the selection, inline handlers and recognized visual library scripts are retained by default. Use capture --omit-scripts to omit them explicitly. Outside initialization, listeners and framework dependencies are not generically recovered; inspect SOURCE_RUNTIME_UNVERIFIED.
17
- 8. If an effect cannot be isolated from original source, explain the limitation. Do not create a visually similar substitute and call it an extraction. Manual integration of necessary original runtime code is separate work requiring inspection and validation.
18
- 9. Deliver `index.html` and `assets/` only in the extraction folder. Put reports/screenshots outside it. State the path, verified behavior and remaining limitations.
13
+ 4. Check the selector first with `uiport capture --url "URL" --selector "SELECTOR" --dry-run`. It reports whether the selector resolves to one visible element and writes nothing.
14
+ 5. Run `uiport capture --url "URL" --selector "SELECTOR" --out "NEW_DIRECTORY" --json`. The default locale is pt-BR. Match locale/color scheme/viewports to the requested source. Never overwrite an existing nonempty directory.
15
+ 6. Read the result. Exit 0 means no known reported limitations, not universal fidelity. Exit 2 means a partial artifact exists; inspect every limitation. Exit 1 means failure. With `--json` stdout carries one JSON document; without it, stdout carries a readable summary and progress goes to stderr.
16
+ 7. Preview with `uiport serve --dir "DIRECTORY"` and compare with `uiport validate --url "URL" --selector "SELECTOR" --dir "DIRECTORY" --json`, using the same viewport/locale/color-scheme options. `uiport inspect --dir "DIRECTORY" --json` reads the limitations of an artifact without opening a browser.
17
+ 8. Inspect hover/focus, animation and relevant interactions separately. Validation disables animation for screenshots and reports behavior as not tested. Source scripts inside the selection, inline handlers and recognized visual library scripts are retained by default. Use capture --omit-scripts to omit them explicitly. Outside initialization, listeners and framework dependencies are not generically recovered; inspect SOURCE_RUNTIME_UNVERIFIED.
18
+ 9. If an effect cannot be isolated from original source, explain the limitation. Do not create a visually similar substitute and call it an extraction. Manual integration of necessary original runtime code is separate work requiring inspection and validation.
19
+ 10. Deliver `index.html` and `assets/` only in the extraction folder. Put reports/screenshots outside it. State the path, verified behavior and remaining limitations.
20
+
21
+ ## When the command fails
22
+
23
+ The error document carries a `code` and a `hint`.
24
+
25
+ | Code | What to do |
26
+ |---|---|
27
+ | `USAGE_INVALID` | Fix the arguments; the hint names the option. |
28
+ | `BROWSER_NOT_FOUND` | Run `uiport browser install`, or set `UIPORT_BROWSER_PATH`. |
29
+ | `OUTPUT_NOT_EMPTY` | Choose a new directory, or empty the existing one. |
30
+ | `SELECTOR_NOT_FOUND` | The selector matched nothing: inspect the page, check whether the element needs an interaction first. |
31
+ | `SELECTOR_AMBIGUOUS` | Narrow the selector, or capture the whole page with `--selector body`. |
32
+ | `TIMEOUT` | Raise `--timeout` or reduce `--viewports`. |
33
+ | `CANCELLED` | The run was interrupted. |
34
+
35
+ ## What each limitation asks for
36
+
37
+ | Limitation | What to do |
38
+ |---|---|
39
+ | `SOURCE_RUNTIME_UNVERIFIED` | Test the interactions before delivering. |
40
+ | `SOURCE_RUNTIME_OMITTED` | The behavior of the section is not reproduced. |
41
+ | `RESOURCE_UNAVAILABLE` | A resource was not downloaded: check it in the output. |
42
+ | `SRCSET_INVALID` | A descriptor list was not parsed: check which image the browser picks. |
43
+ | `SCROLL_LIMIT` | The lazy loading was cut short: raise `--max-scroll-steps`. |
44
+ | `RESPONSIVE_DOM_CHANGED` | The structure changes across viewports; the first viewport was exported. |
45
+ | `SECTION_NOT_VISIBLE` / `SECTION_EMPTY_AREA` | The selected root displays nothing: choose an element that renders. |
46
+ | `CANVAS_STATIC` / `CANVAS_UNREADABLE` | A canvas was exported as a still image, or could not be read. |
47
+ | `EMBED_OMITTED` | An embedded document was disabled. |
48
+ | `ANIMATION_UNSUPPORTED` | An animation could not be replayed. |
49
+ | `CSS_IMPORT_CYCLE` / `CSS_IMPORT_UNSUPPORTED` | A stylesheet import was omitted. |
19
50
 
20
51
  The tool does not generate React/Next components or clone application backends. The project license covers UIport, not third-party captured assets. Never publish customer extracts or credentials as fixtures.
package/uiport.md CHANGED
@@ -90,14 +90,21 @@ node bin/cli.mjs capture --url "<URL>" --selector "<SELETOR>" --out "./extractio
90
90
 
91
91
  Ajuste `--locale`, `--color-scheme` e `--viewports` conforme a origem e use os mesmos valores na validação. A captura não sobrescreve uma pasta existente com conteúdo. `UIPORT_BROWSER_PATH` permite escolher o executável do navegador; a instalação do Chromium é explícita.
92
92
 
93
- Os mesmos subcomandos podem ser executados com `npx uiport@0.1.2` no lugar de `node bin/cli.mjs`. Ao testar uma versão ainda não publicada, use o checkout local. Consulte os [comandos e opções](README.pt-BR.md) ou execute `node bin/cli.mjs --help`.
93
+ Os mesmos subcomandos podem ser executados com `npx uiport@0.1.3` no lugar de `node bin/cli.mjs`. Ao testar uma versão ainda não publicada, use o checkout local. Consulte os [comandos e opções](README.pt-BR.md) ou execute `node bin/cli.mjs --help`.
94
+
95
+ Confira o seletor antes de capturar, sem escrever nada:
96
+
97
+ ```sh
98
+ node bin/cli.mjs capture --url "<URL>" --selector "<SELETOR>" --dry-run
99
+ ```
94
100
 
95
101
  Leia o diagnóstico antes de entregar:
96
102
 
97
103
  - Capture com retorno **0**: artefato criado sem limitações conhecidas relatadas; não é prova de fidelidade universal.
98
104
  - Capture com retorno **2**: artefato parcial criado; investigue cada item de `limitations`.
99
105
  - Retorno **1**: falha operacional ou falha das verificações solicitadas no validate.
100
- - `--json`: resultado em stdout e progresso em stderr. Não confunda um artefato parcial com falha sem saída.
106
+ - `--json`: um único documento JSON em stdout. Sem `--json`, o stdout traz um resumo legível e o progresso vai para stderr. Não confunda um artefato parcial com falha sem saída.
107
+ - `node bin/cli.mjs inspect --dir "<PASTA>"`: lê as limitações de um artefato já exportado, sem abrir navegador.
101
108
 
102
109
  O idioma padrão permanece `pt-BR`. `capture --omit-scripts` desativa a cópia de scripts da origem e eventos inline; nesse modo, animações WAAPI observadas continuam podendo ser reproduzidas. Sem essa opção, `SOURCE_RUNTIME_UNVERIFIED` pede inspeção do código preservado.
103
110