@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/scripts/jskit.mjs CHANGED
@@ -35,7 +35,7 @@ function usage() {
35
35
  " jskit i18n check <locale> [--root <path>]",
36
36
  " jskit package nix [--root <path>]",
37
37
  " jskit test [node options] [files or globs]",
38
- " jskit browser-test-server [host] [port]",
38
+ " jskit browser-test-server [host] [port] [workers]",
39
39
  "",
40
40
  "Commands:",
41
41
  " update Align root and workspace @jskit-ai/* declarations to this published catalog, then run npm install.",
@@ -47,8 +47,10 @@ function usage() {
47
47
  " fixed button height, or a rule for using components (ui/*), such as a prop a JSKIT component",
48
48
  " no longer has. It also fails when",
49
49
  " a package script runs tests outside the machine's test budget (test/*): node --test instead of",
50
- " jskit test, a fixed test concurrency or worker count, or a Playwright or Vitest config whose",
51
- " workers do not come from testConcurrency() of @jskit-ai/jskit-catalog/test-budget. A Playwright",
50
+ " jskit test, a fixed test concurrency or worker count, a Vitest config whose workers do not come",
51
+ " from testConcurrency() of @jskit-ai/jskit-catalog/test-budget, or a Playwright config whose",
52
+ " workers do not come from browserTestWorkers() of @jskit-ai/jskit-catalog/browser-tests (half the",
53
+ " budget, as each worker drives a browser and often its own app server). A Playwright",
52
54
  " config with a webServer uses browserTestConfig() of @jskit-ai/jskit-catalog/browser-tests (one",
53
55
  " production-build server and database per worker), never a development server, and every one",
54
56
  " has a globalTimeout. It fails when two table resources (defineTableResource) of the app and its",
@@ -57,11 +59,13 @@ function usage() {
57
59
  " and it lists every system scope and every file the infrastructure exception lifts past the",
58
60
  " data-access lint rules for review. It fails when an application package's manifest",
59
61
  " (jskit.capabilities) misses a capability its features (server providers) provide or require, or",
60
- " provides one none of them does (manifest/capabilities), and lists each requirement no feature has,",
61
- " which only install time may need, for review. When the app has a package.nix that jskit package nix",
62
- " wrote, it fails when that file is not the one this release writes (package/nix-current), when",
63
- " package.json lacks what the package needs (package/nix-manifest), or when package-lock.json names a",
64
- " dependency a build with no network cannot fetch by its hash (package/nix-offline).",
62
+ " provides one none of them does, or its installRequires marks one they require or the manifest does",
63
+ " not (manifest/capabilities), and lists for review each requirement no feature has that",
64
+ " installRequires does not mark (only install time may need it). When the app has a package.nix",
65
+ " that jskit package nix wrote, it fails when that file is not the one this release writes",
66
+ " (package/nix-current), when package.json lacks what the package needs (package/nix-manifest), or",
67
+ " when package-lock.json names a dependency a build with no network cannot fetch by its hash",
68
+ " (package/nix-offline).",
65
69
  " check m3 Check application UI source against the JSKIT Material 3 guide alone, with each finding's guide",
66
70
  " section and every exception: the whole app, or only the given files and directories (a section,",
67
71
  " or a task's changed files). Plain jskit check applies the same rules to the whole app.",
@@ -81,16 +85,19 @@ function usage() {
81
85
  " (at least 1). A file whose first line is `// jskit-test: alone - <reason>` runs after the others,",
82
86
  " on its own. With --databases, each file running at once gets its own copy of TEST_DB_NAME,",
83
87
  " restored from a schema snapshot (the app's knexfile.js and @jskit-ai/database-runtime), rows",
84
- " included, before each file; with no usable TEST_DB_NAME, the files run one at a time on the",
85
- " connected database. Given no files, it",
86
- " fails when a file under tests/ is named as a test (x.integration.js, x.spec.js) that node's",
87
- " default pattern would leave out; a database test is named x.integration.test.js.",
88
+ " included, before each file, with the app's DB_CLIENT. With no usable TEST_DB_NAME, the files",
89
+ " run one at a time on the connected database; a run that gets fewer databases than its budget",
90
+ " asked for (no TEST_DB_NAME, or copies the database user may not create) says why at its start",
91
+ " and end, and fails, unless V64_TEST_CONCURRENCY is set to what the databases allow. Given no",
92
+ " files, it fails when a file under tests/ is named as a test (x.integration.js, x.spec.js) that",
93
+ " node's default pattern would leave out; a database test is named x.integration.test.js.",
88
94
  " browser-test-server",
89
95
  " Serve the app for a host's browser test run, such as a Vibe64 Outputs target with Data test, on",
90
- " [host] [port] (else HOST and PORT): one worker's server of the app's playwright.config.mjs",
91
- " browserTestConfig(), on the production build, with the database its prepare module gives that",
92
- " worker, its test-only env and APP_ENV=test. The host's suite runs against it with",
93
- " PLAYWRIGHT_BASE_URL and the login state the host supplies. It runs until it is stopped.",
96
+ " [host] [port] (else HOST and PORT): [workers] servers (1 to 64, else 1) of the app's",
97
+ " playwright.config.mjs browserTestConfig(), worker i on port+i, on the production build, each with",
98
+ " the database its prepare module gives that worker, its test-only env and APP_ENV=test. The",
99
+ " host's suite runs against them with PLAYWRIGHT_BASE_URL (and PLAYWRIGHT_WORKER_TARGETS for",
100
+ " several) and the login state the host supplies. It runs until it is stopped.",
94
101
  "",
95
102
  "<locale> is a BCP 47 language tag, such as fr or pt-BR."
96
103
  ].join("\n");
@@ -326,6 +333,14 @@ async function main(argv = process.argv.slice(2)) {
326
333
  `${result.addedMigrations.map((entry) => `- ${entry}`).join("\n")}\n`
327
334
  );
328
335
  }
336
+ if (result.uncomparedPackages.length > 0) {
337
+ process.stdout.write(
338
+ `The update could not tell whether ${result.uncomparedPackages.length} updated package(s) add migrations, since ` +
339
+ `node_modules did not hold their previous versions; run npm run db:migrate before the app serves requests:\n` +
340
+ `${result.uncomparedPackages.map(({ packageId, previousVersion, version }) =>
341
+ `- ${packageId} ${previousVersion} -> ${version}`).join("\n")}\n`
342
+ );
343
+ }
329
344
  if (!options.install) {
330
345
  process.stdout.write(
331
346
  "Skipped npm install; run it before jskit check. If it installs new package migrations, run npm run db:migrate " +
@@ -12,10 +12,10 @@ import { toPosixPath } from "./files.mjs";
12
12
  const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/framework/typed-features#package-manifest";
13
13
  const KERNEL_PLATFORM = "@jskit-ai/kernel/server/platform";
14
14
 
15
- // The line naming a capability in a manifest's `capabilities` block, else the block's own line.
16
- function capabilityLine(contents, capabilityId = "") {
15
+ // The line naming a capability in a manifest's `capabilities` block (or in its `within` list), else the block's own line.
16
+ function capabilityLine(contents, capabilityId = "", within = "capabilities") {
17
17
  const text = String(contents);
18
- const block = text.indexOf('"capabilities"');
18
+ const block = text.indexOf(`"${within}"`);
19
19
  if (block < 0) return 1;
20
20
  const named = capabilityId ? text.indexOf(`"${capabilityId}"`, block) : -1;
21
21
  return text.slice(0, named < 0 ? block : named).split("\n").length;
@@ -38,13 +38,14 @@ async function kernelPlatform(manifestPath, root) {
38
38
  async function checkManifestCapabilities({ projectRoot, manifests }) {
39
39
  const root = path.resolve(projectRoot);
40
40
  const findings = [];
41
- const installTime = [];
41
+ const extraRequires = [];
42
42
  let packages = 0;
43
43
  for (const manifest of manifests) {
44
44
  const jskit = manifest.value?.jskit;
45
45
  if (!Array.isArray(jskit?.runtime?.server?.providers) || jskit.runtime.server.providers.length < 1) continue;
46
46
  const file = toPosixPath(path.relative(root, manifest.absolutePath)) || "package.json";
47
- const at = (capabilityId, message) => findings.push({ file, line: capabilityLine(manifest.contents, capabilityId), rule: "manifest/capabilities", message });
47
+ const at = (capabilityId, message, within) =>
48
+ findings.push({ file, line: capabilityLine(manifest.contents, capabilityId, within), rule: "manifest/capabilities", message });
48
49
  const kernel = await kernelPlatform(manifest.absolutePath, root);
49
50
  if (typeof kernel?.packageCapabilityDrift !== "function") {
50
51
  at("", `declares server providers, but no installed ${KERNEL_PLATFORM} compares a manifest with them; run jskit update.`);
@@ -66,18 +67,25 @@ async function checkManifestCapabilities({ projectRoot, manifests }) {
66
67
  for (const id of drift.unlistedProvides) at("", `its features provide ${id}, which jskit.capabilities.provides does not list; add it.`);
67
68
  for (const id of drift.extraProvides) at(id, `jskit.capabilities.provides lists ${id}, which none of its features provides; remove it.`);
68
69
  for (const id of drift.unlistedRequires) at("", `its features require ${id}, which jskit.capabilities.requires does not list; add it.`);
69
- for (const id of drift.extraRequires) installTime.push({ file, line: capabilityLine(manifest.contents, id), capabilityId: id });
70
+ for (const id of drift.requiredInstallRequires || []) {
71
+ at(id, `jskit.capabilities.installRequires lists ${id}, which its features require; remove it from installRequires.`, "installRequires");
72
+ }
73
+ for (const id of drift.unlistedInstallRequires || []) {
74
+ at(id, `jskit.capabilities.installRequires lists ${id}, which jskit.capabilities.requires does not list; add it to requires or remove it.`, "installRequires");
75
+ }
76
+ for (const id of drift.extraRequires) extraRequires.push({ file, line: capabilityLine(manifest.contents, id), capabilityId: id });
70
77
  }
71
78
  findings.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
72
- return { ok: findings.length < 1, findings, installTime, packages };
79
+ return { ok: findings.length < 1, findings, extraRequires, packages };
73
80
  }
74
81
 
75
82
  function formatManifestCapabilitiesReport(result) {
76
83
  const lines = result.findings.flatMap(({ file, line, rule, message }) => [`${file}:${line} ${rule} ${message}`, ` ${GUIDE}`]);
77
- if (result.installTime.length > 0) {
78
- lines.push(`Manifest requirements no feature has (${result.installTime.length}), each needed only at install time, such as ` +
79
- `the database a migration needs; remove any other (${GUIDE}):`);
80
- for (const { file, line, capabilityId } of result.installTime) lines.push(` ${file}:${line} ${capabilityId}`);
84
+ if (result.extraRequires.length > 0) {
85
+ lines.push(`Manifest requirements no feature has and installRequires does not mark (${result.extraRequires.length}): mark ` +
86
+ "each one only install time needs, such as the database a migration needs, in jskit.capabilities.installRequires; " +
87
+ `remove any other (${GUIDE}):`);
88
+ for (const { file, line, capabilityId } of result.extraRequires) lines.push(` ${file}:${line} ${capabilityId}`);
81
89
  }
82
90
  lines.push(result.ok
83
91
  ? `JSKIT package manifests name what their features provide and require in ${result.packages} package(s).`
@@ -0,0 +1,67 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileExists, toPosixPath } from "./files.mjs";
4
+ import { readJsonRecord } from "./project-manifests.mjs";
5
+
6
+ // The package migrations a JSKIT update installs, which the app must run before the new packages serve requests.
7
+
8
+ const JSKIT_SCOPE_PREFIX = "@jskit-ai/";
9
+
10
+ // The @jskit-ai packages installed in node_modules, each with its version and the migration files it ships
11
+ // (jskit.migrations.directories and their constraints/), each by its path in the package, as the app's migrations
12
+ // read them from node_modules.
13
+ async function installedPackageMigrations(root) {
14
+ const scope = path.join(root, "node_modules", JSKIT_SCOPE_PREFIX);
15
+ const names = await readdir(scope).catch((error) => {
16
+ if (error?.code === "ENOENT") return [];
17
+ throw error;
18
+ });
19
+ const installed = new Map();
20
+ for (const name of names) {
21
+ const packageRoot = path.join(scope, name);
22
+ const manifestPath = path.join(packageRoot, "package.json");
23
+ if (!(await fileExists(manifestPath))) continue;
24
+ const manifest = (await readJsonRecord(manifestPath)).value;
25
+ const directories = manifest.jskit?.migrations?.directories;
26
+ const migrations = new Set();
27
+ for (const directory of Array.isArray(directories) ? directories : []) {
28
+ for (const folder of [directory, path.join(directory, "constraints")]) {
29
+ const files = await readdir(path.join(packageRoot, folder)).catch(() => []);
30
+ for (const file of files.filter((entry) => entry.endsWith(".cjs"))) {
31
+ migrations.add(toPosixPath(path.join(folder, file)));
32
+ }
33
+ }
34
+ }
35
+ installed.set(`${JSKIT_SCOPE_PREFIX}${name}`, { version: String(manifest.version || ""), migrations });
36
+ }
37
+ return installed;
38
+ }
39
+
40
+ // The package migrations an update added: the files its installed packages ship that the app's previous packages did
41
+ // not. A package node_modules held before is compared file by file. One it did not hold (a fresh checkout or worktree,
42
+ // never installed) is compared through its version in the previous package-lock.json (previousVersions, by package
43
+ // id): at the same version it ships the same files, and one the lock lacks is new to the app, with all its migrations.
44
+ // One whose version moved has earlier files that are nowhere on disk, so it is uncompared: none of its migrations are
45
+ // counted as new.
46
+ function packageMigrationChanges(before, after, previousVersions) {
47
+ const addedMigrations = [];
48
+ const uncomparedPackages = [];
49
+ for (const [packageId, { version, migrations }] of after) {
50
+ const previous = before.get(packageId);
51
+ const previousVersion = previousVersions.get(packageId);
52
+ if (previous) {
53
+ addedMigrations.push(...[...migrations].filter((file) => !previous.migrations.has(file))
54
+ .map((file) => `${packageId}: ${file}`));
55
+ } else if (previousVersion === undefined) {
56
+ addedMigrations.push(...[...migrations].map((file) => `${packageId}: ${file}`));
57
+ } else if (previousVersion !== version && migrations.size > 0) {
58
+ uncomparedPackages.push(Object.freeze({ packageId, previousVersion, version }));
59
+ }
60
+ }
61
+ return {
62
+ addedMigrations: addedMigrations.sort(),
63
+ uncomparedPackages: uncomparedPackages.sort((left, right) => left.packageId.localeCompare(right.packageId))
64
+ };
65
+ }
66
+
67
+ export { installedPackageMigrations, packageMigrationChanges };
@@ -2,6 +2,7 @@ import { readdir, readFile, realpath, rename, rm, writeFile } from "node:fs/prom
2
2
  import path from "node:path";
3
3
  import { fileExists, toPosixPath } from "./files.mjs";
4
4
  import { readOptionalFile, restoreProjectFiles, runNpmInstall, writeManifestUpdates } from "./project-install.mjs";
5
+ import { installedPackageMigrations, packageMigrationChanges } from "./project-migrations.mjs";
5
6
  import { discoverProjectManifests, readJsonRecord, serializePackageJson } from "./project-manifests.mjs";
6
7
 
7
8
  const JSKIT_SCOPE_PREFIX = "@jskit-ai/";
@@ -517,32 +518,6 @@ async function findImports(root, packageIds) {
517
518
  return imports;
518
519
  }
519
520
 
520
- // The migration files the installed @jskit-ai packages ship (jskit.migrations.directories and their constraints/),
521
- // each "<package>: <path in the package>", as the app's migrations read them from node_modules.
522
- async function installedPackageMigrations(root) {
523
- const scope = path.join(root, "node_modules", JSKIT_SCOPE_PREFIX);
524
- const names = await readdir(scope).catch((error) => {
525
- if (error?.code === "ENOENT") return [];
526
- throw error;
527
- });
528
- const migrations = new Set();
529
- for (const name of names) {
530
- const packageRoot = path.join(scope, name);
531
- const manifestPath = path.join(packageRoot, "package.json");
532
- if (!(await fileExists(manifestPath))) continue;
533
- const directories = (await readJsonRecord(manifestPath)).value.jskit?.migrations?.directories;
534
- for (const directory of Array.isArray(directories) ? directories : []) {
535
- for (const folder of [directory, path.join(directory, "constraints")]) {
536
- const files = await readdir(path.join(packageRoot, folder)).catch(() => []);
537
- for (const file of files.filter((entry) => entry.endsWith(".cjs"))) {
538
- migrations.add(`${JSKIT_SCOPE_PREFIX}${name}: ${toPosixPath(path.join(folder, file))}`);
539
- }
540
- }
541
- }
542
- }
543
- return migrations;
544
- }
545
-
546
521
  /**
547
522
  * Approves, in the root manifest's allowScripts, the install script of each JSKIT package in `declared` that has one,
548
523
  * unless the app already allows it by name or denies it in any entry.
@@ -682,10 +657,10 @@ async function updateProject({
682
657
  const packageLockPath = path.join(root, "package-lock.json");
683
658
  const packageLockSnapshot = install ? await readOptionalFile(packageLockPath) : null;
684
659
  // npm install replaces node_modules, so the migrations the packages shipped are read before it.
685
- const migrationsBefore = install ? await installedPackageMigrations(root) : new Set();
660
+ const migrationsBefore = install ? await installedPackageMigrations(root) : new Map();
686
661
  await writeManifestUpdates(updates);
687
662
  let installTransaction = null;
688
- let addedMigrations = [];
663
+ let migrationChanges = { addedMigrations: [], uncomparedPackages: [] };
689
664
  try {
690
665
  if (install) {
691
666
  const updatedManifests = await discoverProjectManifests(root, additionalManifests);
@@ -695,7 +670,12 @@ async function updateProject({
695
670
  if (!result.ok) {
696
671
  throw new Error(`JSKIT graph remains inconsistent after npm install:\n- ${result.issues.join("\n- ")}`);
697
672
  }
698
- addedMigrations = [...await installedPackageMigrations(root)].filter((entry) => !migrationsBefore.has(entry)).sort();
673
+ // The previous lock's top-level JSKIT versions, for packages node_modules did not hold before.
674
+ const previousLock = packageLockSnapshot.exists ? JSON.parse(packageLockSnapshot.contents) : {};
675
+ const previousVersions = new Map(collectLockInstallations(previousLock)
676
+ .filter((entry) => entry.path === `node_modules/${entry.packageId}`)
677
+ .map((entry) => [entry.packageId, entry.version]));
678
+ migrationChanges = packageMigrationChanges(migrationsBefore, await installedPackageMigrations(root), previousVersions);
699
679
  await installTransaction.commit();
700
680
  }
701
681
  } catch (error) {
@@ -727,7 +707,8 @@ async function updateProject({
727
707
  updates.map((update) => toPosixPath(path.relative(root, update.manifest.absolutePath)))
728
708
  ),
729
709
  catalogVersion,
730
- addedMigrations: Object.freeze(addedMigrations),
710
+ addedMigrations: Object.freeze(migrationChanges.addedMigrations),
711
+ uncomparedPackages: Object.freeze(migrationChanges.uncomparedPackages),
731
712
  retiredPackages: Object.freeze(retiredPackageIds.map((packageId) => Object.freeze({
732
713
  packageId,
733
714
  replacedBy: RETIRED_PACKAGES[packageId].packageId
@@ -1,19 +1,57 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import os from "node:os";
3
+ import path from "node:path";
2
4
  import process from "node:process";
3
5
 
4
- // The machine's test budget: how many test files (node --test), Playwright workers or Vitest workers a run may use at
5
- // once. A test runner that hands out slots exports V64_TEST_CONCURRENCY for each run; anywhere else a run takes half
6
- // of the machine, so a test suite neither runs one file at a time nor overwhelms the machine (a 2-vCPU VPS stays at 1).
6
+ // The machine's test budget: how many test files (node --test) or Vitest workers a run may use at once; a Playwright
7
+ // worker, a browser and often an app server, takes two of it (browserTestWorkers() of ./browser-tests.mjs). A test
8
+ // runner that hands out slots exports V64_TEST_CONCURRENCY for each run; anywhere else a run takes half of the CPUs it
9
+ // may use, so a test suite neither runs one file at a time nor overwhelms the machine (a 2-vCPU VPS stays at 1).
7
10
  const BUDGET_VARIABLE = "V64_TEST_CONCURRENCY";
11
+ const CGROUP_ROOT = "/sys/fs/cgroup";
12
+
13
+ /** The CPUs a cgroup v2 `cpu.max` ("<quota> <period>" or "max <period>") allows, or Infinity. */
14
+ function quotaCpus(text) {
15
+ const [quota = "max", period] = String(text).trim().split(/\s+/u);
16
+ const cpus = Number(quota) / Number(period);
17
+ return quota !== "max" && Number.isFinite(cpus) && cpus > 0 ? cpus : Infinity;
18
+ }
19
+
20
+ /**
21
+ * The CPUs this process may use: the machine's (availableParallelism(), which follows CPU affinity), capped by the
22
+ * tightest cgroup v2 `cpu.max` quota from the process's own cgroup up to the root, which availableParallelism() does
23
+ * not read. A container or a VPS slice given 3 CPUs of a 16-thread host has 3, not 16. Without cgroup v2 (another
24
+ * system, or cgroup v1 alone), the machine's.
25
+ * @param {{ parallelism?: number, readFile?: (file: string, encoding: string) => string }} [options]
26
+ * @returns {number} a whole number of at least 1
27
+ */
28
+ function availableCpus({ parallelism = os.availableParallelism(), readFile = readFileSync } = {}) {
29
+ const read = (file) => {
30
+ try {
31
+ return String(readFile(file, "utf8"));
32
+ } catch {
33
+ return "";
34
+ }
35
+ };
36
+ const line = read("/proc/self/cgroup").split("\n").find((entry) => entry.startsWith("0::"));
37
+ let quota = Infinity;
38
+ if (line) {
39
+ for (let group = path.posix.join(CGROUP_ROOT, line.slice(3).trim()).replace(/\/+$/u, "");
40
+ group.startsWith(CGROUP_ROOT); group = path.posix.dirname(group)) {
41
+ quota = Math.min(quota, quotaCpus(read(path.posix.join(group, "cpu.max"))));
42
+ }
43
+ }
44
+ return Math.max(1, Math.min(parallelism, Math.floor(quota)));
45
+ }
8
46
 
9
47
  /**
10
48
  * @param {{ env?: Record<string, string | undefined>, parallelism?: number }} [options]
11
49
  * @returns {number} a whole number of at least 1
12
50
  */
13
- function testConcurrency({ env = process.env, parallelism = os.availableParallelism() } = {}) {
51
+ function testConcurrency({ env = process.env, parallelism = availableCpus() } = {}) {
14
52
  const configured = String(env[BUDGET_VARIABLE] ?? "").trim();
15
53
  if (/^[1-9]\d*$/u.test(configured)) return Number(configured);
16
54
  return Math.max(1, Math.floor(parallelism / 2));
17
55
  }
18
56
 
19
- export { BUDGET_VARIABLE, testConcurrency };
57
+ export { BUDGET_VARIABLE, availableCpus, testConcurrency };
@@ -18,7 +18,11 @@ import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
18
18
  // --test-shard=<index>/<total> it runs only its shard's alone files, picked the way node --test picks a shard's files.
19
19
  // Given no files, it fails instead of leaving out a file under tests/ named as a test that node's default misses.
20
20
  // Every run also reports to test-time-report.mjs, which times the command's files against coarse bounds, and preloads
21
- // test-file-stop.mjs, which stops a file still running at a generous multiple of its time.
21
+ // test-file-stop.mjs, which stops a file still running at a generous multiple of its time. With --databases, a run whose
22
+ // test databases let fewer files run at once than the budget asked for (no usable TEST_DB_NAME, or copies the database
23
+ // user may not create) says so, and why, at its start and its end, and fails once its tests have run: a machine that
24
+ // should run files in parallel never silently runs them one at a time. A budget set to what the databases allow
25
+ // (V64_TEST_CONCURRENCY) runs that way on purpose.
22
26
 
23
27
  // node --test's own default (Node 26) when it is given no files.
24
28
  const DEFAULT_PATTERN = "**/{test,test/**/*,test-*,*[._-]test}.{js,mjs,cjs,ts,mts,cts}";
@@ -31,6 +35,8 @@ const OTHER_RUNNER_IMPORT = /\b(?:from|import|require)\s*\(?\s*["'](?:vitest|@pl
31
35
  const MARKER = /^\s*\/\/\s*jskit-test:(.*)$/u;
32
36
  const ALONE = /^\s*alone\s+-\s+(\S.*)$/u;
33
37
  const SHARD = "--test-shard";
38
+ // A run of only some of its files' tests, by name or `only`, says nothing about how long a whole file takes.
39
+ const TEST_FILTER = /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/u;
34
40
  const REPORTER = "--test-reporter";
35
41
  const DESTINATION = "--test-reporter-destination";
36
42
  const TIME_REPORTER = new URL("./test-time-report.mjs", import.meta.url).href;
@@ -177,6 +183,21 @@ function withTimeReporter(run, destination) {
177
183
  ];
178
184
  }
179
185
 
186
+ /**
187
+ * What a run says, at its start and its end, when its test databases let fewer files run at once than it asked for, or
188
+ * "" when they gave all it asked. An installed @jskit-ai/database-runtime from before `shortfall` is read by its summary.
189
+ * @param {{ concurrency: number, shortfall?: string, summary: string }} databases
190
+ * @param {number} asked
191
+ */
192
+ function databaseShortfall(databases, asked) {
193
+ if (databases.concurrency >= asked) return "";
194
+ const copies = asked > 2 ? `\`<TEST_DB_NAME>_1\` to \`<TEST_DB_NAME>_${asked - 1}\`` : "`<TEST_DB_NAME>_1`";
195
+ return `test files run ${databases.concurrency} at a time, not the ${asked} this machine's test budget allows: ` +
196
+ `${databases.shortfall || databases.summary}. Each file running at once needs a database of its own: TEST_DB_NAME, ` +
197
+ `then ${copies}, which the database user creates and drops (MySQL and MariaDB: grant it \`<TEST_DB_NAME>\\_%\`; ` +
198
+ `PostgreSQL: CREATEDB). To run this way on purpose, set ${BUDGET_VARIABLE}=${databases.concurrency}.`;
199
+ }
200
+
180
201
  function runNode(args, env) {
181
202
  return new Promise((resolve, reject) => {
182
203
  const child = spawn(process.execPath, args, { stdio: "inherit", env: { ...process.env, ...env } });
@@ -204,11 +225,12 @@ async function runTests(args) {
204
225
  let plan = planTestRuns(nodeArgs);
205
226
  const source = process.env[BUDGET_VARIABLE] ? BUDGET_VARIABLE : "half of this machine";
206
227
  // A database for each file that can run at once: a focused run of one file prepares one.
207
- const databases = nodeArgs.length < args.length
208
- ? await testDatabaseRunFor(Math.max(1, Math.min(plan.concurrency, plan.files)))
209
- : null;
228
+ const asked = Math.max(1, Math.min(plan.concurrency, plan.files));
229
+ const databases = nodeArgs.length < args.length ? await testDatabaseRunFor(asked) : null;
230
+ const shortfall = databases ? databaseShortfall(databases, asked) : "";
210
231
  if (databases) {
211
232
  process.stderr.write(`jskit test: ${databases.summary}.\n`);
233
+ if (shortfall) process.stderr.write(`jskit test: ${shortfall}\n`);
212
234
  plan = planTestRuns(nodeArgs, { concurrency: databases.concurrency });
213
235
  }
214
236
  process.stderr.write(`jskit test: ${plan.concurrency} test file(s) at a time (${databases ? "test databases" : source}).\n`);
@@ -235,9 +257,14 @@ async function runTests(args) {
235
257
  }
236
258
  const times = interrupted
237
259
  ? null
238
- : reportTestTimes({ cwd: process.cwd(), collected, directory: timesDirectory, wallMs: performance.now() - started });
260
+ : reportTestTimes({ cwd: process.cwd(), collected, directory: timesDirectory, wallMs: performance.now() - started,
261
+ filtered: nodeArgs.some((argument) => TEST_FILTER.test(argument)) });
239
262
  if (times) process.stderr.write(times.report);
240
263
  if (times?.overruns.length > 0 && exitCode === 0) exitCode = 1;
264
+ if (shortfall && !interrupted) {
265
+ process.stderr.write(`jskit test: ${shortfall}\njskit test: the run fails: its test databases cost it concurrency.\n`);
266
+ if (exitCode === 0) exitCode = 1;
267
+ }
241
268
  } finally {
242
269
  // However the run ended, it drops its numbered test databases, and says what it dropped.
243
270
  const ended = await databases?.cleanup();
@@ -4,7 +4,9 @@ import { fileExists, toPosixPath } from "./files.mjs";
4
4
 
5
5
  // The test-run part of plain `jskit check`: every test run uses the machine's test budget, so a suite neither runs one
6
6
  // file at a time nor overwhelms the machine. A package script runs node's test runner through `jskit test`, passes no
7
- // fixed worker count, and the Playwright and Vitest configs its scripts use set their workers from testConcurrency().
7
+ // fixed worker count, and the configs its scripts use set their workers from the budget: Vitest's from
8
+ // testConcurrency(), Playwright's from browserTestWorkers(), half of it, since each worker drives a browser and often
9
+ // its own app server, about two threads (browserTestConfig() does that itself).
8
10
  // The one exception is a test file's own first line, `// jskit-test: alone - <reason>`, which `jskit test` honours.
9
11
  // A Playwright config those scripts use bounds its whole run (globalTimeout) and, when it starts the app (webServer),
10
12
  // does so through browserTestConfig(): the production build, and a server, port and database for each worker.
@@ -76,12 +78,14 @@ const RUNNERS = Object.freeze({
76
78
  rule: "test/playwright-workers",
77
79
  configNames: ["playwright"],
78
80
  setting: "workers",
81
+ budget: { module: BROWSER_TESTS_MODULE, call: "browserTestWorkers" },
79
82
  fixedArgument: FIXED_PLAYWRIGHT_WORKERS
80
83
  },
81
84
  vitest: {
82
85
  rule: "test/vitest-workers",
83
86
  configNames: ["vitest", "vite"],
84
87
  setting: "maxWorkers",
88
+ budget: { module: BUDGET_MODULE, call: "testConcurrency" },
85
89
  fixedArgument: FIXED_VITEST_WORKERS
86
90
  }
87
91
  });
@@ -125,8 +129,8 @@ function checkPlaywrightIsolation({ file, source, report }) {
125
129
 
126
130
  // A config sets the runner's workers from the budget, and Vitest's never turns file parallelism off.
127
131
  async function checkRunnerConfig({ root, configPath, directory, runner, report }) {
128
- const { rule, setting, configNames } = RUNNERS[runner];
129
- const wanted = `set \`${setting}: testConcurrency()\` from ${BUDGET_MODULE}`;
132
+ const { rule, setting, configNames, budget } = RUNNERS[runner];
133
+ const wanted = `set \`${setting}: ${budget.call}()\` from ${budget.module}`;
130
134
  if (!configPath || !(await fileExists(configPath))) {
131
135
  const missing = configPath || path.join(directory, `${configNames[0]}.config.*`);
132
136
  report({ file: toPosixPath(path.relative(root, missing)), line: 1, rule,
@@ -141,8 +145,13 @@ async function checkRunnerConfig({ root, configPath, directory, runner, report }
141
145
  report({ file, line: lineOf(source, "workers:"), rule,
142
146
  message: "playwright's workers are set over browserTestConfig()'s; drop them, so the machine's test budget sets them." });
143
147
  }
144
- } else if (!source.includes(BUDGET_MODULE) || !new RegExp(`\\b${setting}\\s*:\\s*testConcurrency\\(\\s*\\)`, "u").test(source)) {
145
- report({ file, line: lineOf(source, `${setting}:`), rule, message: `${runner} runs at a fixed or default worker count; ${wanted}.` });
148
+ } else if (!source.includes(budget.module) || !new RegExp(`\\b${setting}\\s*:\\s*${budget.call}\\(\\s*\\)`, "u").test(source)) {
149
+ // A Playwright worker drives a browser, and its own app server where the config starts one: two of the budget.
150
+ const message = runner === "playwright"
151
+ ? "playwright's workers are not browserTestWorkers(): each worker drives a browser, and its own app server where it " +
152
+ `starts one, about two threads, so it takes half the test budget (1 on a managed target); ${wanted}.`
153
+ : `${runner} runs at a fixed or default worker count; ${wanted}.`;
154
+ report({ file, line: lineOf(source, `${setting}:`), rule, message });
146
155
  }
147
156
  if (runner === "playwright") checkPlaywrightIsolation({ file, source, report });
148
157
  if (runner === "vitest" && /\bfileParallelism\s*:\s*false\b/u.test(source)) {
@@ -178,7 +187,7 @@ async function checkTestRuns({ projectRoot, manifests }) {
178
187
  const args = runnerArguments(tokens, runner);
179
188
  if (!args) continue;
180
189
  if (args.some((token) => RUNNERS[runner].fixedArgument.test(token))) {
181
- at(RUNNERS[runner].rule, `passes ${runner} a fixed worker count; drop it, so the config's testConcurrency() sets it.`);
190
+ at(RUNNERS[runner].rule, `passes ${runner} a fixed worker count; drop it, so the config's ${RUNNERS[runner].budget.call}() sets it.`);
182
191
  }
183
192
  const configPath = await findConfig(directory, configOption(args), RUNNERS[runner].configNames);
184
193
  configs.set(`${runner}\0${configPath || directory}`, { runner, configPath, directory });
@@ -122,14 +122,16 @@ function checkTestTimes({ bounds, files, tests, wallMs, stopped = [] }) {
122
122
 
123
123
  /**
124
124
  * Reads what the runs' reporters wrote and which files test-file-stop.mjs stopped, records each finished file's time
125
- * for the next command (a stopped file, or one that skipped a test, keeps the time it last finished all its tests in,
126
- * since the next stop is reckoned from it), and checks the times. A run whose
127
- * reporters were replaced (inside another node --test run) wrote nothing, and has no report unless a file was stopped.
128
- * @param {{ cwd: string, collected: string[], directory: string, wallMs: number }} options `collected`: the reporters'
129
- * destination files; `directory`: where the stopped files are written
125
+ * for the next command (a stopped file, one that skipped a test, and every file of a run filtered to some of its tests
126
+ * keep the time they last finished all their tests in, since the next stop is reckoned from it), and checks the times.
127
+ * A run whose reporters were replaced (inside another node --test run) wrote nothing, and has no report unless a file
128
+ * was stopped.
129
+ * @param {{ cwd: string, collected: string[], directory: string, wallMs: number, filtered?: boolean }} options
130
+ * `collected`: the reporters' destination files; `directory`: where the stopped files are written; `filtered`: the run
131
+ * ran only the tests a name pattern or `only` picked
130
132
  * @returns {{ overruns: string[], report: string } | null}
131
133
  */
132
- function reportTestTimes({ cwd, collected, directory, wallMs }) {
134
+ function reportTestTimes({ cwd, collected, directory, wallMs, filtered = false }) {
133
135
  const runs = collected.filter((file) => existsSync(file) && readFileSync(file, "utf8").trim())
134
136
  .map((file) => JSON.parse(readFileSync(file, "utf8")));
135
137
  const stopped = readdirSync(directory).filter((name) => name.startsWith(STOPPED_PREFIX)).sort()
@@ -137,7 +139,7 @@ function reportTestTimes({ cwd, collected, directory, wallMs }) {
137
139
  const files = Object.assign({}, ...runs.map((run) => run.files));
138
140
  if (Object.keys(files).length === 0 && stopped.length === 0) return null;
139
141
  const unrepresentative = new Set([...stopped.map((stop) => stop.file), ...runs.flatMap((run) => run.skipped ?? [])]);
140
- const finished = Object.fromEntries(Object.entries(files).filter(([name]) => !unrepresentative.has(name)));
142
+ const finished = filtered ? {} : Object.fromEntries(Object.entries(files).filter(([name]) => !unrepresentative.has(name)));
141
143
  const record = path.join(cwd, FILE_TIMES);
142
144
  const recorded = existsSync(record) ? JSON.parse(readFileSync(record, "utf8")) : {};
143
145
  mkdirSync(path.dirname(record), { recursive: true });