@jskit-ai/jskit-catalog 0.2.116 → 0.2.118

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.
@@ -8,6 +8,7 @@ import { toPosixPath } from "./files.mjs";
8
8
  import { BUDGET_VARIABLE, testConcurrency } from "./test-budget.mjs";
9
9
  import { DATABASES_OPTION, testDatabaseRunFor } from "./test-databases.mjs";
10
10
  import { useTestAppEnvironment } from "./test-environment.mjs";
11
+ import { networkGuardEnvironment, withoutNetworkGuard } from "./test-network-guard.mjs";
11
12
  import { STOPS_VARIABLE } from "./test-file-stop.mjs";
12
13
  import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
13
14
 
@@ -24,7 +25,10 @@ import { reportTestTimes, writeFileStops } from "./test-time-report.mjs";
24
25
  // should run files in parallel never silently runs them one at a time. A budget set to what the databases allow
25
26
  // (V64_TEST_CONCURRENCY) runs that way on purpose. With --list it prints the files that run would take, one per line,
26
27
  // then `Total: <n> file(s)` (the closing line Playwright's --list prints), and runs nothing: a host checks that a run
27
- // of named files takes exactly those before it sends them anywhere.
28
+ // of named files takes exactly those before it sends them anywhere. Every test file, and every process it starts with
29
+ // its environment, reaches only this machine and the test database (test-network-guard.mjs); a file that must reach
30
+ // an outside service says why on its first line, `// jskit-test: network - <reason>`, and runs without that guard, in
31
+ // a parallel run of its own after the others.
28
32
 
29
33
  // node --test's own default (Node 26) when it is given no files.
30
34
  const DEFAULT_PATTERN = "**/{test,test/**/*,test-*,*[._-]test}.{js,mjs,cjs,ts,mts,cts}";
@@ -35,7 +39,13 @@ const TEST_LIKE_PATTERN = "**/tests/**/*[._-]{integration,spec,specs,tests}.{js,
35
39
  const OTHER_RUNNER_FOLDER = /(?:^|\/)(?:e2e|browser)\//u;
36
40
  const OTHER_RUNNER_IMPORT = /\b(?:from|import|require)\s*\(?\s*["'](?:vitest|@playwright\/test)["']/u;
37
41
  const MARKER = /^\s*\/\/\s*jskit-test:(.*)$/u;
38
- const ALONE = /^\s*alone\s+-\s+(\S.*)$/u;
42
+ // jskit check's marker for the wait on the line after it (test-sources.mjs), wherever that is: not a file marker.
43
+ const CHECK_MARKER = /^\s*fixed-wait\b/u;
44
+ const MARKED = /^\s*(alone|network)\s+-\s+(\S.*)$/u;
45
+ const MARKER_FORMS = Object.freeze({
46
+ alone: "`// jskit-test: alone - <why this file cannot run beside others>`",
47
+ network: "`// jskit-test: network - <why this file must reach an outside service>`"
48
+ });
39
49
  const SHARD = "--test-shard";
40
50
  // A run of only some of its files' tests, by name or `only`, says nothing about how long a whole file takes.
41
51
  const TEST_FILTER = /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/u;
@@ -64,57 +74,63 @@ function missedTestFiles(defaultFiles, cwd) {
64
74
  }
65
75
 
66
76
  /**
67
- * The files of a run that must run alone, from their first line. A marker that is malformed or not on the first line
68
- * (after a shebang) is an error, so a file never runs in parallel because its marker was missed.
69
- * @returns {{ alone: Array<{ file: string, reason: string }>, problems: string[] }}
77
+ * The files of a run that must run alone, or reach an outside service, from their first line. A marker that is
78
+ * malformed or not on the first line (after a shebang) is an error, so a file never runs in parallel, or unguarded,
79
+ * because its marker was missed. jskit check's fixed-wait marker is its own, on any line, and left to it.
80
+ * @returns {{ alone: Array<{ file: string, reason: string }>, network: Array<{ file: string, reason: string }>, problems: string[] }}
70
81
  */
71
- function readAloneFiles(files, cwd) {
72
- const alone = [];
82
+ function readMarkedFiles(files, cwd) {
83
+ const marked = { alone: [], network: [] };
73
84
  const problems = [];
74
85
  for (const file of files) {
75
86
  const lines = readFileSync(path.resolve(cwd, file), "utf8").split("\n");
76
87
  const top = lines[0]?.startsWith("#!") ? 1 : 0;
77
88
  lines.forEach((line, index) => {
78
89
  const marker = MARKER.exec(line);
79
- if (!marker) return;
80
- const reason = ALONE.exec(marker[1])?.[1]?.trim();
90
+ if (!marker || CHECK_MARKER.test(marker[1])) return;
91
+ const [, kind, reason] = MARKED.exec(marker[1]) || [];
92
+ const meant = /^\s*network\b/u.test(marker[1]) ? MARKER_FORMS.network : MARKER_FORMS.alone;
81
93
  if (index !== top) problems.push(`${file}:${index + 1}: a jskit-test marker belongs on the file's first line.`);
82
- else if (!reason) problems.push(`${file}:${index + 1}: write it as \`// jskit-test: alone - <why this file cannot run beside others>\`.`);
83
- else alone.push({ file, reason });
94
+ else if (!reason?.trim()) problems.push(`${file}:${index + 1}: write it as ${meant}.`);
95
+ else marked[kind].push({ file, reason: reason.trim() });
84
96
  });
85
97
  }
86
- return { alone, problems };
98
+ return { ...marked, problems };
87
99
  }
88
100
 
89
- /** A reporter's file destination for the alone run, beside the parallel run's: `<name>.alone<ext>`; streams stay. */
90
- function aloneDestination(destination) {
101
+ /** A reporter's file destination for a run of marked files, beside the parallel run's (`<name>.<kind><ext>`); streams stay. */
102
+ function markedDestination(destination, kind) {
91
103
  if (STREAM_DESTINATIONS.has(destination)) return destination;
92
104
  const { dir, name, ext } = path.parse(destination);
93
- return path.join(dir, `${name}.alone${ext}`);
105
+ return path.join(dir, `${name}.${kind}${ext}`);
94
106
  }
95
107
 
96
108
  /**
97
- * The alone run's options: the parallel run's, with each file destination moved beside it and without the shard, which
98
- * `aloneShard` has already applied to the alone files.
109
+ * A run of marked files' options: the parallel run's, with each file destination moved beside it and without the
110
+ * shard, which `markedShard` has already applied to those files.
99
111
  * @param {string[]} options
112
+ * @param {"alone" | "network"} kind
100
113
  */
101
- function aloneRunOptions(options) {
114
+ function markedRunOptions(options, kind) {
102
115
  const result = [];
103
116
  for (let index = 0; index < options.length; index += 1) {
104
117
  const option = options[index];
105
118
  if (option === SHARD) index += 1;
106
119
  else if (option.startsWith(`${SHARD}=`)) continue;
107
120
  else if (option === DESTINATION && index + 1 < options.length) {
108
- result.push(option, aloneDestination(options[index + 1]));
121
+ result.push(option, markedDestination(options[index + 1], kind));
109
122
  index += 1;
110
- } else if (option.startsWith(`${DESTINATION}=`)) result.push(`${DESTINATION}=${aloneDestination(option.slice(DESTINATION.length + 1))}`);
123
+ } else if (option.startsWith(`${DESTINATION}=`)) result.push(`${DESTINATION}=${markedDestination(option.slice(DESTINATION.length + 1), kind)}`);
111
124
  else result.push(option);
112
125
  }
113
126
  return result;
114
127
  }
115
128
 
116
- /** The alone files of this run's shard (`--test-shard=<index>/<total>`), as node --test picks a shard's files. */
117
- function aloneShard(files, options) {
129
+ /**
130
+ * The marked files (alone or network) of this run's shard (`--test-shard=<index>/<total>`), as node --test picks a
131
+ * shard's files.
132
+ */
133
+ function markedShard(files, options) {
118
134
  const at = options.findIndex((option) => option === SHARD || option.startsWith(`${SHARD}=`));
119
135
  if (at < 0) return files;
120
136
  const [index, total] = (options[at] === SHARD ? options[at + 1] : options[at].slice(SHARD.length + 1)).split("/").map(Number);
@@ -122,7 +138,9 @@ function aloneShard(files, options) {
122
138
  }
123
139
 
124
140
  /**
125
- * The node --test runs for these arguments: one in parallel within the budget, then the files that must run alone.
141
+ * The node --test runs for these arguments: one in parallel within the budget, then the files that must reach an
142
+ * outside service, in parallel too, then the files that must run alone. `guarded` says, for each run, whether its
143
+ * processes get the network guard: all but the run of network files.
126
144
  * @param {string[]} args the arguments after `jskit test`
127
145
  * @param {{ cwd?: string, concurrency?: number }} [options]
128
146
  */
@@ -144,24 +162,34 @@ function planTestRuns(args, { cwd = process.cwd(), concurrency = testConcurrency
144
162
  `- ${missed.join("\n- ")}\nRename each to end in .test.js (a database test: <name>.integration.test.js), or ` +
145
163
  "name the files to run.");
146
164
  }
147
- const { alone, problems } = readAloneFiles(files, cwd);
165
+ const { alone, network, problems } = readMarkedFiles(files, cwd);
148
166
  if (problems.length > 0) throw new Error(`jskit test:\n- ${problems.join("\n- ")}`);
149
167
  const parallel = ["--test", `--test-concurrency=${concurrency}`];
150
- if (alone.length < 1) return { concurrency, files: files.length, paths: files, alone, runs: [[...parallel, ...args]] };
168
+ if (alone.length < 1 && network.length < 1) {
169
+ return { concurrency, files: files.length, paths: files, alone, network, runs: [[...parallel, ...args]], guarded: [true] };
170
+ }
151
171
 
152
172
  const options = args.filter((argument) => !(matched.get(argument)?.length > 0));
153
- const aloneFiles = new Set(alone.map((entry) => entry.file));
154
- const others = files.filter((file) => !aloneFiles.has(file));
155
- const shardAlone = aloneShard([...aloneFiles], options);
173
+ const marked = new Set([...alone, ...network].map((entry) => entry.file));
174
+ const others = files.filter((file) => !marked.has(file));
175
+ const shardNetwork = markedShard(network.map((entry) => entry.file), options);
176
+ const shardAlone = markedShard(alone.map((entry) => entry.file), options);
177
+ const runs = [
178
+ ...(others.length > 0 ? [{ run: [...parallel, ...options, ...others], guarded: true }] : []),
179
+ ...(shardNetwork.length > 0 ? [{ run: [...parallel, ...markedRunOptions(options, "network"), ...shardNetwork], guarded: false }] : []),
180
+ ...(shardAlone.length > 0
181
+ ? [{ run: ["--test", "--test-concurrency=1", ...markedRunOptions(options, "alone"), ...shardAlone], guarded: true }]
182
+ : [])
183
+ ];
156
184
  return {
157
185
  concurrency,
158
- files: others.length,
186
+ // The most files running at once: the guarded ones, then the network ones, each run in parallel.
187
+ files: Math.max(others.length, network.length),
159
188
  paths: files,
160
189
  alone,
161
- runs: [
162
- ...(others.length > 0 ? [[...parallel, ...options, ...others]] : []),
163
- ...(shardAlone.length > 0 ? [["--test", "--test-concurrency=1", ...aloneRunOptions(options), ...shardAlone]] : [])
164
- ]
190
+ network,
191
+ runs: runs.map(({ run }) => run),
192
+ guarded: runs.map(({ guarded }) => guarded)
165
193
  };
166
194
  }
167
195
 
@@ -247,6 +275,7 @@ async function runTests(args) {
247
275
  }
248
276
  process.stderr.write(`jskit test: ${plan.concurrency} test file(s) at a time (${databases ? "test databases" : source}).\n`);
249
277
  for (const { file, reason } of plan.alone) process.stderr.write(`jskit test: ${file} runs alone: ${reason}\n`);
278
+ for (const { file, reason } of plan.network) process.stderr.write(`jskit test: ${file} reaches the network: ${reason}\n`);
250
279
  const preload = [...(databases?.preload ? ["--import", pathToFileURL(databases.preload).href] : []), "--import", FILE_STOP];
251
280
  const timesDirectory = mkdtempSync(path.join(os.tmpdir(), "jskit-test-times-"));
252
281
  const stops = writeFileStops({ cwd: process.cwd(), files: plan.paths, directory: timesDirectory });
@@ -259,7 +288,11 @@ async function runTests(args) {
259
288
  const env = {
260
289
  NODE_COMPILE_CACHE: process.env.NODE_COMPILE_CACHE || path.resolve(COMPILE_CACHE),
261
290
  [STOPS_VARIABLE]: stops,
262
- ...databases?.env
291
+ ...databases?.env,
292
+ // Its test files, and what they start, reach only this machine and the test database; network files, anywhere.
293
+ ...(plan.guarded[index]
294
+ ? networkGuardEnvironment(process.env, "jskit test")
295
+ : { NODE_OPTIONS: withoutNetworkGuard(process.env.NODE_OPTIONS) })
263
296
  };
264
297
  const { code, signal } = await runNode([...preload, ...withTimeReporter(run, collected[index])], env);
265
298
  if (exitCode === 0) exitCode = code;
@@ -278,9 +311,8 @@ async function runTests(args) {
278
311
  if (exitCode === 0) exitCode = 1;
279
312
  }
280
313
  } finally {
281
- // However the run ended, it drops its numbered test databases, and says what it dropped.
282
- const ended = await databases?.cleanup();
283
- if (ended) process.stderr.write(`jskit test: ${ended}.\n`);
314
+ // However the run ended, its settings go; its test databases stay for the next run, which restores them.
315
+ await databases?.cleanup();
284
316
  rmSync(timesDirectory, { recursive: true, force: true });
285
317
  }
286
318
  return exitCode;
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import process from "node:process";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { readTableResourceSources } from "./data-access.mjs";
7
+ import { useTestAppEnvironment } from "./test-environment.mjs";
7
8
 
8
9
  // `jskit test --databases`: each test file running at once gets a database of its own, a copy of TEST_DB_NAME restored
9
10
  // from a schema snapshot, from the application's installed @jskit-ai/database-runtime and its knexfile.js, which loads
@@ -123,8 +124,8 @@ async function applicationTestDatabases(cwd, command) {
123
124
 
124
125
  /**
125
126
  * The run's databases for `count` files at once, or one file at a time on the connected database. Its `cleanup()` ends
126
- * the run: it removes the run's settings and drops its numbered copies of TEST_DB_NAME, answering what it dropped (an
127
- * installed @jskit-ai/database-runtime from before that answers nothing and leaves the copies).
127
+ * the run: it removes the run's settings, and the databases stay for the next run (an installed
128
+ * @jskit-ai/database-runtime from before drops the numbered copies, and answers what it dropped).
128
129
  * @param {number} count at most the run's test budget, and no more than its test files
129
130
  * @param {string} [cwd]
130
131
  * @returns {Promise<{ concurrency: number, env: Record<string, string>, preload: string, summary: string,
@@ -137,12 +138,14 @@ async function testDatabaseRunFor(count, cwd = process.cwd()) {
137
138
 
138
139
  /**
139
140
  * `jskit migration-history`: the full-history migration proof of the application in `cwd` (proveMigrationHistory() in
140
- * @jskit-ai/database-runtime), written to stdout, or why it failed to stderr. Answers the exit code.
141
+ * @jskit-ai/database-runtime), written to stdout, or why it failed to stderr. Answers the exit code. It runs as
142
+ * APP_ENV=test, as `jskit test` does, and throws where APP_ENV is staging or production.
141
143
  * @param {string} [cwd]
142
144
  * @returns {Promise<number>}
143
145
  */
144
146
  async function runMigrationHistory(cwd = process.cwd()) {
145
147
  const command = "jskit migration-history";
148
+ useTestAppEnvironment(process.env, command);
146
149
  try {
147
150
  const { knexConfig, schema, environment, runtime } = await applicationTestDatabases(cwd, command);
148
151
  if (!runtime.proveMigrationHistory) {
@@ -1,11 +1,14 @@
1
- // Tests run as APP_ENV=test: `jskit test` and the browser test servers set it, whatever the shell says, so a test
2
- // never sends real email or payments and the test databases may be prepared. A shell whose APP_ENV is staging or
3
- // production belongs to a staging or production server, and no test runs there.
1
+ // Tests run as APP_ENV=test: `jskit test`, `jskit migration-history` and the browser test servers set it, whatever the
2
+ // shell says, so a test never sends real email or payments and the test databases may be prepared. A shell whose
3
+ // APP_ENV is staging or production belongs to a staging or production server, and no test runs there. They log at
4
+ // warn unless the shell's LOG_LEVEL asks for more, so a test server does not log every request and a failure stays
5
+ // readable (an app's logger options take their level from LOG_LEVEL).
4
6
 
5
7
  const STAGING_AND_PRODUCTION = Object.freeze(["staging", "production"]);
6
8
 
7
9
  /**
8
- * Sets `env.APP_ENV` to test, or throws, naming the fix, when it says staging or production.
10
+ * Sets `env.APP_ENV` to test, and `env.LOG_LEVEL` to warn when it names no level; throws, naming the fix, when APP_ENV
11
+ * says staging or production.
9
12
  * @param {Record<string, string | undefined>} env The process environment, changed in place.
10
13
  * @param {string} command The command that runs the tests, for the refusal.
11
14
  */
@@ -18,6 +21,7 @@ function useTestAppEnvironment(env, command) {
18
21
  );
19
22
  }
20
23
  env.APP_ENV = "test";
24
+ if (!String(env.LOG_LEVEL ?? "").trim()) env.LOG_LEVEL = "warn";
21
25
  }
22
26
 
23
27
  export { useTestAppEnvironment };
@@ -0,0 +1,5 @@
1
+ // Preloaded through NODE_OPTIONS (`--import`) into every process `jskit test` and the browser test servers start, and
2
+ // so into the processes those start with the same environment: guards its outbound connections (test-network-guard.mjs).
3
+ import { installNetworkGuard } from "./test-network-guard.mjs";
4
+
5
+ installNetworkGuard();
@@ -0,0 +1,133 @@
1
+ // The test network guard: a test, and every app server and process it starts, reaches only this machine and the test
2
+ // database. `jskit test` and the browser test servers give their processes NODE_OPTIONS with the guard's preload
3
+ // (test-network-guard-preload.mjs), so a process those start with the same environment is guarded too. Every outbound
4
+ // TCP connection a guarded Node process makes passes through net.Socket.prototype.connect (net.connect, tls.connect,
5
+ // http and https agents, fetch); the guard lets through loopback addresses, `localhost` names, unix sockets and named
6
+ // pipes, and the database host the environment names (DB_HOST, DATABASE_URL's host, read when the connection is made),
7
+ // and refuses every other host before any name is looked up: the socket fails with JSKIT_TEST_NETWORK_REFUSED, naming
8
+ // the host and the fix, and the same line goes to stderr once per host, so an app that swallows the error still shows
9
+ // it. A test that reaches a real outside service (an AI provider, a payment or mail API, a hosting API) costs money,
10
+ // sends real messages or changes real data whenever a developer's keys sit in the environment the test inherits. A file
11
+ // that must reach one says why on its first line, `// jskit-test: network - <reason>`, and `jskit test` runs it
12
+ // without the guard (test-command.mjs).
13
+ import net from "node:net";
14
+ import process from "node:process";
15
+
16
+ const NETWORK_REFUSED_CODE = "JSKIT_TEST_NETWORK_REFUSED";
17
+ // Names the command whose processes are guarded, for the refusal: `jskit test` or `jskit browser tests`.
18
+ const NETWORK_GUARD_VARIABLE = "JSKIT_TEST_NETWORK_GUARD";
19
+ const NETWORK_GUARD_PRELOAD = new URL("./test-network-guard-preload.mjs", import.meta.url).href;
20
+ const PRELOAD_OPTION = `--import=${NETWORK_GUARD_PRELOAD}`;
21
+ const INSTALLED = Symbol.for("@jskit-ai/jskit-catalog/testNetworkGuard");
22
+ const BROWSER_TESTS = "jskit browser tests";
23
+
24
+ // This machine: IPv4 loopback, IPv6 loopback and IPv4 loopback mapped into IPv6, and the unspecified addresses, which
25
+ // a connection on Linux reaches as this machine (a test connecting to the address its server listened on, `::`).
26
+ const LOOPBACK = new net.BlockList();
27
+ LOOPBACK.addSubnet("127.0.0.0", 8, "ipv4");
28
+ LOOPBACK.addAddress("0.0.0.0", "ipv4");
29
+ LOOPBACK.addAddress("::1", "ipv6");
30
+ LOOPBACK.addAddress("::", "ipv6");
31
+ LOOPBACK.addSubnet("::ffff:127.0.0.0", 104, "ipv6");
32
+
33
+ const hostName = (host) => String(host ?? "").trim().toLowerCase().replace(/^\[(.*)\]$/u, "$1").replace(/\.$/u, "");
34
+
35
+ /** The database hosts the environment names now: DB_HOST, and DATABASE_URL's host. */
36
+ function databaseHosts(env) {
37
+ const hosts = [hostName(env.DB_HOST)];
38
+ try {
39
+ hosts.push(hostName(new URL(String(env.DATABASE_URL ?? "")).hostname));
40
+ } catch {
41
+ // No DATABASE_URL, or one that names no host.
42
+ }
43
+ return hosts.filter(Boolean);
44
+ }
45
+
46
+ /**
47
+ * Whether a guarded test process may connect to `host`: loopback, a `localhost` name, or a database host `env` names.
48
+ * @param {string} host
49
+ * @param {Record<string, string | undefined>} env
50
+ */
51
+ function isAllowedTestHost(host, env) {
52
+ const name = hostName(host);
53
+ if (name === "localhost" || name.endsWith(".localhost") || databaseHosts(env).includes(name)) return true;
54
+ const family = net.isIP(name);
55
+ return family !== 0 && LOOPBACK.check(name, family === 4 ? "ipv4" : "ipv6");
56
+ }
57
+
58
+ /** NODE_OPTIONS without the guard's preload. */
59
+ function withoutNetworkGuard(nodeOptions) {
60
+ return String(nodeOptions ?? "").split(PRELOAD_OPTION).map((part) => part.trim()).filter(Boolean).join(" ");
61
+ }
62
+
63
+ /**
64
+ * The variables that guard the processes started with them: NODE_OPTIONS with the guard's preload added once, and the
65
+ * command that guards them, for the refusal.
66
+ * @param {Record<string, string | undefined>} env the environment the processes would get
67
+ * @param {string} command `jskit test` or `jskit browser tests`
68
+ */
69
+ function networkGuardEnvironment(env, command) {
70
+ return {
71
+ NODE_OPTIONS: [withoutNetworkGuard(env.NODE_OPTIONS), PRELOAD_OPTION].filter(Boolean).join(" "),
72
+ [NETWORK_GUARD_VARIABLE]: command
73
+ };
74
+ }
75
+
76
+ function refusal(command, host, port) {
77
+ const target = `${host}${port ? `:${port}` : ""}`;
78
+ const fix = command === BROWSER_TESTS
79
+ ? "Stub it at the seam the app already uses: a test-only driver or env value, in browserTestConfig()'s `env` or its " +
80
+ "`prepare` module, pointing at a local fake."
81
+ : "Stub it at the seam the app already uses (an injected client or provider double, a test-only env value pointing " +
82
+ "at a local fake); a test file that must reach it says why on its first line: `// jskit-test: network - <reason>`.";
83
+ const error = new Error(`${command} refused a connection to ${target}: tests never reach an outside service. ${fix} ` +
84
+ "Tests reach only loopback, unix sockets and the database host (DB_HOST, DATABASE_URL).");
85
+ return Object.assign(error, { code: NETWORK_REFUSED_CODE, host, port });
86
+ }
87
+
88
+ /** Where a call to net.Socket.prototype.connect goes, as net reads its arguments: a path, or a host and port. */
89
+ function connectTarget(args) {
90
+ let first = args[0];
91
+ // net.connect() hands the socket its arguments already read, as an array.
92
+ if (Array.isArray(first)) first = first[0];
93
+ if (first !== null && typeof first === "object") {
94
+ if (first.path) return { path: String(first.path) };
95
+ return { host: first.host || "localhost", port: first.port };
96
+ }
97
+ if (typeof first === "string" && !/^\s*\d+\s*$/u.test(first)) return { path: first };
98
+ return { host: typeof args[1] === "string" && args[1] ? args[1] : "localhost", port: first };
99
+ }
100
+
101
+ /**
102
+ * Guards this process's outbound connections. Calling it again changes nothing.
103
+ * @param {{ env?: Record<string, string | undefined>, command?: string, stderr?: { write(text: string): unknown } }} [options]
104
+ */
105
+ function installNetworkGuard({ env = process.env, command = env[NETWORK_GUARD_VARIABLE] || "jskit test", stderr = process.stderr } = {}) {
106
+ if (net.Socket.prototype.connect[INSTALLED]) return;
107
+ const connect = net.Socket.prototype.connect;
108
+ const reported = new Set();
109
+ function guardedConnect(...args) {
110
+ const target = connectTarget(args);
111
+ if (target.path !== undefined || isAllowedTestHost(target.host, env)) return connect.apply(this, args);
112
+ const error = refusal(command, hostName(target.host), target.port);
113
+ if (!reported.has(error.host)) {
114
+ reported.add(error.host);
115
+ stderr.write(`${error.message}\n`);
116
+ }
117
+ // As a failed connection does: the error comes after connect() returns, so its caller's listeners hear it.
118
+ process.nextTick(() => this.destroy(error));
119
+ return this;
120
+ }
121
+ guardedConnect[INSTALLED] = true;
122
+ net.Socket.prototype.connect = guardedConnect;
123
+ }
124
+
125
+ export {
126
+ NETWORK_GUARD_PRELOAD,
127
+ NETWORK_GUARD_VARIABLE,
128
+ NETWORK_REFUSED_CODE,
129
+ installNetworkGuard,
130
+ isAllowedTestHost,
131
+ networkGuardEnvironment,
132
+ withoutNetworkGuard
133
+ };
@@ -10,6 +10,8 @@ import { fileExists, toPosixPath } from "./files.mjs";
10
10
  // The one exception is a test file's own first line, `// jskit-test: alone - <reason>`, which `jskit test` honours.
11
11
  // A Playwright config those scripts use bounds its whole run (globalTimeout) and, when it starts the app (webServer),
12
12
  // does so through browserTestConfig(): the production build, and a server, port and database for each worker.
13
+ // An app's server/lib/loggerOptions.js (the foundation patterns') takes its level from LOG_LEVEL, which `jskit test` and
14
+ // the browser test servers set to warn, so a test server does not log every request.
13
15
 
14
16
  const GUIDE = "https://mobily-enterprises.github.io/jskit-ai/guide/framework/typed-features#test-files-run-in-parallel";
15
17
  const BUDGET_MODULE = "@jskit-ai/jskit-catalog/test-budget";
@@ -21,6 +23,7 @@ const PINNED_BUDGET = /^(?:V64_TEST_CONCURRENCY|PLAYWRIGHT_WORKERS)=/u;
21
23
  const CONFIG_EXTENSIONS = Object.freeze(["ts", "mts", "cts", "js", "mjs", "cjs"]);
22
24
  const SCRIPT_FILE = /\.(?:[cm]?[jt]s|jsx|tsx)$/u;
23
25
  const FIXED_PLAYWRIGHT_WORKERS = /^(?:--workers(?:=.*)?|-j.*)$/u;
26
+ const LOGGER_OPTIONS = "server/lib/loggerOptions.js";
24
27
  const FIXED_VITEST_WORKERS = /^--(?:max-?[wW]orkers|min-?[wW]orkers|no-file-?[pP]arallelism|file-?[pP]arallelism)(?:=.*)?$/u;
25
28
 
26
29
  function commandsOf(script) {
@@ -127,6 +130,18 @@ function checkPlaywrightIsolation({ file, source, report }) {
127
130
  }
128
131
  }
129
132
 
133
+ // The app's logger options take their level from LOG_LEVEL.
134
+ async function checkLoggerLevel({ root, report }) {
135
+ const file = path.join(root, LOGGER_OPTIONS);
136
+ if (!(await fileExists(file))) return;
137
+ const source = await readFile(file, "utf8");
138
+ if (source.includes("LOG_LEVEL")) return;
139
+ report({ file: LOGGER_OPTIONS, line: lineOf(source, "function buildLoggerOptions"), rule: "test/log-level",
140
+ message: "buildLoggerOptions() takes no level from LOG_LEVEL, so a test server logs every request at info: give its " +
141
+ 'options `level: String(runtimeEnv.LOG_LEVEL || "").trim() || "info"` and pass it server.js\'s runtimeEnv; ' +
142
+ "`jskit test` and the browser test servers set LOG_LEVEL=warn." });
143
+ }
144
+
130
145
  // A config sets the runner's workers from the budget, and Vitest's never turns file parallelism off.
131
146
  async function checkRunnerConfig({ root, configPath, directory, runner, report }) {
132
147
  const { rule, setting, configNames, budget } = RUNNERS[runner];
@@ -196,6 +211,7 @@ async function checkTestRuns({ projectRoot, manifests }) {
196
211
  }
197
212
  }
198
213
  for (const config of configs.values()) await checkRunnerConfig({ root, report, ...config });
214
+ await checkLoggerLevel({ root, report });
199
215
  findings.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line);
200
216
  return { ok: findings.length < 1, findings, manifests: manifests.length };
201
217
  }