@mark1russell7/site-pages 0.8.1 → 0.8.2

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
@@ -688,6 +688,60 @@ The file sets no look for the content. Buttons, cards, code and tables stay in t
688
688
 
689
689
  A site with its own look does not import `shell.css`. It uses only the plugin and `showBuild`, or nothing from this section.
690
690
 
691
+ ## The offline shell of a site
692
+
693
+ The entry `@mark1russell7/site-pages/offline` is for `vite.config.ts`. Its plugin `siteOffline` lets a built site open with no network. A phone can also install the site as an app.
694
+
695
+ ```ts
696
+ import { defineConfig } from "vite";
697
+ import { siteOffline } from "@mark1russell7/site-pages/offline";
698
+
699
+ export default defineConfig({
700
+ root: "site",
701
+ plugins: [siteOffline({ manifest: { name: "Field notes", icons: [{ src: "icon.svg", sizes: "any", type: "image/svg+xml" }] } })],
702
+ });
703
+ ```
704
+
705
+ The plugin operates only in a build. It does these three operations:
706
+
707
+ - It adds a manifest link and a small script to each HTML page. The script registers the service worker. A failure goes to `console.warn`, so a browser with no service worker shows the page as usual.
708
+ - It writes `manifest.webmanifest`. The app starts at the site home, and its scope is the site home.
709
+ - It writes `service-worker.js`. The worker keeps each file of the built folder. These files include the files of the public folder and of other plugins.
710
+
711
+ Put `siteOffline` last in the list of plugins. A file that a step after the Vite build adds is not in the list of the worker.
712
+
713
+ These files stay out of the cache:
714
+
715
+ - source maps,
716
+ - the files and folders with a name that starts with a dot,
717
+ - each file larger than `maxFileBytes` (the default is 10 MiB),
718
+ - each file that a pattern of `exclude` matches. A pattern examines the path from the root of the folder.
719
+
720
+ The worker answers a request of a kept file from its cache. The path of a folder gives its `index.html`. A navigation to a page that the worker does not keep goes to the network. With no network, it gets the home page from the cache, with the header `x-site-offline: fallback`. The worker does not answer other requests.
721
+
722
+ The name of the cache has the base of the site and a SHA-256 hash of the kept files. A new build with a changed file gives a new name. The new worker then removes the old cache of the same base, and only that cache.
723
+
724
+ The worker keeps only the built files. It keeps no data of the site. Data that the site reads or writes goes offline through its own store.
725
+
726
+ The base of the site must be a path from the root of the origin, for example `/` or `/name/`. A relative base, for example `./`, stops the build.
727
+
728
+ | Export of `./offline` | Operation |
729
+ | --- | --- |
730
+ | `siteOffline({ manifest, maxFileBytes, exclude, onList })` | Makes the plugin. The value `false` for `manifest` writes no manifest. `onList` gets the kept files and the files that stay out. |
731
+ | `precacheList(files, { base, maxFileBytes, exclude })` | Gives the URLs that the worker keeps, in order, and the reason of each file that stays out. It has no I/O. |
732
+ | `offlineCacheName(base, files)` | Gives the name of the cache from the URLs and the contents of the kept files. |
733
+ | `serviceWorkerSource({ base, cache, urls })` | Gives the source of the service worker. |
734
+ | `webManifest(options, base)` | Gives the web manifest. |
735
+ | `registerScript(base)` | Gives the script that registers the worker, for a page without the plugin. |
736
+
737
+ The command `site-pages check --out <dir> --offline` is the gate of the offline shell. After the usual views, it opens the home page in a new browser and waits until a service worker controls the page. Then it stops its server, cuts the network of the page, and opens each page again, at the first width and in the first scheme. An offline view fails for each of these problems:
738
+
739
+ - No service worker of the site becomes active in the time limit of a page load.
740
+ - The worker does not answer the page, or gives the home page in its place.
741
+ - Each problem of a usual view, for example a request that fails.
742
+
743
+ The option `--offline` needs `--out`, because the check stops the server of the folder to cut the network.
744
+
691
745
  ## The response explorer
692
746
 
693
747
  The entry `@mark1russell7/site-pages/explorer` shows a measured response in the browser. A visitor chooses a measure, varies one or two dimensions, and holds or facets the others. The view shows the measured points, the fitted curve or surface, and its held-out error in plain words. The record has the format `response-records/1` of `@mark1russell7/rigor-statistics`.
@@ -0,0 +1,11 @@
1
+ // src/check/offline-header.ts
2
+ /**
3
+ * The header of the home page that the service worker of the offline shell gives in place of a page that it does not keep.
4
+ * The gate `site-pages check --offline` reads it. Thus a page of the check that the worker does not keep fails.
5
+ *
6
+ * This file is in the folder of the check, because the site-pages action starts the check from a sparse checkout of this folder.
7
+ */
8
+ const FALLBACK_HEADER = "x-site-offline";
9
+ export { FALLBACK_HEADER as t };
10
+
11
+ //# sourceMappingURL=offline-header.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offline-header.js","names":[],"sources":["../../src/check/offline-header.ts"],"sourcesContent":["/**\n * The header of the home page that the service worker of the offline shell gives in place of a page that it does not keep.\n * The gate `site-pages check --offline` reads it. Thus a page of the check that the worker does not keep fails.\n *\n * This file is in the folder of the check, because the site-pages action starts the check from a sparse checkout of this folder.\n */\nexport const FALLBACK_HEADER = \"x-site-offline\";\n"],"mappings":";;;;;;;AAMA,MAAa,kBAAkB"}
package/build/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { T as safeUrl, b as escapeHtml, m as runFreshnessCli } from "./chunks/freshness.js";
3
3
  import { a as runCli, o as TYPESCRIPT_PROBE, s as probeScript } from "./chunks/build.js";
4
+ import { t as FALLBACK_HEADER } from "./chunks/offline-header.js";
4
5
  import { spawn } from "node:child_process";
5
6
  import { appendFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
7
  import { delimiter, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
@@ -847,7 +848,10 @@ async function serve(root, base) {
847
848
  if (address === null || typeof address === "string") throw new Error("the server has no port");
848
849
  return {
849
850
  url: `http://127.0.0.1:${address.port}${base.endsWith("/") ? base : `${base}/`}`,
850
- close: () => new Promise((done) => server.close(() => done()))
851
+ close: () => new Promise((done) => {
852
+ server.close(() => done());
853
+ server.closeAllConnections();
854
+ })
851
855
  };
852
856
  }
853
857
  /**
@@ -935,6 +939,7 @@ async function checkSite(options) {
935
939
  if (options.pages.length === 0) throw new Error("no page to check");
936
940
  const probes = pageProbes(options);
937
941
  if (options.out === void 0 && options.url === void 0) throw new Error("give out or url");
942
+ if (options.offline === true && options.out === void 0) throw new Error("the offline check needs out: it stops the server of the folder to cut the network");
938
943
  const server = options.out !== void 0 ? await serve(options.out, options.base ?? "/") : void 0;
939
944
  const views = [];
940
945
  let homeUrl;
@@ -989,7 +994,41 @@ async function checkSite(options) {
989
994
  }
990
995
  }
991
996
  views.push(view);
992
- log(`${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${path} ${width} ${scheme}${view.measure ? ` scrollWidth=${view.measure.scrollWidth} innerWidth=${view.measure.innerWidth}` : ""}${view.probe ? ` probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length}` : ""}${view.problems.length > 0 ? `\n - ${view.problems.join("\n - ")}` : ""}`);
997
+ log(viewLine(view));
998
+ }
999
+ }
1000
+ if (options.offline === true && server !== void 0) {
1001
+ ({page, events} = await restart());
1002
+ const notReady = await offlineReady(page, homeUrl.href, options.timeoutMs);
1003
+ await server.close();
1004
+ await page.send("Network.emulateNetworkConditions", {
1005
+ offline: true,
1006
+ latency: 0,
1007
+ downloadThroughput: -1,
1008
+ uploadThroughput: -1
1009
+ });
1010
+ const width = options.widths[0] ?? 1280;
1011
+ const scheme = options.schemes[0] ?? "light";
1012
+ for (const path of options.pages) {
1013
+ const target = new URL(path.replace(/^\/+/, ""), homeUrl).href;
1014
+ const view = notReady === void 0 ? (await checkView(page, events, {
1015
+ target,
1016
+ path,
1017
+ width,
1018
+ scheme,
1019
+ probe: void 0,
1020
+ options,
1021
+ offline: true
1022
+ })).view : {
1023
+ page: path,
1024
+ width,
1025
+ scheme,
1026
+ ok: false,
1027
+ problems: [notReady],
1028
+ offline: true
1029
+ };
1030
+ views.push(view);
1031
+ log(viewLine(view));
993
1032
  }
994
1033
  }
995
1034
  } finally {
@@ -1008,6 +1047,44 @@ async function checkSite(options) {
1008
1047
  }
1009
1048
  return result;
1010
1049
  }
1050
+ /** This function gives the log line of a view. */
1051
+ function viewLine(view) {
1052
+ const measure = view.measure ? ` scrollWidth=${view.measure.scrollWidth} innerWidth=${view.measure.innerWidth}` : "";
1053
+ const probe = view.probe ? ` probe ${view.probe.filter((c) => c.ok).length}/${view.probe.length}` : "";
1054
+ const problems = view.problems.length > 0 ? `\n - ${view.problems.join("\n - ")}` : "";
1055
+ return `${view.ok ? "PASS" : "FAIL"}${view.retried ? " (retried)" : ""} ${view.page} ${view.width} ${view.scheme}${view.offline ? " offline" : ""}${measure}${probe}${problems}`;
1056
+ }
1057
+ /**
1058
+ * This function gives a page expression that waits until a service worker of the site controls the page. The expression gives an
1059
+ * empty text when a worker controls the page, else the problem.
1060
+ */
1061
+ function offlineReadyExpression(limitMs) {
1062
+ return `(async () => {
1063
+ if (!("serviceWorker" in navigator)) return "the browser has no service worker API";
1064
+ const end = performance.now() + ${String(limitMs)};
1065
+ const later = new Promise((done) => setTimeout(() => done(false), ${String(limitMs)}));
1066
+ const ready = await Promise.race([navigator.serviceWorker.ready.then(() => true), later]);
1067
+ if (!ready) return "no service worker of the site became active in ${String(limitMs)} ms: the site has no offline copy";
1068
+ while (!navigator.serviceWorker.controller && performance.now() < end) await new Promise((done) => setTimeout(done, 50));
1069
+ return navigator.serviceWorker.controller ? "" : "the service worker of the site did not take control of the page in ${String(limitMs)} ms";
1070
+ })()`;
1071
+ }
1072
+ /** This function opens the home page with the network on, and waits for its service worker. It gives the problem, or undefined. */
1073
+ async function offlineReady(page, home, timeoutMs) {
1074
+ try {
1075
+ const loaded = page.once("Page.loadEventFired", timeoutMs);
1076
+ const navigation = await page.send("Page.navigate", { url: home });
1077
+ if (navigation.errorText) {
1078
+ loaded.catch(() => {});
1079
+ return `the home page did not open before the network went off: ${navigation.errorText}`;
1080
+ }
1081
+ await loaded;
1082
+ const problem = await page.evaluate(offlineReadyExpression(timeoutMs));
1083
+ return problem === "" ? void 0 : problem;
1084
+ } catch (error) {
1085
+ return `the check did not see the service worker of the site: ${error instanceof Error ? error.message : String(error)}`;
1086
+ }
1087
+ }
1011
1088
  /**
1012
1089
  * A script that each page starts before its own scripts. A script or a style sheet that does not load fires `error` on its
1013
1090
  * element. This script writes that event as a console error. Thus a module script whose imports do not load is a problem too.
@@ -1023,6 +1100,7 @@ const OTHER_PATHS = `document.querySelector('meta[name="site-check-other-paths"]
1023
1100
  function watch(page, origin) {
1024
1101
  let problems = [];
1025
1102
  let refused = [];
1103
+ let documents = /* @__PURE__ */ new Map();
1026
1104
  const urls = /* @__PURE__ */ new Map();
1027
1105
  const own = (url) => {
1028
1106
  try {
@@ -1047,6 +1125,13 @@ function watch(page, origin) {
1047
1125
  page.on("Network.responseReceived", (params) => {
1048
1126
  const response = params["response"];
1049
1127
  if (response.status >= 400 && own(response.url)) refused.push(response);
1128
+ if (params["type"] === "Document") {
1129
+ const header = Object.entries(response.headers ?? {}).find(([name]) => name.toLowerCase() === FALLBACK_HEADER)?.[1];
1130
+ documents.set(urls.get(String(params["requestId"])) ?? response.url, {
1131
+ fromServiceWorker: response.fromServiceWorker === true,
1132
+ fallback: header === "fallback"
1133
+ });
1134
+ }
1050
1135
  });
1051
1136
  page.on("Network.loadingFailed", (params) => {
1052
1137
  const url = urls.get(String(params["requestId"])) ?? "";
@@ -1056,7 +1141,9 @@ function watch(page, origin) {
1056
1141
  reset: () => {
1057
1142
  problems = [];
1058
1143
  refused = [];
1144
+ documents = /* @__PURE__ */ new Map();
1059
1145
  },
1146
+ document: (url) => documents.get(url),
1060
1147
  problems: (other) => {
1061
1148
  const shown = refused.filter((response) => other?.test(new URL(response.url).pathname) !== true);
1062
1149
  return [.../* @__PURE__ */ new Set([...problems, ...shown.map((response) => `HTTP ${response.status}: ${response.url}`)])];
@@ -1070,7 +1157,8 @@ async function checkView(page, events, input) {
1070
1157
  width,
1071
1158
  scheme,
1072
1159
  ok: false,
1073
- problems: []
1160
+ problems: [],
1161
+ ...input.offline === true ? { offline: true } : {}
1074
1162
  };
1075
1163
  let other;
1076
1164
  let hung = false;
@@ -1108,7 +1196,7 @@ async function checkView(page, events, input) {
1108
1196
  view.problems.push(...cutProblems(measure.cut, width));
1109
1197
  if (measure.text === 0) view.problems.push("the page shows no text");
1110
1198
  if (options.shots) {
1111
- const file = join(options.shots, `${pageSlug(path)}-${width}-${scheme}.png`);
1199
+ const file = join(options.shots, `${pageSlug(path)}-${width}-${scheme}${input.offline === true ? "-offline" : ""}.png`);
1112
1200
  const height = Math.min(Math.max(measure.height, 1), 8e3);
1113
1201
  const shot = await page.send("Page.captureScreenshot", {
1114
1202
  format: "png",
@@ -1134,6 +1222,7 @@ async function checkView(page, events, input) {
1134
1222
  hung = error instanceof NoReplyError;
1135
1223
  view.problems.push(error instanceof Error ? error.message : String(error));
1136
1224
  }
1225
+ if (input.offline === true && view.problems.length === 0) view.problems.push(...offlineProblems(events.document(target)));
1137
1226
  view.problems.push(...events.problems(other));
1138
1227
  view.ok = view.problems.length === 0;
1139
1228
  return {
@@ -1141,6 +1230,13 @@ async function checkView(page, events, input) {
1141
1230
  hung
1142
1231
  };
1143
1232
  }
1233
+ /** This function gives the problems of the answer of a page with the network off. A page with no seen answer is a problem: the check cannot tell. */
1234
+ function offlineProblems(answer) {
1235
+ if (answer === void 0) return ["the check saw no answer of the page, so it cannot tell if the service worker keeps the page"];
1236
+ if (!answer.fromServiceWorker) return ["the service worker did not answer the page"];
1237
+ if (answer.fallback) return ["the service worker does not keep the page: it gave the home page in its place"];
1238
+ return [];
1239
+ }
1144
1240
  /** This function makes a text safe for a cell of a Markdown table. It escapes `\`, `|`, `<` and `>`. It changes each new line to a space. */
1145
1241
  function cell(text) {
1146
1242
  return text.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r?\n/g, " ");
@@ -1156,7 +1252,7 @@ function summary(result) {
1156
1252
  "",
1157
1253
  "| Page | Width | Scheme | Result | Problems |",
1158
1254
  "| --- | ---: | --- | --- | --- |",
1159
- ...result.views.map((view) => `| \`${view.page}\` | ${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>")} |`),
1255
+ ...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>")} |`),
1160
1256
  ""
1161
1257
  ].join("\n");
1162
1258
  }
@@ -1190,6 +1286,10 @@ Options:
1190
1286
  Playwright, else Chrome or Edge)
1191
1287
  --settle <ms> The wait after the load event (default: 1500)
1192
1288
  --timeout <ms> The time limit of a page load (default: 30000)
1289
+ --offline Also opens each page with the network off, at the first width and scheme.
1290
+ A new browser opens the home page and waits for the service worker of the
1291
+ site. Then the check stops the server. A page fails when the worker does not
1292
+ answer it. It needs --out.
1193
1293
  --help Shows this text
1194
1294
 
1195
1295
  With $GITHUB_STEP_SUMMARY, the check adds its table to the job summary.
@@ -1218,6 +1318,7 @@ async function runCheckCli(argv, io) {
1218
1318
  browser: { type: "string" },
1219
1319
  settle: { type: "string" },
1220
1320
  timeout: { type: "string" },
1321
+ offline: { type: "boolean" },
1221
1322
  help: { type: "boolean" }
1222
1323
  }
1223
1324
  }));
@@ -1238,6 +1339,7 @@ async function runCheckCli(argv, io) {
1238
1339
  const out = text("out");
1239
1340
  const url = text("url");
1240
1341
  if (out === void 0 === (url === void 0)) return usage("give --out or --url, not both");
1342
+ if (values["offline"] === true && out === void 0) return usage("--offline needs --out: the check stops the server of the folder to cut the network");
1241
1343
  const widths = list("widths", "360,400,1280").map(Number);
1242
1344
  if (widths.length === 0 || widths.some((width) => !Number.isInteger(width) || width < 200 || width > 4e3)) return usage("--widths must be whole numbers from 200 to 4000");
1243
1345
  const schemes = list("schemes", "light,dark");
@@ -1313,6 +1415,7 @@ async function runCheckCli(argv, io) {
1313
1415
  browser: text("browser"),
1314
1416
  settleMs,
1315
1417
  timeoutMs,
1418
+ offline: values["offline"] === true,
1316
1419
  log: (line) => io.stdout(`${line}\n`)
1317
1420
  });
1318
1421
  const failed = result.views.filter((view) => !view.ok).length;