uiport 0.1.2 → 0.1.4

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.
@@ -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,17 +140,47 @@ 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
 
120
- /** @param {string} command @param {Record<string, string | boolean>} args */
150
+ /**
151
+ * @typedef {object} Options
152
+ * @property {boolean} json
153
+ * @property {boolean} omitScripts
154
+ * @property {boolean} dryRun
155
+ * @property {string} sourceUrl
156
+ * @property {string} selector
157
+ * @property {string} before
158
+ * @property {string} after
159
+ * @property {string} directory
160
+ * @property {{width:number,height:number,name:string}[]} viewports
161
+ * @property {number} settleMs
162
+ * @property {number} timeoutMs
163
+ * @property {string} locale
164
+ * @property {'light' | 'dark'} colorScheme
165
+ * @property {number} maxResourceBytes
166
+ * @property {number} maxTotalBytes
167
+ * @property {number} maxScrollSteps
168
+ * @property {number} maximumDifferenceRatio
169
+ * @property {boolean} allowExternal
170
+ * @property {number} port
171
+ */
172
+
173
+ /** @param {string} command @param {Record<string, string | boolean>} args @returns {Options} */
121
174
  export function optionsFor(command, args) {
175
+ /** @type {Options} */
122
176
  const options = {
123
177
  json: args.json === true,
124
178
  omitScripts: args["omit-scripts"] === true,
179
+ dryRun: args["dry-run"] === true,
125
180
  sourceUrl: "",
126
181
  selector: "",
182
+ before: "",
183
+ after: "",
127
184
  directory: "",
128
185
  viewports: parseViewports(
129
186
  typeof args.viewports === "string" ? args.viewports : undefined,
@@ -160,17 +217,32 @@ export function optionsFor(command, args) {
160
217
  port: numeric(args.port, "port", 4173, 0, 65535),
161
218
  };
162
219
  if (!["light", "dark"].includes(options.colorScheme))
163
- throw new Error("--color-scheme must be light or dark");
220
+ throw new UiportError(
221
+ "USAGE_INVALID",
222
+ "--color-scheme must be light or dark",
223
+ );
164
224
  if (
165
225
  !Number.isInteger(options.port) ||
166
226
  !Number.isInteger(options.maxScrollSteps)
167
227
  )
168
- throw new Error("--port and --max-scroll-steps must be integers");
228
+ throw new UiportError(
229
+ "USAGE_INVALID",
230
+ "--port and --max-scroll-steps must be integers",
231
+ );
169
232
  if (command === "capture" || command === "validate") {
170
233
  options.sourceUrl = httpUrl(required(args, "url"));
171
234
  options.selector = required(args, "selector");
172
235
  }
173
- if (["capture", "validate", "serve"].includes(command))
236
+ if (command === "diff") {
237
+ options.before = path.resolve(required(args, "before"));
238
+ options.after = path.resolve(required(args, "after"));
239
+ }
240
+ if (command === "capture" && options.dryRun)
241
+ // A dry run writes nothing, so it needs no destination.
242
+ options.directory = path.resolve(
243
+ typeof args.out === "string" ? args.out : ".uiport-dry-run",
244
+ );
245
+ else if (["capture", "validate", "serve", "inspect"].includes(command))
174
246
  options.directory = path.resolve(
175
247
  required(args, command === "capture" ? "out" : "dir"),
176
248
  );
@@ -0,0 +1,133 @@
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
+ // The limitations of the exported section are collected from every
75
+ // viewport, because they belong to the artifact and not to one of them.
76
+ const collected = new Map();
77
+ for (const entry of result.results)
78
+ for (const item of entry.captureLimitations || [])
79
+ collected.set(`${item.code}|${item.message}`, item);
80
+ for (const entry of failed) {
81
+ const visual = entry.visual || {};
82
+ // The pixels are only the reason when the pixels are the reason.
83
+ if (visual.pass === false)
84
+ lines.push(
85
+ ` ! ${entry.viewport} — ${(visual.differenceRatio * 100).toFixed(1)}% of the pixels differ (limit ${(visual.maximumDifferenceRatio * 100).toFixed(0)}%)`,
86
+ );
87
+ if (entry.network && entry.network.pass === false)
88
+ lines.push(
89
+ ` ! ${entry.viewport} — the exported page made a request it could not satisfy`,
90
+ );
91
+ for (const error of entry.errors || []) lines.push(` ${error}`);
92
+ for (const url of entry.network?.failedRequests || [])
93
+ lines.push(` failed request: ${url}`);
94
+ }
95
+ lines.push(...limitations([...collected.values()]));
96
+ lines.push(...limitations(result.limitations));
97
+ lines.push(" behavior: not tested; inspect the interactions yourself");
98
+ } else if (result.command === "diff") {
99
+ const changed = result.results.filter((entry) => !entry.identical);
100
+ const views = result.results.length === 1 ? "viewport" : "viewports";
101
+ const added = result.limitations.added || [];
102
+ const removed = result.limitations.removed || [];
103
+ if (!changed.length && !added.length && !removed.length)
104
+ lines.push(
105
+ `UIport: the two exports are identical in ${result.results.length} ${views}`,
106
+ );
107
+ else {
108
+ lines.push(
109
+ `UIport: the two exports differ — ${changed.length} of ${result.results.length} ${views} with different pixels, ${added.length} limitation(s) added and ${removed.length} removed`,
110
+ );
111
+ for (const entry of changed)
112
+ lines.push(
113
+ ` ! ${entry.viewport} — ${(entry.differenceRatio * 100).toFixed(1)}% of the pixels differ${entry.dimensionsMatch ? "" : `, and the height differs by ${entry.heightDifference} px`}`,
114
+ );
115
+ for (const entry of added)
116
+ lines.push(` + ${entry.code} — reported only by the second export`);
117
+ for (const entry of removed)
118
+ lines.push(` - ${entry.code} — reported only by the first export`);
119
+ }
120
+ } else if (result.command === "inspect") {
121
+ lines.push(`UIport: ${result.outputDirectory}`);
122
+ lines.push(
123
+ ` ${result.elements ?? "?"} elements · ${result.assets ?? 0} asset${result.assets === 1 ? "" : "s"}`,
124
+ );
125
+ lines.push(...limitations(result.limitations));
126
+ }
127
+ return lines.join("\n");
128
+ }
129
+
130
+ /** @param {{code:string,message:string,hint:string}} error */
131
+ export function reportError(error) {
132
+ return [`UIport: ${error.message}`, ` ${error.hint}`].join("\n");
133
+ }
@@ -12,7 +12,7 @@ import {
12
12
  limitation,
13
13
  } from "./lib.mjs";
14
14
 
15
- /** @param {string} directory @param {import('./options.mjs').optionsFor extends (...args: any[]) => infer T ? T : never} options @param {AbortSignal} signal @param {{code:string,message:string}[]} limitations @param {{get:(url:string)=>Promise<any>} | undefined} [browserCache] */
15
+ /** @param {string} directory @param {import('./options.mjs').Options} options @param {AbortSignal} signal @param {{code:string,message:string}[]} limitations @param {{get:(url:string)=>Promise<any>} | undefined} [browserCache] */
16
16
  export function resources(
17
17
  directory,
18
18
  options,
@@ -29,12 +29,14 @@ export function resources(
29
29
  const localPaths = new Set();
30
30
  const maxConcurrentDownloads = 8;
31
31
  let activeDownloads = 0;
32
+ /** @type {((value?: unknown) => void)[]} */
32
33
  const waitingDownloads = [];
33
34
  // Bytes read from the network, and bytes charged against the total budget.
34
35
  // The charge happens before the bytes are retained, so concurrent transfers
35
36
  // cannot pass the limit together; the reported download size stays the
36
37
  // amount actually received.
37
38
  let received = 0;
39
+ /** @param {number} bytes */
38
40
  function consume(bytes) {
39
41
  received += bytes;
40
42
  if (consumed + bytes > options.maxTotalBytes)
@@ -178,6 +180,7 @@ export function resources(
178
180
  // Most declarations carry no URL at all: parsing them is wasted work.
179
181
  if (!/url\(|image-set\(/i.test(value)) return value;
180
182
  const parsed = valueParser(value);
183
+ /** @type {any[]} */
181
184
  const nodes = [];
182
185
  parsed.walk((node) => {
183
186
  if (node.type === "function" && node.value.toLowerCase() === "url") {
@@ -217,19 +220,22 @@ export function resources(
217
220
  /** @param {string} text @param {string} base @param {Set<string>} [stack] */
218
221
  async function css(text, base, stack = new Set()) {
219
222
  const root = postcss.parse(text, { from: undefined });
223
+ /** @type {import('postcss').Declaration[]} */
220
224
  const declarations = [];
221
225
  root.walkDecls((decl) => {
222
226
  declarations.push(decl);
223
227
  });
228
+ /** @type {import('postcss').AtRule[]} */
224
229
  const imports = [];
225
230
  root.walkAtRules(/^import$/i, (rule) => {
226
231
  imports.push(rule);
227
232
  });
228
233
  for (const rule of imports) {
229
234
  const parsed = valueParser(rule.params);
230
- const first = parsed.nodes.find(
235
+ const firstIndex = parsed.nodes.findIndex(
231
236
  (n) => n.type !== "space" && n.type !== "comment",
232
237
  );
238
+ const first = parsed.nodes[firstIndex];
233
239
  const raw =
234
240
  first?.type === "string"
235
241
  ? first.value
@@ -256,7 +262,7 @@ export function resources(
256
262
  }
257
263
  const imported = await download(url);
258
264
  if (!imported) {
259
- rule.params = `url(${JSON.stringify(url)}) ${valueParser.stringify(parsed.nodes.slice(parsed.nodes.indexOf(first) + 1))}`;
265
+ rule.params = `url(${JSON.stringify(url)}) ${valueParser.stringify(parsed.nodes.slice(firstIndex + 1))}`;
260
266
  continue;
261
267
  }
262
268
  let body = await css(
@@ -265,19 +271,27 @@ export function resources(
265
271
  new Set([...stack, url]),
266
272
  );
267
273
  const tail = parsed.nodes
268
- .slice(parsed.nodes.indexOf(first) + 1)
274
+ .slice(firstIndex + 1)
269
275
  .filter((n) => n.type !== "space" && n.type !== "comment");
270
276
  const wrappers = [];
271
277
  if (tail[0]?.value === "layer") {
272
278
  const layer = tail.shift();
273
279
  wrappers.push([
274
280
  "layer",
275
- layer.type === "function" ? valueParser.stringify(layer.nodes) : "",
281
+ layer?.type === "function"
282
+ ? valueParser.stringify(
283
+ /** @type {import('postcss-value-parser').FunctionNode} */ (
284
+ layer
285
+ ).nodes,
286
+ )
287
+ : "",
276
288
  ]);
277
289
  }
278
290
  if (tail[0]?.type === "function" && tail[0].value === "supports") {
279
- const supports = tail[0];
280
- tail.shift();
291
+ const supports =
292
+ /** @type {import('postcss-value-parser').FunctionNode} */ (
293
+ tail.shift()
294
+ );
281
295
  const v = valueParser.stringify(supports.nodes);
282
296
  wrappers.push([
283
297
  "supports",
@@ -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,
@@ -10,6 +18,7 @@ import {
10
18
  redactedUrl,
11
19
  scrollForLazyContent,
12
20
  startStaticServer,
21
+ navigationError,
13
22
  waitForPageStable,
14
23
  } from "./lib.mjs";
15
24
  // Copy a decoded PNG into a buffer of the comparison size, padding the rows
@@ -32,7 +41,16 @@ function copy(source, destination, width) {
32
41
  }
33
42
 
34
43
  export async function validate(options) {
35
- await fs.access(path.join(options.directory, "index.html"));
44
+ const index = path.join(options.directory, "index.html");
45
+ try {
46
+ await fs.access(index);
47
+ } catch (error) {
48
+ throw new UiportError(
49
+ "ARTIFACT_MISSING",
50
+ `The directory has no exported section: ${index}`,
51
+ { cause: error },
52
+ );
53
+ }
36
54
  const life = lifecycle(options.timeoutMs);
37
55
  const results = [];
38
56
  try {
@@ -57,10 +75,14 @@ export async function validate(options) {
57
75
  try {
58
76
  const source = await sourceContext.newPage();
59
77
  source.setDefaultTimeout(10000);
60
- await source.goto(options.sourceUrl, {
61
- waitUntil: "domcontentloaded",
62
- timeout: Math.min(options.timeoutMs, 60000),
63
- });
78
+ await source
79
+ .goto(options.sourceUrl, {
80
+ waitUntil: "domcontentloaded",
81
+ timeout: Math.min(options.timeoutMs, 60000),
82
+ })
83
+ .catch((error) => {
84
+ throw life.failure() || navigationError(error, options.sourceUrl);
85
+ });
64
86
  await waitForPageStable(source, options.settleMs);
65
87
  const scrollLimited = await scrollForLazyContent(
66
88
  source,
@@ -69,7 +91,10 @@ export async function validate(options) {
69
91
  await waitForPageStable(source, options.settleMs);
70
92
  const root = source.locator(options.selector);
71
93
  if ((await root.count()) !== 1)
72
- throw new Error("Source selector is missing or ambiguous");
94
+ throw new UiportError(
95
+ "SELECTOR_AMBIGUOUS",
96
+ "The source selector matched no element or more than one",
97
+ );
73
98
  const box = await root.boundingBox();
74
99
  if (!box || box.width <= 0 || box.height <= 0)
75
100
  throw new Error(
@@ -124,14 +149,21 @@ export async function validate(options) {
124
149
  });
125
150
  await waitForPageStable(local, options.settleMs);
126
151
  // Legacy root markers remain supported for existing user exports.
127
- const rootSelector = (await local
128
- .locator('[data-uiport-root="true"]')
129
- .count())
130
- ? '[data-uiport-root="true"]'
131
- : '[data-effect-extractor-root="true"]';
152
+ const isCurrent =
153
+ (await local.locator(`[${ROOT_ATTR}="${ROOT_VALUE}"]`).count()) > 0;
154
+ const rootSelector = isCurrent
155
+ ? `[${ROOT_ATTR}="${ROOT_VALUE}"]`
156
+ : `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
132
157
  const localRoot = local.locator(rootSelector);
133
158
  if ((await localRoot.count()) !== 1)
134
159
  throw new Error("UIport extraction root is missing or ambiguous");
160
+ // An export of this version carries its metadata. Without it the
161
+ // artifact was changed after the capture, and the result would report
162
+ // no limitation at all.
163
+ if (isCurrent && !(await local.locator(`#${METADATA_ID}`).count()))
164
+ throw new Error(
165
+ "The exported section has no UIport metadata; capture it again",
166
+ );
135
167
  const localBox = await localRoot.boundingBox();
136
168
  if (!localBox || localBox.width <= 0 || localBox.height <= 0)
137
169
  throw new Error(
@@ -176,10 +208,10 @@ export async function validate(options) {
176
208
  failedRequests.length === 0 &&
177
209
  (options.allowExternal || externalRequests.length === 0);
178
210
  const captureLimitations = (await local
179
- .locator("#uiport-metadata")
211
+ .locator(`#${METADATA_ID}`)
180
212
  .count())
181
213
  ? await local
182
- .locator("#uiport-metadata")
214
+ .locator(`#${METADATA_ID}`)
183
215
  .evaluate((el) => JSON.parse(el.textContent).limitations)
184
216
  : [];
185
217
  results.push({
@@ -199,7 +231,7 @@ export async function validate(options) {
199
231
  failedRequests,
200
232
  externalBlocked: !options.allowExternal,
201
233
  },
202
- behavior: "not-tested",
234
+ behavior: BEHAVIOR,
203
235
  captureLimitations,
204
236
  errors,
205
237
  scrollLimited,
@@ -214,9 +246,13 @@ export async function validate(options) {
214
246
  command: "validate",
215
247
  status: results.every((r) => r.pass) ? "complete" : "failed",
216
248
  browser: { selected, version: browser.version() },
217
- behavior: "not-tested",
249
+ behavior: BEHAVIOR,
218
250
  results,
219
251
  };
252
+ } catch (error) {
253
+ // A cancellation is reported with its own code, even when the browser
254
+ // rejected the pending operation first.
255
+ throw life.failure() || error;
220
256
  } finally {
221
257
  await life.close();
222
258
  }
@@ -8,13 +8,53 @@ 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.4` 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
+ | `SOURCE_UNREACHABLE` | The page could not be reached: check the address and that the service is up. |
35
+ | `ARTIFACT_MISSING` | The directory has no exported section: capture it first. |
36
+ | `ARTIFACT_DAMAGED` | The export has no metadata or no extraction root: capture it again. |
37
+ | `COMPARISON_TOO_LARGE` | The section is above 20 megapixels: compare a narrower section. |
38
+ | `INTERNAL` | An unexpected failure: read the message, and report it with the version. |
39
+
40
+ ## What each limitation asks for
41
+
42
+ | Limitation | What to do |
43
+ |---|---|
44
+ | `SOURCE_RUNTIME_UNVERIFIED` | Test the interactions before delivering. |
45
+ | `SOURCE_RUNTIME_OMITTED` | The behavior of the section is not reproduced. |
46
+ | `RESOURCE_UNAVAILABLE` | A resource was not downloaded: check it in the output. |
47
+ | `INVALID_RESOURCE_URL` | A resource address could not be resolved: check it in the output. |
48
+ | `STYLESHEET_UNAVAILABLE` | A stylesheet could not be read: the section may be missing styles. |
49
+ | `SOURCE_REQUEST_FAILED` | A request of the source failed: check whether the section depends on it. |
50
+ | `SOURCE_SCRIPT_ERROR` | The source raised a JavaScript error: the section may be incomplete. |
51
+ | `SRCSET_INVALID` | A descriptor list was not parsed: check which image the browser picks. |
52
+ | `SCROLL_LIMIT` | The lazy loading was cut short: raise `--max-scroll-steps`. |
53
+ | `RESPONSIVE_DOM_CHANGED` | The structure changes across viewports; the first viewport was exported. |
54
+ | `SECTION_NOT_VISIBLE` / `SECTION_EMPTY_AREA` | The selected root displays nothing: choose an element that renders. |
55
+ | `CANVAS_STATIC` / `CANVAS_UNREADABLE` | A canvas was exported as a still image, or could not be read. |
56
+ | `EMBED_OMITTED` | An embedded document was disabled. |
57
+ | `ANIMATION_UNSUPPORTED` | An animation could not be replayed. |
58
+ | `CSS_IMPORT_CYCLE` / `CSS_IMPORT_UNSUPPORTED` | A stylesheet import was omitted. |
19
59
 
20
60
  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.4` 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