tina4-nodejs 3.13.163 → 3.13.165

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.
@@ -0,0 +1,129 @@
1
+ /*
2
+ Copyright (c) 2026 Code Infinity
3
+ SPDX-License-Identifier: MPL-2.0
4
+ This Source Code Form is subject to the terms of the Mozilla Public
5
+ License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+
9
+ /**
10
+ * Run a program that may be a Windows batch file (`.cmd` / `.bat`).
11
+ *
12
+ * Since the 2024 BatBadBut fix (CVE-2024-27980) Node refuses to spawn a batch
13
+ * file without a shell: `spawnSync("C:\\...\\npm.cmd", args)` fails with EINVAL.
14
+ * The other three Tina4 frameworks start batch files directly, so `npm.cmd`
15
+ * and a `tina4.cmd` client have to work here too.
16
+ *
17
+ * Handing the arguments to `shell: true` is not the fix: Node joins them with
18
+ * spaces and no escaping, so an argument such as `a&calc` would run `calc`.
19
+ * Instead the command line is built here the way cross-spawn builds it
20
+ * (https://qntm.org/cmd): each argument is quoted, embedded quotes and the
21
+ * backslashes before them are escaped, and every cmd.exe metacharacter is
22
+ * caret-escaped TWICE - once for the `cmd /c` line, once more because a batch
23
+ * file re-parses the `%*` it forwards. The line goes to cmd.exe verbatim
24
+ * (`windowsVerbatimArguments`) so libuv adds no quoting of its own.
25
+ *
26
+ * Anything that is not a batch file, and every non-Windows platform, is spawned
27
+ * exactly as before.
28
+ */
29
+ import { spawnSync } from "node:child_process";
30
+ import type { SpawnSyncOptions, SpawnSyncReturns } from "node:child_process";
31
+ import { existsSync, statSync } from "node:fs";
32
+ import { delimiter, extname, join } from "node:path";
33
+
34
+ /** cmd.exe metacharacters, the same set cross-spawn escapes. */
35
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
36
+
37
+ /** True when `file` is a batch file that Node will not spawn without a shell. */
38
+ export function isBatchFile(file: string, platform: NodeJS.Platform = process.platform): boolean {
39
+ return platform === "win32" && /\.(cmd|bat)$/i.test(file);
40
+ }
41
+
42
+ /** One argument, quoted and escaped for a batch file run through `cmd /d /s /c`. */
43
+ export function escapeBatchArgument(arg: string): string {
44
+ let quoted = String(arg)
45
+ // backslashes before a quote double, and the quote is backslash-escaped
46
+ .replace(/(\\*)"/g, '$1$1\\"')
47
+ // backslashes before the closing quote we are about to add double too
48
+ .replace(/(\\*)$/, "$1$1");
49
+ quoted = `"${quoted}"`;
50
+ return quoted.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
51
+ }
52
+
53
+ /** The batch file's own path, escaped for the head of the `cmd /c` line. */
54
+ function escapeBatchCommand(file: string): string {
55
+ return file.replace(CMD_META, "^$1");
56
+ }
57
+
58
+ /**
59
+ * Resolve a bare program name such as `npm` to the file Windows would run.
60
+ *
61
+ * Without a shell, Windows' CreateProcess only adds `.exe`, so `npm` (which is
62
+ * `npm.cmd`) is never found and the spawn fails with ENOENT. This walks PATH
63
+ * with PATHEXT the way cmd.exe does. A name that already has a directory or an
64
+ * extension, every other platform, and a name that is not found are returned
65
+ * unchanged, so the spawn reports its own error exactly as before.
66
+ */
67
+ export function findExecutable(name: string, platform: NodeJS.Platform = process.platform): string {
68
+ if (platform !== "win32" || /[\\/]/.test(name) || extname(name) !== "") return name;
69
+ const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
70
+ const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
71
+ // PATH order first, then PATHEXT order within each directory, as cmd.exe does.
72
+ const candidates = dirs.flatMap((dir) => exts.map((ext) => join(dir, name + ext.toLowerCase())));
73
+ return candidates.find(isRegularFile) ?? name;
74
+ }
75
+
76
+ /** True when `path` exists and is a file (a directory named `npm.cmd` is not). */
77
+ function isRegularFile(path: string): boolean {
78
+ try {
79
+ return existsSync(path) && statSync(path).isFile();
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * `spawnSync`, except that a batch file on Windows runs through cmd.exe with
87
+ * every argument escaped. Returns what spawnSync returns either way.
88
+ */
89
+ export function spawnSyncAllowingBatch(
90
+ file: string,
91
+ args: readonly string[],
92
+ options: SpawnSyncOptions = {},
93
+ ): SpawnSyncReturns<Buffer | string> {
94
+ if (!isBatchFile(file)) return spawnSync(file, args, options);
95
+ const line = [escapeBatchCommand(file), ...args.map(escapeBatchArgument)].join(" ");
96
+ const shell = process.env.comspec || "cmd.exe";
97
+ return spawnSync(shell, ["/d", "/s", "/c", `"${line}"`], {
98
+ ...options,
99
+ windowsVerbatimArguments: true,
100
+ });
101
+ }
102
+
103
+ /**
104
+ * `execFileSync` for a bare program name (`npm`, `npx`) that may be a batch
105
+ * file: resolves it with {@link findExecutable}, runs it with
106
+ * {@link spawnSyncAllowingBatch}, and like execFileSync returns stdout and
107
+ * throws on a spawn error or a non-zero exit (the error carries `status`,
108
+ * `stdout` and `stderr`).
109
+ */
110
+ export function execFileSyncAllowingBatch(
111
+ name: string,
112
+ args: readonly string[],
113
+ options: SpawnSyncOptions = {},
114
+ ): string {
115
+ const result = spawnSyncAllowingBatch(findExecutable(name), args, { encoding: "utf-8", ...options });
116
+ if (result.error) throw result.error;
117
+ const stdout = String(result.stdout ?? "");
118
+ const stderr = String(result.stderr ?? "");
119
+ if (result.status !== 0) {
120
+ const err = new Error(
121
+ `Command failed: ${name} ${args.join(" ")} (exit ${result.status ?? result.signal})\n${stderr}`.trim(),
122
+ ) as Error & { status: number | null; stdout: string; stderr: string };
123
+ err.status = result.status;
124
+ err.stdout = stdout;
125
+ err.stderr = stderr;
126
+ throw err;
127
+ }
128
+ return stdout;
129
+ }
@@ -21,6 +21,7 @@ import { cpus as osCpus } from "node:os";
21
21
  import { rtrimSlashes } from "./slashTrim.js";
22
22
  import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync, copyFileSync, statSync, openSync, closeSync, fstatSync, fchmodSync, ftruncateSync, constants, realpathSync, lstatSync } from "node:fs";
23
23
  import { join, dirname, resolve, relative, sep, basename } from "node:path";
24
+ import { execFileSyncAllowingBatch } from "./batchSpawn.js";
24
25
  import { fileURLToPath } from "node:url";
25
26
  import type { Router } from "./router.js";
26
27
  import type { RouteHandler, Tina4Request } from "./types.js";
@@ -1102,6 +1103,9 @@ const handleSystem: RouteHandler = async (_req, res) => {
1102
1103
  const mem = process.memoryUsage();
1103
1104
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
1104
1105
  const rssMb = Math.round(mem.rss / 1048576);
1106
+ // Peak RSS: ru_maxrss, which libuv reports in kilobytes on every platform
1107
+ // (it converts macOS bytes). The current RSS is not the peak.
1108
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
1105
1109
  let dbTableCount: number | undefined;
1106
1110
  let dbConnected = false;
1107
1111
  try {
@@ -1118,12 +1122,14 @@ const handleSystem: RouteHandler = async (_req, res) => {
1118
1122
  architecture: process.arch,
1119
1123
  os: `${process.platform} ${process.arch}`,
1120
1124
  pid: process.pid,
1121
- memory_mb: heapUsedMb,
1125
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
1126
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
1127
+ memory_mb: rssMb,
1122
1128
  db_tables: dbTableCount !== undefined ? dbTableCount : "N/A",
1123
1129
  db_connected: dbConnected,
1124
1130
  memory: {
1125
- current_mb: heapUsedMb,
1126
- peak_mb: rssMb,
1131
+ current_mb: rssMb,
1132
+ peak_mb: peakRssMb,
1127
1133
  limit: "V8 default",
1128
1134
  rss: `${rssMb} MB`,
1129
1135
  heapUsed: `${heapUsedMb} MB`,
@@ -2747,13 +2753,12 @@ const handleDepsInstall: RouteHandler = async (req, res) => {
2747
2753
  return;
2748
2754
  }
2749
2755
  try {
2750
- const { execFileSync } = await import("node:child_process");
2751
2756
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
2752
- const output = execFileSync("npm", args, {
2757
+ // npm is npm.cmd on Windows, which execFileSync cannot find or start.
2758
+ const output = execFileSyncAllowingBatch("npm", args, {
2753
2759
  cwd: resolve(process.cwd()),
2754
2760
  timeout: 120_000,
2755
- encoding: "utf-8",
2756
- }).toString();
2761
+ });
2757
2762
  res.json({ ok: true, package: pkg, output });
2758
2763
  } catch (e) {
2759
2764
  res.json({ error: (e as Error).message }, 500);
@@ -2989,12 +2994,11 @@ const handleScaffoldRun: RouteHandler = async (req, res) => {
2989
2994
  return;
2990
2995
  }
2991
2996
  try {
2992
- const { execFileSync } = await import("node:child_process");
2993
- const output = execFileSync("npx", ["tina4nodejs", "generate", kind, name], {
2997
+ // npx is npx.cmd on Windows, which execFileSync cannot find or start.
2998
+ const output = execFileSyncAllowingBatch("npx", ["tina4nodejs", "generate", kind, name], {
2994
2999
  cwd: resolve(process.cwd()),
2995
3000
  timeout: 30_000,
2996
- encoding: "utf-8",
2997
- }).toString();
3001
+ });
2998
3002
  res.json({ ok: true, kind, name, output });
2999
3003
  } catch (e) {
3000
3004
  res.json({ error: (e as Error).message }, 500);
@@ -27,6 +27,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
27
27
  import { randomInt, randomUUID } from "node:crypto";
28
28
  import { existsSync, readdirSync } from "node:fs";
29
29
  import { resolve, join } from "node:path";
30
+ import { pathToFileURL } from "node:url";
30
31
 
31
32
  // ── Word Banks ───────────────────────────────────────────────────
32
33
 
@@ -352,7 +353,9 @@ export class FakeData {
352
353
  for (const file of files) {
353
354
  const fullPath = join(dir, file);
354
355
  try {
355
- const mod = await import(fullPath);
356
+ // A raw path is not an import specifier: D:\... reads as a URL scheme,
357
+ // and a # anywhere in the path starts a URL fragment.
358
+ const mod = await import(pathToFileURL(fullPath).href);
356
359
  if (typeof mod.default === "function") {
357
360
  await mod.default();
358
361
  }
@@ -27,6 +27,7 @@ import { rtrimSlashes } from "./slashTrim.js";
27
27
  import * as path from "node:path";
28
28
  import * as os from "node:os";
29
29
  import { spawnSync } from "node:child_process";
30
+ import { findExecutable, spawnSyncAllowingBatch } from "./batchSpawn.js";
30
31
  import { createRequire } from "node:module";
31
32
  import { randomBytes } from "node:crypto";
32
33
  import { TINA4_VERSION } from "./version.js";
@@ -1109,7 +1110,9 @@ function verifyNodeSyntax(absPath: string, relPath: string): string | null {
1109
1110
  if (!target) return null;
1110
1111
  const { cmd, args } = syntaxCheckCommand(absPath, target.ext);
1111
1112
  try {
1112
- const proc = spawnSync(cmd, args, {
1113
+ // npx is npx.cmd on Windows: a plain spawnSync gets ENOENT, which reads as
1114
+ // "tsc not installed" below and skips the check without a word.
1115
+ const proc = spawnSyncAllowingBatch(findExecutable(cmd), args, {
1113
1116
  encoding: "utf-8",
1114
1117
  timeout: 5000,
1115
1118
  cwd: path.dirname(path.dirname(absPath)),
@@ -177,11 +177,70 @@ function sleepSync(ms: number): void {
177
177
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
178
178
  }
179
179
 
180
+ // Listens on argv host:port and exits 0 once bound, PROBE_HELD when the bind
181
+ // fails with EADDRINUSE, and PROBE_OTHER on any other bind error. A child
182
+ // process, because takeOverPort is synchronous and a Node bind is not. The host
183
+ // and port arrive as argv, never interpolated into the code.
184
+ const PROBE_HELD = 3;
185
+ const PROBE_OTHER = 4;
186
+ const BIND_PROBE = 'const s = require("node:net").createServer();'
187
+ + `s.on("error", (e) => process.exit(e && e.code === "EADDRINUSE" ? ${PROBE_HELD} : ${PROBE_OTHER}));`
188
+ + 's.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
189
+
190
+ /** What a bind probe learned about a port. */
191
+ export type BindProbe = "free" | "held" | "unknown";
192
+
193
+ /**
194
+ * Try a plain TCP listener on `host`:`port` (the same net.listen the server
195
+ * uses) and report what happened.
196
+ *
197
+ * Only a bind that fails with EADDRINUSE is "held". A probe that times out,
198
+ * cannot start, or hits any other bind error (EACCES, EADDRNOTAVAIL) is
199
+ * "unknown": it says nothing about whether something holds the port, so the
200
+ * caller must not report the port as in use. The real bind then decides, and
201
+ * it fails loudly with the true error. A probe is a child `node`, so on a slow
202
+ * host (arm64 under emulation, a small board, a CPU-throttled container) the
203
+ * child alone can take longer than the timeout to start.
204
+ */
205
+ export function probeBind(host: string, port: number, timeout = 5000): BindProbe {
206
+ try {
207
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout });
208
+ return "free";
209
+ } catch (err) {
210
+ return (err as { status?: number | null }).status === PROBE_HELD ? "held" : "unknown";
211
+ }
212
+ }
213
+
214
+ /**
215
+ * The result to return before any holder lookup, or null to carry on.
216
+ *
217
+ * Takeover is refused when opted out or outside dev mode. Before a bind, the
218
+ * caller passes the host it will bind: unless a probe sees that port held,
219
+ * there is nothing to refuse and nothing to say (an inconclusive probe leaves
220
+ * the decision to the real bind).
221
+ */
222
+ function refusal(port: number, dev: boolean, noTakeover: boolean, host?: string): TakeoverResult | null {
223
+ if (dev && !noTakeover) return null;
224
+ if (host !== undefined && probeBind(host, port) !== "held") {
225
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
226
+ }
227
+ if (noTakeover) {
228
+ return { status: TAKEOVER_REFUSED_OPTOUT, port, killed: [], message:
229
+ `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) `
230
+ + `-- free it or choose another port.` };
231
+ }
232
+ return { status: TAKEOVER_REFUSED_PROD, port, killed: [], message:
233
+ `Port ${port} is in use; takeover is disabled outside dev mode `
234
+ + `-- free it or choose another port.` };
235
+ }
236
+
180
237
  /**
181
238
  * Reclaim `port` ONLY from an identity-confirmed Tina4 dev server. The single
182
239
  * guarded path for both the CLI (`tina4 serve`) and the runtime bind-failure
183
240
  * fallback. `dev`/`noTakeover` are passed in so this stays pure and directly
184
241
  * testable; callers resolve them from isDev() / noTakeoverOptedOut().
242
+ * Before a bind, the caller passes the `host` it will bind, so a free port is
243
+ * reported as nothing rather than refused as "in use".
185
244
  */
186
245
  export function takeOverPort(
187
246
  port: number,
@@ -189,6 +248,7 @@ export function takeOverPort(
189
248
  noTakeover: boolean,
190
249
  baseDir?: string,
191
250
  grace = 500,
251
+ host?: string,
192
252
  ): TakeoverResult {
193
253
  const make = (status: string, killed: number[] = [], message = ""): TakeoverResult => ({
194
254
  status,
@@ -197,16 +257,8 @@ export function takeOverPort(
197
257
  message,
198
258
  });
199
259
 
200
- if (noTakeover) {
201
- return make(TAKEOVER_REFUSED_OPTOUT, [],
202
- `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) `
203
- + `-- free it or choose another port.`);
204
- }
205
- if (!dev) {
206
- return make(TAKEOVER_REFUSED_PROD, [],
207
- `Port ${port} is in use; takeover is disabled outside dev mode `
208
- + `-- free it or choose another port.`);
209
- }
260
+ const early = refusal(port, dev, noTakeover, host);
261
+ if (early !== null) return early;
210
262
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
211
263
 
212
264
  const tokens = portHolders(port);
@@ -17,9 +17,8 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
17
17
  * Python) using regex. No LLM involvement — pure static analysis.
18
18
  */
19
19
 
20
- import * as path from "node:path";
21
20
  import * as fs from "node:fs";
22
- import { extract, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
21
+ import { extract, indexKey, indexPath, loadRaw, projectRoot, saveRaw, walk } from "./projectIndexStorage.js";
23
22
  import type { IndexData } from "./projectIndexStorage.js";
24
23
 
25
24
  export interface FileRoute {
@@ -80,7 +79,7 @@ export const ProjectIndex = {
80
79
  const found: string[] = [];
81
80
  walk(root, found);
82
81
  for (const fp of found) {
83
- const rel = path.relative(root, fp);
82
+ const rel = indexKey(root, fp);
84
83
  seen.add(rel);
85
84
  let mtime: number;
86
85
  try {
@@ -106,7 +105,7 @@ export const ProjectIndex = {
106
105
  updated,
107
106
  removed: removed.length,
108
107
  total: Object.keys(files).length,
109
- path: path.relative(root, indexPath()),
108
+ path: indexKey(root, indexPath()),
110
109
  };
111
110
  },
112
111
 
@@ -31,6 +31,14 @@ export interface IndexData {
31
31
  generated_at: number;
32
32
  }
33
33
 
34
+ /**
35
+ * The index key for a file: its path relative to `root`, always `/`-separated
36
+ * so the same file has the same key on every OS (PHP's rule).
37
+ */
38
+ export function indexKey(root: string, fullPath: string): string {
39
+ return path.relative(root, fullPath).split(path.sep).join("/");
40
+ }
41
+
34
42
  export function projectRoot(): string {
35
43
  return path.resolve(process.cwd());
36
44
  }
@@ -69,7 +77,7 @@ export function extract(fullPath: string): FileEntry {
69
77
  return {};
70
78
  }
71
79
  const entry: FileEntry = {
72
- path: path.relative(projectRoot(), fullPath),
80
+ path: indexKey(projectRoot(), fullPath),
73
81
  size: st.size,
74
82
  mtime: Math.floor(st.mtimeMs / 1000),
75
83
  language: languageFor(fullPath),
@@ -9,6 +9,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
9
9
  import type { ServerResponse } from "node:http";
10
10
  import fs from "node:fs";
11
11
  import nodePath from "node:path";
12
+ import { fileURLToPath } from "node:url";
12
13
  import { once } from "node:events";
13
14
  import type { Tina4Response, CookieOptions } from "./types.js";
14
15
  import { currentCspNonce } from "./csp.js";
@@ -108,7 +109,9 @@ export async function getFrond(): Promise<InstanceType<any>> {
108
109
  * Syncs custom filters/globals from the user engine.
109
110
  */
110
111
  export async function getFrameworkFrond(): Promise<InstanceType<any> | null> {
111
- const frameworkDir = nodePath.resolve(nodePath.dirname(import.meta.url.replace("file://", "")), "..", "templates");
112
+ // fileURLToPath, not a string replace of "file://": the URL of a module under
113
+ // C:\ is file:///C:/..., and any path with a space or # is percent-encoded.
114
+ const frameworkDir = nodePath.resolve(nodePath.dirname(fileURLToPath(import.meta.url)), "..", "templates");
112
115
  if (!_frameworkFrond && fs.existsSync(frameworkDir)) {
113
116
  try {
114
117
  const { Frond, setCspNonceProvider } = await import("../../frond/src/engine.js");
@@ -8,6 +8,7 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
8
 
9
9
  import { readdirSync, statSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
10
10
  import { join, relative, basename, extname } from "node:path";
11
+ import { pathToFileURL } from "node:url";
11
12
  import type { RouteDefinition, RouteHandler, RouteMeta } from "./types.js";
12
13
 
13
14
  const VALID_METHODS = new Set(["get", "post", "put", "delete", "patch"]);
@@ -71,7 +72,9 @@ export async function discoverRoutes(routesDir: string): Promise<RouteDefinition
71
72
  try {
72
73
  // Cache-bust for hot-reload, keyed on mtime: identical content reuses the
73
74
  // same module URL (no needless re-import), an edit produces a fresh URL.
74
- const moduleUrl = `file://${filePath}?t=${currentMtime}`;
75
+ // pathToFileURL, not a hand-built file:// string: it percent-encodes #, ? and %, which
76
+ // would otherwise end the path early, and writes a drive letter correctly.
77
+ const moduleUrl = `${pathToFileURL(filePath).href}?t=${currentMtime}`;
75
78
  const mod = await import(moduleUrl);
76
79
 
77
80
  const handler: RouteHandler = mod.default ?? mod.handler;
@@ -146,7 +149,10 @@ function recordBrokenImport(filePath: string, error: Error): void {
146
149
  try {
147
150
  const brokenDir = join(process.cwd(), "data", ".broken");
148
151
  if (!existsSync(brokenDir)) mkdirSync(brokenDir, { recursive: true });
149
- const slug = filePath.replace(/[/\\]/g, "_");
152
+ // `:` too: an absolute Windows path starts with a drive letter, and on NTFS
153
+ // a colon in a file name writes an alternate data stream instead of a file,
154
+ // so no *.broken listing would ever see the marker.
155
+ const slug = filePath.replace(/[/\\:]/g, "_");
150
156
  const payload = JSON.stringify({
151
157
  type: "auto_discover_failure",
152
158
  file: filePath,
@@ -14,7 +14,7 @@ import { resolve, dirname, join, relative } from "node:path";
14
14
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
15
15
  import { isatty } from "node:tty";
16
16
  import { fileURLToPath } from "node:url";
17
- import { execFileSync, execFile } from "node:child_process";
17
+ import { execFile } from "node:child_process";
18
18
  import cluster from "node:cluster";
19
19
  import os from "node:os";
20
20
  import type { Socket } from "node:net";
@@ -24,6 +24,7 @@ import { enforceRouteAuth } from "./authGate.js";
24
24
  import { discoverRoutes } from "./routeDiscovery.js";
25
25
  import {
26
26
  takeOverPort,
27
+ probeBind,
27
28
  isDev as isTakeoverDev,
28
29
  noTakeoverOptedOut,
29
30
  writePidfile,
@@ -160,6 +161,54 @@ function swaggerAdvertised(): boolean {
160
161
  return TRUTHY.includes(raw);
161
162
  }
162
163
 
164
+ /**
165
+ * A connection URL (or any text that may embed one) with every `user:pass@`
166
+ * removed, for a boot log line. Core never imports the ORM statically, so this
167
+ * cannot borrow its redactCredentials(); stripping the whole userinfo is
168
+ * stricter than redaction anyway (the user name goes too).
169
+ */
170
+ function stripUrlCredentials(text: string): string {
171
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
172
+ }
173
+
174
+ /** A dynamic import that failed because the module itself is absent. */
175
+ function isModuleNotFound(err: unknown): boolean {
176
+ const code = (err as { code?: unknown } | null)?.code;
177
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
178
+ }
179
+
180
+ /**
181
+ * The database connect error from this boot's initializeOrm(), if it failed
182
+ * to connect. autoMigrateOnStartup() reports it instead of the bare "no adapter
183
+ * configured" that a failed connect leaves behind.
184
+ */
185
+ let bootDbConnectError: string | null = null;
186
+
187
+ /**
188
+ * Say WHY initializeOrm() failed, by the step that failed: only a missing ORM
189
+ * module is "install @tina4/orm"; a refused connection names the database
190
+ * (without credentials) and the error (review of tina4-ruby#172).
191
+ */
192
+ function reportOrmBootFailure(
193
+ stage: "import" | "connect" | "models",
194
+ err: unknown,
195
+ dbConfig: { type?: string; path?: string },
196
+ ): void {
197
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
198
+ if (stage === "connect") {
199
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
200
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
201
+ bootDbConnectError = message;
202
+ console.warn(`\n Database could not be reached (${target}): ${message}`);
203
+ } else if (stage === "import" && isModuleNotFound(err)) {
204
+ console.warn(`\n ORM not available (install @tina4/orm to enable): ${message}`);
205
+ } else if (stage === "import") {
206
+ console.warn(`\n ORM failed to load:`, err);
207
+ } else {
208
+ console.warn(`\n ORM model setup failed:`, err);
209
+ }
210
+ }
211
+
163
212
  /**
164
213
  * Apply pending DB migrations on startup — NON-BREAKING.
165
214
  *
@@ -205,9 +254,23 @@ export async function autoMigrateOnStartup(
205
254
  let orm: typeof import("../../orm/src/index.js");
206
255
  try {
207
256
  orm = await import("../../orm/src/index.js");
257
+ } catch (err) {
258
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
259
+ return;
260
+ }
261
+ try {
208
262
  orm.getAdapter(); // throws if no adapter configured
209
263
  } catch (err) {
210
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
264
+ // Only an unset TINA4_DATABASE_URL is "no database configured". A set but
265
+ // unreachable one must say so, or the operator chases a missing setting
266
+ // that is in fact present (review of tina4-ruby#172).
267
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
268
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
269
+ if (configuredUrl) {
270
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
271
+ } else {
272
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
273
+ }
211
274
  return;
212
275
  }
213
276
 
@@ -350,22 +413,17 @@ export function killPort(port: number): void {
350
413
  }
351
414
 
352
415
  /**
353
- * Check if *port* is available; if not, kill the process on it and return *port*.
354
- * The auto-increment behaviour is intentionally removed — the server always
355
- * claims the requested port.
416
+ * Check if *port* is held; if it is, reclaim it through the guarded takeover
417
+ * path and return *port*. The auto-increment behaviour is intentionally
418
+ * removed — the server always claims the requested port.
419
+ *
420
+ * Only a probe that sees EADDRINUSE counts as held. A probe that times out on a
421
+ * slow start says nothing about the port, so the real bind decides: it used to
422
+ * count as "in use", and a production server on a slow host refused a free port.
356
423
  */
357
424
  function findAvailablePort(start: number): number {
358
- try {
359
- execFileSync(process.execPath, ["-e", `
360
- const s = require("net").createServer();
361
- s.listen(${start}, "0.0.0.0", () => { s.close(); process.exit(0); });
362
- s.on("error", () => process.exit(1));
363
- `], { timeout: 1000 });
364
- return start;
365
- } catch {
366
- killPort(start);
367
- return start;
368
- }
425
+ if (probeBind("0.0.0.0", start) === "held") killPort(start);
426
+ return start;
369
427
  }
370
428
 
371
429
  /**
@@ -2085,6 +2143,13 @@ function startProductionCluster(port: number, host: string): {
2085
2143
  Debug: OFF (Log level: ${logLevel})
2086
2144
  ${reset}`);
2087
2145
  }
2146
+ // Round-robin, so every worker gets requests. Node already defaults to it
2147
+ // everywhere except Windows, where the default is SCHED_NONE (the OS picks a
2148
+ // worker, and under load it may keep picking the same one). Must be set before
2149
+ // the first fork. An operator's explicit NODE_CLUSTER_SCHED_POLICY wins.
2150
+ if (process.env.NODE_CLUSTER_SCHED_POLICY === undefined) {
2151
+ cluster.schedulingPolicy = cluster.SCHED_RR;
2152
+ }
2088
2153
  for (let i = 0; i < numCPUs; i++) cluster.fork();
2089
2154
  cluster.on("exit", (worker, code) => {
2090
2155
  if (code !== 0) {
@@ -2108,9 +2173,14 @@ function wireLocaleGlobal(frondEngine: any, base: string): void {
2108
2173
  if (!existsSync(localeDir)) return;
2109
2174
  try {
2110
2175
  const localeFiles = readdirSync(localeDir).filter((file: string) => file.endsWith(".json"));
2111
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
2176
+ // The engine's class: Frond is imported dynamically, so take it from the instance.
2177
+ const FrondClass = frondEngine.constructor;
2178
+ // Don't overwrite a user-registered t() (class-level, or on this engine).
2179
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
2112
2180
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
2113
- frondEngine.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2181
+ // Class-level, so t() reaches every engine (res.render's included) whenever
2182
+ // it was built. Templates call t("key") or t("key", {"name": n}).
2183
+ FrondClass.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2114
2184
  } catch {
2115
2185
  // Locale directory unreadable — skip auto-wire.
2116
2186
  }
@@ -2742,13 +2812,20 @@ async function initializeOrm(
2742
2812
  const hasOrmDir = existsSync(ormDir);
2743
2813
  const hasModelsDir = existsSync(modelsDir);
2744
2814
  if (hasOrmDir || hasModelsDir) {
2815
+ // Which step failed decides what the warning says: only a missing ORM
2816
+ // module is "install @tina4/orm"; a refused connection is a database
2817
+ // problem and must name the database (review of tina4-ruby#172).
2818
+ let ormStage: "import" | "connect" | "models" = "import";
2819
+ const dbConfig = config?.database ?? {};
2745
2820
  try {
2746
2821
  const orm = await import("../../orm/src/index.js");
2747
- const dbConfig = config?.database ?? {};
2822
+ ormStage = "connect";
2823
+ bootDbConnectError = null;
2748
2824
  await orm.initDatabase({
2749
2825
  type: dbConfig.type ?? "sqlite",
2750
2826
  path: dbConfig.path ?? "./data/tina4.db",
2751
2827
  });
2828
+ ormStage = "models";
2752
2829
 
2753
2830
  // Discover from src/orm/ (primary) and src/models/ (fallback), merge results
2754
2831
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
@@ -2792,7 +2869,7 @@ async function initializeOrm(
2792
2869
  }
2793
2870
  }
2794
2871
  } catch (err) {
2795
- console.warn(`\n ORM not available (install @tina4/orm to enable):`, err);
2872
+ reportOrmBootFailure(ormStage, err, dbConfig);
2796
2873
  }
2797
2874
 
2798
2875
  // Auto-run pending migrations on startup — AFTER initDatabase()/model sync,
@@ -181,6 +181,11 @@ export interface SessionHandler {
181
181
  destroy(sessionId: string): void;
182
182
  /** Garbage-collect expired sessions. Optional — Redis/Valkey/Mongo handle TTL natively. */
183
183
  gc?(maxLifetime: number): void;
184
+ /**
185
+ * Release a connection the handler opened itself. Optional; idempotent; the
186
+ * next read or write reopens it.
187
+ */
188
+ close?(): void;
184
189
  }
185
190
 
186
191
  // ── File Session Handler ──────────────────────────────────────────
@@ -244,6 +244,22 @@ export class DatabaseSessionHandler implements SessionHandler {
244
244
  return this.sqliteHandle;
245
245
  }
246
246
 
247
+ /**
248
+ * Release the SQLite connection this handler opened, so its file (and the
249
+ * WAL's -wal / -shm side files) is no longer held open: on Windows an open
250
+ * file cannot be deleted or replaced. Idempotent, and the next read or write
251
+ * reopens the connection. A server engine needs nothing here - each call goes
252
+ * through the sync bridge, which holds no connection between calls.
253
+ */
254
+ close(): void {
255
+ if (this.sqliteHandle === null) return;
256
+ try {
257
+ this.sqliteHandle.close();
258
+ } finally {
259
+ this.sqliteHandle = null;
260
+ }
261
+ }
262
+
247
263
  private get engine(): string {
248
264
  return this.target === null ? "sqlite" : this.target.engine;
249
265
  }