uiport 0.1.1 → 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
@@ -2,6 +2,47 @@
2
2
 
3
3
  Notable changes are documented here. Versions follow Semantic Versioning.
4
4
 
5
+ ## [Unreleased]
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
+
28
+ ## [0.1.2] — 2026-11-28
29
+
30
+ ### Fixed
31
+ - Keep stdout clean: a capture or a validation writes exactly one JSON document, and anything a dependency prints meanwhile goes to the diagnostics channel.
32
+ - Preserve an unparsable `srcset` unchanged and report `SRCSET_INVALID`, instead of dropping the attribute silently and changing which image the browser picks.
33
+ - Report a selected root that renders nothing (`SECTION_NOT_VISIBLE`, `SECTION_EMPTY_AREA`) instead of waiting for a screenshot that cannot succeed, and refuse it during validation with an actionable message. A root that renders through its children — `display: contents`, a zero-sized wrapper, a parent whose visibility is overridden — is no longer reported as empty.
34
+ - Wait for the decoding of fonts and images after the network idle window, with its own budget, so a slow image is decoded before the source is compared with the export.
35
+ - Report the bytes read from the network and the bytes charged against the total budget separately, and enforce the budget across concurrent transfers instead of counting the bytes of a rejected transfer.
36
+ - Order the reported limitations independently of the locale of the machine.
37
+ - Document `INVALID_RESOURCE_URL` in the support matrix.
38
+
39
+ ### Changed
40
+ - Accept a manual publication run only from the release tag, and abort when the registry check fails for a reason other than an unknown version.
41
+ - Download the resources referenced by a section concurrently, with a bounded pool of eight transfers. The total budget, the per-resource limit and the exported files stay the same; a capture of forty assets over a 100 ms round trip went from 8.1 s to 4.5 s.
42
+ - Compare the source and the export without copying pixels one by one: when both sides have the same size their decoded pixels are compared directly. Validating a 20-megapixel section went from 7.9 s to 7.0 s and from 618 MB to 529 MB of resident memory.
43
+ - Collect in the browser only what the export uses. The per-element computed styles, the custom property snapshot and the font list were collected for every element and never read.
44
+ - Wait for the network and for the fonts and images at the same time, and localize the assets of the document concurrently.
45
+
5
46
  ## [0.1.1] — 2026-10-01
6
47
 
7
48
  ### Fixed
package/README.md CHANGED
@@ -25,13 +25,13 @@ 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.1 browser install
29
- npx uiport@0.1.1 capture --url "https://your-site.example" --selector "#hero" --out ./my-section
30
- npx uiport@0.1.1 serve --dir ./my-section
31
- npx uiport@0.1.1 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
- Choose the selector using your browser's **Inspect element** tool. It must match exactly one container, such as `main`, `section` or a `div`. 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.
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.
35
35
 
36
36
  For repeated use: `npm install -g uiport`, then `uiport --help`. Pin a version for repeatable captures; `npx uiport@latest` follows future releases.
37
37
 
@@ -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,13 +25,13 @@ 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.1 browser install
29
- npx uiport@0.1.1 capture --url "https://seu-site.example" --selector "#hero" --out ./minha-secao
30
- npx uiport@0.1.1 serve --dir ./minha-secao
31
- npx uiport@0.1.1 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
- Para escolher o seletor, use **Inspecionar elemento** no navegador. Ele precisa encontrar exatamente um container, como `main`, `section` ou `div`. 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.
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.
35
35
 
36
36
  Para uso frequente: `npm install -g uiport`, depois `uiport --help`. Fixe uma versão quando precisar reproduzir uma captura; `npx uiport@latest` acompanha versões futuras.
37
37
 
@@ -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/SECURITY.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Security policy
2
2
 
3
- The latest 0.1.x release is the supported line once released. Before the first release, report against the current development branch.
3
+ The latest 0.1.x release is the supported line.
4
4
 
5
5
  Please use GitHub's **Report a vulnerability** feature:
6
6
  https://github.com/LorranHippolyte/uiport/security/advisories/new
package/bin/cli.mjs CHANGED
@@ -4,6 +4,9 @@ import { spawn } from "node:child_process";
4
4
  import path from "node:path";
5
5
  import { allowed, parseArgs, optionsFor } from "../scripts/options.mjs";
6
6
  import { safeErrorMessage } from "../scripts/lib.mjs";
7
+ import { guardStdout } from "../scripts/stdout.mjs";
8
+ import { describeError, UiportError } from "../scripts/errors.mjs";
9
+ import { report, reportError } from "../scripts/report.mjs";
7
10
  const require = createRequire(import.meta.url);
8
11
  const { version } = require("../package.json");
9
12
  const argv = process.argv.slice(2);
@@ -15,9 +18,12 @@ Usage:
15
18
  uiport capture --url URL --selector CSS --out DIRECTORY [options]
16
19
  uiport validate --url URL --selector CSS --dir DIRECTORY [options]
17
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]
18
24
  uiport browser install
19
25
 
20
- Capture / validate:
26
+ Capture / validate / diff:
21
27
  --viewports 1440x900,1024x768,768x1024,375x812
22
28
  --wait 1200 Settle time per navigation (ms, 0–60000)
23
29
  --timeout 120000 Whole operation deadline (ms, 1000–600000)
@@ -27,6 +33,7 @@ Capture / validate:
27
33
  --json One JSON result on stdout; progress on stderr
28
34
  Capture:
29
35
  --omit-scripts Omit source scripts and inline event handlers
36
+ --dry-run Check the selector against the page and stop
30
37
  --max-resource-mb 20 Maximum copied resource size (0.001–100 MiB)
31
38
  --max-total-mb 100 Total resource download budget (0.001–500 MiB)
32
39
  Validate:
@@ -48,7 +55,7 @@ try {
48
55
  console.log(json ? JSON.stringify({ version }) : version);
49
56
  else {
50
57
  if (!Object.hasOwn(allowed, command))
51
- throw new Error(`Unknown command: ${command}`);
58
+ throw new UiportError("USAGE_INVALID", `Unknown command: ${command}`);
52
59
  const args = parseArgs(
53
60
  argv.slice(command === "browser" && argv[1] === "install" ? 2 : 1),
54
61
  allowed[command],
@@ -102,23 +109,42 @@ try {
102
109
  process.exitCode = Number(code);
103
110
  } else {
104
111
  const options = optionsFor(command, args);
105
- const { [command]: run } = await import(`../scripts/${command}.mjs`);
106
- const result = await run(options);
107
- if (command !== "serve")
108
- console.log(JSON.stringify(result, null, args.json ? undefined : 2));
112
+ // A capture or a validation writes exactly one JSON document to stdout.
113
+ // The guard is installed before the command module is loaded, so that
114
+ // anything printed while loading also goes to the diagnostics channel.
115
+ const guarded = command === "capture" || command === "validate";
116
+ const restore = guarded ? guardStdout() : () => {};
117
+ let result;
118
+ try {
119
+ const { [command]: run } = await import(`../scripts/${command}.mjs`);
120
+ result = await run(options);
121
+ } finally {
122
+ restore();
123
+ }
124
+ if (command !== "serve" && command !== "examples")
125
+ console.log(
126
+ args.json ? JSON.stringify(result, null, undefined) : report(result),
127
+ );
109
128
  process.exitCode =
110
129
  result.status === "partial" ? 2 : result.status === "failed" ? 1 : 0;
111
130
  }
112
131
  }
113
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);
114
136
  if (json)
115
137
  console.log(
116
138
  JSON.stringify({
117
139
  command: Object.hasOwn(allowed, command) ? command : "help",
118
140
  status: "failed",
119
- error: { code: "OPERATION_FAILED", message: safeErrorMessage(error) },
141
+ error: {
142
+ code: described.code,
143
+ message,
144
+ hint: described.hint,
145
+ },
120
146
  }),
121
147
  );
122
- else process.stderr.write(`UIport: ${safeErrorMessage(error)}\n`);
148
+ else process.stderr.write(`${reportError({ ...described, message })}\n`);
123
149
  process.exitCode = 1;
124
150
  }
@@ -18,7 +18,7 @@ flowchart LR
18
18
  - `scripts/options.mjs`: strict arguments, URL/number/viewport validation.
19
19
  - `scripts/capture.mjs`: capture orchestration, staged filesystem output, metadata and exact-data WAAPI replay.
20
20
  - `scripts/dom.mjs`: browser-side DOM serialization; preserves source scripts/handlers by default (explicit --omit-scripts opt-out), supports section/body/html roots, handles open shadow trees, records styles and animation data.
21
- - `scripts/resources.mjs`: streamed size/deadline limits, hash-named assets, PostCSS import processing and URL rewriting. Responses from the capture browser are preferred; independent HTTP fetch is a fallback. No personal browser session is imported.
21
+ - `scripts/resources.mjs`: streamed size/deadline limits, hash-named assets, PostCSS import processing and URL rewriting. Responses from the capture browser are preferred; independent HTTP fetch is a fallback. Referenced assets are fetched concurrently through a bounded pool that shares the total budget. No personal browser session is imported.
22
22
  - `scripts/browser-resources.mjs`: bounded retention of response bodies and redirect aliases from the fresh source context; Playwright body materialization is not a streaming memory limit.
23
23
  - `scripts/css-context.mjs`: restores custom-property declarations whose selectors lost structural context, preserving their specificity, order and enclosing conditions instead of freezing computed viewport values.
24
24
  - `scripts/validate.mjs`: isolated source/output contexts, screenshot comparison, resource and execution diagnostics. Does not infer behavioral equivalence.
package/docs/support.md CHANGED
@@ -1,4 +1,6 @@
1
- # UIport 0.1 support matrix
1
+ # UIport support matrix
2
+
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.
2
4
 
3
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.
4
6
 
@@ -11,7 +13,7 @@ UIport exports a rendered section or a selected whole page. It does not reconstr
11
13
  | SVG fragments | Preserved | Hash stays on local URL, e.g. `assets/…svg#shape` |
12
14
  | Hover/focus and CSS animations | Original CSS preserved | Example states and animations exercised by integration tests |
13
15
  | Web Animations API | Observed keyframes/timing on DocumentTimeline | Paused/infinite timing tested; does not reconstruct triggering events |
14
- | Open Shadow DOM | Partial | Declarative shadow tree and inline/adopted styles; simple local fixture covered |
16
+ | Open Shadow DOM | Partial | Declarative shadow tree and inline/adopted styles; simple local fixture covered. The selector must match an element of the light DOM: shadow content is captured when its host is inside the selection, but a root inside a shadow tree is not resolved |
15
17
  | Source scripts, handlers and visual libraries | Preserved as in the prototype; capture --omit-scripts opts out | Scripts in the selection and recognized visual libraries are copied; initialization outside the selection, module dependencies and arbitrary listeners still need review. Preserved source code reports SOURCE_RUNTIME_UNVERIFIED |
16
18
  | Canvas | Static readable frame only | An unreadable frame is reported; no dynamic WebGL guarantee |
17
19
  | Iframes, object/embed | Disabled | Embedded documents are not extracted or allowed to run automatically |
@@ -30,19 +32,31 @@ Contextual custom-property rules that matched the source but lose structural con
30
32
 
31
33
  Existing prototype exports are accepted by their legacy root marker; validate does not rewrite them. The locale default remains pt-BR.
32
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
+
33
43
  ## Limits and diagnostics
34
44
 
35
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.
36
46
  - Viewports: 1–8, dimensions 200–3840 pixels. Screenshot comparisons capped at 20 megapixels.
37
47
  - Total operation: default 120 seconds, configurable 1–600 seconds. The deadline also covers browser startup; cancellation closes the owned browser process tree. Process cleanup can add a short shutdown interval. Source navigation is bounded; resource fetches have up to 15 seconds each.
38
48
  - Lazy scroll: default 80 steps, configurable 1–1000. `SCROLL_LIMIT` means content may remain unloaded.
49
+ - The selected root must render something at the captured viewport. A root that displays nothing — hidden, without a box of its own, or fully transparent — is reported as a partial result instead of failing the capture, and validation refuses it with an actionable message instead of waiting for a screenshot that can never succeed.
39
50
  - Export resource budget: default 20 MiB/file, 100 MiB total; controls downloaded copies, not source browser memory. Successful responses from the fresh capture context are reused, including Referer-dependent resources. Retention has the same per-file/aggregate budgets, but Playwright materializes response bodies before actual-size validation; peak memory is not bounded by these budgets. All referenced CSS resources may be retained, including resources unused by the selected DOM, because CSS is conservative.
51
+ - Resources are downloaded concurrently, with at most eight transfers at a time. The per-file and total budgets are shared by those transfers, so a section that references many assets does not exceed the total budget. The same URL is downloaded once even when several declarations reference it. The result reports `downloadedBytes`, the bytes read from the network, and `budgetBytes`, the bytes charged against the total budget; the charged amount never exceeds the limit, while the read amount can exceed it by the chunk that the limit refused.
40
52
  - Public HTTP(S) only; no session/cookie import. Local development URLs are supported. The capture reuses its own navigation responses; fallback fetch does not import browser cookies.
41
53
  - Source JavaScript executes in the capture browser. The optional --omit-scripts mode is not a general-purpose sanitizer or sandbox for hostile websites.
42
54
  - Source style values and content remain in the HTML. Review artifacts before redistribution. The CLI redacts URL credentials, queries and fragments in resource diagnostics and operational errors and does not print source page content or form values.
43
55
  - Network/rendering differences, DOM changed by runtime, special CSS/HTML features and states not observed can still require manual work. No invented replacement effects.
44
56
 
45
- Common partial-result codes: `SOURCE_RUNTIME_UNVERIFIED`, `SOURCE_RUNTIME_OMITTED`, `RESOURCE_UNAVAILABLE`, `STYLESHEET_UNAVAILABLE`, `SCROLL_LIMIT`, `RESPONSIVE_DOM_CHANGED`, `CANVAS_STATIC`, `CANVAS_UNREADABLE`, `EMBED_OMITTED`, `ANIMATION_UNSUPPORTED`, `SOURCE_REQUEST_FAILED`, `SOURCE_SCRIPT_ERROR`, `CSS_IMPORT_CYCLE`, `CSS_IMPORT_UNSUPPORTED`.
57
+ Common partial-result codes: `SOURCE_RUNTIME_UNVERIFIED`, `SOURCE_RUNTIME_OMITTED`, `RESOURCE_UNAVAILABLE`, `INVALID_RESOURCE_URL`, `STYLESHEET_UNAVAILABLE`, `SRCSET_INVALID`, `SCROLL_LIMIT`, `RESPONSIVE_DOM_CHANGED`, `SECTION_NOT_VISIBLE`, `SECTION_EMPTY_AREA`, `CANVAS_STATIC`, `CANVAS_UNREADABLE`, `EMBED_OMITTED`, `ANIMATION_UNSUPPORTED`, `SOURCE_REQUEST_FAILED`, `SOURCE_SCRIPT_ERROR`, `CSS_IMPORT_CYCLE`, `CSS_IMPORT_UNSUPPORTED`.
58
+
59
+ `SECTION_NOT_VISIBLE` and `SECTION_EMPTY_AREA` mean the selected root does not render at that viewport: its markup is still exported, but it displays nothing. Choose a selector that matches a visible element, or capture the whole page with `body`. `SRCSET_INVALID` means a `srcset` descriptor list could not be parsed; the original value is preserved unchanged instead of being dropped, so check which image the browser picks. `INVALID_RESOURCE_URL` means a resource URL could not be resolved and was left as it was.
46
60
 
47
61
  ## Supported environments
48
62
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uiport",
3
- "version": "0.1.1",
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": {
@@ -2,8 +2,17 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { chromium } from "playwright-core";
4
4
  import { parseFragment, serialize } from "parse5";
5
- import parseSrcset from "parse-srcset";
6
- import { extractSection } from "./dom.mjs";
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";
15
+ import { parseSrcsetAttribute } from "./srcset.mjs";
7
16
  import { resources } from "./resources.mjs";
8
17
  import { browserResources } from "./browser-resources.mjs";
9
18
  import { contextualCss } from "./css-context.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,13 +141,33 @@ 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
- await root.scrollIntoViewIfNeeded();
148
+ // A root that does not render is reported instead of waiting for a
149
+ // screenshot that can never succeed. The locator is used for the
150
+ // measurement so that a root inside an open shadow tree is found.
151
+ const rendered = await root.evaluate(measureRoot);
152
+ if (rendered.hidden)
153
+ limitation(
154
+ limitations,
155
+ "SECTION_NOT_VISIBLE",
156
+ `The selected root is hidden at ${viewport.name}; its markup is exported but displays nothing`,
157
+ );
158
+ else if (!rendered.visible)
159
+ limitation(
160
+ limitations,
161
+ "SECTION_EMPTY_AREA",
162
+ `The selected root has no rendered size at ${viewport.name}; its markup is exported but displays nothing`,
163
+ );
164
+ else await root.scrollIntoViewIfNeeded();
95
165
  const snapshot = await page.evaluate(extractSection, {
96
166
  selector,
97
167
  omitScripts: options.omitScripts,
168
+ idAttribute: ID_ATTR,
169
+ rootAttribute: ROOT_ATTR,
170
+ rootValue: ROOT_VALUE,
98
171
  });
99
172
  captures.push(snapshot);
100
173
  await cache.settle();
@@ -122,7 +195,12 @@ export async function capture(options) {
122
195
  }
123
196
  cssContext = contextualCss(cssParts);
124
197
  }
125
- 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);
126
204
  }
127
205
  await cache.settle();
128
206
  await close();
@@ -184,7 +262,30 @@ export async function capture(options) {
184
262
  })
185
263
  .join("\n");
186
264
  const head = parseFragment(runtimeHtml + primary.headHtml);
187
- async function rewrite(node) {
265
+ // Every referenced resource is localized concurrently and the document is
266
+ // assembled once all of them are known. The download pool inside the
267
+ // resource layer bounds how many transfers run at the same time.
268
+ const pending = [];
269
+ const localizeSrcset = async (value) => {
270
+ const parsed = parseSrcsetAttribute(value);
271
+ if (!parsed.length && value.trim()) {
272
+ // An unparsable descriptor list is preserved unchanged: dropping it
273
+ // would silently change which image the browser picks.
274
+ limitation(
275
+ limitations,
276
+ "SRCSET_INVALID",
277
+ "A srcset attribute could not be parsed and was preserved unchanged",
278
+ );
279
+ return value;
280
+ }
281
+ const candidates = [];
282
+ for (const item of parsed)
283
+ candidates.push(
284
+ `${await assets.localize(item.url, primary.baseUrl)}${item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : ""}`,
285
+ );
286
+ return candidates.join(", ");
287
+ };
288
+ function rewrite(node) {
188
289
  if (node.attrs) {
189
290
  for (const attr of node.attrs) {
190
291
  if (
@@ -193,37 +294,69 @@ export async function capture(options) {
193
294
  ) ||
194
295
  (["use", "image"].includes(node.tagName) &&
195
296
  ["href", "xlink:href"].includes(attr.name))
196
- )
197
- attr.value = await assets.localize(
198
- attr.value,
199
- primary.baseUrl,
200
- node.tagName === "script" && attr.name === "src"
201
- ? "script"
202
- : undefined,
297
+ ) {
298
+ const original = attr.value;
299
+ pending.push(
300
+ assets
301
+ .localize(
302
+ original,
303
+ primary.baseUrl,
304
+ node.tagName === "script" && attr.name === "src"
305
+ ? "script"
306
+ : undefined,
307
+ )
308
+ .then((value) => {
309
+ attr.value = value;
310
+ }),
203
311
  );
312
+ }
204
313
  if (attr.name === "srcset") {
205
- const candidates = [];
206
- for (const item of parseSrcset(attr.value))
207
- candidates.push(
208
- `${await assets.localize(item.url, primary.baseUrl)}${item.w ? ` ${item.w}w` : item.d ? ` ${item.d}x` : ""}`,
209
- );
210
- attr.value = candidates.join(", ");
314
+ const original = attr.value;
315
+ pending.push(
316
+ localizeSrcset(original).then((value) => {
317
+ attr.value = value;
318
+ }),
319
+ );
320
+ }
321
+ if (attr.name === "style") {
322
+ const original = attr.value;
323
+ pending.push(
324
+ assets.cssValue(original, primary.baseUrl).then((value) => {
325
+ attr.value = value;
326
+ }),
327
+ );
211
328
  }
212
- if (attr.name === "style")
213
- attr.value = await assets.cssValue(attr.value, primary.baseUrl);
214
329
  }
215
330
  }
216
331
  if (node.tagName === "style")
217
332
  for (const child of node.childNodes || [])
218
- if (child.nodeName === "#text")
219
- child.value = await assets.css(child.value, primary.baseUrl);
220
- for (const child of node.childNodes || []) await rewrite(child);
221
- if (node.content) await rewrite(node.content);
333
+ if (child.nodeName === "#text") {
334
+ const original = child.value;
335
+ pending.push(
336
+ assets.css(original, primary.baseUrl).then((value) => {
337
+ child.value = value;
338
+ }),
339
+ );
340
+ }
341
+ for (const child of node.childNodes || []) rewrite(child);
342
+ if (node.content) rewrite(node.content);
222
343
  }
223
- await rewrite(fragment);
224
- await rewrite(head);
225
- await rewrite({ attrs: primary.htmlAttributes });
226
- await rewrite({ attrs: primary.bodyAttributes });
344
+ rewrite(fragment);
345
+ rewrite(head);
346
+ rewrite({ attrs: primary.htmlAttributes });
347
+ rewrite({ attrs: primary.bodyAttributes });
348
+ // Every pending localization settles before the document is assembled. A
349
+ // cancellation must not leave sibling rejections unhandled.
350
+ const settled = await Promise.allSettled(pending);
351
+ const failure = settled.find((entry) => entry.status === "rejected");
352
+ if (failure) throw failure.reason;
353
+ // Resources are localized concurrently, so the order in which problems
354
+ // are observed is not stable. Sorting keeps the reported result
355
+ // reproducible from one run to the next and from one machine to another.
356
+ const compare = (x, y) => (x < y ? -1 : x > y ? 1 : 0);
357
+ limitations.sort(
358
+ (a, b) => compare(a.code, b.code) || compare(a.message, b.message),
359
+ );
227
360
  // Context-dependent custom properties retain their original conditions;
228
361
  // ordinary inherited/responsive variables are never frozen to one viewport.
229
362
  const animations = primary.animations.filter(
@@ -244,8 +377,10 @@ export async function capture(options) {
244
377
  "Some observed animations cannot be replayed on DocumentTimeline",
245
378
  );
246
379
  const metadata = {
380
+ elements: primary.featureCounts.elements,
381
+ assets: assets.stats().assets,
247
382
  limitations,
248
- behavior: "not-tested",
383
+ behavior: BEHAVIOR,
249
384
  source: redactedUrl(sourceUrl),
250
385
  };
251
386
  const html = `<!doctype html>
@@ -253,22 +388,22 @@ export async function capture(options) {
253
388
  <head>
254
389
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
255
390
  <title>${escapeHtml(primary.title || "UIport — extracted section")}</title>
256
- <style>${parts.join("\n").replaceAll("</style", "<\\/style")}</style>
391
+ <style>${parts.join("\n").replace(/<\/style/gi, "<\\/style")}</style>
257
392
  ${serialize(head)}
258
393
  </head>
259
394
  <body${serializeAttributes(primary.bodyAttributes)}>
260
395
  ${serialize(fragment)}
261
- <script type="application/json" id="uiport-metadata">${jsonForInlineScript(metadata)}</script>
262
- <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>
263
398
  <script>
264
399
  (() => {
265
400
  const find = (id, root = document) => {
266
- const direct = root.querySelector('[data-uiport-id="' + CSS.escape(id) + '"]');
401
+ const direct = root.querySelector('[${ID_ATTR}="' + CSS.escape(id) + '"]');
267
402
  if (direct) return direct;
268
403
  for (const element of root.querySelectorAll('*')) if (element.shadowRoot) { const found = find(id, element.shadowRoot); if (found) return found; }
269
404
  return null;
270
405
  };
271
- for (const record of JSON.parse(document.getElementById('uiport-animations').textContent)) {
406
+ for (const record of JSON.parse(document.getElementById('${ANIMATIONS_ID}').textContent)) {
272
407
  const target = find(record.targetId);
273
408
  if (!target) continue;
274
409
  try {
@@ -297,7 +432,7 @@ ${serialize(fragment)}
297
432
  ...assets.stats(),
298
433
  elements: primary.featureCounts.elements,
299
434
  animationsReplayed: animations.length,
300
- behavior: "not-tested",
435
+ behavior: BEHAVIOR,
301
436
  limitations,
302
437
  };
303
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";