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.
package/CLAUDE.md CHANGED
@@ -14,13 +14,13 @@ Even if the skill text is not currently loaded, these are non-negotiable:
14
14
 
15
15
  The full discipline lives in `.claude/skills/tina4-maintainer/SKILL.md`; this block is the always-on floor.
16
16
 
17
- # CLAUDE.md - AI Developer Guide for tina4-nodejs (v3.13.163)
17
+ # CLAUDE.md - AI Developer Guide for tina4-nodejs (v3.13.164)
18
18
 
19
19
  > This file helps AI assistants (Claude, Copilot, Cursor, etc.) understand and work on this codebase effectively.
20
20
 
21
21
  ## What This Project Is
22
22
 
23
- Tina4 for Node.js/TypeScript v3.13.163 - The Intelligent Native Application 4ramework. A convention-over-configuration structural paradigm. The developer writes TypeScript; Tina4 is invisible infrastructure.
23
+ Tina4 for Node.js/TypeScript v3.13.164 - The Intelligent Native Application 4ramework. A convention-over-configuration structural paradigm. The developer writes TypeScript; Tina4 is invisible infrastructure.
24
24
 
25
25
  The philosophy: zero ceremony, batteries included, file system as source of truth.
26
26
 
@@ -82,9 +82,9 @@ This is an **npm workspaces monorepo**. All packages are in `packages/*`.
82
82
  ## Tech Stack
83
83
 
84
84
  - **Language:** TypeScript (strict mode, ES2022 target, Node16 module resolution)
85
- - **Runtime:** Node.js 20+ (ESM only, `"type": "module"` everywhere)
85
+ - **Runtime:** Node.js 22+ (`engines.node >=22.0.0`; ESM only, `"type": "module"` everywhere)
86
86
  - **HTTP:** Native `node:http` — no Express, no Fastify
87
- - **Database:** SQLite via `node:sqlite` (default), with adapters for Postgres, MySQL, MSSQL/SQL Server, and Firebird
87
+ - **Database:** SQLite via `node:sqlite` (default), with adapters for Postgres, MySQL, MSSQL/SQL Server, Firebird, MongoDB and ODBC
88
88
  - **Templates:** Frond — built-in zero-dependency Twig-compatible engine (`@tina4/frond`)
89
89
  - **Dev tooling:** `tsx` for runtime TS execution, `esbuild` for builds
90
90
  - **Testing:** 267 `*.test.ts` files via `tsx test/run-all.ts`
@@ -163,6 +163,8 @@ Database layer with auto-CRUD generation, seeding, fake data, and SQL translatio
163
163
  - `adapters/mysql.ts` — MySQL adapter
164
164
  - `adapters/mssql.ts` — MSSQL / SQL Server adapter (`mssql` or `sqlserver` scheme)
165
165
  - `adapters/firebird.ts` — Firebird adapter
166
+ - `adapters/mongodb.ts` — MongoDB adapter (SQL translated to MongoDB queries)
167
+ - `adapters/odbc.ts` — ODBC adapter
166
168
  - `model.ts` — Discovers models from `src/models/`, reads `static tableName` and `static fields`
167
169
  - `migration.ts` — Schema sync on startup (creates tables, adds columns, warns on destructive changes)
168
170
  - `autoCrud.ts` — Generates GET/POST/PUT/DELETE route handlers for each model
@@ -210,11 +212,11 @@ Max upload size: `TINA4_MAX_UPLOAD_SIZE` env var (default 10MB).
210
212
  ### Auth
211
213
 
212
214
  ```typescript
213
- // expires_in is in MINUTES (default 60). Reads SECRET from env if not passed.
215
+ // expires_in is in MINUTES (default 60). Reads TINA4_SECRET from env if not passed.
214
216
  getToken(payload, secret?, expiresIn=60): string
215
217
  validToken(token, secret?): Record | null
216
218
  getPayload(token): Record | null
217
- refreshToken(token, expiresIn=60): string | null // reads SECRET from env
219
+ refreshToken(token, expiresIn=60): string | null // reads TINA4_SECRET from env
218
220
  hashPassword(password, salt?, iterations=260000): string // PBKDF2-SHA256, $ delimiter
219
221
  checkPassword(password, hash): boolean // timing-safe
220
222
  validateApiKey(provided, expected?): boolean // reads TINA4_API_KEY from env
@@ -1213,6 +1215,8 @@ No configuration needed — set `TINA4_DEBUG=true` to enable. If you're running
1213
1215
 
1214
1216
  ## Conventions You Must Follow
1215
1217
 
1218
+ - **Pull requests only (ADR-0073)** — Never push directly to `v3` or `main` (or `v2`); work on a feature branch, open a PR, wait for the required checks, then merge. Never force-push or move a tag. A tag publishes, merging never does.
1219
+
1216
1220
  ### Route Files
1217
1221
  - Located in `src/routes/`
1218
1222
  - Filename = HTTP method: `get.ts`, `post.ts`, `put.ts`, `delete.ts`, `patch.ts`
@@ -1267,7 +1271,7 @@ import { Router } from "./router.js"; // .js even though the file is .ts
1267
1271
  3. **Convention-based models** — `static fields = {}` over decorators. No special TypeScript config needed.
1268
1272
  4. **CDN for Swagger UI** — Keeps install under 8MB. Single HTML file loads from jsdelivr.net (the same default across all four frameworks).
1269
1273
  5. **Browser reload, not process restart** — The `tina4` Rust CLI watches `src/`, `migrations/`, `.env` and POSTs `/__dev/api/reload` to the running server. The server stays up; only the browser reloads (via WS on `/__dev_reload`, polling fallback on `GET /__dev/api/mtime`). No ESM HMR gymnastics, no server restart, no framework-side watcher.
1270
- 6. **SQLite default** — `node:sqlite` is synchronous and fast. Full adapters for Postgres, MySQL, MSSQL/SQL Server, and Firebird.
1274
+ 6. **SQLite default** — `node:sqlite` is synchronous and fast. Full adapters for Postgres, MySQL, MSSQL/SQL Server, Firebird, MongoDB and ODBC.
1271
1275
  7. **CLI named `tina4nodejs`** (primary) with `tina4` as alias — So `npx tina4nodejs init` or `npx tina4 init` both work.
1272
1276
  8. **Event system** — Static `Events` class, synchronous dispatch, priority ordering, zero deps.
1273
1277
  9. **Inline testing** — Tests as decorators on functions, no external test runner for unit-level checks.
@@ -1481,7 +1485,7 @@ When adding new features, add a corresponding `test/<feature>.test.ts` file.
1481
1485
  - **Frond template engine optimizations**: pre-compiled regexes, lazy loop context (copy-on-write), filter chain caching, path split caching, inline common filters (11-15% speedup)
1482
1486
  - **Production server auto-detect**: `npx tina4nodejs serve --production` auto-uses cluster mode
1483
1487
  - **`tina4 generate`**: model, route, migration, middleware scaffolding. `tina4nodejs` is the Node package's own CLI; the `tina4` client forwards `generate` to it.
1484
- - **Database**: 5 engines (SQLite, PostgreSQL, MySQL, MSSQL, Firebird), DB query caching — request-scoped auto cache **off by default — opt-in via `TINA4_AUTO_CACHING=true`** (TTL `TINA4_AUTO_CACHING_TTL=5`s) which dedupes identical `db.fetch()`/ORM reads within a request and flushes on writes (always in-process); default OFF because a request-scoped cache defaulting on is a read-after-write footgun (cached pre-write `SELECT MAX(id)` → duplicate PKs); persistent cross-request cache opt-in via `TINA4_DB_CACHE=true` (TTL `TINA4_DB_CACHE_TTL=30`s) routed through the unified async backend set via `TINA4_DB_CACHE_BACKEND` (memory/file/redis/valkey/memcached/mongodb/database) + `TINA4_DB_CACHE_URL`, so instances share one cache with global write-invalidation (full parity with Python/PHP/Ruby). `db.cacheStats()` reports `mode` (request/persistent/off) + `backend`
1488
+ - **Database**: 7 engines (SQLite, PostgreSQL, MySQL, MSSQL, Firebird, MongoDB, ODBC), DB query caching — request-scoped auto cache **off by default — opt-in via `TINA4_AUTO_CACHING=true`** (TTL `TINA4_AUTO_CACHING_TTL=5`s) which dedupes identical `db.fetch()`/ORM reads within a request and flushes on writes (always in-process); default OFF because a request-scoped cache defaulting on is a read-after-write footgun (cached pre-write `SELECT MAX(id)` → duplicate PKs); persistent cross-request cache opt-in via `TINA4_DB_CACHE=true` (TTL `TINA4_DB_CACHE_TTL=30`s) routed through the unified async backend set via `TINA4_DB_CACHE_BACKEND` (memory/file/redis/valkey/memcached/mongodb/database) + `TINA4_DB_CACHE_URL`, so instances share one cache with global write-invalidation (full parity with Python/PHP/Ruby). `db.cacheStats()` reports `mode` (request/persistent/off) + `backend`
1485
1489
  - **Cache**: unified backend set — `memory` (default), `file`, `redis`, `valkey`, `memcached`, `mongodb`, `database` — via `TINA4_CACHE_BACKEND` (+ `TINA4_CACHE_URL`/credentials); file-backend fallback if a backend is unreachable. The KV API, the `responseCache` middleware, and the persistent DB query cache all route through this async backend set (native async clients, no child processes) — a network backend distributes them cross-instance, full parity with Python/PHP/Ruby; `memory` (default) keeps them in-process. `await` the async API (`cacheGet`/`cacheSet`/`clearCache`)
1486
1490
  - **Sessions**: file backend (default). `TINA4_SESSION_SAMESITE` env var (default: Lax)
1487
1491
  - **Queue**: file/RabbitMQ/Kafka/MongoDB backends, configured via env vars. **Reservation/visibility timeout** (file + MongoDB): a popped job is reserved for `TINA4_QUEUE_VISIBILITY_TIMEOUT` seconds (default 300; `visibilityTimeout` Queue option; `<= 0` disables) — if the consumer dies before `complete()`/`fail()`, the next `pop()` reclaims it (incrementing `attempts`, dead-lettering past `maxRetries`), so a crashed/evicted consumer never strands a job. RabbitMQ/Kafka delegate redelivery to the broker.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tina4-nodejs",
3
- "version": "3.13.163",
3
+ "version": "3.13.164",
4
4
  "type": "module",
5
5
  "description": "Tina4 for Node.js/TypeScript - native TypeScript conventions and shared Tina4 contracts",
6
6
  "keywords": [
@@ -12054,8 +12054,14 @@ var init_engine = __esm({
12054
12054
  // and every future ``new Frond()`` inherits it automatically.
12055
12055
  // Mirrors Python's _class_globals / _class_filters / _class_tests.
12056
12056
  static classFilters = /* @__PURE__ */ new Map();
12057
- static classGlobals = /* @__PURE__ */ new Map();
12057
+ // Globals are read LIVE at render time (not copied at construction), so a
12058
+ // Frond.addGlobal() made after an engine exists still reaches it. A plain
12059
+ // object rather than a Map so render() can spread it in one step.
12060
+ static classGlobals = {};
12058
12061
  static classTests = /* @__PURE__ */ new Map();
12062
+ // Bumped on every class-level filter/test change, so an engine knows when
12063
+ // to rebuild its merged filter/test maps (see syncRegistries).
12064
+ static classRegistryVersion = 0;
12059
12065
  // ── Live-block registries (server-rendered {% live %} regions) ──
12060
12066
  // A {% live %} block registers three things when its page first renders:
12061
12067
  // liveFragments[name] -> the raw body source, re-rendered on every
@@ -12075,20 +12081,27 @@ var init_engine = __esm({
12075
12081
  static liveBroadcaster = null;
12076
12082
  /**
12077
12083
  * Register a custom filter at the class level — available to every
12078
- * future ``new Frond()`` instance. Callable as ``Frond.addFilter()``
12084
+ * instance, existing ones included: an engine merges the class filters
12085
+ * again at its next render (ADR-0107). Callable as ``Frond.addFilter()``
12079
12086
  * (static) or ``frond.addFilter()`` (instance). See instance method
12080
12087
  * below for the dual-call semantics.
12081
12088
  */
12082
12089
  static addFilter(name, fn) {
12083
12090
  _Frond.classFilters.set(name, fn);
12091
+ _Frond.classRegistryVersion++;
12084
12092
  }
12085
12093
  /**
12086
12094
  * Register a global variable available in all templates of every
12087
- * future instance. Callable as ``Frond.addGlobal()`` (static) or
12095
+ * instance, existing ones included: class globals are read at render time
12096
+ * (ADR-0106). Callable as ``Frond.addGlobal()`` (static) or
12088
12097
  * ``frond.addGlobal()`` (instance).
12089
12098
  */
12090
12099
  static addGlobal(name, value) {
12091
- _Frond.classGlobals.set(name, value);
12100
+ _Frond.classGlobals[name] = value;
12101
+ }
12102
+ /** True when a class-level global with this name is registered. */
12103
+ static hasGlobal(name) {
12104
+ return Object.prototype.hasOwnProperty.call(_Frond.classGlobals, name);
12092
12105
  }
12093
12106
  /**
12094
12107
  * Register a custom test (``{% if x is positive %}``) at the class
@@ -12097,6 +12110,7 @@ var init_engine = __esm({
12097
12110
  */
12098
12111
  static addTest(name, fn) {
12099
12112
  _Frond.classTests.set(name, fn);
12113
+ _Frond.classRegistryVersion++;
12100
12114
  }
12101
12115
  /**
12102
12116
  * Clear the class-level globals/filters/tests registries.
@@ -12106,15 +12120,25 @@ var init_engine = __esm({
12106
12120
  */
12107
12121
  static clearRegistry() {
12108
12122
  _Frond.classFilters.clear();
12109
- _Frond.classGlobals.clear();
12123
+ _Frond.classGlobals = {};
12110
12124
  _Frond.classTests.clear();
12125
+ _Frond.classRegistryVersion++;
12111
12126
  _Frond.liveFragments.clear();
12112
12127
  _Frond.liveSources.clear();
12113
12128
  _Frond.liveWsPaths.clear();
12114
12129
  }
12115
12130
  templateDir;
12116
- filters;
12131
+ /** Effective filters: built-in < class < instance (see syncRegistries). */
12132
+ filters = {};
12133
+ /** Filters / tests registered on THIS instance only (ADR-0052). */
12134
+ localFilters = {};
12135
+ localTests = {};
12136
+ /** The class-registry version `filters` / `tests` were last merged at. */
12137
+ registryVersion = -1;
12138
+ /** Globals registered on THIS instance only (ADR-0052). */
12117
12139
  globals;
12140
+ /** Built-in globals (formToken, range, dump, csp_nonce, ...). */
12141
+ builtinGlobals;
12118
12142
  tests;
12119
12143
  _sandbox;
12120
12144
  _allowedFilters;
@@ -12144,9 +12168,10 @@ var init_engine = __esm({
12144
12168
  }
12145
12169
  constructor(templateDir = "src/templates") {
12146
12170
  this.templateDir = resolve5(templateDir);
12147
- this.filters = { ...BUILTIN_FILTERS };
12148
12171
  this.globals = {};
12172
+ this.builtinGlobals = {};
12149
12173
  this.tests = {};
12174
+ this.syncRegistries();
12150
12175
  this._sandbox = false;
12151
12176
  this._allowedFilters = null;
12152
12177
  this._allowedTags = null;
@@ -12194,16 +12219,25 @@ var init_engine = __esm({
12194
12219
  return { output, next };
12195
12220
  }
12196
12221
  };
12197
- this.globals.formToken = (descriptor) => _generateFormToken(descriptor || "");
12198
- this.globals.form_token = (descriptor) => _generateFormToken(descriptor || "");
12199
- this.globals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
12200
- this.globals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
12201
- this.globals.range = frondRange;
12202
- this.globals.dump = (value) => renderDump(value);
12203
- this.globals.csp_nonce = () => _cspNonceProvider();
12204
- for (const [k, v] of _Frond.classFilters) this.filters[k] = v;
12205
- for (const [k, v] of _Frond.classGlobals) this.globals[k] = v;
12206
- for (const [k, v] of _Frond.classTests) this.tests[k] = v;
12222
+ this.builtinGlobals.formToken = (descriptor) => _generateFormToken(descriptor || "");
12223
+ this.builtinGlobals.form_token = (descriptor) => _generateFormToken(descriptor || "");
12224
+ this.builtinGlobals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
12225
+ this.builtinGlobals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
12226
+ this.builtinGlobals.range = frondRange;
12227
+ this.builtinGlobals.dump = (value) => renderDump(value);
12228
+ this.builtinGlobals.csp_nonce = () => _cspNonceProvider();
12229
+ }
12230
+ /**
12231
+ * Rebuild the merged filter/test maps when the class registry changed.
12232
+ * Same layering as globals -- built-ins < class < this instance. Filter
12233
+ * lookup is on the hot path, so the merge is a plain object rebuilt only
12234
+ * when the class-registry version moves, never a per-lookup chain.
12235
+ */
12236
+ syncRegistries() {
12237
+ if (this.registryVersion === _Frond.classRegistryVersion) return;
12238
+ this.filters = { ...BUILTIN_FILTERS, ...Object.fromEntries(_Frond.classFilters), ...this.localFilters };
12239
+ this.tests = { ...Object.fromEntries(_Frond.classTests), ...this.localTests };
12240
+ this.registryVersion = _Frond.classRegistryVersion;
12207
12241
  }
12208
12242
  sandbox(filters, tags, vars) {
12209
12243
  this._sandbox = true;
@@ -12224,6 +12258,7 @@ var init_engine = __esm({
12224
12258
  * for process-global registration. tina4: ADR-0052.
12225
12259
  */
12226
12260
  addFilter(name, fn) {
12261
+ this.localFilters[name] = fn;
12227
12262
  this.filters[name] = fn;
12228
12263
  }
12229
12264
  /**
@@ -12236,6 +12271,7 @@ var init_engine = __esm({
12236
12271
  * Register a custom test on this instance only.
12237
12272
  */
12238
12273
  addTest(name, fn) {
12274
+ this.localTests[name] = fn;
12239
12275
  this.tests[name] = fn;
12240
12276
  }
12241
12277
  /**
@@ -12251,8 +12287,19 @@ var init_engine = __esm({
12251
12287
  const n = parseInt(raw, 10);
12252
12288
  return isNaN(n) || n < 0 ? 0 : n;
12253
12289
  }
12290
+ /**
12291
+ * Layer the globals under the render data: built-ins < class globals (read
12292
+ * live, so registration order never matters) < this instance's own globals
12293
+ * < the data passed to render(). Every render starts here, so this is also
12294
+ * where the filter/test maps catch up with any class registration made
12295
+ * since the last render.
12296
+ */
12297
+ withGlobals(data) {
12298
+ this.syncRegistries();
12299
+ return { ...this.builtinGlobals, ..._Frond.classGlobals, ...this.globals, ...data || {} };
12300
+ }
12254
12301
  render(template, data) {
12255
- const context = { ...this.globals, ...data || {} };
12302
+ const context = this.withGlobals(data);
12256
12303
  const filePath = join8(this.templateDir, template);
12257
12304
  if (!existsSync6(filePath)) {
12258
12305
  throw new Error(`Template not found: ${filePath}`);
@@ -12275,7 +12322,7 @@ var init_engine = __esm({
12275
12322
  return this.executeWithSource(source, tokens, context);
12276
12323
  }
12277
12324
  renderString(source, data) {
12278
- const context = { ...this.globals, ...data || {} };
12325
+ const context = this.withGlobals(data);
12279
12326
  const key = createHash3("md5").update(source).digest("hex");
12280
12327
  const ttlMs = this.cacheTtlSeconds() * 1e3;
12281
12328
  const cached = this.compiledStrings.get(key);
@@ -23994,27 +24041,33 @@ function sleepSync(ms) {
23994
24041
  if (ms <= 0) return;
23995
24042
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
23996
24043
  }
23997
- function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24044
+ function bindable(host, port) {
24045
+ try {
24046
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5e3 });
24047
+ return true;
24048
+ } catch {
24049
+ return false;
24050
+ }
24051
+ }
24052
+ function refusal(port, dev, noTakeover, host) {
24053
+ if (dev && !noTakeover) return null;
24054
+ if (host !== void 0 && bindable(host, port)) {
24055
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
24056
+ }
24057
+ if (noTakeover) {
24058
+ 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.` };
24059
+ }
24060
+ 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.` };
24061
+ }
24062
+ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500, host) {
23998
24063
  const make = (status2, killed2 = [], message = "") => ({
23999
24064
  status: status2,
24000
24065
  port,
24001
24066
  killed: killed2,
24002
24067
  message
24003
24068
  });
24004
- if (noTakeover) {
24005
- return make(
24006
- TAKEOVER_REFUSED_OPTOUT,
24007
- [],
24008
- `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) -- free it or choose another port.`
24009
- );
24010
- }
24011
- if (!dev) {
24012
- return make(
24013
- TAKEOVER_REFUSED_PROD,
24014
- [],
24015
- `Port ${port} is in use; takeover is disabled outside dev mode -- free it or choose another port.`
24016
- );
24017
- }
24069
+ const early = refusal(port, dev, noTakeover, host);
24070
+ if (early !== null) return early;
24018
24071
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
24019
24072
  const tokens = portHolders(port);
24020
24073
  if (tokens.length === 0) return make(TAKEOVER_NOTHING);
@@ -24046,7 +24099,7 @@ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24046
24099
  `Reclaimed port ${port} from Tina4 dev server (PID: ${killed.join(", ")}).`
24047
24100
  );
24048
24101
  }
24049
- var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS;
24102
+ var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS, BIND_PROBE;
24050
24103
  var init_portTakeover = __esm({
24051
24104
  "../core/src/portTakeover.ts"() {
24052
24105
  "use strict";
@@ -24061,6 +24114,7 @@ var init_portTakeover = __esm({
24061
24114
  TAKEOVER_REFUSED_OPTOUT,
24062
24115
  TAKEOVER_REFUSED_PROD
24063
24116
  ];
24117
+ 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)));';
24064
24118
  }
24065
24119
  });
24066
24120
 
@@ -40348,6 +40402,7 @@ var init_devAdmin = __esm({
40348
40402
  const mem = process.memoryUsage();
40349
40403
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
40350
40404
  const rssMb = Math.round(mem.rss / 1048576);
40405
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
40351
40406
  let dbTableCount;
40352
40407
  let dbConnected = false;
40353
40408
  try {
@@ -40364,12 +40419,14 @@ var init_devAdmin = __esm({
40364
40419
  architecture: process.arch,
40365
40420
  os: `${process.platform} ${process.arch}`,
40366
40421
  pid: process.pid,
40367
- memory_mb: heapUsedMb,
40422
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
40423
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
40424
+ memory_mb: rssMb,
40368
40425
  db_tables: dbTableCount !== void 0 ? dbTableCount : "N/A",
40369
40426
  db_connected: dbConnected,
40370
40427
  memory: {
40371
- current_mb: heapUsedMb,
40372
- peak_mb: rssMb,
40428
+ current_mb: rssMb,
40429
+ peak_mb: peakRssMb,
40373
40430
  limit: "V8 default",
40374
40431
  rss: `${rssMb} MB`,
40375
40432
  heapUsed: `${heapUsedMb} MB`,
@@ -43306,6 +43363,33 @@ var init_docsAutoDiscovery = __esm({
43306
43363
  });
43307
43364
 
43308
43365
  // ../core/src/server.ts
43366
+ var server_exports = {};
43367
+ __export(server_exports, {
43368
+ CI_ENVIRONMENT_VARIABLES: () => CI_ENVIRONMENT_VARIABLES,
43369
+ CI_NOT_SET_VALUES: () => CI_NOT_SET_VALUES,
43370
+ DEFAULT_SHUTDOWN_TIMEOUT_SECONDS: () => DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,
43371
+ _checkLegacyEnvVars: () => _checkLegacyEnvVars,
43372
+ autoMigrateOnStartup: () => autoMigrateOnStartup,
43373
+ bannerSurfaceLines: () => bannerSurfaceLines,
43374
+ buildDispatchContext: () => buildDispatchContext,
43375
+ getLiveDispatchContext: () => getLiveDispatchContext,
43376
+ handle: () => handle,
43377
+ httpReason: () => httpReason,
43378
+ isBannerSuppressed: () => isBannerSuppressed,
43379
+ killPort: () => killPort,
43380
+ loopbackBindHosts: () => loopbackBindHosts,
43381
+ resetTemplateCache: () => resetTemplateCache,
43382
+ resolveHandlerArgs: () => resolveHandlerArgs,
43383
+ resolvePortAndHost: () => resolvePortAndHost,
43384
+ resolveTemplate: () => resolveTemplate,
43385
+ runDispatch: () => runDispatch,
43386
+ shouldOpenBrowser: () => shouldOpenBrowser,
43387
+ shutdownTimeoutSeconds: () => shutdownTimeoutSeconds,
43388
+ start: () => start,
43389
+ startServer: () => startServer,
43390
+ stop: () => stop,
43391
+ templateAutoRoutingEnabled: () => templateAutoRoutingEnabled
43392
+ });
43309
43393
  import { randomBytes as randomBytes9 } from "node:crypto";
43310
43394
  import { resolve as resolve20, dirname as dirname16, join as join32, relative as relative10 } from "node:path";
43311
43395
  import { existsSync as existsSync27, readdirSync as readdirSync18, readFileSync as readFileSync23, statSync as statSync19 } from "node:fs";
@@ -43345,6 +43429,32 @@ function swaggerAdvertised() {
43345
43429
  }
43346
43430
  return TRUTHY3.includes(raw);
43347
43431
  }
43432
+ function stripUrlCredentials(text) {
43433
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
43434
+ }
43435
+ function isModuleNotFound(err) {
43436
+ const code = err?.code;
43437
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
43438
+ }
43439
+ function reportOrmBootFailure(stage, err, dbConfig) {
43440
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
43441
+ if (stage === "connect") {
43442
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
43443
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
43444
+ bootDbConnectError = message;
43445
+ console.warn(`
43446
+ Database could not be reached (${target}): ${message}`);
43447
+ } else if (stage === "import" && isModuleNotFound(err)) {
43448
+ console.warn(`
43449
+ ORM not available (install @tina4/orm to enable): ${message}`);
43450
+ } else if (stage === "import") {
43451
+ console.warn(`
43452
+ ORM failed to load:`, err);
43453
+ } else {
43454
+ console.warn(`
43455
+ ORM model setup failed:`, err);
43456
+ }
43457
+ }
43348
43458
  async function autoMigrateOnStartup(migrationDir = "migrations", base = process.cwd()) {
43349
43459
  const dir = resolve20(base, migrationDir);
43350
43460
  if (!existsSync27(dir)) return;
@@ -43363,9 +43473,20 @@ async function autoMigrateOnStartup(migrationDir = "migrations", base = process.
43363
43473
  let orm;
43364
43474
  try {
43365
43475
  orm = await Promise.resolve().then(() => (init_src(), src_exports));
43476
+ } catch (err) {
43477
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
43478
+ return;
43479
+ }
43480
+ try {
43366
43481
  orm.getAdapter();
43367
43482
  } catch (err) {
43368
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
43483
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
43484
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
43485
+ if (configuredUrl) {
43486
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
43487
+ } else {
43488
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
43489
+ }
43369
43490
  return;
43370
43491
  }
43371
43492
  try {
@@ -44288,9 +44409,10 @@ function wireLocaleGlobal(frondEngine, base) {
44288
44409
  if (!existsSync27(localeDir)) return;
44289
44410
  try {
44290
44411
  const localeFiles = readdirSync18(localeDir).filter((file) => file.endsWith(".json"));
44291
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
44412
+ const FrondClass = frondEngine.constructor;
44413
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
44292
44414
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
44293
- frondEngine.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44415
+ FrondClass.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44294
44416
  } catch {
44295
44417
  }
44296
44418
  }
@@ -44623,13 +44745,17 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
44623
44745
  const hasOrmDir = existsSync27(ormDir);
44624
44746
  const hasModelsDir = existsSync27(modelsDir);
44625
44747
  if (hasOrmDir || hasModelsDir) {
44748
+ let ormStage = "import";
44749
+ const dbConfig = config?.database ?? {};
44626
44750
  try {
44627
44751
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
44628
- const dbConfig = config?.database ?? {};
44752
+ ormStage = "connect";
44753
+ bootDbConnectError = null;
44629
44754
  await orm.initDatabase({
44630
44755
  type: dbConfig.type ?? "sqlite",
44631
44756
  path: dbConfig.path ?? "./data/tina4.db"
44632
44757
  });
44758
+ ormStage = "models";
44633
44759
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
44634
44760
  if (hasModelsDir) {
44635
44761
  const extraModels = await orm.discoverModels(modelsDir);
@@ -44664,8 +44790,7 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
44664
44790
  }
44665
44791
  }
44666
44792
  } catch (err) {
44667
- console.warn(`
44668
- ORM not available (install @tina4/orm to enable):`, err);
44793
+ reportOrmBootFailure(ormStage, err, dbConfig);
44669
44794
  }
44670
44795
  await autoMigrateOnStartup("migrations", base);
44671
44796
  }
@@ -44703,7 +44828,7 @@ async function configureSwagger(router, ormDir, modelsDir) {
44703
44828
  }
44704
44829
  return enabled;
44705
44830
  }
44706
- 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;
44831
+ 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;
44707
44832
  var init_server = __esm({
44708
44833
  "../core/src/server.ts"() {
44709
44834
  "use strict";
@@ -44738,6 +44863,7 @@ var init_server = __esm({
44738
44863
  BUILTIN_PUBLIC_DIR = resolve20(__dirname, "..", "public");
44739
44864
  swaggerAssetsEnabled = false;
44740
44865
  DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;
44866
+ bootDbConnectError = null;
44741
44867
  frondCache2 = /* @__PURE__ */ new Map();
44742
44868
  _LEGACY_ENV_VARS = {
44743
44869
  DATABASE_URL: "TINA4_DATABASE_URL",
@@ -53299,9 +53425,9 @@ function readCliVersion() {
53299
53425
  }
53300
53426
  return "0.0.0";
53301
53427
  }
53302
- async function killProcessOnPort(port) {
53428
+ async function killProcessOnPort(port, host) {
53303
53429
  const { takeOverPort: takeOverPort2, isDev: isDev2, noTakeoverOptedOut: noTakeoverOptedOut2, TAKEOVER_KILLED: TAKEOVER_KILLED2, TAKEOVER_REFUSALS: TAKEOVER_REFUSALS2 } = await Promise.resolve().then(() => (init_portTakeover(), portTakeover_exports));
53304
- const result = takeOverPort2(port, isDev2(), noTakeoverOptedOut2());
53430
+ const result = takeOverPort2(port, isDev2(), noTakeoverOptedOut2(), void 0, void 0, host);
53305
53431
  if (result.status === TAKEOVER_KILLED2) {
53306
53432
  console.log(` ${result.message}`);
53307
53433
  return true;
@@ -53469,7 +53595,8 @@ var COMMANDS = {
53469
53595
  const noBrowser = a.includes("--no-browser");
53470
53596
  const noReload = a.includes("--no-reload");
53471
53597
  if (a.includes("--no-kill")) process.env.TINA4_NO_TAKEOVER = "true";
53472
- await killProcessOnPort(port);
53598
+ const { resolvePortAndHost: resolvePortAndHost2 } = await Promise.resolve().then(() => (init_server(), server_exports));
53599
+ await killProcessOnPort(port, resolvePortAndHost2({ port }).host);
53473
53600
  await serveProject({ port, noBrowser, noReload });
53474
53601
  },
53475
53602
  flags: SERVE_FLAGS,
@@ -68,12 +68,15 @@ function readCliVersion(): string {
68
68
  * message is printed; takeover is also skipped in a container, outside dev mode,
69
69
  * and when opted out (`TINA4_NO_TAKEOVER` / `tina4 serve --no-kill`).
70
70
  *
71
+ * `host` is the address serve will bind; a port that binds there is reported
72
+ * as free, not "in use".
73
+ *
71
74
  * Returns true only when a Tina4 holder was actually signalled.
72
75
  */
73
- async function killProcessOnPort(port: number): Promise<boolean> {
76
+ async function killProcessOnPort(port: number, host?: string): Promise<boolean> {
74
77
  const { takeOverPort, isDev, noTakeoverOptedOut, TAKEOVER_KILLED, TAKEOVER_REFUSALS } =
75
78
  await import("../../core/src/portTakeover.js");
76
- const result = takeOverPort(port, isDev(), noTakeoverOptedOut());
79
+ const result = takeOverPort(port, isDev(), noTakeoverOptedOut(), undefined, undefined, host);
77
80
  if (result.status === TAKEOVER_KILLED) {
78
81
  console.log(` ${result.message}`);
79
82
  return true;
@@ -359,7 +362,9 @@ export const COMMANDS: Record<string, CommandSpec> = {
359
362
  // path here AND the runtime bind-failure fallback both honour it
360
363
  // (TAKEOVER-DEC-03).
361
364
  if (a.includes("--no-kill")) process.env.TINA4_NO_TAKEOVER = "true";
362
- await killProcessOnPort(port);
365
+ // Probe the host the server will bind, resolved exactly as it resolves it.
366
+ const { resolvePortAndHost } = await import("../../core/src/server.js");
367
+ await killProcessOnPort(port, resolvePortAndHost({ port }).host);
363
368
  await serveProject({ port, noBrowser, noReload });
364
369
  },
365
370
  flags: SERVE_FLAGS,