@jskit-ai/jskit-catalog 0.2.105 → 0.2.107

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/jskit-catalog",
3
- "version": "0.2.105",
3
+ "version": "0.2.107",
4
4
  "description": "Published metadata catalog for JSKIT package metadata.",
5
5
  "type": "module",
6
6
  "files": [
@@ -2,12 +2,19 @@
2
2
  // does: a page then loads a few bundled files instead of every source module from a development server. The build goes where the app
3
3
  // server serves it from (dist/), never a folder of its own: the server tells every page which build it serves from
4
4
  // dist/index.html, and a page from any other build offers a reload over the screen. It is reused while its inputs' contents
5
- // are unchanged and dist/index.html is still the one it made, so a repeated focused run does not rebuild, even though a
6
- // build rewrites files it generates among its inputs (vue-router's src/typed-router.d.ts). Two runs in one tree build one
5
+ // are unchanged and dist/index.html is still the one it made, so a repeated focused run does not rebuild. Its inputs are
6
+ // what the build read: the modules it bundled, which @jskit-ai/kernel's createJskitClientBootstrapPlugin (in every JSKIT
7
+ // app's Vite config) records, the listing of every folder they came from, so an added file counts, and the files every
8
+ // build reads; an edit to server code alone reuses the build. Those are read after the build, so a build during which
9
+ // one of them changed is not kept for reuse: it may hold code from before the change. A build that records no modules (a
10
+ // Vite config without that plugin, or a build that is not Vite's) is keyed on every source file instead, taken before it
11
+ // runs, as it rewrites files it generates among them (vue-router's src/typed-router.d.ts). Two runs in one tree build one
7
12
  // at a time: the second waits, then reuses the first one's build.
8
13
  import { spawn } from "node:child_process";
9
14
  import { createHash } from "node:crypto";
10
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
15
+ import {
16
+ closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, writeSync
17
+ } from "node:fs";
11
18
  import path from "node:path";
12
19
  import process from "node:process";
13
20
 
@@ -17,23 +24,42 @@ const FINGERPRINT_FILE = path.join("node_modules", ".cache", "jskit-browser-test
17
24
  const BUILD_LOCK = path.join("node_modules", ".cache", "jskit-browser-test-build.lock");
18
25
  const BUILD_WAIT_MS = 10 * 60_000;
19
26
  const SERVED_INDEX = path.join("dist", "index.html");
20
- // The app's folders a frontend build reads, and the installed packages it bundles. Every file at the app's root is an
21
- // input too (index.html, vite.config.*, favicon.svg, package.json, the .env files Vite reads), except other dotfiles,
22
- // such as caches, and notes.
23
- const BUILD_DIRECTORIES = Object.freeze(["src", "packages", "shared", "config", "public", "node_modules/@jskit-ai"]);
27
+ // The file a build appends the ids of the modules it read to, one per line, when this variable names it
28
+ // (createJskitClientBootstrapPlugin in @jskit-ai/kernel/client/vite).
29
+ const BUILD_MODULES_VARIABLE = "JSKIT_BUILD_MODULES_FILE";
30
+ const BUILD_MODULES_FILE = path.join("node_modules", ".cache", "jskit-browser-test-build-modules.txt");
31
+ // Read by every build: Vite copies public/, and the installed packages decide the bundled code. Every file at the app's
32
+ // root is an input too (index.html, vite.config.*, favicon.svg, package.json, the .env files Vite reads), except other
33
+ // dotfiles, such as caches, and notes.
24
34
  const INSTALLED_PACKAGES = "node_modules/.package-lock.json";
35
+ const ALWAYS_READ = Object.freeze(["public", INSTALLED_PACKAGES]);
36
+ // Without the modules a build read: the app's folders a frontend build may read, and the installed packages it bundles.
37
+ const SOURCE_DIRECTORIES = Object.freeze(["src", "packages", "shared", "config", "node_modules/@jskit-ai"]);
25
38
  const NOT_AN_INPUT = /^\.(?!env(?:\.|$))|\.(?:md|log|txt)$/u;
26
39
 
27
40
  const seconds = (since) => `${((performance.now() - since) / 1000).toFixed(1)}s`;
28
41
  const digest = (file) => (existsSync(file) ? createHash("sha256").update(readFileSync(file)).digest("hex") : "");
29
42
 
30
- /** Every build input's path and contents, the build command and the VITE_ settings, hashed. */
31
- function buildFingerprint(appRoot, build, env = process.env) {
43
+ /**
44
+ * Every build input's path and contents, the build command and the VITE_ settings, hashed, and the input changed last.
45
+ * The inputs are the files the last build read, with the listing of each folder they came from and the manifest
46
+ * (package.json) of any such folder that has one, or, without them, every source file.
47
+ * @param {string} appRoot
48
+ * @param {string} build
49
+ * @param {{ files: string[], directories: string[] } | null} [read] what the build read, relative to appRoot
50
+ * @returns {{ inputs: string, newest: { path: string, time: number } }}
51
+ */
52
+ function buildFingerprint(appRoot, build, read = null, env = process.env) {
32
53
  const hash = createHash("sha256").update(`${build}\n`);
54
+ const newest = { path: "", time: 0 };
55
+ const changed = (relative, stats) => {
56
+ if (stats.mtimeMs > newest.time) Object.assign(newest, { path: relative, time: stats.mtimeMs });
57
+ return stats;
58
+ };
33
59
  const visit = (relative) => {
34
60
  const absolute = path.join(appRoot, relative);
35
61
  if (!existsSync(absolute)) return;
36
- const stats = statSync(absolute);
62
+ const stats = changed(relative, statSync(absolute));
37
63
  if (!stats.isDirectory()) {
38
64
  hash.update(`${relative}\0${stats.size}\0`).update(readFileSync(absolute));
39
65
  return;
@@ -45,20 +71,56 @@ function buildFingerprint(appRoot, build, env = process.env) {
45
71
  for (const entry of readdirSync(appRoot, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
46
72
  if (!entry.isDirectory() && !NOT_AN_INPUT.test(entry.name)) visit(entry.name);
47
73
  }
48
- [INSTALLED_PACKAGES, ...BUILD_DIRECTORIES].forEach(visit);
74
+ ALWAYS_READ.forEach(visit);
75
+ if (!read) {
76
+ SOURCE_DIRECTORIES.forEach(visit);
77
+ } else {
78
+ read.files.forEach(visit);
79
+ for (const directory of read.directories) {
80
+ const absolute = path.join(appRoot, directory);
81
+ let listing = "(missing)";
82
+ if (existsSync(absolute)) {
83
+ changed(directory, statSync(absolute));
84
+ listing = readdirSync(absolute).sort().join("\0");
85
+ }
86
+ hash.update(`${directory}/\0${listing}\0`);
87
+ visit(path.join(directory, "package.json"));
88
+ }
89
+ }
49
90
  for (const [name, value] of Object.entries(env).filter(([key]) => key.startsWith("VITE_")).sort()) {
50
91
  hash.update(`${name}=${value}\n`);
51
92
  }
52
- return hash.digest("hex");
93
+ return { inputs: hash.digest("hex"), newest };
53
94
  }
54
95
 
55
- function runToCompletion(command, appRoot) {
96
+ /**
97
+ * The files and folders the build recorded reading, relative to appRoot, or null when it recorded no module. Virtual
98
+ * modules and queries (`?vue&type=style`) are not files; installed packages' folders are left to their record.
99
+ */
100
+ function readModules(appRoot, modulesFile) {
101
+ if (!existsSync(modulesFile)) return null;
102
+ // Vite names modules by their real paths.
103
+ const root = realpathSync(appRoot);
104
+ const files = new Set();
105
+ const directories = new Set();
106
+ for (const id of readFileSync(modulesFile, "utf8").split("\n")) {
107
+ const file = id.split("?")[0];
108
+ if (!path.isAbsolute(file) || !existsSync(file) || !statSync(file).isFile()) continue;
109
+ const relative = path.relative(root, file);
110
+ files.add(relative);
111
+ if (relative.split(path.sep).includes("node_modules")) continue;
112
+ for (let directory = path.dirname(relative); directory !== "."; directory = path.dirname(directory)) directories.add(directory);
113
+ }
114
+ return files.size ? { files: [...files].sort(), directories: [...directories].sort() } : null;
115
+ }
116
+
117
+ function runToCompletion(command, appRoot, environment = {}) {
56
118
  const [program, ...args] = String(command).trim().split(/\s+/u);
57
119
  return new Promise((resolve, reject) => {
58
120
  // The build a staging or production server serves, whatever NODE_ENV the launcher was given.
59
121
  const child = spawn(program, args, {
60
122
  cwd: appRoot,
61
- env: { ...process.env, NODE_ENV: "production" },
123
+ env: { ...process.env, ...environment, NODE_ENV: "production" },
62
124
  stdio: ["ignore", "ignore", "inherit"]
63
125
  });
64
126
  child.once("error", reject);
@@ -115,35 +177,51 @@ async function lockBuild(appRoot) {
115
177
  }
116
178
  }
117
179
 
118
- function isCurrent(appRoot, inputs) {
180
+ function isCurrent(appRoot, build) {
119
181
  const last = lastBuild(appRoot);
120
- return last.inputs === inputs && Boolean(last.index) && last.index === digest(path.join(appRoot, SERVED_INDEX));
182
+ return Boolean(last.index) && last.index === digest(path.join(appRoot, SERVED_INDEX)) &&
183
+ last.inputs === buildFingerprint(appRoot, build, last.read || null).inputs;
121
184
  }
122
185
 
123
186
  /**
124
187
  * Builds the frontend with `build` unless dist/ already holds the build of the current inputs.
125
- * @param {{ appRoot?: string, build?: string, run?: (command: string, appRoot: string) => Promise<void> }} [options]
188
+ * @param {{ appRoot?: string, build?: string,
189
+ * run?: (command: string, appRoot: string, environment: Record<string, string>) => Promise<void> }} [options]
126
190
  * @returns {Promise<{ built: boolean }>}
127
191
  */
128
192
  async function buildFrontend({ appRoot = process.cwd(), build = "npm run build", run = runToCompletion } = {}) {
129
193
  const started = performance.now();
130
- const inputs = buildFingerprint(appRoot, build);
131
- if (isCurrent(appRoot, inputs)) {
194
+ if (isCurrent(appRoot, build)) {
132
195
  console.log(`[browser-tests] Frontend build unchanged, reused (${seconds(started)}).`);
133
196
  return { built: false };
134
197
  }
135
198
  const unlock = await lockBuild(appRoot);
136
199
  try {
137
200
  // The run that held the lock may have just built these inputs.
138
- if (isCurrent(appRoot, inputs)) {
201
+ if (isCurrent(appRoot, build)) {
139
202
  console.log(`[browser-tests] Frontend built by another run, reused (${seconds(started)}).`);
140
203
  return { built: false };
141
204
  }
142
- await run(build, appRoot);
205
+ const modulesFile = path.join(appRoot, BUILD_MODULES_FILE);
206
+ // Made empty as the build starts: its modification time is the start by the file system's own clock, which stamps
207
+ // the inputs' times too.
208
+ writeFileSync(modulesFile, "");
209
+ const buildStart = statSync(modulesFile).mtimeMs;
210
+ const everySource = buildFingerprint(appRoot, build).inputs;
211
+ await run(build, appRoot, { [BUILD_MODULES_VARIABLE]: modulesFile });
143
212
  const index = digest(path.join(appRoot, SERVED_INDEX));
144
213
  if (!index) throw new Error(`${build} made no ${SERVED_INDEX}, which the app server serves.`);
145
- writeFileSync(path.join(appRoot, FINGERPRINT_FILE), JSON.stringify({ inputs, index }));
146
- console.log(`[browser-tests] Frontend built in ${seconds(started)}.`);
214
+ const read = readModules(appRoot, modulesFile);
215
+ rmSync(modulesFile, { force: true });
216
+ let inputs = everySource;
217
+ let note = "; it recorded no modules, so every source file is its input";
218
+ if (read) {
219
+ const { inputs: readInputs, newest } = buildFingerprint(appRoot, build, read);
220
+ inputs = newest.time >= buildStart ? "" : readInputs;
221
+ note = inputs ? "" : `; not kept for reuse, as ${newest.path} changed while it ran`;
222
+ }
223
+ writeFileSync(path.join(appRoot, FINGERPRINT_FILE), JSON.stringify({ inputs, index, read }));
224
+ console.log(`[browser-tests] Frontend built in ${seconds(started)}${note}.`);
147
225
  return { built: true };
148
226
  } finally {
149
227
  unlock();
@@ -1,10 +1,12 @@
1
- // `jskit browser-test-server [host] [port]`: the app as a host serves it for a browser test run, such as a Vibe64 Outputs
2
- // target with `Data: test`. It is one worker of a local run (browser-tests.mjs, browser-test-servers.mjs), read from the
3
- // app's own playwright.config.mjs: the production build, the database the app's `prepare` module gives that worker (its
4
- // own copy of BROWSER_TEST_DB_NAME in the database patterns), the test-only `env` and APP_ENV=test, on the host's address
5
- // in place of the run's own port. The host's suite then runs against it as a managed target (PLAYWRIGHT_BASE_URL),
6
- // signed in with the login state its host supplies, so this server signs nothing in. The host and port come from the
7
- // arguments, else HOST and PORT. The app server's output also reaches this command's own; stopping the command stops it.
1
+ // `jskit browser-test-server [host] [port] [workers]`: the app as a host serves it for a browser test run, such as a
2
+ // Vibe64 Outputs target with `Data: test`. It is the servers of a local run's workers (browser-tests.mjs,
3
+ // browser-test-servers.mjs), read from the app's own playwright.config.mjs: the production build, built once, and for
4
+ // each worker i on port+i the database the app's `prepare` module gives it (its own copy of BROWSER_TEST_DB_NAME in the
5
+ // database patterns, prepared once for every worker), the test-only `env` and APP_ENV=test, on the host's address in
6
+ // place of the run's own ports. The host's suite then runs against them as a managed target (PLAYWRIGHT_BASE_URL, and
7
+ // PLAYWRIGHT_WORKER_TARGETS for several), signed in with the login state its host supplies, so these servers sign
8
+ // nothing in. The host and port come from the arguments, else HOST and PORT; workers, from 1 to 64, from the third
9
+ // argument, else 1. The servers' output also reaches this command's own; stopping the command stops them.
8
10
  import { existsSync } from "node:fs";
9
11
  import path from "node:path";
10
12
  import process from "node:process";
@@ -12,24 +14,32 @@ import { pathToFileURL } from "node:url";
12
14
  import { SETTINGS_VARIABLE } from "./browser-tests.mjs";
13
15
 
14
16
  const CONFIG_FILES = Object.freeze(["playwright.config.mjs", "playwright.config.js"]);
17
+ // As many app servers as one host run asks for (Vibe64 admits a run of at most 64 workers).
18
+ const MAX_WORKERS = 64;
15
19
 
16
20
  /**
17
- * Serves the app in `appRoot` as one browser test server, until it is stopped.
18
- * @param {string[]} args `[host, port]`, either of which may be left to HOST and PORT.
21
+ * Serves the app in `appRoot` as browser test servers, until it is stopped.
22
+ * @param {string[]} args `[host, port, workers]`: host and port may be left to HOST and PORT, workers to 1.
19
23
  * @param {Record<string, string | undefined>} [environment] This process's environment, given the run's settings.
20
24
  * @param {string} [appRoot]
21
25
  */
22
26
  async function serveBrowserTestTarget(args = [], environment = process.env, appRoot = process.cwd()) {
23
- if (args.length > 2) throw new Error("Usage: jskit browser-test-server [host] [port]");
27
+ if (args.length > 3) throw new Error("Usage: jskit browser-test-server [host] [port] [workers]");
24
28
  const host = String(args[0] || environment.HOST || "").trim() || "127.0.0.1";
25
29
  const port = String(args[1] || environment.PORT || "").trim();
26
30
  if (!/^[1-9]\d{0,4}$/u.test(port) || Number(port) > 65_535) {
27
31
  throw new Error(`jskit browser-test-server needs the port to serve on, as its second argument or PORT, not ${port || "nothing"}.`);
28
32
  }
29
- // What a local run's config reads for one worker on this port. A suite runner's settings left in a host's environment
30
- // (its managed target, login state, worker count or index) are not this server's.
31
- for (const name of ["PLAYWRIGHT_BASE_URL", "PLAYWRIGHT_STORAGE_STATE", "TEST_PARALLEL_INDEX"]) delete environment[name];
32
- Object.assign(environment, { PLAYWRIGHT_PORT: port, PLAYWRIGHT_WORKERS: "1" });
33
+ const workers = String(args[2] ?? "1").trim();
34
+ if (!/^[1-9]\d?$/u.test(workers) || Number(workers) > MAX_WORKERS) {
35
+ throw new Error(`jskit browser-test-server serves 1 to ${MAX_WORKERS} app servers, not ${workers || "nothing"}.`);
36
+ }
37
+ // What a local run's config reads for its workers from this port. A suite runner's settings left in a host's
38
+ // environment (its managed target and servers, login state, worker count or index) are not these servers'.
39
+ for (const name of ["PLAYWRIGHT_BASE_URL", "PLAYWRIGHT_STORAGE_STATE", "PLAYWRIGHT_WORKER_TARGETS", "TEST_PARALLEL_INDEX"]) {
40
+ delete environment[name];
41
+ }
42
+ Object.assign(environment, { PLAYWRIGHT_PORT: port, PLAYWRIGHT_WORKERS: workers });
33
43
  const config = CONFIG_FILES.map((name) => path.join(appRoot, name)).find((file) => existsSync(file));
34
44
  const loaded = config ? (await import(pathToFileURL(config).href)).default : null;
35
45
  const settings = loaded?.webServer?.env?.[SETTINGS_VARIABLE];
@@ -5,14 +5,18 @@
5
5
  // (browser-tests.mjs). With the app's `signIn` module, each server is then signed in once, and its storage state left
6
6
  // for its worker. Each server's output goes to test-results/browser-test-servers/worker-<n>.log; a server that stops
7
7
  // ends the run. A port that already answers is refused before anything is built or started: a server left there by an
8
- // earlier run would answer for this run's. Stopped by Playwright (SIGTERM), by Ctrl-C, or by the end of the stdin pipe
9
- // Playwright gives its webServer (a Playwright that ended without stopping it), the launcher stops its servers and
10
- // waits for them, then drops the numbered database copies the prepare module made, within Playwright's grace, before it
11
- // exits; it drops them too when its start fails. `jskit browser-test-server` (browser-test-server.mjs) runs it
12
- // for one server a host starts, with `terminal`: that server's output also reaches the launcher's own.
8
+ // earlier run would answer for this run's. Stopped by Playwright (SIGTERM), by Ctrl-C, by its terminal's hang-up (SIGHUP,
9
+ // which a host such as Vibe64 sends a target's command first), by the end of the stdin pipe Playwright gives its
10
+ // webServer (a Playwright that ended without stopping it) or by a write its output refused (a hung-up terminal answers
11
+ // EIO, a pipe without a reader EPIPE), the launcher stops its servers and waits for them, then
12
+ // drops the numbered database copies the prepare module made, within Playwright's grace, before it exits; it drops
13
+ // them too when its start fails. `jskit browser-test-server` (browser-test-server.mjs) runs it
14
+ // for one server a host starts, with `terminal`: that server's output also reaches the launcher's own. A run takes free
15
+ // ports of its own, so its worker environments and signed-in states have names of their own; the launcher removes them
16
+ // when it stops, so they never pile up in the cache, nor outlive the sessions they hold.
13
17
  import { spawn } from "node:child_process";
14
18
  import { once } from "node:events";
15
- import { createWriteStream, fstatSync, mkdirSync, writeFileSync } from "node:fs";
19
+ import { createWriteStream, fstatSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
16
20
  import { createRequire } from "node:module";
17
21
  import net from "node:net";
18
22
  import path from "node:path";
@@ -102,6 +106,8 @@ async function waitUntilReady(url, server, name) {
102
106
 
103
107
  const servers = [];
104
108
  let stopping = false;
109
+ // The files this run leaves for its workers, which it removes when it stops.
110
+ let runFiles = [];
105
111
  // The prepare module's work, which a stop waits for (within DROP_WAIT_MS) so the copies it is making are dropped too.
106
112
  let preparing = Promise.resolve();
107
113
  const running = (server) => server.exitCode === null && server.signalCode === null;
@@ -129,10 +135,17 @@ async function stopAndExit(code) {
129
135
  console.error(`[browser-tests] The prepared test database copies were not all dropped within ${DROP_WAIT_MS / 1000}s; ` +
130
136
  "the next run makes them afresh and drops them.");
131
137
  }
138
+ for (const file of runFiles) rmSync(file, { force: true });
132
139
  process.exit(code);
133
140
  }
134
- process.once("SIGINT", () => stopAndExit(130));
135
- process.once("SIGTERM", () => stopAndExit(143));
141
+ // Kept for every signal, not once: a host's stop signals more than once (Vibe64's wrapper SIGTERM, its terminal's
142
+ // SIGHUP, then the process group's SIGTERM), and a signal with no handler left would kill the launcher mid-stop.
143
+ process.on("SIGINT", () => stopAndExit(130));
144
+ process.on("SIGTERM", () => stopAndExit(143));
145
+ process.on("SIGHUP", () => stopAndExit(129));
146
+ // Its servers' output passes through its own, which can go before its stop does: a write that fails there stops it like
147
+ // a signal, never as an uncaught error that would end it before its copies are dropped.
148
+ for (const output of [process.stdout, process.stderr]) output.on("error", () => stopAndExit(1));
136
149
  // Only a pipe ends when Playwright does; a launcher started without one (stdin ignored, /dev/null) would end at once.
137
150
  const input = fstatSync(0);
138
151
  if (input.isFIFO() || input.isSocket()) {
@@ -152,6 +165,8 @@ useTestAppEnvironment(process.env, "jskit browser tests");
152
165
  const baseEnvironment = { ...process.env };
153
166
  delete baseEnvironment[SETTINGS_VARIABLE];
154
167
  const baseUrls = Array.from({ length: workers }, (_, index) => `http://${host}:${basePort + index}`);
168
+ runFiles = [workerEnvironmentsFile, ...(signedInStates ? baseUrls.map((_, index) => `${signedInStates}-${index}.json`) : [])]
169
+ .filter(Boolean);
155
170
  try {
156
171
  await refuseBusyPorts(host, baseUrls.map((_, index) => basePort + index));
157
172
  preparing = prepareWorkers(appRoot, prepare, workers, baseUrls);
@@ -1,3 +1,4 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import { readFileSync } from "node:fs";
2
3
  import path from "node:path";
3
4
  import process from "node:process";
@@ -10,17 +11,20 @@ import { testConcurrency } from "./test-budget.mjs";
10
11
  // (browser-test-servers.mjs). With the app's `signIn` module, each worker's server is signed in once and every test of
11
12
  // that worker starts from its signed-in state. With PLAYWRIGHT_BASE_URL set, the tests use that managed target instead,
12
13
  // as its host serves it and with the login state its host supplies, one worker at a time unless the runner sets
13
- // PLAYWRIGHT_WORKERS.
14
+ // PLAYWRIGHT_WORKERS. A host serving such a target several app servers (Vibe64's targets whose Run step takes
15
+ // {workers}) lists them in PLAYWRIGHT_WORKER_TARGETS: one Playwright worker per server, each with its own signed-in
16
+ // state.
14
17
 
15
18
  const SERVERS = fileURLToPath(new URL("./browser-test-servers.mjs", import.meta.url));
16
19
  const SLOWEST_TESTS = fileURLToPath(new URL("./browser-test-times.mjs", import.meta.url));
17
20
  const SETTINGS_VARIABLE = "JSKIT_BROWSER_TESTS";
18
21
  const READY = /^jskit browser tests: \d+ server\(s\) ready/mu;
19
22
  const HOST = "127.0.0.1";
20
- const DEFAULT_PORT = 4173;
21
- // A whole run's default bound: a suite that would take hours stops instead, and says so. A suite measured to need
22
- // longer passes its own globalTimeout, with the measurement beside it.
23
- const GLOBAL_TIMEOUT_MS = 20 * 60_000;
23
+ // A whole run's default bound, as work: 80 worker-minutes, so 20 minutes on 4 workers and 80 on one, never under 20
24
+ // minutes, so a run with fewer browsers is not cut short for the host's size. A suite that would take hours stops
25
+ // instead, and says so. A suite measured to need longer passes its own globalTimeout, with the measurement beside it.
26
+ const WORKER_MINUTES_MS = 80 * 60_000;
27
+ const MIN_GLOBAL_TIMEOUT_MS = 20 * 60_000;
24
28
  // A click, fill or navigation waiting on something that never comes (a stale locator) fails in seconds, with its own
25
29
  // error, instead of holding the test until its 60 s timeout. Over 652 passing app tests the slowest action or page
26
30
  // load took 9.0 s, and expect already waits 10 s.
@@ -33,8 +37,41 @@ const WORKER_ENVIRONMENTS = path.join("node_modules", ".cache", "jskit-browser-t
33
37
 
34
38
  const positiveInteger = (value) => (/^[1-9]\d*$/u.test(String(value ?? "").trim()) ? Number(String(value).trim()) : 0);
35
39
 
40
+ const withoutTrailingSlash = (url) => String(url || "").trim().replace(/\/+$/u, "");
41
+
36
42
  function managedBaseUrl(env) {
37
- return String(env.PLAYWRIGHT_BASE_URL || "").trim().replace(/\/+$/u, "");
43
+ return withoutTrailingSlash(env.PLAYWRIGHT_BASE_URL);
44
+ }
45
+
46
+ const WORKER_TARGETS_FORM = "PLAYWRIGHT_WORKER_TARGETS is a JSON list of { baseURL, storageState? }: each Playwright " +
47
+ "worker's app server, an HTTP URL, and its signed-in state file";
48
+
49
+ /**
50
+ * A host's app servers for a managed run, one per Playwright worker, from PLAYWRIGHT_WORKER_TARGETS, or null without it.
51
+ * @param {Record<string, string | undefined>} env
52
+ * @returns {Array<{ baseURL: string, storageState: string }> | null}
53
+ */
54
+ function managedWorkerTargets(env) {
55
+ const text = String(env.PLAYWRIGHT_WORKER_TARGETS || "").trim();
56
+ if (!text) return null;
57
+ let list;
58
+ try {
59
+ list = JSON.parse(text);
60
+ } catch {
61
+ throw new Error(`${WORKER_TARGETS_FORM}; it is not JSON.`);
62
+ }
63
+ const valid = Array.isArray(list) && list.length > 0 && list.every((entry) => {
64
+ let protocol = "";
65
+ try {
66
+ protocol = new URL(String(entry?.baseURL)).protocol;
67
+ } catch {
68
+ return false;
69
+ }
70
+ return ["http:", "https:"].includes(protocol) &&
71
+ (entry.storageState === undefined || (typeof entry.storageState === "string" && entry.storageState.trim() !== ""));
72
+ });
73
+ if (!valid) throw new Error(`${WORKER_TARGETS_FORM}.`);
74
+ return list.map(({ baseURL, storageState = "" }) => ({ baseURL: withoutTrailingSlash(baseURL), storageState }));
38
75
  }
39
76
 
40
77
  /**
@@ -58,12 +95,51 @@ function commandLineWorkers(argv) {
58
95
  * How many workers a browser run uses: the command line's `--workers`, else PLAYWRIGHT_WORKERS, else half the machine's
59
96
  * test budget for a local run and 1 for a managed target (one server). A local worker drives a browser and its own app
60
97
  * server, about two threads' work: with a budget of 4, the shell foundation's 9 tests took 11.5 s on 4 workers and
61
- * 7.9 s on 2.
98
+ * 7.9 s on 2. A managed target whose host lists several app servers (PLAYWRIGHT_WORKER_TARGETS) runs one worker per
99
+ * server, and refuses another count: a worker would have no server, or a server no worker.
62
100
  * @param {{ env?: Record<string, string | undefined>, argv?: ReadonlyArray<string> }} [options]
63
101
  */
64
102
  function browserTestWorkers({ env = process.env, argv = process.argv } = {}) {
65
- return commandLineWorkers(argv) || positiveInteger(env.PLAYWRIGHT_WORKERS) ||
66
- (managedBaseUrl(env) ? 1 : Math.max(1, Math.floor(testConcurrency({ env }) / 2)));
103
+ const asked = commandLineWorkers(argv) || positiveInteger(env.PLAYWRIGHT_WORKERS);
104
+ const targets = managedBaseUrl(env) ? managedWorkerTargets(env) : null;
105
+ if (targets && asked && asked !== targets.length) {
106
+ throw new Error(`PLAYWRIGHT_WORKER_TARGETS lists ${targets.length} app servers, one per Playwright worker, so this run ` +
107
+ `cannot use ${asked} workers. Leave the count to the host that serves them.`);
108
+ }
109
+ return targets?.length || asked || (managedBaseUrl(env) ? 1 : Math.max(1, Math.floor(testConcurrency({ env }) / 2)));
110
+ }
111
+
112
+ // Finds `count` consecutive ports nothing listens on, at a random place below Linux's ephemeral range, and prints the
113
+ // first. A child process, since a Playwright configuration is built synchronously.
114
+ const FREE_PORTS = `
115
+ const net = require("node:net");
116
+ const [host, count] = [process.argv[1], Number(process.argv[2])];
117
+ const listen = (port) => new Promise((resolve) => {
118
+ const server = net.createServer();
119
+ server.once("error", () => resolve(null));
120
+ server.listen(port, host, () => resolve(server));
121
+ });
122
+ (async () => {
123
+ for (let attempt = 0; attempt < 50; attempt += 1) {
124
+ const base = 20000 + Math.floor(Math.random() * (12000 - count));
125
+ const held = [];
126
+ while (held.length < count) {
127
+ const server = await listen(base + held.length);
128
+ if (!server) break;
129
+ held.push(server);
130
+ }
131
+ await Promise.all(held.map((server) => new Promise((resolve) => server.close(resolve))));
132
+ if (held.length === count) return process.stdout.write(String(base));
133
+ }
134
+ process.exitCode = 1;
135
+ })();`;
136
+
137
+ /** The first of `count` consecutive free ports on host: a local run's default, so two runs on one machine never share. */
138
+ function freeConsecutivePorts(host, count) {
139
+ const found = spawnSync(process.execPath, ["-e", FREE_PORTS, host, String(count)], { encoding: "utf8", timeout: 30_000 });
140
+ const port = positiveInteger(found.stdout);
141
+ if (!port) throw new Error(`browserTestConfig() found no ${count} consecutive free port(s) on ${host}; set PLAYWRIGHT_PORT to free ports.`);
142
+ return port;
67
143
  }
68
144
 
69
145
  /** The environment the launcher gave worker `index`'s server, from the app's prepare module, or none. */
@@ -80,7 +156,8 @@ function preparedWorkerEnvironment(file, index) {
80
156
  * The Playwright configuration of an application's browser tests.
81
157
  * @param {object} [options]
82
158
  * @param {string} [options.testDir] Where the specs are.
83
- * @param {number} [options.port] The first worker's port; worker n uses port + n. PLAYWRIGHT_PORT overrides it.
159
+ * @param {number} [options.port] The first worker's port; worker n uses port + n. PLAYWRIGHT_PORT overrides it. By
160
+ * default a local run takes free ports and gives them to its workers in PLAYWRIGHT_PORT.
84
161
  * @param {string} [options.server] The command that starts the app server, reading PORT and HOST.
85
162
  * @param {string} [options.build] The command that builds the production frontend into the folder the server serves.
86
163
  * @param {string} [options.prepare] An app module, run once before the servers start, whose default export
@@ -94,7 +171,8 @@ function preparedWorkerEnvironment(file, index) {
94
171
  * out or ends sessions signs in on its own first, so the worker's shared session lives on.
95
172
  * @param {Record<string, string>} [options.env] Environment every server gets, such as its test-only drivers.
96
173
  * @param {string} [options.health] The path that answers 200 once a server is ready.
97
- * @param {number} [options.globalTimeout] The whole run's bound in milliseconds (20 minutes); never 0.
174
+ * @param {number} [options.globalTimeout] The whole run's bound in milliseconds (80 worker-minutes, never under 20
175
+ * minutes); never 0.
98
176
  * @param {number} [options.actionTimeout] One click, fill or other action's bound in milliseconds (15 s); never 0.
99
177
  * @param {number} [options.navigationTimeout] One navigation's bound in milliseconds (30 s); never 0.
100
178
  * @param {Record<string, string | undefined>} [options.environment] Read, and given a worker's prepared environment,
@@ -103,20 +181,20 @@ function preparedWorkerEnvironment(file, index) {
103
181
  */
104
182
  function browserTestConfig({
105
183
  testDir = "./tests/e2e",
106
- port = DEFAULT_PORT,
184
+ port = 0,
107
185
  server = "node ./bin/server.js",
108
186
  build = "npm run build",
109
187
  prepare = "",
110
188
  signIn = "",
111
189
  env = {},
112
190
  health = "/api/health",
113
- globalTimeout = GLOBAL_TIMEOUT_MS,
191
+ globalTimeout,
114
192
  actionTimeout = ACTION_TIMEOUT_MS,
115
193
  navigationTimeout = NAVIGATION_TIMEOUT_MS,
116
194
  environment = process.env,
117
195
  cwd = process.cwd()
118
196
  } = {}) {
119
- if (!Number.isInteger(globalTimeout) || globalTimeout < 1) {
197
+ if (globalTimeout !== undefined && (!Number.isInteger(globalTimeout) || globalTimeout < 1)) {
120
198
  throw new Error("browserTestConfig() needs a globalTimeout of at least 1 ms; a run is always bounded.");
121
199
  }
122
200
  for (const [name, value] of Object.entries({ actionTimeout, navigationTimeout })) {
@@ -126,7 +204,23 @@ function browserTestConfig({
126
204
  }
127
205
  const managed = managedBaseUrl(environment);
128
206
  const workers = browserTestWorkers({ env: environment });
129
- const basePort = positiveInteger(environment.PLAYWRIGHT_PORT) || port;
207
+ // A host serving the managed target several app servers: this worker's own, and its signed-in state.
208
+ const workerTargets = managed ? managedWorkerTargets(environment) : null;
209
+ const managedIndex = Number.parseInt(String(environment.TEST_PARALLEL_INDEX || "0"), 10) || 0;
210
+ const workerTarget = workerTargets ? workerTargets[managedIndex] : null;
211
+ if (workerTargets && !workerTarget) {
212
+ throw new Error(`PLAYWRIGHT_WORKER_TARGETS has no app server for Playwright worker ${managedIndex}.`);
213
+ }
214
+ const runTimeout = globalTimeout ?? Math.max(MIN_GLOBAL_TIMEOUT_MS, Math.ceil(WORKER_MINUTES_MS / workers));
215
+ let basePort = positiveInteger(environment.PLAYWRIGHT_PORT) || port;
216
+ if (!basePort && !managed) {
217
+ // Playwright's workers load this config again: they take the ports the run took, which only the run finds.
218
+ if (String(environment.TEST_PARALLEL_INDEX ?? "").trim() !== "") {
219
+ throw new Error("A Playwright worker found no PLAYWRIGHT_PORT: the run's own configuration sets it before its workers start.");
220
+ }
221
+ basePort = freeConsecutivePorts(HOST, workers);
222
+ environment.PLAYWRIGHT_PORT = String(basePort);
223
+ }
130
224
  // A Playwright worker loads this config again, with its own TEST_PARALLEL_INDEX, and reaches its own server; its
131
225
  // process takes the environment prepare gave that server, such as its DB_NAME, before any test file loads.
132
226
  const workerIndex = managed ? 0 : Number.parseInt(String(environment.TEST_PARALLEL_INDEX || "0"), 10) || 0;
@@ -142,7 +236,7 @@ function browserTestConfig({
142
236
  Object.assign(environment, preparedWorkerEnvironment(workerEnvironments, workerIndex));
143
237
  if (signedInStates) environment.PLAYWRIGHT_STORAGE_STATE = `${signedInStates}-${workerIndex}.json`;
144
238
  }
145
- const storageState = String(environment.PLAYWRIGHT_STORAGE_STATE || "").trim();
239
+ const storageState = workerTarget ? workerTarget.storageState : String(environment.PLAYWRIGHT_STORAGE_STATE || "").trim();
146
240
  const settings = {
147
241
  workers, host: HOST, basePort, server, build, prepare, env, health, workerEnvironments,
148
242
  ...(signedInStates ? { signIn, signedInStates } : {})
@@ -151,13 +245,13 @@ function browserTestConfig({
151
245
  return {
152
246
  testDir,
153
247
  workers,
154
- globalTimeout,
248
+ globalTimeout: runTimeout,
155
249
  timeout: 60_000,
156
250
  expect: { timeout: 10_000 },
157
251
  // Every run ends with its 10 slowest tests and their times.
158
252
  reporter: [["list"], [SLOWEST_TESTS]],
159
253
  use: {
160
- baseURL: managed || `http://${HOST}:${basePort + workerIndex}`,
254
+ baseURL: workerTarget?.baseURL || managed || `http://${HOST}:${basePort + workerIndex}`,
161
255
  headless: true,
162
256
  actionTimeout,
163
257
  navigationTimeout,