tina4-nodejs 3.13.163 → 3.13.164

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.
@@ -12053,8 +12053,14 @@ var init_engine = __esm({
12053
12053
  // and every future ``new Frond()`` inherits it automatically.
12054
12054
  // Mirrors Python's _class_globals / _class_filters / _class_tests.
12055
12055
  static classFilters = /* @__PURE__ */ new Map();
12056
- static classGlobals = /* @__PURE__ */ new Map();
12056
+ // Globals are read LIVE at render time (not copied at construction), so a
12057
+ // Frond.addGlobal() made after an engine exists still reaches it. A plain
12058
+ // object rather than a Map so render() can spread it in one step.
12059
+ static classGlobals = {};
12057
12060
  static classTests = /* @__PURE__ */ new Map();
12061
+ // Bumped on every class-level filter/test change, so an engine knows when
12062
+ // to rebuild its merged filter/test maps (see syncRegistries).
12063
+ static classRegistryVersion = 0;
12058
12064
  // ── Live-block registries (server-rendered {% live %} regions) ──
12059
12065
  // A {% live %} block registers three things when its page first renders:
12060
12066
  // liveFragments[name] -> the raw body source, re-rendered on every
@@ -12074,20 +12080,27 @@ var init_engine = __esm({
12074
12080
  static liveBroadcaster = null;
12075
12081
  /**
12076
12082
  * Register a custom filter at the class level — available to every
12077
- * future ``new Frond()`` instance. Callable as ``Frond.addFilter()``
12083
+ * instance, existing ones included: an engine merges the class filters
12084
+ * again at its next render (ADR-0107). Callable as ``Frond.addFilter()``
12078
12085
  * (static) or ``frond.addFilter()`` (instance). See instance method
12079
12086
  * below for the dual-call semantics.
12080
12087
  */
12081
12088
  static addFilter(name, fn) {
12082
12089
  _Frond.classFilters.set(name, fn);
12090
+ _Frond.classRegistryVersion++;
12083
12091
  }
12084
12092
  /**
12085
12093
  * Register a global variable available in all templates of every
12086
- * future instance. Callable as ``Frond.addGlobal()`` (static) or
12094
+ * instance, existing ones included: class globals are read at render time
12095
+ * (ADR-0106). Callable as ``Frond.addGlobal()`` (static) or
12087
12096
  * ``frond.addGlobal()`` (instance).
12088
12097
  */
12089
12098
  static addGlobal(name, value) {
12090
- _Frond.classGlobals.set(name, value);
12099
+ _Frond.classGlobals[name] = value;
12100
+ }
12101
+ /** True when a class-level global with this name is registered. */
12102
+ static hasGlobal(name) {
12103
+ return Object.prototype.hasOwnProperty.call(_Frond.classGlobals, name);
12091
12104
  }
12092
12105
  /**
12093
12106
  * Register a custom test (``{% if x is positive %}``) at the class
@@ -12096,6 +12109,7 @@ var init_engine = __esm({
12096
12109
  */
12097
12110
  static addTest(name, fn) {
12098
12111
  _Frond.classTests.set(name, fn);
12112
+ _Frond.classRegistryVersion++;
12099
12113
  }
12100
12114
  /**
12101
12115
  * Clear the class-level globals/filters/tests registries.
@@ -12105,15 +12119,25 @@ var init_engine = __esm({
12105
12119
  */
12106
12120
  static clearRegistry() {
12107
12121
  _Frond.classFilters.clear();
12108
- _Frond.classGlobals.clear();
12122
+ _Frond.classGlobals = {};
12109
12123
  _Frond.classTests.clear();
12124
+ _Frond.classRegistryVersion++;
12110
12125
  _Frond.liveFragments.clear();
12111
12126
  _Frond.liveSources.clear();
12112
12127
  _Frond.liveWsPaths.clear();
12113
12128
  }
12114
12129
  templateDir;
12115
- filters;
12130
+ /** Effective filters: built-in < class < instance (see syncRegistries). */
12131
+ filters = {};
12132
+ /** Filters / tests registered on THIS instance only (ADR-0052). */
12133
+ localFilters = {};
12134
+ localTests = {};
12135
+ /** The class-registry version `filters` / `tests` were last merged at. */
12136
+ registryVersion = -1;
12137
+ /** Globals registered on THIS instance only (ADR-0052). */
12116
12138
  globals;
12139
+ /** Built-in globals (formToken, range, dump, csp_nonce, ...). */
12140
+ builtinGlobals;
12117
12141
  tests;
12118
12142
  _sandbox;
12119
12143
  _allowedFilters;
@@ -12143,9 +12167,10 @@ var init_engine = __esm({
12143
12167
  }
12144
12168
  constructor(templateDir = "src/templates") {
12145
12169
  this.templateDir = resolve4(templateDir);
12146
- this.filters = { ...BUILTIN_FILTERS };
12147
12170
  this.globals = {};
12171
+ this.builtinGlobals = {};
12148
12172
  this.tests = {};
12173
+ this.syncRegistries();
12149
12174
  this._sandbox = false;
12150
12175
  this._allowedFilters = null;
12151
12176
  this._allowedTags = null;
@@ -12193,16 +12218,25 @@ var init_engine = __esm({
12193
12218
  return { output, next };
12194
12219
  }
12195
12220
  };
12196
- this.globals.formToken = (descriptor) => _generateFormToken(descriptor || "");
12197
- this.globals.form_token = (descriptor) => _generateFormToken(descriptor || "");
12198
- this.globals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
12199
- this.globals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
12200
- this.globals.range = frondRange;
12201
- this.globals.dump = (value) => renderDump(value);
12202
- this.globals.csp_nonce = () => _cspNonceProvider();
12203
- for (const [k, v] of _Frond.classFilters) this.filters[k] = v;
12204
- for (const [k, v] of _Frond.classGlobals) this.globals[k] = v;
12205
- for (const [k, v] of _Frond.classTests) this.tests[k] = v;
12221
+ this.builtinGlobals.formToken = (descriptor) => _generateFormToken(descriptor || "");
12222
+ this.builtinGlobals.form_token = (descriptor) => _generateFormToken(descriptor || "");
12223
+ this.builtinGlobals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
12224
+ this.builtinGlobals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
12225
+ this.builtinGlobals.range = frondRange;
12226
+ this.builtinGlobals.dump = (value) => renderDump(value);
12227
+ this.builtinGlobals.csp_nonce = () => _cspNonceProvider();
12228
+ }
12229
+ /**
12230
+ * Rebuild the merged filter/test maps when the class registry changed.
12231
+ * Same layering as globals -- built-ins < class < this instance. Filter
12232
+ * lookup is on the hot path, so the merge is a plain object rebuilt only
12233
+ * when the class-registry version moves, never a per-lookup chain.
12234
+ */
12235
+ syncRegistries() {
12236
+ if (this.registryVersion === _Frond.classRegistryVersion) return;
12237
+ this.filters = { ...BUILTIN_FILTERS, ...Object.fromEntries(_Frond.classFilters), ...this.localFilters };
12238
+ this.tests = { ...Object.fromEntries(_Frond.classTests), ...this.localTests };
12239
+ this.registryVersion = _Frond.classRegistryVersion;
12206
12240
  }
12207
12241
  sandbox(filters, tags, vars) {
12208
12242
  this._sandbox = true;
@@ -12223,6 +12257,7 @@ var init_engine = __esm({
12223
12257
  * for process-global registration. tina4: ADR-0052.
12224
12258
  */
12225
12259
  addFilter(name, fn) {
12260
+ this.localFilters[name] = fn;
12226
12261
  this.filters[name] = fn;
12227
12262
  }
12228
12263
  /**
@@ -12235,6 +12270,7 @@ var init_engine = __esm({
12235
12270
  * Register a custom test on this instance only.
12236
12271
  */
12237
12272
  addTest(name, fn) {
12273
+ this.localTests[name] = fn;
12238
12274
  this.tests[name] = fn;
12239
12275
  }
12240
12276
  /**
@@ -12250,8 +12286,19 @@ var init_engine = __esm({
12250
12286
  const n = parseInt(raw, 10);
12251
12287
  return isNaN(n) || n < 0 ? 0 : n;
12252
12288
  }
12289
+ /**
12290
+ * Layer the globals under the render data: built-ins < class globals (read
12291
+ * live, so registration order never matters) < this instance's own globals
12292
+ * < the data passed to render(). Every render starts here, so this is also
12293
+ * where the filter/test maps catch up with any class registration made
12294
+ * since the last render.
12295
+ */
12296
+ withGlobals(data) {
12297
+ this.syncRegistries();
12298
+ return { ...this.builtinGlobals, ..._Frond.classGlobals, ...this.globals, ...data || {} };
12299
+ }
12253
12300
  render(template, data) {
12254
- const context = { ...this.globals, ...data || {} };
12301
+ const context = this.withGlobals(data);
12255
12302
  const filePath = join7(this.templateDir, template);
12256
12303
  if (!existsSync5(filePath)) {
12257
12304
  throw new Error(`Template not found: ${filePath}`);
@@ -12274,7 +12321,7 @@ var init_engine = __esm({
12274
12321
  return this.executeWithSource(source, tokens, context);
12275
12322
  }
12276
12323
  renderString(source, data) {
12277
- const context = { ...this.globals, ...data || {} };
12324
+ const context = this.withGlobals(data);
12278
12325
  const key = createHash3("md5").update(source).digest("hex");
12279
12326
  const ttlMs = this.cacheTtlSeconds() * 1e3;
12280
12327
  const cached = this.compiledStrings.get(key);
@@ -23973,27 +24020,33 @@ function sleepSync(ms) {
23973
24020
  if (ms <= 0) return;
23974
24021
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
23975
24022
  }
23976
- function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24023
+ function bindable(host, port) {
24024
+ try {
24025
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5e3 });
24026
+ return true;
24027
+ } catch {
24028
+ return false;
24029
+ }
24030
+ }
24031
+ function refusal(port, dev, noTakeover, host) {
24032
+ if (dev && !noTakeover) return null;
24033
+ if (host !== void 0 && bindable(host, port)) {
24034
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
24035
+ }
24036
+ if (noTakeover) {
24037
+ return { status: TAKEOVER_REFUSED_OPTOUT, port, killed: [], message: `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) -- free it or choose another port.` };
24038
+ }
24039
+ return { status: TAKEOVER_REFUSED_PROD, port, killed: [], message: `Port ${port} is in use; takeover is disabled outside dev mode -- free it or choose another port.` };
24040
+ }
24041
+ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500, host) {
23977
24042
  const make = (status2, killed2 = [], message = "") => ({
23978
24043
  status: status2,
23979
24044
  port,
23980
24045
  killed: killed2,
23981
24046
  message
23982
24047
  });
23983
- if (noTakeover) {
23984
- return make(
23985
- TAKEOVER_REFUSED_OPTOUT,
23986
- [],
23987
- `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) -- free it or choose another port.`
23988
- );
23989
- }
23990
- if (!dev) {
23991
- return make(
23992
- TAKEOVER_REFUSED_PROD,
23993
- [],
23994
- `Port ${port} is in use; takeover is disabled outside dev mode -- free it or choose another port.`
23995
- );
23996
- }
24048
+ const early = refusal(port, dev, noTakeover, host);
24049
+ if (early !== null) return early;
23997
24050
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
23998
24051
  const tokens = portHolders(port);
23999
24052
  if (tokens.length === 0) return make(TAKEOVER_NOTHING);
@@ -24025,7 +24078,7 @@ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24025
24078
  `Reclaimed port ${port} from Tina4 dev server (PID: ${killed.join(", ")}).`
24026
24079
  );
24027
24080
  }
24028
- var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS;
24081
+ var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS, BIND_PROBE;
24029
24082
  var init_portTakeover = __esm({
24030
24083
  "src/portTakeover.ts"() {
24031
24084
  "use strict";
@@ -24040,6 +24093,7 @@ var init_portTakeover = __esm({
24040
24093
  TAKEOVER_REFUSED_OPTOUT,
24041
24094
  TAKEOVER_REFUSED_PROD
24042
24095
  ];
24096
+ BIND_PROBE = 'const s = require("node:net").createServer();s.on("error", () => process.exit(1));s.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
24043
24097
  }
24044
24098
  });
24045
24099
 
@@ -40304,6 +40358,7 @@ var init_devAdmin = __esm({
40304
40358
  const mem = process.memoryUsage();
40305
40359
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
40306
40360
  const rssMb = Math.round(mem.rss / 1048576);
40361
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
40307
40362
  let dbTableCount;
40308
40363
  let dbConnected = false;
40309
40364
  try {
@@ -40320,12 +40375,14 @@ var init_devAdmin = __esm({
40320
40375
  architecture: process.arch,
40321
40376
  os: `${process.platform} ${process.arch}`,
40322
40377
  pid: process.pid,
40323
- memory_mb: heapUsedMb,
40378
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
40379
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
40380
+ memory_mb: rssMb,
40324
40381
  db_tables: dbTableCount !== void 0 ? dbTableCount : "N/A",
40325
40382
  db_connected: dbConnected,
40326
40383
  memory: {
40327
- current_mb: heapUsedMb,
40328
- peak_mb: rssMb,
40384
+ current_mb: rssMb,
40385
+ peak_mb: peakRssMb,
40329
40386
  limit: "V8 default",
40330
40387
  rss: `${rssMb} MB`,
40331
40388
  heapUsed: `${heapUsedMb} MB`,
@@ -43301,6 +43358,32 @@ function swaggerAdvertised() {
43301
43358
  }
43302
43359
  return TRUTHY3.includes(raw);
43303
43360
  }
43361
+ function stripUrlCredentials(text) {
43362
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
43363
+ }
43364
+ function isModuleNotFound(err) {
43365
+ const code = err?.code;
43366
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
43367
+ }
43368
+ function reportOrmBootFailure(stage, err, dbConfig) {
43369
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
43370
+ if (stage === "connect") {
43371
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
43372
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
43373
+ bootDbConnectError = message;
43374
+ console.warn(`
43375
+ Database could not be reached (${target}): ${message}`);
43376
+ } else if (stage === "import" && isModuleNotFound(err)) {
43377
+ console.warn(`
43378
+ ORM not available (install @tina4/orm to enable): ${message}`);
43379
+ } else if (stage === "import") {
43380
+ console.warn(`
43381
+ ORM failed to load:`, err);
43382
+ } else {
43383
+ console.warn(`
43384
+ ORM model setup failed:`, err);
43385
+ }
43386
+ }
43304
43387
  async function autoMigrateOnStartup(migrationDir = "migrations", base = process.cwd()) {
43305
43388
  const dir = resolve19(base, migrationDir);
43306
43389
  if (!existsSync26(dir)) return;
@@ -43319,9 +43402,20 @@ async function autoMigrateOnStartup(migrationDir = "migrations", base = process.
43319
43402
  let orm;
43320
43403
  try {
43321
43404
  orm = await Promise.resolve().then(() => (init_src(), src_exports));
43405
+ } catch (err) {
43406
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
43407
+ return;
43408
+ }
43409
+ try {
43322
43410
  orm.getAdapter();
43323
43411
  } catch (err) {
43324
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
43412
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
43413
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
43414
+ if (configuredUrl) {
43415
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
43416
+ } else {
43417
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
43418
+ }
43325
43419
  return;
43326
43420
  }
43327
43421
  try {
@@ -44244,9 +44338,10 @@ function wireLocaleGlobal(frondEngine, base) {
44244
44338
  if (!existsSync26(localeDir)) return;
44245
44339
  try {
44246
44340
  const localeFiles = readdirSync18(localeDir).filter((file) => file.endsWith(".json"));
44247
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
44341
+ const FrondClass = frondEngine.constructor;
44342
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
44248
44343
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
44249
- frondEngine.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44344
+ FrondClass.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44250
44345
  } catch {
44251
44346
  }
44252
44347
  }
@@ -44579,13 +44674,17 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
44579
44674
  const hasOrmDir = existsSync26(ormDir);
44580
44675
  const hasModelsDir = existsSync26(modelsDir);
44581
44676
  if (hasOrmDir || hasModelsDir) {
44677
+ let ormStage = "import";
44678
+ const dbConfig = config?.database ?? {};
44582
44679
  try {
44583
44680
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
44584
- const dbConfig = config?.database ?? {};
44681
+ ormStage = "connect";
44682
+ bootDbConnectError = null;
44585
44683
  await orm.initDatabase({
44586
44684
  type: dbConfig.type ?? "sqlite",
44587
44685
  path: dbConfig.path ?? "./data/tina4.db"
44588
44686
  });
44687
+ ormStage = "models";
44589
44688
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
44590
44689
  if (hasModelsDir) {
44591
44690
  const extraModels = await orm.discoverModels(modelsDir);
@@ -44620,8 +44719,7 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
44620
44719
  }
44621
44720
  }
44622
44721
  } catch (err) {
44623
- console.warn(`
44624
- ORM not available (install @tina4/orm to enable):`, err);
44722
+ reportOrmBootFailure(ormStage, err, dbConfig);
44625
44723
  }
44626
44724
  await autoMigrateOnStartup("migrations", base);
44627
44725
  }
@@ -44659,7 +44757,7 @@ async function configureSwagger(router, ormDir, modelsDir) {
44659
44757
  }
44660
44758
  return enabled;
44661
44759
  }
44662
- var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swaggerAssetsEnabled, DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, frondCache2, _LEGACY_ENV_VARS, CI_ENVIRONMENT_VARIABLES, CI_NOT_SET_VALUES, portDeprecationWarned, TEMPLATE_PAGES_DIR, HTTP_REASON_PHRASES, templateCache, _dispatchFn, _liveDispatchContext, _serverHandle, LOOP_WATCHDOG_TICK_MS, FALLBACK_STAGES;
44760
+ var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swaggerAssetsEnabled, DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, bootDbConnectError, frondCache2, _LEGACY_ENV_VARS, CI_ENVIRONMENT_VARIABLES, CI_NOT_SET_VALUES, portDeprecationWarned, TEMPLATE_PAGES_DIR, HTTP_REASON_PHRASES, templateCache, _dispatchFn, _liveDispatchContext, _serverHandle, LOOP_WATCHDOG_TICK_MS, FALLBACK_STAGES;
44663
44761
  var init_server = __esm({
44664
44762
  "src/server.ts"() {
44665
44763
  "use strict";
@@ -44694,6 +44792,7 @@ var init_server = __esm({
44694
44792
  BUILTIN_PUBLIC_DIR = resolve19(__dirname, "..", "public");
44695
44793
  swaggerAssetsEnabled = false;
44696
44794
  DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;
44795
+ bootDbConnectError = null;
44697
44796
  frondCache2 = /* @__PURE__ */ new Map();
44698
44797
  _LEGACY_ENV_VARS = {
44699
44798
  DATABASE_URL: "TINA4_DATABASE_URL",
@@ -1102,6 +1102,9 @@ const handleSystem: RouteHandler = async (_req, res) => {
1102
1102
  const mem = process.memoryUsage();
1103
1103
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
1104
1104
  const rssMb = Math.round(mem.rss / 1048576);
1105
+ // Peak RSS: ru_maxrss, which libuv reports in kilobytes on every platform
1106
+ // (it converts macOS bytes). The current RSS is not the peak.
1107
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
1105
1108
  let dbTableCount: number | undefined;
1106
1109
  let dbConnected = false;
1107
1110
  try {
@@ -1118,12 +1121,14 @@ const handleSystem: RouteHandler = async (_req, res) => {
1118
1121
  architecture: process.arch,
1119
1122
  os: `${process.platform} ${process.arch}`,
1120
1123
  pid: process.pid,
1121
- memory_mb: heapUsedMb,
1124
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
1125
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
1126
+ memory_mb: rssMb,
1122
1127
  db_tables: dbTableCount !== undefined ? dbTableCount : "N/A",
1123
1128
  db_connected: dbConnected,
1124
1129
  memory: {
1125
- current_mb: heapUsedMb,
1126
- peak_mb: rssMb,
1130
+ current_mb: rssMb,
1131
+ peak_mb: peakRssMb,
1127
1132
  limit: "V8 default",
1128
1133
  rss: `${rssMb} MB`,
1129
1134
  heapUsed: `${heapUsedMb} MB`,
@@ -177,11 +177,52 @@ 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, 1 on any error. A child
181
+ // process, because takeOverPort is synchronous and a Node bind is not. The
182
+ // host and port arrive as argv, never interpolated into the code.
183
+ const BIND_PROBE = 'const s = require("node:net").createServer();'
184
+ + 's.on("error", () => process.exit(1));'
185
+ + 's.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
186
+
187
+ /** True when a plain TCP listener on `host`:`port` binds right now (the same net.listen the server uses). */
188
+ function bindable(host: string, port: number): boolean {
189
+ try {
190
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5000 });
191
+ return true;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * The result to return before any holder lookup, or null to carry on.
199
+ *
200
+ * Takeover is refused when opted out or outside dev mode. Before a bind, the
201
+ * caller passes the host it will bind: if that bind succeeds, nothing holds the
202
+ * port, so there is nothing to refuse and nothing to say.
203
+ */
204
+ function refusal(port: number, dev: boolean, noTakeover: boolean, host?: string): TakeoverResult | null {
205
+ if (dev && !noTakeover) return null;
206
+ if (host !== undefined && bindable(host, port)) {
207
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
208
+ }
209
+ if (noTakeover) {
210
+ return { status: TAKEOVER_REFUSED_OPTOUT, port, killed: [], message:
211
+ `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) `
212
+ + `-- free it or choose another port.` };
213
+ }
214
+ return { status: TAKEOVER_REFUSED_PROD, port, killed: [], message:
215
+ `Port ${port} is in use; takeover is disabled outside dev mode `
216
+ + `-- free it or choose another port.` };
217
+ }
218
+
180
219
  /**
181
220
  * Reclaim `port` ONLY from an identity-confirmed Tina4 dev server. The single
182
221
  * guarded path for both the CLI (`tina4 serve`) and the runtime bind-failure
183
222
  * fallback. `dev`/`noTakeover` are passed in so this stays pure and directly
184
223
  * testable; callers resolve them from isDev() / noTakeoverOptedOut().
224
+ * Before a bind, the caller passes the `host` it will bind, so a free port is
225
+ * reported as nothing rather than refused as "in use".
185
226
  */
186
227
  export function takeOverPort(
187
228
  port: number,
@@ -189,6 +230,7 @@ export function takeOverPort(
189
230
  noTakeover: boolean,
190
231
  baseDir?: string,
191
232
  grace = 500,
233
+ host?: string,
192
234
  ): TakeoverResult {
193
235
  const make = (status: string, killed: number[] = [], message = ""): TakeoverResult => ({
194
236
  status,
@@ -197,16 +239,8 @@ export function takeOverPort(
197
239
  message,
198
240
  });
199
241
 
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
- }
242
+ const early = refusal(port, dev, noTakeover, host);
243
+ if (early !== null) return early;
210
244
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
211
245
 
212
246
  const tokens = portHolders(port);
@@ -160,6 +160,54 @@ function swaggerAdvertised(): boolean {
160
160
  return TRUTHY.includes(raw);
161
161
  }
162
162
 
163
+ /**
164
+ * A connection URL (or any text that may embed one) with every `user:pass@`
165
+ * removed, for a boot log line. Core never imports the ORM statically, so this
166
+ * cannot borrow its redactCredentials(); stripping the whole userinfo is
167
+ * stricter than redaction anyway (the user name goes too).
168
+ */
169
+ function stripUrlCredentials(text: string): string {
170
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
171
+ }
172
+
173
+ /** A dynamic import that failed because the module itself is absent. */
174
+ function isModuleNotFound(err: unknown): boolean {
175
+ const code = (err as { code?: unknown } | null)?.code;
176
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
177
+ }
178
+
179
+ /**
180
+ * The database connect error from this boot's initializeOrm(), if it failed
181
+ * to connect. autoMigrateOnStartup() reports it instead of the bare "no adapter
182
+ * configured" that a failed connect leaves behind.
183
+ */
184
+ let bootDbConnectError: string | null = null;
185
+
186
+ /**
187
+ * Say WHY initializeOrm() failed, by the step that failed: only a missing ORM
188
+ * module is "install @tina4/orm"; a refused connection names the database
189
+ * (without credentials) and the error (review of tina4-ruby#172).
190
+ */
191
+ function reportOrmBootFailure(
192
+ stage: "import" | "connect" | "models",
193
+ err: unknown,
194
+ dbConfig: { type?: string; path?: string },
195
+ ): void {
196
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
197
+ if (stage === "connect") {
198
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
199
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
200
+ bootDbConnectError = message;
201
+ console.warn(`\n Database could not be reached (${target}): ${message}`);
202
+ } else if (stage === "import" && isModuleNotFound(err)) {
203
+ console.warn(`\n ORM not available (install @tina4/orm to enable): ${message}`);
204
+ } else if (stage === "import") {
205
+ console.warn(`\n ORM failed to load:`, err);
206
+ } else {
207
+ console.warn(`\n ORM model setup failed:`, err);
208
+ }
209
+ }
210
+
163
211
  /**
164
212
  * Apply pending DB migrations on startup — NON-BREAKING.
165
213
  *
@@ -205,9 +253,23 @@ export async function autoMigrateOnStartup(
205
253
  let orm: typeof import("../../orm/src/index.js");
206
254
  try {
207
255
  orm = await import("../../orm/src/index.js");
256
+ } catch (err) {
257
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
258
+ return;
259
+ }
260
+ try {
208
261
  orm.getAdapter(); // throws if no adapter configured
209
262
  } catch (err) {
210
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
263
+ // Only an unset TINA4_DATABASE_URL is "no database configured". A set but
264
+ // unreachable one must say so, or the operator chases a missing setting
265
+ // that is in fact present (review of tina4-ruby#172).
266
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
267
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
268
+ if (configuredUrl) {
269
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
270
+ } else {
271
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
272
+ }
211
273
  return;
212
274
  }
213
275
 
@@ -2108,9 +2170,14 @@ function wireLocaleGlobal(frondEngine: any, base: string): void {
2108
2170
  if (!existsSync(localeDir)) return;
2109
2171
  try {
2110
2172
  const localeFiles = readdirSync(localeDir).filter((file: string) => file.endsWith(".json"));
2111
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
2173
+ // The engine's class: Frond is imported dynamically, so take it from the instance.
2174
+ const FrondClass = frondEngine.constructor;
2175
+ // Don't overwrite a user-registered t() (class-level, or on this engine).
2176
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
2112
2177
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
2113
- frondEngine.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2178
+ // Class-level, so t() reaches every engine (res.render's included) whenever
2179
+ // it was built. Templates call t("key") or t("key", {"name": n}).
2180
+ FrondClass.addGlobal("t", (key: string, params?: Record<string, string>) => i18nInstance.t(key, params));
2114
2181
  } catch {
2115
2182
  // Locale directory unreadable — skip auto-wire.
2116
2183
  }
@@ -2742,13 +2809,20 @@ async function initializeOrm(
2742
2809
  const hasOrmDir = existsSync(ormDir);
2743
2810
  const hasModelsDir = existsSync(modelsDir);
2744
2811
  if (hasOrmDir || hasModelsDir) {
2812
+ // Which step failed decides what the warning says: only a missing ORM
2813
+ // module is "install @tina4/orm"; a refused connection is a database
2814
+ // problem and must name the database (review of tina4-ruby#172).
2815
+ let ormStage: "import" | "connect" | "models" = "import";
2816
+ const dbConfig = config?.database ?? {};
2745
2817
  try {
2746
2818
  const orm = await import("../../orm/src/index.js");
2747
- const dbConfig = config?.database ?? {};
2819
+ ormStage = "connect";
2820
+ bootDbConnectError = null;
2748
2821
  await orm.initDatabase({
2749
2822
  type: dbConfig.type ?? "sqlite",
2750
2823
  path: dbConfig.path ?? "./data/tina4.db",
2751
2824
  });
2825
+ ormStage = "models";
2752
2826
 
2753
2827
  // Discover from src/orm/ (primary) and src/models/ (fallback), merge results
2754
2828
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
@@ -2792,7 +2866,7 @@ async function initializeOrm(
2792
2866
  }
2793
2867
  }
2794
2868
  } catch (err) {
2795
- console.warn(`\n ORM not available (install @tina4/orm to enable):`, err);
2869
+ reportOrmBootFailure(ormStage, err, dbConfig);
2796
2870
  }
2797
2871
 
2798
2872
  // Auto-run pending migrations on startup — AFTER initDatabase()/model sync,