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.
@@ -0,0 +1,203 @@
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
+ import { UiportError } from "./errors.mjs";
21
+
22
+ const rootSelector = `[${ROOT_ATTR}="${ROOT_VALUE}"]`;
23
+ const legacyRootSelector = `[${LEGACY_ROOT_ATTR}="${ROOT_VALUE}"]`;
24
+ const SCREENSHOT_PIXEL_LIMIT = 20_000_000;
25
+
26
+ /** Reads the metadata of an exported section, refusing a damaged artifact. */
27
+ async function readMetadata(directory) {
28
+ const file = path.join(directory, "index.html");
29
+ let html;
30
+ try {
31
+ html = await fs.readFile(file, "utf8");
32
+ } catch (error) {
33
+ throw new UiportError(
34
+ "ARTIFACT_MISSING",
35
+ `The directory has no exported section: ${file}`,
36
+ { cause: error },
37
+ );
38
+ }
39
+ const match = html.match(
40
+ new RegExp(
41
+ `<script type="application/json" id="${METADATA_ID}">([\\s\\S]*?)</script>`,
42
+ ),
43
+ );
44
+ if (!match)
45
+ throw new UiportError(
46
+ "ARTIFACT_DAMAGED",
47
+ `The exported section has no UIport metadata: ${file}`,
48
+ );
49
+ try {
50
+ return JSON.parse(match[1]);
51
+ } catch {
52
+ throw new UiportError(
53
+ "ARTIFACT_DAMAGED",
54
+ `The metadata of the exported section is not valid JSON: ${file}`,
55
+ );
56
+ }
57
+ }
58
+
59
+ /** The multiset difference of two limitation lists, by code and message. */
60
+ function difference(left, right) {
61
+ const counts = new Map();
62
+ for (const entry of right) {
63
+ const key = `${entry.code}|${entry.message}`;
64
+ counts.set(key, (counts.get(key) || 0) + 1);
65
+ }
66
+ const missing = [];
67
+ for (const entry of left) {
68
+ const key = `${entry.code}|${entry.message}`;
69
+ const remaining = counts.get(key) || 0;
70
+ if (remaining > 0) counts.set(key, remaining - 1);
71
+ else missing.push(entry);
72
+ }
73
+ return missing;
74
+ }
75
+
76
+ /** Compares two exported sections: the pixels they render and what they report. */
77
+ export async function diff(options) {
78
+ const before = path.resolve(options.before);
79
+ const after = path.resolve(options.after);
80
+ // The metadata is read first: a damaged artifact is reported before a browser
81
+ // is started, and it is never read as an artifact without limitations.
82
+ const beforeMetadata = await readMetadata(before);
83
+ const afterMetadata = await readMetadata(after);
84
+ const life = lifecycle(options.timeoutMs);
85
+ try {
86
+ const beforeServer = await startStaticServer(before);
87
+ life.add(beforeServer.close);
88
+ const afterServer = await startStaticServer(after);
89
+ life.add(afterServer.close);
90
+ const { browser, selected } = await launchChromium(chromium, life);
91
+ const results = [];
92
+ for (const viewport of options.viewports) {
93
+ life.check();
94
+ log(`Comparing ${viewport.name}…`);
95
+ const context = await browser.newContext({
96
+ viewport,
97
+ deviceScaleFactor: 1,
98
+ locale: options.locale,
99
+ colorScheme: options.colorScheme,
100
+ serviceWorkers: "block",
101
+ });
102
+ try {
103
+ const page = await context.newPage();
104
+ const shots = [];
105
+ for (const server of [beforeServer, afterServer]) {
106
+ await page.goto(`${server.url}/index.html`, {
107
+ waitUntil: "domcontentloaded",
108
+ });
109
+ await waitForPageStable(page, options.settleMs);
110
+ const root = page.locator(
111
+ (await page.locator(rootSelector).count())
112
+ ? rootSelector
113
+ : legacyRootSelector,
114
+ );
115
+ if ((await root.count()) !== 1)
116
+ throw new UiportError(
117
+ "ARTIFACT_DAMAGED",
118
+ "An exported section is missing its extraction root",
119
+ );
120
+ // The size is checked before the screenshot, so an oversized section
121
+ // is refused instead of being rendered and decoded first.
122
+ const box = await root.boundingBox();
123
+ if (box && box.width * box.height > SCREENSHOT_PIXEL_LIMIT)
124
+ throw new UiportError(
125
+ "COMPARISON_TOO_LARGE",
126
+ "The section exceeds the 20 megapixel comparison limit",
127
+ );
128
+ shots.push(
129
+ await root.screenshot({ animations: "disabled", caret: "hide" }),
130
+ );
131
+ }
132
+ const left = PNG.sync.read(shots[0]);
133
+ const right = PNG.sync.read(shots[1]);
134
+ const width = Math.max(left.width, right.width);
135
+ const height = Math.max(left.height, right.height);
136
+ if (width * height > SCREENSHOT_PIXEL_LIMIT)
137
+ throw new UiportError(
138
+ "COMPARISON_TOO_LARGE",
139
+ "The comparison exceeds the 20 megapixel limit",
140
+ );
141
+ const sameSize =
142
+ left.width === right.width && left.height === right.height;
143
+ const buffer = (source) => {
144
+ if (sameSize) return source.data;
145
+ const target = new Uint8Array(width * height * 4);
146
+ const rowBytes = source.width * 4;
147
+ for (let y = 0; y < source.height; y += 1)
148
+ source.data.copy(
149
+ target,
150
+ y * width * 4,
151
+ y * rowBytes,
152
+ y * rowBytes + rowBytes,
153
+ );
154
+ return target;
155
+ };
156
+ const differentPixels = pixelmatch(
157
+ buffer(left),
158
+ buffer(right),
159
+ null,
160
+ width,
161
+ height,
162
+ { threshold: 0.1, includeAA: false },
163
+ );
164
+ const ratio = differentPixels / (width * height);
165
+ results.push({
166
+ viewport: viewport.name,
167
+ identical: ratio === 0,
168
+ differentPixels,
169
+ differenceRatio: ratio,
170
+ dimensionsMatch: sameSize,
171
+ heightDifference: Math.abs(left.height - right.height),
172
+ });
173
+ } finally {
174
+ await context.close();
175
+ }
176
+ }
177
+ const added = difference(
178
+ afterMetadata.limitations || [],
179
+ beforeMetadata.limitations || [],
180
+ );
181
+ const removed = difference(
182
+ beforeMetadata.limitations || [],
183
+ afterMetadata.limitations || [],
184
+ );
185
+ const changed = results.some((entry) => !entry.identical);
186
+ const limitationsDiffer = added.length > 0 || removed.length > 0;
187
+ return {
188
+ command: "diff",
189
+ // Any difference leaves the result partial: a lost limitation is as
190
+ // relevant as a new one.
191
+ status: changed || limitationsDiffer ? "partial" : "complete",
192
+ before,
193
+ after,
194
+ browser: { selected, version: browser.version() },
195
+ identical: !changed,
196
+ results,
197
+ limitations: { added, removed },
198
+ behavior: BEHAVIOR,
199
+ };
200
+ } finally {
201
+ await life.close();
202
+ }
203
+ }
package/scripts/dom.mjs CHANGED
@@ -4,49 +4,68 @@
4
4
  // `display: contents`, a zero-sized wrapper around an absolutely positioned
5
5
  // child, or a parent whose visibility is overridden by a child.
6
6
  export function measureRoot(element) {
7
- const renders = (node) => {
8
- const style = getComputedStyle(node);
9
- if (style.display === "none" || style.visibility === "hidden") return false;
10
- if (
7
+ const styleOf = (node) => getComputedStyle(node);
8
+ const hiddenByStyle = (node) => {
9
+ const style = styleOf(node);
10
+ if (style.display === "none" || style.visibility === "hidden") return true;
11
+ return Boolean(
11
12
  node.checkVisibility &&
12
- !node.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })
13
- )
14
- return false;
15
- const box = node.getBoundingClientRect();
16
- return box.width > 0 && box.height > 0;
13
+ !node.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }),
14
+ );
17
15
  };
16
+ // The largest box that renders, considering the element itself, its
17
+ // descendants at any depth and the text it holds. A root without a box of
18
+ // its own is still visible when something inside it renders.
18
19
  let width = 0;
19
20
  let height = 0;
20
- for (const child of element.children) {
21
- if (!renders(child)) continue;
22
- const box = child.getBoundingClientRect();
23
- width = Math.max(width, box.width);
24
- height = Math.max(height, box.height);
25
- }
26
- if (renders(element)) {
27
- const box = element.getBoundingClientRect();
28
- width = Math.max(width, box.width);
29
- height = Math.max(height, box.height);
30
- }
31
- const style = getComputedStyle(element);
21
+ const consider = (box) => {
22
+ if (box.width > 0 && box.height > 0) {
23
+ width = Math.max(width, box.width);
24
+ height = Math.max(height, box.height);
25
+ }
26
+ };
27
+ const walk = (node, depth, inheritedOpacity) => {
28
+ if (depth > 16) return;
29
+ const style = styleOf(node);
30
+ if (style.display === "none" || style.visibility === "hidden") return;
31
+ if (style.contentVisibility === "hidden") return;
32
+ // The opacity of the ancestors multiplies, so a transparent ancestor
33
+ // hides everything below it.
34
+ const opacity = inheritedOpacity * (Number(style.opacity) || 0);
35
+ if (opacity <= 0) return;
36
+ const box = node.getBoundingClientRect();
37
+ consider(box);
38
+ // Text nodes have no box of their own. A range over the content reports
39
+ // theirs, but only when the element does not clip that text away: a
40
+ // zero-sized box with overflow hidden hides it, while `display: contents`
41
+ // lays the text out in the parent.
42
+ const holdsText = style.display === "contents" || box.height > 0;
43
+ if (holdsText && node.textContent && node.textContent.trim()) {
44
+ const range = document.createRange();
45
+ range.selectNodeContents(node);
46
+ for (const rect of range.getClientRects()) consider(rect);
47
+ }
48
+ for (const child of node.children) walk(child, depth + 1, opacity);
49
+ };
50
+ walk(element, 0, 1);
32
51
  const displaysNothing = width <= 0 || height <= 0;
33
52
  // A root hidden by its own style displays nothing even when a child could
34
53
  // override the visibility. A root without a box is empty instead.
54
+ // `display: contents` has no box of its own, and the browser reports it as
55
+ // not visible even when its children render.
35
56
  const hidden =
36
57
  displaysNothing &&
37
- (style.display === "none" ||
38
- style.visibility === "hidden" ||
39
- (element.checkVisibility &&
40
- !element.checkVisibility({
41
- checkOpacity: true,
42
- checkVisibilityCSS: true,
43
- })));
58
+ styleOf(element).display !== "contents" &&
59
+ hiddenByStyle(element);
44
60
  return { hidden, visible: !displaysNothing, width, height };
45
61
  }
46
62
 
47
63
  export function extractSection({
48
64
  selector: targetSelector,
49
65
  omitScripts = false,
66
+ idAttribute = "data-uiport-id",
67
+ rootAttribute = "data-uiport-root",
68
+ rootValue = "true",
50
69
  }) {
51
70
  const target = document.querySelector(targetSelector);
52
71
  if (!target) throw new Error("Target disappeared before capture.");
@@ -106,13 +125,13 @@ export function extractSection({
106
125
  };
107
126
  visit(target);
108
127
  deepElements.forEach((element, index) =>
109
- element.setAttribute("data-uiport-id", `up-${index}`),
128
+ element.setAttribute(idAttribute, `up-${index}`),
110
129
  );
111
- target.setAttribute("data-uiport-root", "true");
130
+ target.setAttribute(rootAttribute, rootValue);
112
131
  let parent = target.parentElement;
113
132
  let ancestorId = 0;
114
133
  while (parent) {
115
- parent.setAttribute("data-uiport-id", `up-ancestor-${ancestorId++}`);
134
+ parent.setAttribute(idAttribute, `up-ancestor-${ancestorId++}`);
116
135
  parent = parent.parentElement;
117
136
  }
118
137
  let preservedScripts = 0;
@@ -202,7 +221,13 @@ export function extractSection({
202
221
  }
203
222
  }
204
223
  if (source.tagName === "STYLE") {
205
- clone.textContent = absolutizeCssUrls(source.textContent, source.baseURI);
224
+ // A style element created by a script can hold text that an HTML parser
225
+ // would read as the end of the element. The escape keeps the text in one
226
+ // piece and is equivalent CSS.
227
+ clone.textContent = absolutizeCssUrls(
228
+ source.textContent,
229
+ source.baseURI,
230
+ ).replace(/<\/style/gi, "<\\/style");
206
231
  return clone;
207
232
  }
208
233
  if (source.shadowRoot) {
@@ -288,7 +313,7 @@ export function extractSection({
288
313
  } catch {}
289
314
  animations.push({
290
315
  kind: animation.constructor?.name || "Animation",
291
- targetId: effect?.target?.getAttribute?.("data-uiport-id") || null,
316
+ targetId: effect?.target?.getAttribute?.(idAttribute) || null,
292
317
  pseudoElement: effect?.pseudoElement || null,
293
318
  keyframes,
294
319
  timing,
@@ -0,0 +1,57 @@
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
+ ARTIFACT_DAMAGED:
21
+ "The exported section is incomplete: it has no UIport metadata or no extraction root. Capture it again.",
22
+ COMPARISON_TOO_LARGE:
23
+ "The section exceeds the 20 megapixel comparison limit. Compare a narrower section or a single viewport.",
24
+ INTERNAL: "The operation failed for an unexpected reason.",
25
+ };
26
+
27
+ export class UiportError extends Error {
28
+ /**
29
+ * @param {keyof typeof CODES} code
30
+ * @param {string} message
31
+ * @param {{cause?: unknown, hint?: string}} [options]
32
+ */
33
+ constructor(code, message, options = {}) {
34
+ super(message, options.cause ? { cause: options.cause } : undefined);
35
+ this.name = "UiportError";
36
+ this.code = code;
37
+ this.hint = options.hint || CODES[code];
38
+ }
39
+ }
40
+
41
+ /**
42
+ * @param {unknown} error
43
+ * @returns {{code: string, message: string, hint: string}}
44
+ */
45
+ export function describeError(error) {
46
+ if (error instanceof UiportError)
47
+ return {
48
+ code: error.code,
49
+ message: error.message,
50
+ hint: error.hint,
51
+ };
52
+ const message = String(error?.message || error || "Operation failed").split(
53
+ /[\r\n]/,
54
+ 1,
55
+ )[0];
56
+ return { code: "INTERNAL", message, hint: CODES.INTERNAL };
57
+ }
@@ -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,63 @@
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
+ // An artifact without readable metadata is not read as an artifact without
25
+ // limitations: the validation refuses it, and the inspection refuses it too.
26
+ if (!match)
27
+ throw new UiportError(
28
+ "ARTIFACT_DAMAGED",
29
+ `The exported section has no UIport metadata: ${file}`,
30
+ );
31
+ let metadata;
32
+ try {
33
+ metadata = JSON.parse(match[1]);
34
+ } catch {
35
+ throw new UiportError(
36
+ "ARTIFACT_DAMAGED",
37
+ `The metadata of the exported section is not valid JSON: ${file}`,
38
+ );
39
+ }
40
+ // The metadata carries the number of assets the capture recorded; the
41
+ // directory is the fallback for an artifact written before it did.
42
+ let assets = Number.isInteger(metadata.assets) ? metadata.assets : undefined;
43
+ if (assets === undefined)
44
+ try {
45
+ assets = (await fs.readdir(path.join(options.directory, "assets")))
46
+ .length;
47
+ } catch {
48
+ assets = 0;
49
+ }
50
+ const limitations = Array.isArray(metadata.limitations)
51
+ ? metadata.limitations
52
+ : [];
53
+ return {
54
+ command: "inspect",
55
+ status: limitations.length ? "partial" : "complete",
56
+ outputDirectory: options.directory,
57
+ assets,
58
+ elements: metadata.elements ?? null,
59
+ source: metadata.source ?? null,
60
+ behavior: metadata.behavior ?? BEHAVIOR,
61
+ limitations,
62
+ };
63
+ }
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");
@@ -85,7 +86,10 @@ export function extensionFor(url, contentType = "") {
85
86
  export async function inspectOutput(directory) {
86
87
  const destination = path.resolve(directory);
87
88
  if (destination === path.parse(destination).root)
88
- throw new Error("Refusing a filesystem root as output");
89
+ throw new UiportError(
90
+ "USAGE_INVALID",
91
+ "Refusing a filesystem root as output",
92
+ );
89
93
  let existing = false;
90
94
  try {
91
95
  const stat = await fs.lstat(destination);
@@ -94,7 +98,8 @@ export async function inspectOutput(directory) {
94
98
  stat.isSymbolicLink() ||
95
99
  (await fs.readdir(destination)).length
96
100
  )
97
- throw new Error(
101
+ throw new UiportError(
102
+ "OUTPUT_NOT_EMPTY",
98
103
  "Output must be a new or empty directory (not a symlink)",
99
104
  );
100
105
  existing = true;
@@ -108,6 +113,12 @@ export async function inspectOutput(directory) {
108
113
  export async function stageOutput(directory) {
109
114
  const { destination, existing } = await inspectOutput(directory);
110
115
  await fs.mkdir(path.dirname(destination), { recursive: true });
116
+ // The staging directory is created private by mkdtemp. The published
117
+ // directory keeps the mode a plain mkdir would have given it, so that the
118
+ // export can be read by the user's web server or by another account.
119
+ const permission = existing
120
+ ? (await fs.stat(destination)).mode & 0o777
121
+ : 0o777 & ~process.umask();
111
122
  const temporary = await fs.mkdtemp(
112
123
  path.join(path.dirname(destination), ".uiport-"),
113
124
  );
@@ -115,32 +126,25 @@ export async function stageOutput(directory) {
115
126
  return {
116
127
  directory: temporary,
117
128
  async commit() {
118
- // Recheck immediately before moving. Exclusive mkdir prevents replacing a concurrent output.
129
+ // Recheck immediately before moving. The directory is published with a
130
+ // single rename, so a reader never observes it half written.
131
+ await fs.chmod(temporary, permission);
119
132
  if (existing) await fs.rmdir(destination); // only succeeds when still empty
120
- await fs.mkdir(destination);
121
- const moved = [];
122
133
  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;
134
+ await fs.rename(temporary, destination);
131
135
  } catch (error) {
132
- for (const name of moved)
136
+ if (existing)
133
137
  await fs
134
- .rename(path.join(destination, name), path.join(temporary, name))
138
+ .mkdir(destination, { recursive: true, mode: permission })
135
139
  .catch(() => {});
136
- await fs.rmdir(destination).catch(() => {});
137
140
  throw error;
138
141
  }
142
+ committed = true;
139
143
  },
140
144
  async cleanup() {
141
145
  await fs.rm(temporary, { recursive: true, force: true });
142
146
  if (existing && !committed)
143
- await fs.mkdir(destination, { recursive: true });
147
+ await fs.mkdir(destination, { recursive: true }).catch(() => {});
144
148
  },
145
149
  };
146
150
  }
@@ -199,6 +203,7 @@ export function mimeForFile(filePath) {
199
203
  [".woff2", "font/woff2"],
200
204
  [".woff", "font/woff"],
201
205
  [".ttf", "font/ttf"],
206
+ [".otf", "font/otf"],
202
207
  [".mp4", "video/mp4"],
203
208
  [".webm", "video/webm"],
204
209
  [".json", "application/json"],
@@ -292,7 +297,10 @@ export async function launchChromium(chromium, life) {
292
297
  );
293
298
  if (override) {
294
299
  if (!fsSync.existsSync(override))
295
- throw new Error("UIPORT_BROWSER_PATH does not exist");
300
+ throw new UiportError(
301
+ "BROWSER_NOT_FOUND",
302
+ "UIPORT_BROWSER_PATH does not exist; set it to an executable, or run: uiport browser install",
303
+ );
296
304
  return {
297
305
  ...(await launch({ executablePath: override }).catch((error) => {
298
306
  life?.check();
@@ -316,11 +324,36 @@ export async function launchChromium(chromium, life) {
316
324
  /* try next installed browser */
317
325
  }
318
326
  }
319
- throw new Error(
327
+ throw new UiportError(
328
+ "BROWSER_NOT_FOUND",
320
329
  "No supported browser found. Run: uiport browser install (or set UIPORT_BROWSER_PATH).",
321
330
  );
322
331
  }
323
332
 
333
+ const UNREACHABLE = [
334
+ "ERR_CONNECTION_REFUSED",
335
+ "ERR_NAME_NOT_RESOLVED",
336
+ "ERR_INTERNET_DISCONNECTED",
337
+ "ERR_CONNECTION_CLOSED",
338
+ "ERR_CONNECTION_RESET",
339
+ "ERR_ADDRESS_UNREACHABLE",
340
+ "ERR_EMPTY_RESPONSE",
341
+ "ERR_UNSAFE_PORT",
342
+ ];
343
+
344
+ /** Turns a navigation failure into the code that says what to do about it. */
345
+ export function navigationError(error, url) {
346
+ if (error instanceof UiportError) return error;
347
+ const message = String(error?.message || "");
348
+ if (UNREACHABLE.some((code) => message.includes(code)))
349
+ return new UiportError(
350
+ "SOURCE_UNREACHABLE",
351
+ `The page could not be reached: ${redactedUrl(url)}`,
352
+ { cause: error },
353
+ );
354
+ return error;
355
+ }
356
+
324
357
  /** Tracks resources so timeouts and SIGINT/SIGTERM also close failed runs. */
325
358
  export function lifecycle(timeoutMs) {
326
359
  const deadline = performance.now() + timeoutMs;
@@ -333,7 +366,10 @@ export function lifecycle(timeoutMs) {
333
366
  for (const fn of [...cleanups].reverse()) await fn().catch(() => {});
334
367
  })());
335
368
  const cancel = (message) => {
336
- reason ||= new Error(message);
369
+ reason ||= new UiportError(
370
+ message.startsWith("Operation exceeded") ? "TIMEOUT" : "CANCELLED",
371
+ message,
372
+ );
337
373
  controller.abort(reason);
338
374
  void cleanup();
339
375
  };
@@ -355,6 +391,12 @@ export function lifecycle(timeoutMs) {
355
391
  cancel(`Operation exceeded ${timeoutMs} ms`);
356
392
  if (reason) throw reason;
357
393
  },
394
+ // The reason of a cancellation, when there is one. A pending browser
395
+ // operation rejects with the error of the browser before this one is
396
+ // noticed, and the reason is the one the caller should see.
397
+ failure() {
398
+ return reason;
399
+ },
358
400
  remaining() {
359
401
  this.check();
360
402
  return Math.max(1, Math.ceil(deadline - performance.now()));