@mark1russell7/site-pages 0.8.4 → 0.8.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -143,6 +143,22 @@ To hold the size of the built files, give `--budget <glob>=<size>` one time for
143
143
 
144
144
  The unit of a size is `B`, `kB` or `MB`, and a number with no unit is in kB. The option needs `--out`. The log, `report.json` and `summary.md` give the size of each budget.
145
145
 
146
+ ### Error texts with no error view
147
+
148
+ A page that shows `TypeError: Failed to fetch` gives the user no context, no retry and nothing to copy or report. The check finds each such text that a page shows outside an error view:
149
+
150
+ - The text has the shape of a thrown value (`Error: x`, `TypeError: x`, `DOMException: x`), or a message of the browser (`Failed to fetch`, `Cannot read properties of undefined`, `is not a function`, `[object Object]`).
151
+ - A script starts in each page before its own scripts and watches each text that the page adds or changes. Thus a text that shows for a short time also counts, and so does a text that an action of the probe shows.
152
+ - A text in an error view does not count: `<otel-error>` of `@mark1russell7/otel-ts/error-view`, or an element with `data-error-view`. A text in `pre`, `code`, `kbd`, `samp`, `textarea` or a hidden element does not count either.
153
+
154
+ By default, the check only reports each text, and the view does not fail. The log, `summary.md` and `report.json` (the field `bareErrors` of a view) give the texts. To make each text fail its view, set the field `sitePages.bareErrors` to `"fail"` in the `package.json` of the working folder:
155
+
156
+ ```json
157
+ { "sitePages": { "bareErrors": "fail" } }
158
+ ```
159
+
160
+ The option `--bare-errors fail` or `--bare-errors report` overrides the field. In `reusable-pages.yml`, the key `site-check-bare-errors` of `.github/site.json` gives the option. A repository with one package uses the key: the field changes the `package.json` of its npm release. Turn the failure on when the report of the site gives no text.
161
+
146
162
  The folder of `--shots` gets a screenshot of each view, `report.json` and `summary.md`. The exit code is 0 when each view and each budget passes. It is 1 when a view or a budget fails, and 2 for an incorrect command line.
147
163
 
148
164
  The check finds a browser in this order: `--browser`, `$SITE_CHECK_BROWSER`, the newest Chromium of Playwright, and then Chrome or Edge. The folder `src/check` imports only Node.js. Thus Node.js 22.18 or later can start `src/check/main.ts` with no install. The workflow `reusable-pages.yml` of the template uses it this way.
package/build/cli.js CHANGED
@@ -908,6 +908,87 @@ async function serve(root, base) {
908
908
  })
909
909
  };
910
910
  }
911
+ // src/check/bare-errors.ts
912
+ /**
913
+ * Bare error texts. A page that shows `TypeError: Failed to fetch` gives the user no context, no retry and nothing to copy or
914
+ * report. An error view gives all of them. This file finds the texts of an error that a page shows outside an error view.
915
+ *
916
+ * A script starts in each page before its own scripts (`BARE_ERROR_WATCH`). It watches each text that the page adds or changes,
917
+ * also a text that shows for a short time only. `BARE_ERRORS` reads what it found. A repository turns the failure on with the
918
+ * field `sitePages.bareErrors` of its package.json, or with `--bare-errors fail`. Until then the check reports the texts only.
919
+ */
920
+ /** The modes, for the CLI and package.json. */
921
+ const BARE_ERROR_MODES = ["fail", "report"];
922
+ /**
923
+ * The shape of the text of a thrown value, for example `Error: x`, `TypeError: x` or `DOMException: x`. It also matches the
924
+ * messages of the browser that a page shows when it puts `error.message` on the screen.
925
+ */
926
+ const BARE_ERROR_SHAPE = String.raw`(?:^|[\s("'\[:])[A-Z]?[A-Za-z]*(?:Error|Exception): \S|Failed to fetch|NetworkError when attempting to fetch|Cannot read propert(?:y|ies) of (?:undefined|null)|is not a function|\[object Object\]|Unexpected token .{1,20} in JSON`;
927
+ /** The elements whose text is an example, not a message: code, and the text of a form field. */
928
+ const BARE_ERROR_SKIP = "pre, code, kbd, samp, textarea, script, style, template, noscript, [hidden], [aria-hidden=true]";
929
+ /** The error views. A text inside one is not bare. */
930
+ const ERROR_VIEWS = "otel-error, [data-error-view]";
931
+ const KEY = "site-check.bare-errors";
932
+ /**
933
+ * A script that each page starts before its own scripts. It records each text with the shape of an error that the page adds or
934
+ * changes outside an error view. It records the element and the text, at most `MAX_BARE_ERRORS` of them.
935
+ */
936
+ const BARE_ERROR_WATCH = `(() => {
937
+ const shape = new RegExp(${JSON.stringify(BARE_ERROR_SHAPE)});
938
+ const skip = ${JSON.stringify(BARE_ERROR_SKIP)};
939
+ const views = ${JSON.stringify(ERROR_VIEWS)};
940
+ const found = [];
941
+ const seen = new Set();
942
+ Object.defineProperty(globalThis, Symbol.for(${JSON.stringify(KEY)}), { value: found });
943
+ const name = (element) => element.tagName.toLowerCase() + (element.id ? "#" + element.id : element.classList.length > 0 ? "." + element.classList[0] : "");
944
+ const look = (node) => {
945
+ const element = node.parentElement;
946
+ if (found.length >= 20 || !element || element.closest(skip) || element.closest(views)) return;
947
+ const texts = [node.data];
948
+ // The text of the element too, for a message in two nodes. Not when it has code in it: that is an example.
949
+ if (!element.querySelector(skip)) texts.push(element.textContent ?? "");
950
+ const text = texts.map((each) => each.replace(/\\s+/g, " ").trim()).find((each) => shape.test(each));
951
+ if (text === undefined) return;
952
+ const entry = name(element) + ': "' + text.slice(0, 160) + '"';
953
+ if (seen.has(entry)) return;
954
+ seen.add(entry);
955
+ found.push(entry);
956
+ };
957
+ const walk = (root) => {
958
+ if (root.nodeType === 3) return look(root);
959
+ if (root.nodeType !== 1) return;
960
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
961
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) look(node);
962
+ };
963
+ new MutationObserver((records) => {
964
+ for (const record of records) {
965
+ if (record.type === "characterData") look(record.target);
966
+ else for (const node of record.addedNodes) walk(node);
967
+ }
968
+ }).observe(document, { subtree: true, childList: true, characterData: true });
969
+ })();`;
970
+ /** The expression that gives the texts that `BARE_ERROR_WATCH` found in the page. */
971
+ const BARE_ERRORS = `[...(globalThis[Symbol.for(${JSON.stringify(KEY)})] ?? [])]`;
972
+ /** The problem of one bare error text. */
973
+ function bareErrorProblem(entry) {
974
+ return `an error text with no error view: ${entry}`;
975
+ }
976
+ /**
977
+ * This function reads the mode from the field `sitePages.bareErrors` of the package.json in `cwd`. No file or no field gives
978
+ * `report`. A field with another value gives an Error.
979
+ */
980
+ function readBareErrorMode(cwd) {
981
+ let manifest;
982
+ try {
983
+ manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
984
+ } catch {
985
+ return "report";
986
+ }
987
+ const pages = typeof manifest === "object" && manifest !== null ? manifest.sitePages : void 0;
988
+ const value = typeof pages === "object" && pages !== null ? pages.bareErrors : void 0;
989
+ if (value === void 0) return "report";
990
+ return BARE_ERROR_MODES.includes(value) ? value : /* @__PURE__ */ new Error(`the field sitePages.bareErrors of package.json must be fail or report, not ${JSON.stringify(value)}`);
991
+ }
911
992
  /**
912
993
  * This function gives a page expression that scrolls the page to its end, one screen at a time, and then back to the top.
913
994
  * Thus each part that starts when it comes into view starts before the measure. Examples are an Astro island with
@@ -1016,6 +1097,7 @@ async function checkSite(options) {
1016
1097
  page.send("Network.enable")
1017
1098
  ]);
1018
1099
  await page.send("Page.addScriptToEvaluateOnNewDocument", { source: LOAD_WATCH });
1100
+ await page.send("Page.addScriptToEvaluateOnNewDocument", { source: BARE_ERROR_WATCH });
1019
1101
  return {
1020
1102
  page,
1021
1103
  events
@@ -1111,7 +1193,12 @@ function viewLine(view) {
1111
1193
  const measure = view.measure ? ` scrollWidth=${view.measure.scrollWidth} innerWidth=${view.measure.innerWidth}` : "";
1112
1194
  const probe = view.probe ? ` probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length}` : "";
1113
1195
  const problems = view.problems.length > 0 ? `\n - ${view.problems.join("\n - ")}` : "";
1114
- return `${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${view.page} ${view.width} ${view.scheme}${view.offline ? " offline" : ""}${measure}${probe}${problems}`;
1196
+ const notes = reportedOnly(view).map((entry) => `\n ~ report only: ${bareErrorProblem(entry)}`).join("");
1197
+ return `${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${view.page} ${view.width} ${view.scheme}${view.offline ? " offline" : ""}${measure}${probe}${problems}${notes}`;
1198
+ }
1199
+ /** The bare error texts of a view that are not problems of the view: the mode is report. */
1200
+ function reportedOnly(view) {
1201
+ return (view.bareErrors ?? []).filter((entry) => !view.problems.includes(bareErrorProblem(entry)));
1115
1202
  }
1116
1203
  /**
1117
1204
  * This function gives a page expression that waits until a service worker of the site controls the page. The expression gives an
@@ -1277,6 +1364,11 @@ async function checkView(page, events, input) {
1277
1364
  if (checks.length === 0) view.problems.push("the probe made no check");
1278
1365
  for (const check of checks.filter((entry) => !entry.ok)) view.problems.push(`probe: ${check.name}${check.detail ? ` (${check.detail})` : ""}`);
1279
1366
  }
1367
+ const bare = await page.evaluate(BARE_ERRORS);
1368
+ if (bare.length > 0) {
1369
+ view.bareErrors = bare;
1370
+ if (options.bareErrors === "fail") view.problems.push(...bare.map(bareErrorProblem));
1371
+ }
1280
1372
  } catch (error) {
1281
1373
  hung = error instanceof NoReplyError;
1282
1374
  view.problems.push(error instanceof Error ? error.message : String(error));
@@ -1314,6 +1406,8 @@ function summary(result) {
1314
1406
  ...result.views.map((view) => `| \`${view.page}\`${view.offline ? " (offline)" : ""} | ${view.width} | ${view.scheme} | ${view.ok ? "pass" : "**fail**"}${view.retried ? " (retried)" : ""}${view.probe ? ` (probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length})` : ""} | ${view.problems.map(cell).join("<br>")} |`),
1315
1407
  ""
1316
1408
  ];
1409
+ const reported = result.views.filter((view) => reportedOnly(view).length > 0);
1410
+ if (reported.length > 0) lines.push(`${reported.length} of ${result.views.length} views show an error text with no error view. The check does not fail, because package.json has no field sitePages.bareErrors with the value fail.`, "", ...new Set(reported.flatMap((view) => reportedOnly(view).map((entry) => `- \`${view.page}\`: ${cell(entry)}`))), "");
1317
1411
  if (result.budgets !== void 0 && result.budgets.length > 0) lines.push("| Size budget | Largest file | Gzip | Limit | Result |", "| --- | --- | ---: | ---: | --- |", ...result.budgets.map((budget) => {
1318
1412
  const largest = budget.files[0];
1319
1413
  const file = largest === void 0 ? "none" : `\`${cell(largest.file)}\``;
@@ -1329,7 +1423,8 @@ the dark scheme, and fails when a page is wider than the screen, an element goes
1329
1423
  edge, a text area hides its text, a box cuts text, a table goes out of view on a phone, a page
1330
1424
  shows no text, or on a console error, an exception, a failed request of the site, a script that
1331
1425
  does not load or a failed check of the probe. Add data-overflow-ok to a box that is meant to
1332
- scroll or to clip.
1426
+ scroll or to clip. It reports each text with the shape of an error, for example "TypeError: Failed
1427
+ to fetch", that a page shows outside an error view (<otel-error> or [data-error-view]).
1333
1428
 
1334
1429
  Options:
1335
1430
  --out <dir> The built site folder. The check serves it at --base.
@@ -1361,6 +1456,9 @@ Options:
1361
1456
  file of the glob fails the check when its gzip size is over the size. A
1362
1457
  glob with no file fails too. The unit is B, kB or MB (default kB). Give
1363
1458
  the option one time for each budget. It needs --out.
1459
+ --bare-errors <mode> fail: an error text outside an error view fails the view. report: the
1460
+ check reports it only. Default: the field sitePages.bareErrors of the
1461
+ package.json in the working folder, else report.
1364
1462
  --help Shows this text
1365
1463
 
1366
1464
  With $GITHUB_STEP_SUMMARY, the check adds its table to the job summary.
@@ -1394,6 +1492,7 @@ async function runCheckCli(argv, io) {
1394
1492
  type: "string",
1395
1493
  multiple: true
1396
1494
  },
1495
+ "bare-errors": { type: "string" },
1397
1496
  help: { type: "boolean" }
1398
1497
  }
1399
1498
  }));
@@ -1483,6 +1582,9 @@ async function runCheckCli(argv, io) {
1483
1582
  } catch (error) {
1484
1583
  return usage(error instanceof Error ? error.message : String(error));
1485
1584
  }
1585
+ const bareErrors = text("bare-errors") ?? readBareErrorMode(io.cwd);
1586
+ if (bareErrors instanceof Error) return usage(bareErrors.message);
1587
+ if (!BARE_ERROR_MODES.includes(bareErrors)) return usage(`--bare-errors must be fail or report, not "${bareErrors}"`);
1486
1588
  const shots = text("shots");
1487
1589
  const result = await checkSite({
1488
1590
  out: out === void 0 ? void 0 : at(out),
@@ -1499,6 +1601,7 @@ async function runCheckCli(argv, io) {
1499
1601
  timeoutMs,
1500
1602
  offline: values["offline"] === true,
1501
1603
  budgets,
1604
+ bareErrors,
1502
1605
  log: (line) => io.stdout(`${line}\n`)
1503
1606
  });
1504
1607
  const failed = result.views.filter((view) => !view.ok).length;