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.
@@ -147,16 +147,16 @@ function parseEnvContent(content) {
147
147
  }
148
148
  return result;
149
149
  }
150
- function loadEnv(path10, override = false) {
150
+ function loadEnv(path9, override = false) {
151
151
  const fromEnv = (process.env.TINA4_ENV_FILE ?? "").trim();
152
- if (path10 === void 0 && fromEnv.length > 0) {
152
+ if (path9 === void 0 && fromEnv.length > 0) {
153
153
  const named = resolve(fromEnv);
154
154
  return mergeFirstWins(
155
155
  loadEnvFile(join(dirname(named), ".env.local"), override),
156
156
  loadEnvFile(named, override)
157
157
  );
158
158
  }
159
- const target = resolve(path10 ?? ".");
159
+ const target = resolve(path9 ?? ".");
160
160
  if (existsSync(target) && statSync(target).isDirectory()) {
161
161
  return mergeFirstWins(
162
162
  loadEnvFile(join(target, ".env.local"), override),
@@ -393,12 +393,12 @@ function resolveCallerName() {
393
393
  return void 0;
394
394
  }
395
395
  }
396
- function targetIsFile(path10) {
396
+ function targetIsFile(path9) {
397
397
  try {
398
- if (existsSync2(path10) && statSync2(path10).isDirectory()) return false;
398
+ if (existsSync2(path9) && statSync2(path9).isDirectory()) return false;
399
399
  } catch {
400
400
  }
401
- const base = basename(path10);
401
+ const base = basename(path9);
402
402
  return base.includes(".") && !base.startsWith(".");
403
403
  }
404
404
  function resolveBool(explicit, envName, fallback) {
@@ -722,8 +722,8 @@ var init_logger = __esm({
722
722
  rotateSize;
723
723
  rotateKeep;
724
724
  lock;
725
- constructor(path10, rotateSize, rotateKeep, lockBuffer) {
726
- this.path = path10;
725
+ constructor(path9, rotateSize, rotateKeep, lockBuffer) {
726
+ this.path = path9;
727
727
  this.rotateSize = rotateSize;
728
728
  this.rotateKeep = rotateKeep;
729
729
  this.lock = new SinkLock(lockBuffer);
@@ -1244,8 +1244,8 @@ function hashPassword(password, salt, iterations = 26e4) {
1244
1244
  }
1245
1245
  function checkPassword(password, hash) {
1246
1246
  try {
1247
- const delimiter2 = hash.includes("$") ? "$" : ":";
1248
- const parts = hash.split(delimiter2);
1247
+ const delimiter3 = hash.includes("$") ? "$" : ":";
1248
+ const parts = hash.split(delimiter3);
1249
1249
  if (parts.length !== 4 || parts[0] !== "pbkdf2_sha256") return false;
1250
1250
  const iterations = parseInt(parts[1], 10);
1251
1251
  const salt = parts[2];
@@ -1721,8 +1721,8 @@ var init_modelCollection = __esm({
1721
1721
 
1722
1722
  // ../orm/src/databaseUrl.ts
1723
1723
  import { inspect } from "node:util";
1724
- function stripOneSlash(path10) {
1725
- return path10.startsWith("/") ? path10.slice(1) : path10;
1724
+ function stripOneSlash(path9) {
1725
+ return path9.startsWith("/") ? path9.slice(1) : path9;
1726
1726
  }
1727
1727
  function decode(value) {
1728
1728
  if (value === void 0 || value === "") return null;
@@ -3729,8 +3729,8 @@ function resolveSqlitePath(dbPath) {
3729
3729
  return dbPath;
3730
3730
  }
3731
3731
  const cwd = resolve2(process.cwd());
3732
- const path10 = join4(cwd, dbPath);
3733
- const parent = dirname3(path10);
3732
+ const path9 = join4(cwd, dbPath);
3733
+ const parent = dirname3(path9);
3734
3734
  const absParent = resolve2(parent);
3735
3735
  if (absParent !== cwd && !absParent.startsWith(cwd + sep)) {
3736
3736
  throw new Error(
@@ -3738,7 +3738,7 @@ function resolveSqlitePath(dbPath) {
3738
3738
  );
3739
3739
  }
3740
3740
  mkdirSync2(parent, { recursive: true, mode: 509 });
3741
- return path10;
3741
+ return path9;
3742
3742
  }
3743
3743
  function fieldTypeToSQLite(def) {
3744
3744
  switch (def.type) {
@@ -7617,9 +7617,9 @@ async function initDatabase(config) {
7617
7617
  const rawType = config?.type ?? "sqlite";
7618
7618
  const type2 = rawType === "sqlserver" ? "mssql" : rawType;
7619
7619
  if (config === void 0 && !process.env.TINA4_DATABASE_URL) {
7620
- const path10 = "./data/tina4.db";
7620
+ const path9 = "./data/tina4.db";
7621
7621
  console.warn(
7622
- `[tina4] No TINA4_DATABASE_URL set \u2014 falling back to SQLite at ${path10}. If you meant to use Postgres/MySQL/etc., set TINA4_DATABASE_URL in your .env and re-run. (Was the .env loaded? CLI commands must call loadEnv() first.)`
7622
+ `[tina4] No TINA4_DATABASE_URL set \u2014 falling back to SQLite at ${path9}. If you meant to use Postgres/MySQL/etc., set TINA4_DATABASE_URL in your .env and re-run. (Was the .env loaded? CLI commands must call loadEnv() first.)`
7623
7623
  );
7624
7624
  }
7625
7625
  const finished = (adapter) => {
@@ -8834,6 +8834,7 @@ var init_database = __esm({
8834
8834
  // ../orm/src/model.ts
8835
8835
  import { readdirSync, statSync as statSync3 } from "node:fs";
8836
8836
  import { join as join5, extname } from "node:path";
8837
+ import { pathToFileURL } from "node:url";
8837
8838
  async function discoverModels(modelsDir) {
8838
8839
  const models = [];
8839
8840
  let files;
@@ -8849,7 +8850,7 @@ async function discoverModels(modelsDir) {
8849
8850
  const ext = extname(file);
8850
8851
  if (ext !== ".ts" && ext !== ".js") continue;
8851
8852
  try {
8852
- const moduleUrl = `file://${filePath}?t=${Date.now()}`;
8853
+ const moduleUrl = `${pathToFileURL(filePath).href}?t=${Date.now()}`;
8853
8854
  const mod = await import(moduleUrl);
8854
8855
  const ModelClass = mod.default ?? mod;
8855
8856
  if (!ModelClass.tableName || !ModelClass.fields) {
@@ -9190,7 +9191,7 @@ async function removeMigrationRecord(name) {
9190
9191
  [name]
9191
9192
  );
9192
9193
  }
9193
- async function rollback(migrationsDir, delimiter2) {
9194
+ async function rollback(migrationsDir, delimiter3) {
9194
9195
  if (migrationsDir instanceof Map) {
9195
9196
  const downFunctions = migrationsDir;
9196
9197
  const migrations2 = await getLastBatchMigrations();
@@ -9209,7 +9210,7 @@ async function rollback(migrationsDir, delimiter2) {
9209
9210
  return rolledBack2;
9210
9211
  }
9211
9212
  const dir = resolve3(migrationsDir ?? "migrations");
9212
- const delim = delimiter2 ?? ";";
9213
+ const delim = delimiter3 ?? ";";
9213
9214
  const db = getAdapter();
9214
9215
  const migrations = await getLastBatchMigrations();
9215
9216
  const rolledBack = [];
@@ -9332,13 +9333,13 @@ function hasExecutableSql(sql) {
9332
9333
  function isUnappliedScaffold(sql) {
9333
9334
  return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
9334
9335
  }
9335
- function splitStatements(sql, delimiter2 = ";") {
9336
+ function splitStatements(sql, delimiter3 = ";") {
9336
9337
  const state = {
9337
9338
  sql: normalizeQuotes(sql),
9338
9339
  statements: [],
9339
9340
  current: "",
9340
- delimiter: delimiter2,
9341
- dlen: delimiter2.length,
9341
+ delimiter: delimiter3,
9342
+ dlen: delimiter3.length,
9342
9343
  i: 0,
9343
9344
  inDollarBlock: false,
9344
9345
  inSlashBlock: false
@@ -9465,18 +9466,18 @@ async function releaseMigrationLock(db, lock) {
9465
9466
  async function migrate(adapter, options) {
9466
9467
  const db = adapter ?? getAdapter();
9467
9468
  const dir = resolve3(options?.migrationsDir ?? "migrations");
9468
- const delimiter2 = options?.delimiter ?? ";";
9469
+ const delimiter3 = options?.delimiter ?? ";";
9469
9470
  if (!existsSync4(dir)) {
9470
9471
  return { applied: [], skipped: [], failed: [] };
9471
9472
  }
9472
9473
  const lock = await acquireMigrationLock(db, dir);
9473
9474
  try {
9474
- return await runPendingMigrations(db, dir, delimiter2);
9475
+ return await runPendingMigrations(db, dir, delimiter3);
9475
9476
  } finally {
9476
9477
  await releaseMigrationLock(db, lock);
9477
9478
  }
9478
9479
  }
9479
- async function runPendingMigrations(db, dir, delimiter2) {
9480
+ async function runPendingMigrations(db, dir, delimiter3) {
9480
9481
  const result = { applied: [], skipped: [], failed: [] };
9481
9482
  await ensureMigrationTableOn(db);
9482
9483
  const files = sortMigrationFiles(
@@ -9522,7 +9523,7 @@ async function runPendingMigrations(db, dir, delimiter2) {
9522
9523
  );
9523
9524
  continue;
9524
9525
  }
9525
- const statements = splitStatements(sqlContent, delimiter2);
9526
+ const statements = splitStatements(sqlContent, delimiter3);
9526
9527
  try {
9527
9528
  await adapterStartTransaction(db);
9528
9529
  for (const stmt of statements) {
@@ -10702,15 +10703,15 @@ function findOutsideQuotes(expr, needle) {
10702
10703
  }
10703
10704
  return -1;
10704
10705
  }
10705
- function splitOutsideQuotes(expr, sep9) {
10706
- if (!expr.includes(sep9)) return [expr];
10706
+ function splitOutsideQuotes(expr, sep10) {
10707
+ if (!expr.includes(sep10)) return [expr];
10707
10708
  const parts = [];
10708
10709
  let currentStart = 0;
10709
10710
  let inQuote = null;
10710
10711
  let depth = 0;
10711
10712
  let bracketDepth = 0;
10712
10713
  let i = 0;
10713
- const sepLen = sep9.length;
10714
+ const sepLen = sep10.length;
10714
10715
  const lastStart = expr.length - sepLen;
10715
10716
  while (i <= lastStart) {
10716
10717
  const ch = expr[i];
@@ -10731,7 +10732,7 @@ function splitOutsideQuotes(expr, sep9) {
10731
10732
  else if (ch === ")") depth--;
10732
10733
  else if (ch === "[") bracketDepth++;
10733
10734
  else if (ch === "]") bracketDepth--;
10734
- if (depth === 0 && bracketDepth === 0 && expr.startsWith(sep9, i)) {
10735
+ if (depth === 0 && bracketDepth === 0 && expr.startsWith(sep10, i)) {
10735
10736
  parts.push(expr.slice(currentStart, i));
10736
10737
  i += sepLen;
10737
10738
  currentStart = i;
@@ -11909,8 +11910,8 @@ var init_engine = __esm({
11909
11910
  },
11910
11911
  first: (v) => Array.isArray(v) ? v[0] ?? null : null,
11911
11912
  last: (v) => Array.isArray(v) ? v[v.length - 1] ?? null : null,
11912
- join: (v, sep9) => Array.isArray(v) ? v.map(String).join(sep9 !== void 0 ? String(sep9) : ", ") : String(v),
11913
- split: (v, sep9) => String(v).split(sep9 !== void 0 ? String(sep9) : " "),
11913
+ join: (v, sep10) => Array.isArray(v) ? v.map(String).join(sep10 !== void 0 ? String(sep10) : ", ") : String(v),
11914
+ split: (v, sep10) => String(v).split(sep10 !== void 0 ? String(sep10) : " "),
11914
11915
  replace: (v, from, to) => {
11915
11916
  const s = String(v);
11916
11917
  if (from !== void 0 && typeof from === "object" && from !== null && !Array.isArray(from)) {
@@ -12053,8 +12054,14 @@ var init_engine = __esm({
12053
12054
  // and every future ``new Frond()`` inherits it automatically.
12054
12055
  // Mirrors Python's _class_globals / _class_filters / _class_tests.
12055
12056
  static classFilters = /* @__PURE__ */ new Map();
12056
- 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 = {};
12057
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;
12058
12065
  // ── Live-block registries (server-rendered {% live %} regions) ──
12059
12066
  // A {% live %} block registers three things when its page first renders:
12060
12067
  // liveFragments[name] -> the raw body source, re-rendered on every
@@ -12074,20 +12081,27 @@ var init_engine = __esm({
12074
12081
  static liveBroadcaster = null;
12075
12082
  /**
12076
12083
  * Register a custom filter at the class level — available to every
12077
- * 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()``
12078
12086
  * (static) or ``frond.addFilter()`` (instance). See instance method
12079
12087
  * below for the dual-call semantics.
12080
12088
  */
12081
12089
  static addFilter(name, fn) {
12082
12090
  _Frond.classFilters.set(name, fn);
12091
+ _Frond.classRegistryVersion++;
12083
12092
  }
12084
12093
  /**
12085
12094
  * Register a global variable available in all templates of every
12086
- * 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
12087
12097
  * ``frond.addGlobal()`` (instance).
12088
12098
  */
12089
12099
  static addGlobal(name, value) {
12090
- _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);
12091
12105
  }
12092
12106
  /**
12093
12107
  * Register a custom test (``{% if x is positive %}``) at the class
@@ -12096,6 +12110,7 @@ var init_engine = __esm({
12096
12110
  */
12097
12111
  static addTest(name, fn) {
12098
12112
  _Frond.classTests.set(name, fn);
12113
+ _Frond.classRegistryVersion++;
12099
12114
  }
12100
12115
  /**
12101
12116
  * Clear the class-level globals/filters/tests registries.
@@ -12105,15 +12120,25 @@ var init_engine = __esm({
12105
12120
  */
12106
12121
  static clearRegistry() {
12107
12122
  _Frond.classFilters.clear();
12108
- _Frond.classGlobals.clear();
12123
+ _Frond.classGlobals = {};
12109
12124
  _Frond.classTests.clear();
12125
+ _Frond.classRegistryVersion++;
12110
12126
  _Frond.liveFragments.clear();
12111
12127
  _Frond.liveSources.clear();
12112
12128
  _Frond.liveWsPaths.clear();
12113
12129
  }
12114
12130
  templateDir;
12115
- 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). */
12116
12139
  globals;
12140
+ /** Built-in globals (formToken, range, dump, csp_nonce, ...). */
12141
+ builtinGlobals;
12117
12142
  tests;
12118
12143
  _sandbox;
12119
12144
  _allowedFilters;
@@ -12143,9 +12168,10 @@ var init_engine = __esm({
12143
12168
  }
12144
12169
  constructor(templateDir = "src/templates") {
12145
12170
  this.templateDir = resolve4(templateDir);
12146
- this.filters = { ...BUILTIN_FILTERS };
12147
12171
  this.globals = {};
12172
+ this.builtinGlobals = {};
12148
12173
  this.tests = {};
12174
+ this.syncRegistries();
12149
12175
  this._sandbox = false;
12150
12176
  this._allowedFilters = null;
12151
12177
  this._allowedTags = null;
@@ -12193,16 +12219,25 @@ var init_engine = __esm({
12193
12219
  return { output, next };
12194
12220
  }
12195
12221
  };
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;
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;
12206
12241
  }
12207
12242
  sandbox(filters, tags, vars) {
12208
12243
  this._sandbox = true;
@@ -12223,6 +12258,7 @@ var init_engine = __esm({
12223
12258
  * for process-global registration. tina4: ADR-0052.
12224
12259
  */
12225
12260
  addFilter(name, fn) {
12261
+ this.localFilters[name] = fn;
12226
12262
  this.filters[name] = fn;
12227
12263
  }
12228
12264
  /**
@@ -12235,6 +12271,7 @@ var init_engine = __esm({
12235
12271
  * Register a custom test on this instance only.
12236
12272
  */
12237
12273
  addTest(name, fn) {
12274
+ this.localTests[name] = fn;
12238
12275
  this.tests[name] = fn;
12239
12276
  }
12240
12277
  /**
@@ -12250,8 +12287,19 @@ var init_engine = __esm({
12250
12287
  const n = parseInt(raw, 10);
12251
12288
  return isNaN(n) || n < 0 ? 0 : n;
12252
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
+ }
12253
12301
  render(template, data) {
12254
- const context = { ...this.globals, ...data || {} };
12302
+ const context = this.withGlobals(data);
12255
12303
  const filePath = join7(this.templateDir, template);
12256
12304
  if (!existsSync5(filePath)) {
12257
12305
  throw new Error(`Template not found: ${filePath}`);
@@ -12274,7 +12322,7 @@ var init_engine = __esm({
12274
12322
  return this.executeWithSource(source, tokens, context);
12275
12323
  }
12276
12324
  renderString(source, data) {
12277
- const context = { ...this.globals, ...data || {} };
12325
+ const context = this.withGlobals(data);
12278
12326
  const key = createHash3("md5").update(source).digest("hex");
12279
12327
  const ttlMs = this.cacheTtlSeconds() * 1e3;
12280
12328
  const cached = this.compiledStrings.get(key);
@@ -16025,6 +16073,7 @@ var init_baseModel = __esm({
16025
16073
  import { randomInt, randomUUID } from "node:crypto";
16026
16074
  import { existsSync as existsSync7, readdirSync as readdirSync3 } from "node:fs";
16027
16075
  import { resolve as resolve5, join as join8 } from "node:path";
16076
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
16028
16077
  function mulberry32(seed) {
16029
16078
  let s = seed | 0;
16030
16079
  return () => {
@@ -16528,7 +16577,7 @@ var init_fakeData = __esm({
16528
16577
  for (const file of files) {
16529
16578
  const fullPath = join8(dir, file);
16530
16579
  try {
16531
- const mod = await import(fullPath);
16580
+ const mod = await import(pathToFileURL2(fullPath).href);
16532
16581
  if (typeof mod.default === "function") {
16533
16582
  await mod.default();
16534
16583
  }
@@ -17253,12 +17302,12 @@ function regexpFn(pattern, value) {
17253
17302
  }
17254
17303
  function resolveStorePath(dbPath) {
17255
17304
  if (dbPath === ":memory:") return dbPath;
17256
- let path10 = dbPath;
17257
- if (!isAbsolute4(path10)) {
17258
- path10 = join9(process.cwd(), path10);
17259
- mkdirSync4(dirname5(path10), { recursive: true });
17305
+ let path9 = dbPath;
17306
+ if (!isAbsolute4(path9)) {
17307
+ path9 = join9(process.cwd(), path9);
17308
+ mkdirSync4(dirname5(path9), { recursive: true });
17260
17309
  }
17261
- return path10;
17310
+ return path9;
17262
17311
  }
17263
17312
  function mongoUriSource() {
17264
17313
  return MONGO_URI_VARS.find((name) => (process.env[name] ?? "").trim() !== "") ?? "";
@@ -17637,8 +17686,8 @@ var init_docstore = __esm({
17637
17686
  path;
17638
17687
  conn;
17639
17688
  collections = /* @__PURE__ */ new Map();
17640
- constructor(path10) {
17641
- this.path = path10 || process.env.TINA4_DOC_STORE_PATH || "data/tina4_docstore.db";
17689
+ constructor(path9) {
17690
+ this.path = path9 || process.env.TINA4_DOC_STORE_PATH || "data/tina4_docstore.db";
17642
17691
  const resolved = resolveStorePath(this.path);
17643
17692
  this.conn = new DatabaseSync2(resolved);
17644
17693
  this.conn.function("regexp", regexpFn);
@@ -17727,8 +17776,8 @@ var init_graphUrl = __esm({
17727
17776
  this.engine = engine;
17728
17777
  this.host = parsed.hostname || "localhost";
17729
17778
  this.port = parsed.port ? parseInt(parsed.port, 10) : ENGINE_DEFAULT_PORT[engine];
17730
- const path10 = (parsed.pathname || "").replace(/^\//, "");
17731
- this.graph = path10 === "" ? null : path10;
17779
+ const path9 = (parsed.pathname || "").replace(/^\//, "");
17780
+ this.graph = path9 === "" ? null : path9;
17732
17781
  this.username = parsed.username ? decodeURIComponent(parsed.username) : null;
17733
17782
  this.password = parsed.password ? decodeURIComponent(parsed.password) : null;
17734
17783
  this.params = {};
@@ -20889,8 +20938,8 @@ function coerceParam(raw, type2) {
20889
20938
  return raw;
20890
20939
  }
20891
20940
  }
20892
- function joinGroupPath(prefix, path10) {
20893
- const full = `${prefix}/${path10.replace(/^\/+/, "")}`;
20941
+ function joinGroupPath(prefix, path9) {
20942
+ const full = `${prefix}/${path9.replace(/^\/+/, "")}`;
20894
20943
  const trimmed = `/${trimSlashes(full)}`;
20895
20944
  return trimmed.replace(/\/+/g, "/");
20896
20945
  }
@@ -20931,26 +20980,26 @@ async function runRouteMiddlewares(middlewares, req2, res) {
20931
20980
  }
20932
20981
  return true;
20933
20982
  }
20934
- function get(path10, handler, middlewares, meta) {
20935
- return defaultRouter.get(path10, handler, middlewares, meta);
20983
+ function get(path9, handler, middlewares, meta) {
20984
+ return defaultRouter.get(path9, handler, middlewares, meta);
20936
20985
  }
20937
- function post(path10, handler, middlewares, meta) {
20938
- return defaultRouter.post(path10, handler, middlewares, meta);
20986
+ function post(path9, handler, middlewares, meta) {
20987
+ return defaultRouter.post(path9, handler, middlewares, meta);
20939
20988
  }
20940
- function put(path10, handler, middlewares, meta) {
20941
- return defaultRouter.put(path10, handler, middlewares, meta);
20989
+ function put(path9, handler, middlewares, meta) {
20990
+ return defaultRouter.put(path9, handler, middlewares, meta);
20942
20991
  }
20943
- function patch(path10, handler, middlewares, meta) {
20944
- return defaultRouter.patch(path10, handler, middlewares, meta);
20992
+ function patch(path9, handler, middlewares, meta) {
20993
+ return defaultRouter.patch(path9, handler, middlewares, meta);
20945
20994
  }
20946
- function del(path10, handler, middlewares, meta) {
20947
- return defaultRouter.delete(path10, handler, middlewares, meta);
20995
+ function del(path9, handler, middlewares, meta) {
20996
+ return defaultRouter.delete(path9, handler, middlewares, meta);
20948
20997
  }
20949
- function any(path10, handler, middlewares, meta) {
20950
- return defaultRouter.any(path10, handler, middlewares, meta);
20998
+ function any(path9, handler, middlewares, meta) {
20999
+ return defaultRouter.any(path9, handler, middlewares, meta);
20951
21000
  }
20952
- function websocket(path10, handler, options) {
20953
- return defaultRouter.websocket(path10, handler, options);
21001
+ function websocket(path9, handler, options) {
21002
+ return defaultRouter.websocket(path9, handler, options);
20954
21003
  }
20955
21004
  var WsRouteRef, RouteRef, Router, RouteGroup, TINA4_DEFAULT_ROUTER, globalRouterHost, defaultRouter;
20956
21005
  var init_router = __esm({
@@ -21098,32 +21147,32 @@ var init_router = __esm({
21098
21147
  /**
21099
21148
  * Register a GET route programmatically.
21100
21149
  */
21101
- get(path10, handler, middlewares, meta) {
21102
- return this.addRoute({ method: "GET", pattern: path10, handler, middlewares, meta });
21150
+ get(path9, handler, middlewares, meta) {
21151
+ return this.addRoute({ method: "GET", pattern: path9, handler, middlewares, meta });
21103
21152
  }
21104
21153
  /**
21105
21154
  * Register a POST route programmatically.
21106
21155
  */
21107
- post(path10, handler, middlewares, meta) {
21108
- return this.addRoute({ method: "POST", pattern: path10, handler, middlewares, meta });
21156
+ post(path9, handler, middlewares, meta) {
21157
+ return this.addRoute({ method: "POST", pattern: path9, handler, middlewares, meta });
21109
21158
  }
21110
21159
  /**
21111
21160
  * Register a PUT route programmatically.
21112
21161
  */
21113
- put(path10, handler, middlewares, meta) {
21114
- return this.addRoute({ method: "PUT", pattern: path10, handler, middlewares, meta });
21162
+ put(path9, handler, middlewares, meta) {
21163
+ return this.addRoute({ method: "PUT", pattern: path9, handler, middlewares, meta });
21115
21164
  }
21116
21165
  /**
21117
21166
  * Register a PATCH route programmatically.
21118
21167
  */
21119
- patch(path10, handler, middlewares, meta) {
21120
- return this.addRoute({ method: "PATCH", pattern: path10, handler, middlewares, meta });
21168
+ patch(path9, handler, middlewares, meta) {
21169
+ return this.addRoute({ method: "PATCH", pattern: path9, handler, middlewares, meta });
21121
21170
  }
21122
21171
  /**
21123
21172
  * Register a DELETE route programmatically.
21124
21173
  */
21125
- delete(path10, handler, middlewares, meta) {
21126
- return this.addRoute({ method: "DELETE", pattern: path10, handler, middlewares, meta });
21174
+ delete(path9, handler, middlewares, meta) {
21175
+ return this.addRoute({ method: "DELETE", pattern: path9, handler, middlewares, meta });
21127
21176
  }
21128
21177
  /**
21129
21178
  * Register an explicit HEAD route. By default the framework auto-handles
@@ -21133,8 +21182,8 @@ var init_router = __esm({
21133
21182
  * logic, custom validator headers without the cost of building the body.
21134
21183
  * The framework still strips the response body for you on the way out.
21135
21184
  */
21136
- head(path10, handler, middlewares, meta) {
21137
- return this.addRoute({ method: "HEAD", pattern: path10, handler, middlewares, meta });
21185
+ head(path9, handler, middlewares, meta) {
21186
+ return this.addRoute({ method: "HEAD", pattern: path9, handler, middlewares, meta });
21138
21187
  }
21139
21188
  /**
21140
21189
  * Register an explicit OPTIONS route. By default the framework auto-
@@ -21142,16 +21191,16 @@ var init_router = __esm({
21142
21191
  * registered for the path and returning 204 (RFC 9110 §9.3.7). Use
21143
21192
  * this to take over that behaviour.
21144
21193
  */
21145
- options(path10, handler, middlewares, meta) {
21146
- return this.addRoute({ method: "OPTIONS", pattern: path10, handler, middlewares, meta });
21194
+ options(path9, handler, middlewares, meta) {
21195
+ return this.addRoute({ method: "OPTIONS", pattern: path9, handler, middlewares, meta });
21147
21196
  }
21148
21197
  /**
21149
21198
  * Register a route that matches ANY HTTP method.
21150
21199
  */
21151
- any(path10, handler, middlewares, meta) {
21200
+ any(path9, handler, middlewares, meta) {
21152
21201
  let lastRef;
21153
21202
  for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
21154
- lastRef = this.addRoute({ method, pattern: path10, handler, middlewares, meta });
21203
+ lastRef = this.addRoute({ method, pattern: path9, handler, middlewares, meta });
21155
21204
  }
21156
21205
  return lastRef;
21157
21206
  }
@@ -21170,14 +21219,14 @@ var init_router = __esm({
21170
21219
  * the trailing slash. Returning the de-slashed pattern lets callers issue
21171
21220
  * a 308 redirect instead of a hard 404 — Python parity.
21172
21221
  */
21173
- match(method, path10) {
21222
+ match(method, path9) {
21174
21223
  const upperMethod = method.toUpperCase();
21175
21224
  const routes = this.routes.get(upperMethod);
21176
21225
  if (routes) {
21177
- const direct = this.matchRoute(routes, path10);
21226
+ const direct = this.matchRoute(routes, path9);
21178
21227
  if (direct) return direct;
21179
- if (isTrailingSlashRedirectEnabled() && path10.length > 1 && path10.endsWith("/")) {
21180
- const stripped = rtrimSlashes(path10);
21228
+ if (isTrailingSlashRedirectEnabled() && path9.length > 1 && path9.endsWith("/")) {
21229
+ const stripped = rtrimSlashes(path9);
21181
21230
  if (stripped.length > 0) {
21182
21231
  const retry = this.matchRoute(routes, stripped);
21183
21232
  if (retry) return retry;
@@ -21187,7 +21236,7 @@ var init_router = __esm({
21187
21236
  if (upperMethod === "HEAD") {
21188
21237
  const getRoutes = this.routes.get("GET");
21189
21238
  if (getRoutes) {
21190
- return this.matchRoute(getRoutes, path10);
21239
+ return this.matchRoute(getRoutes, path9);
21191
21240
  }
21192
21241
  }
21193
21242
  return null;
@@ -21202,13 +21251,13 @@ var init_router = __esm({
21202
21251
  * OPTIONS is appended whenever any method exists for the path (the
21203
21252
  * framework auto-handles OPTIONS).
21204
21253
  */
21205
- methodsAllowedForPath(path10) {
21254
+ methodsAllowedForPath(path9) {
21206
21255
  const order = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
21207
21256
  const seen = /* @__PURE__ */ new Set();
21208
21257
  for (const m of order) {
21209
21258
  const routes = this.routes.get(m);
21210
21259
  if (!routes) continue;
21211
- if (this.matchRoute(routes, path10)) {
21260
+ if (this.matchRoute(routes, path9)) {
21212
21261
  seen.add(m);
21213
21262
  }
21214
21263
  }
@@ -21219,9 +21268,9 @@ var init_router = __esm({
21219
21268
  return order.filter((m) => seen.has(m));
21220
21269
  }
21221
21270
  /** Inner match against a list of compiled routes, no trailing-slash logic. */
21222
- matchRoute(routes, path10) {
21271
+ matchRoute(routes, path9) {
21223
21272
  for (const route of routes) {
21224
- const match = route.regex.exec(path10);
21273
+ const match = route.regex.exec(path9);
21225
21274
  if (match) {
21226
21275
  const params = {};
21227
21276
  for (let i = 0; i < route.paramNames.length; i++) {
@@ -21309,10 +21358,10 @@ var init_router = __esm({
21309
21358
  * When secured, the upgrade handshake requires a valid JWT (Authorization
21310
21359
  * header / `bearer` subprotocol / `?token=`) or the upgrade is rejected.
21311
21360
  */
21312
- websocket(path10, handler, options) {
21313
- this.wsRoutes = this.wsRoutes.filter((r) => r.pattern !== path10);
21361
+ websocket(path9, handler, options) {
21362
+ this.wsRoutes = this.wsRoutes.filter((r) => r.pattern !== path9);
21314
21363
  const route = {
21315
- pattern: path10,
21364
+ pattern: path9,
21316
21365
  handler,
21317
21366
  // Public unless explicitly secured via options OR a handler `_secured` flag.
21318
21367
  authRequired: Boolean(options?.secured ?? handler._secured ?? false)
@@ -21369,54 +21418,54 @@ var init_router = __esm({
21369
21418
  * Register a route for a specific HTTP method.
21370
21419
  * Core registration method — all convenience methods delegate here.
21371
21420
  */
21372
- static add(method, path10, handler, middleware, swaggerMeta, template) {
21421
+ static add(method, path9, handler, middleware, swaggerMeta, template) {
21373
21422
  const m = method.toUpperCase();
21374
21423
  if (m === "ANY") {
21375
- return defaultRouter.any(path10, handler, middleware, swaggerMeta);
21424
+ return defaultRouter.any(path9, handler, middleware, swaggerMeta);
21376
21425
  }
21377
- return defaultRouter.addRoute({ method: m, pattern: path10, handler, middlewares: middleware, meta: swaggerMeta, template });
21426
+ return defaultRouter.addRoute({ method: m, pattern: path9, handler, middlewares: middleware, meta: swaggerMeta, template });
21378
21427
  }
21379
21428
  /**
21380
21429
  * Register a GET route on the default global router.
21381
21430
  */
21382
- static get(path10, handler, middleware, swaggerMeta, template) {
21383
- return defaultRouter.get(path10, handler, middleware, swaggerMeta);
21431
+ static get(path9, handler, middleware, swaggerMeta, template) {
21432
+ return defaultRouter.get(path9, handler, middleware, swaggerMeta);
21384
21433
  }
21385
21434
  /**
21386
21435
  * Register a POST route on the default global router.
21387
21436
  */
21388
- static post(path10, handler, middleware, swaggerMeta, template) {
21389
- return defaultRouter.post(path10, handler, middleware, swaggerMeta);
21437
+ static post(path9, handler, middleware, swaggerMeta, template) {
21438
+ return defaultRouter.post(path9, handler, middleware, swaggerMeta);
21390
21439
  }
21391
21440
  /**
21392
21441
  * Register a PUT route on the default global router.
21393
21442
  */
21394
- static put(path10, handler, middleware, swaggerMeta, template) {
21395
- return defaultRouter.put(path10, handler, middleware, swaggerMeta);
21443
+ static put(path9, handler, middleware, swaggerMeta, template) {
21444
+ return defaultRouter.put(path9, handler, middleware, swaggerMeta);
21396
21445
  }
21397
21446
  /**
21398
21447
  * Register a PATCH route on the default global router.
21399
21448
  */
21400
- static patch(path10, handler, middleware, swaggerMeta, template) {
21401
- return defaultRouter.patch(path10, handler, middleware, swaggerMeta);
21449
+ static patch(path9, handler, middleware, swaggerMeta, template) {
21450
+ return defaultRouter.patch(path9, handler, middleware, swaggerMeta);
21402
21451
  }
21403
21452
  /**
21404
21453
  * Register a DELETE route on the default global router.
21405
21454
  */
21406
- static delete(path10, handler, middleware, swaggerMeta, template) {
21407
- return defaultRouter.delete(path10, handler, middleware, swaggerMeta);
21455
+ static delete(path9, handler, middleware, swaggerMeta, template) {
21456
+ return defaultRouter.delete(path9, handler, middleware, swaggerMeta);
21408
21457
  }
21409
21458
  /**
21410
21459
  * Register a route that matches ANY HTTP method on the default global router.
21411
21460
  */
21412
- static any(path10, handler, middleware, swaggerMeta, template) {
21413
- return defaultRouter.any(path10, handler, middleware, swaggerMeta);
21461
+ static any(path9, handler, middleware, swaggerMeta, template) {
21462
+ return defaultRouter.any(path9, handler, middleware, swaggerMeta);
21414
21463
  }
21415
21464
  /**
21416
21465
  * Register a WebSocket route on the default global router.
21417
21466
  */
21418
- static websocket(path10, handler, options) {
21419
- return defaultRouter.websocket(path10, handler, options);
21467
+ static websocket(path9, handler, options) {
21468
+ return defaultRouter.websocket(path9, handler, options);
21420
21469
  }
21421
21470
  /**
21422
21471
  * Match a WebSocket upgrade path against routes on the default global router.
@@ -21532,57 +21581,57 @@ var init_router = __esm({
21532
21581
  const merged = [...group, ...route];
21533
21582
  return merged.length > 0 ? merged : void 0;
21534
21583
  }
21535
- get(path10, handler, middlewares, meta) {
21584
+ get(path9, handler, middlewares, meta) {
21536
21585
  return this.router.addRoute({
21537
21586
  method: "GET",
21538
- pattern: joinGroupPath(this.prefix, path10),
21587
+ pattern: joinGroupPath(this.prefix, path9),
21539
21588
  handler,
21540
21589
  middlewares: this.mergeMiddlewares(middlewares),
21541
21590
  meta
21542
21591
  });
21543
21592
  }
21544
- post(path10, handler, middlewares, meta) {
21593
+ post(path9, handler, middlewares, meta) {
21545
21594
  return this.router.addRoute({
21546
21595
  method: "POST",
21547
- pattern: joinGroupPath(this.prefix, path10),
21596
+ pattern: joinGroupPath(this.prefix, path9),
21548
21597
  handler,
21549
21598
  middlewares: this.mergeMiddlewares(middlewares),
21550
21599
  meta
21551
21600
  });
21552
21601
  }
21553
- put(path10, handler, middlewares, meta) {
21602
+ put(path9, handler, middlewares, meta) {
21554
21603
  return this.router.addRoute({
21555
21604
  method: "PUT",
21556
- pattern: joinGroupPath(this.prefix, path10),
21605
+ pattern: joinGroupPath(this.prefix, path9),
21557
21606
  handler,
21558
21607
  middlewares: this.mergeMiddlewares(middlewares),
21559
21608
  meta
21560
21609
  });
21561
21610
  }
21562
- patch(path10, handler, middlewares, meta) {
21611
+ patch(path9, handler, middlewares, meta) {
21563
21612
  return this.router.addRoute({
21564
21613
  method: "PATCH",
21565
- pattern: joinGroupPath(this.prefix, path10),
21614
+ pattern: joinGroupPath(this.prefix, path9),
21566
21615
  handler,
21567
21616
  middlewares: this.mergeMiddlewares(middlewares),
21568
21617
  meta
21569
21618
  });
21570
21619
  }
21571
- delete(path10, handler, middlewares, meta) {
21620
+ delete(path9, handler, middlewares, meta) {
21572
21621
  return this.router.addRoute({
21573
21622
  method: "DELETE",
21574
- pattern: joinGroupPath(this.prefix, path10),
21623
+ pattern: joinGroupPath(this.prefix, path9),
21575
21624
  handler,
21576
21625
  middlewares: this.mergeMiddlewares(middlewares),
21577
21626
  meta
21578
21627
  });
21579
21628
  }
21580
- any(path10, handler, middlewares, meta) {
21629
+ any(path9, handler, middlewares, meta) {
21581
21630
  let lastRef;
21582
21631
  for (const method of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
21583
21632
  lastRef = this.router.addRoute({
21584
21633
  method,
21585
- pattern: joinGroupPath(this.prefix, path10),
21634
+ pattern: joinGroupPath(this.prefix, path9),
21586
21635
  handler,
21587
21636
  middlewares: this.mergeMiddlewares(middlewares),
21588
21637
  meta
@@ -21784,6 +21833,7 @@ var init_trustedProxy = __esm({
21784
21833
  // src/response.ts
21785
21834
  import fs2 from "node:fs";
21786
21835
  import nodePath from "node:path";
21836
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
21787
21837
  import { once } from "node:events";
21788
21838
  async function closeSource(source) {
21789
21839
  const s = source;
@@ -21826,7 +21876,7 @@ async function getFrond() {
21826
21876
  return engine;
21827
21877
  }
21828
21878
  async function getFrameworkFrond() {
21829
- const frameworkDir = nodePath.resolve(nodePath.dirname(import.meta.url.replace("file://", "")), "..", "templates");
21879
+ const frameworkDir = nodePath.resolve(nodePath.dirname(fileURLToPath2(import.meta.url)), "..", "templates");
21830
21880
  if (!_frameworkFrond && fs2.existsSync(frameworkDir)) {
21831
21881
  try {
21832
21882
  const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
@@ -22861,9 +22911,9 @@ var init_middleware = __esm({
22861
22911
  const duration = Date.now() - (req2.startTime ?? Date.now());
22862
22912
  const status2 = res.raw.statusCode;
22863
22913
  const method = req2.method ?? "?";
22864
- const path10 = logPath(req2);
22914
+ const path9 = logPath(req2);
22865
22915
  const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
22866
- console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
22916
+ console.log(` ${color}${status2}\x1B[0m ${method} ${path9} \x1B[90m${duration}ms\x1B[0m`);
22867
22917
  return [req2, res];
22868
22918
  }
22869
22919
  };
@@ -23028,7 +23078,7 @@ function createRequest(req2) {
23028
23078
  const xfHost = trustedPeer ? req2.headers["x-forwarded-host"] : void 0;
23029
23079
  const host = (Array.isArray(xfHost) ? xfHost[0] : xfHost) ?? (req2.headers.host ?? "localhost");
23030
23080
  const query = {};
23031
- let path10;
23081
+ let path9;
23032
23082
  let queryString;
23033
23083
  let fullUrl;
23034
23084
  try {
@@ -23037,13 +23087,13 @@ function createRequest(req2) {
23037
23087
  if (isUnsafeFieldName(key)) continue;
23038
23088
  Reflect.set(query, key, value);
23039
23089
  }
23040
- path10 = url.pathname;
23090
+ path9 = url.pathname;
23041
23091
  queryString = url.search.replace(/^\?/, "");
23042
23092
  fullUrl = url.toString();
23043
23093
  } catch {
23044
23094
  const rawTarget = req2.url ?? "/";
23045
23095
  const questionIdx = rawTarget.indexOf("?");
23046
- path10 = questionIdx >= 0 ? rawTarget.slice(0, questionIdx) : rawTarget;
23096
+ path9 = questionIdx >= 0 ? rawTarget.slice(0, questionIdx) : rawTarget;
23047
23097
  queryString = questionIdx >= 0 ? rawTarget.slice(questionIdx + 1) : "";
23048
23098
  try {
23049
23099
  for (const [key, value] of new URLSearchParams(queryString)) {
@@ -23056,7 +23106,7 @@ function createRequest(req2) {
23056
23106
  }
23057
23107
  tReq.params = {};
23058
23108
  w.query = query;
23059
- w.path = path10;
23109
+ w.path = path9;
23060
23110
  w.queryString = queryString;
23061
23111
  w.url = fullUrl;
23062
23112
  tReq.body = void 0;
@@ -23171,14 +23221,14 @@ function extractBoundary(contentType) {
23171
23221
  function parseMultipart(body, boundary) {
23172
23222
  const pairs = [];
23173
23223
  const files = {};
23174
- const delimiter2 = Buffer.from(`--${boundary}`);
23224
+ const delimiter3 = Buffer.from(`--${boundary}`);
23175
23225
  const closeDelimiter = Buffer.from(`--${boundary}--`);
23176
23226
  const crlf = Buffer.from("\r\n");
23177
23227
  const doubleCrlf = Buffer.from("\r\n\r\n");
23178
23228
  let offset = 0;
23179
- const firstIdx = bufferIndexOf(body, delimiter2, offset);
23229
+ const firstIdx = bufferIndexOf(body, delimiter3, offset);
23180
23230
  if (firstIdx === -1) return { fields: {}, files };
23181
- offset = firstIdx + delimiter2.length;
23231
+ offset = firstIdx + delimiter3.length;
23182
23232
  if (body[offset] === 13 && body[offset + 1] === 10) {
23183
23233
  offset += 2;
23184
23234
  }
@@ -23187,7 +23237,7 @@ function parseMultipart(body, boundary) {
23187
23237
  if (headersEnd === -1) break;
23188
23238
  const headersStr = body.subarray(offset, headersEnd).toString("utf-8");
23189
23239
  offset = headersEnd + doubleCrlf.length;
23190
- const nextDelimIdx = bufferIndexOf(body, delimiter2, offset);
23240
+ const nextDelimIdx = bufferIndexOf(body, delimiter3, offset);
23191
23241
  if (nextDelimIdx === -1) break;
23192
23242
  const contentEnd = nextDelimIdx - crlf.length;
23193
23243
  const content = body.subarray(offset, contentEnd);
@@ -23211,7 +23261,7 @@ function parseMultipart(body, boundary) {
23211
23261
  } else if (disposition.name) {
23212
23262
  pairs.push([disposition.name, content.toString("utf-8")]);
23213
23263
  }
23214
- offset = nextDelimIdx + delimiter2.length;
23264
+ offset = nextDelimIdx + delimiter3.length;
23215
23265
  if (body[offset] === 45 && body[offset + 1] === 45) {
23216
23266
  break;
23217
23267
  }
@@ -23771,6 +23821,7 @@ __export(routeDiscovery_exports, {
23771
23821
  });
23772
23822
  import { readdirSync as readdirSync5, statSync as statSync7, mkdirSync as mkdirSync8, writeFileSync as writeFileSync5, existsSync as existsSync9 } from "node:fs";
23773
23823
  import { join as join12, relative, basename as basename2, extname as extname2 } from "node:path";
23824
+ import { pathToFileURL as pathToFileURL3 } from "node:url";
23774
23825
  function boolExport(value) {
23775
23826
  return typeof value === "boolean" ? value : void 0;
23776
23827
  }
@@ -23792,7 +23843,7 @@ async function discoverRoutes(routesDir) {
23792
23843
  const relativePath2 = relative(routesDir, filePath);
23793
23844
  const pattern = filePathToPattern(relativePath2);
23794
23845
  try {
23795
- const moduleUrl = `file://${filePath}?t=${currentMtime}`;
23846
+ const moduleUrl = `${pathToFileURL3(filePath).href}?t=${currentMtime}`;
23796
23847
  const mod = await import(moduleUrl);
23797
23848
  const handler = mod.default ?? mod.handler;
23798
23849
  if (typeof handler !== "function") {
@@ -23833,7 +23884,7 @@ function recordBrokenImport(filePath, error2) {
23833
23884
  try {
23834
23885
  const brokenDir = join12(process.cwd(), "data", ".broken");
23835
23886
  if (!existsSync9(brokenDir)) mkdirSync8(brokenDir, { recursive: true });
23836
- const slug = filePath.replace(/[/\\]/g, "_");
23887
+ const slug = filePath.replace(/[/\\:]/g, "_");
23837
23888
  const payload = JSON.stringify({
23838
23889
  type: "auto_discover_failure",
23839
23890
  file: filePath,
@@ -23973,27 +24024,33 @@ function sleepSync(ms) {
23973
24024
  if (ms <= 0) return;
23974
24025
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
23975
24026
  }
23976
- function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24027
+ function probeBind(host, port, timeout = 5e3) {
24028
+ try {
24029
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout });
24030
+ return "free";
24031
+ } catch (err) {
24032
+ return err.status === PROBE_HELD ? "held" : "unknown";
24033
+ }
24034
+ }
24035
+ function refusal(port, dev, noTakeover, host) {
24036
+ if (dev && !noTakeover) return null;
24037
+ if (host !== void 0 && probeBind(host, port) !== "held") {
24038
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
24039
+ }
24040
+ if (noTakeover) {
24041
+ 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.` };
24042
+ }
24043
+ 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.` };
24044
+ }
24045
+ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500, host) {
23977
24046
  const make = (status2, killed2 = [], message = "") => ({
23978
24047
  status: status2,
23979
24048
  port,
23980
24049
  killed: killed2,
23981
24050
  message
23982
24051
  });
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
- }
24052
+ const early = refusal(port, dev, noTakeover, host);
24053
+ if (early !== null) return early;
23997
24054
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
23998
24055
  const tokens = portHolders(port);
23999
24056
  if (tokens.length === 0) return make(TAKEOVER_NOTHING);
@@ -24025,7 +24082,7 @@ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
24025
24082
  `Reclaimed port ${port} from Tina4 dev server (PID: ${killed.join(", ")}).`
24026
24083
  );
24027
24084
  }
24028
- var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS;
24085
+ var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS, PROBE_HELD, PROBE_OTHER, BIND_PROBE;
24029
24086
  var init_portTakeover = __esm({
24030
24087
  "src/portTakeover.ts"() {
24031
24088
  "use strict";
@@ -24040,6 +24097,9 @@ var init_portTakeover = __esm({
24040
24097
  TAKEOVER_REFUSED_OPTOUT,
24041
24098
  TAKEOVER_REFUSED_PROD
24042
24099
  ];
24100
+ PROBE_HELD = 3;
24101
+ PROBE_OTHER = 4;
24102
+ BIND_PROBE = `const s = require("node:net").createServer();s.on("error", (e) => process.exit(e && e.code === "EADDRINUSE" ? ${PROBE_HELD} : ${PROBE_OTHER}));s.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));`;
24043
24103
  }
24044
24104
  });
24045
24105
 
@@ -25217,6 +25277,21 @@ var init_databaseHandler = __esm({
25217
25277
  }
25218
25278
  return this.sqliteHandle;
25219
25279
  }
25280
+ /**
25281
+ * Release the SQLite connection this handler opened, so its file (and the
25282
+ * WAL's -wal / -shm side files) is no longer held open: on Windows an open
25283
+ * file cannot be deleted or replaced. Idempotent, and the next read or write
25284
+ * reopens the connection. A server engine needs nothing here - each call goes
25285
+ * through the sync bridge, which holds no connection between calls.
25286
+ */
25287
+ close() {
25288
+ if (this.sqliteHandle === null) return;
25289
+ try {
25290
+ this.sqliteHandle.close();
25291
+ } finally {
25292
+ this.sqliteHandle = null;
25293
+ }
25294
+ }
25220
25295
  get engine() {
25221
25296
  return this.target === null ? "sqlite" : this.target.engine;
25222
25297
  }
@@ -26417,8 +26492,8 @@ function tryServeStatic(staticDir, req2, res) {
26417
26492
  }
26418
26493
  return false;
26419
26494
  }
26420
- function hasHiddenSegment(path10, separator = "/") {
26421
- return path10.split(separator).some((segment) => segment.length > 0 && segment.startsWith("."));
26495
+ function hasHiddenSegment(path9, separator = "/") {
26496
+ return path9.split(separator).some((segment) => segment.length > 0 && segment.startsWith("."));
26422
26497
  }
26423
26498
  function conditionalHeader(req2, name) {
26424
26499
  const headers = req2.headers;
@@ -26742,10 +26817,10 @@ function createHealthRoute(version = "3.0.0") {
26742
26817
  function createHealthRoutes(version = "3.0.0") {
26743
26818
  startTime = Date.now();
26744
26819
  const routes = [];
26745
- const path10 = healthPath();
26820
+ const path9 = healthPath();
26746
26821
  routes.push({
26747
26822
  method: "GET",
26748
- pattern: path10,
26823
+ pattern: path9,
26749
26824
  handler: buildHandler(version),
26750
26825
  meta: {
26751
26826
  summary: "Health check",
@@ -26753,7 +26828,7 @@ function createHealthRoutes(version = "3.0.0") {
26753
26828
  tags: ["System"]
26754
26829
  }
26755
26830
  });
26756
- if (path10 !== "/health") {
26831
+ if (path9 !== "/health") {
26757
26832
  routes.push({
26758
26833
  method: "GET",
26759
26834
  pattern: "/health",
@@ -26831,9 +26906,72 @@ var init_rateLimiter = __esm({
26831
26906
  }
26832
26907
  });
26833
26908
 
26909
+ // src/batchSpawn.ts
26910
+ import { spawnSync } from "node:child_process";
26911
+ import { existsSync as existsSync12, statSync as statSync10 } from "node:fs";
26912
+ import { delimiter, extname as extname4, join as join16 } from "node:path";
26913
+ function isBatchFile(file, platform = process.platform) {
26914
+ return platform === "win32" && /\.(cmd|bat)$/i.test(file);
26915
+ }
26916
+ function escapeBatchArgument(arg) {
26917
+ let quoted = String(arg).replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1");
26918
+ quoted = `"${quoted}"`;
26919
+ return quoted.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
26920
+ }
26921
+ function escapeBatchCommand(file) {
26922
+ return file.replace(CMD_META, "^$1");
26923
+ }
26924
+ function findExecutable(name, platform = process.platform) {
26925
+ if (platform !== "win32" || /[\\/]/.test(name) || extname4(name) !== "") return name;
26926
+ const exts = (process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
26927
+ const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
26928
+ const candidates = dirs.flatMap((dir) => exts.map((ext) => join16(dir, name + ext.toLowerCase())));
26929
+ return candidates.find(isRegularFile) ?? name;
26930
+ }
26931
+ function isRegularFile(path9) {
26932
+ try {
26933
+ return existsSync12(path9) && statSync10(path9).isFile();
26934
+ } catch {
26935
+ return false;
26936
+ }
26937
+ }
26938
+ function spawnSyncAllowingBatch(file, args, options = {}) {
26939
+ if (!isBatchFile(file)) return spawnSync(file, args, options);
26940
+ const line = [escapeBatchCommand(file), ...args.map(escapeBatchArgument)].join(" ");
26941
+ const shell = process.env.comspec || "cmd.exe";
26942
+ return spawnSync(shell, ["/d", "/s", "/c", `"${line}"`], {
26943
+ ...options,
26944
+ windowsVerbatimArguments: true
26945
+ });
26946
+ }
26947
+ function execFileSyncAllowingBatch(name, args, options = {}) {
26948
+ const result = spawnSyncAllowingBatch(findExecutable(name), args, { encoding: "utf-8", ...options });
26949
+ if (result.error) throw result.error;
26950
+ const stdout = String(result.stdout ?? "");
26951
+ const stderr = String(result.stderr ?? "");
26952
+ if (result.status !== 0) {
26953
+ const err = new Error(
26954
+ `Command failed: ${name} ${args.join(" ")} (exit ${result.status ?? result.signal})
26955
+ ${stderr}`.trim()
26956
+ );
26957
+ err.status = result.status;
26958
+ err.stdout = stdout;
26959
+ err.stderr = stderr;
26960
+ throw err;
26961
+ }
26962
+ return stdout;
26963
+ }
26964
+ var CMD_META;
26965
+ var init_batchSpawn = __esm({
26966
+ "src/batchSpawn.ts"() {
26967
+ "use strict";
26968
+ CMD_META = /([()\][%!^"`<>&|;, *?])/g;
26969
+ }
26970
+ });
26971
+
26834
26972
  // src/devMailbox.ts
26835
- import { mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync8, unlinkSync as unlinkSync7, existsSync as existsSync12 } from "node:fs";
26836
- import { join as join16 } from "node:path";
26973
+ import { mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync8, unlinkSync as unlinkSync7, existsSync as existsSync13 } from "node:fs";
26974
+ import { join as join17 } from "node:path";
26837
26975
  import { randomUUID as randomUUID2 } from "node:crypto";
26838
26976
  var DevMailbox;
26839
26977
  var init_devMailbox = __esm({
@@ -26848,7 +26986,7 @@ var init_devMailbox = __esm({
26848
26986
  * Ensure a folder directory exists.
26849
26987
  */
26850
26988
  ensureFolder(folder) {
26851
- const dir = join16(this.mailboxDir, folder);
26989
+ const dir = join17(this.mailboxDir, folder);
26852
26990
  mkdirSync11(dir, { recursive: true });
26853
26991
  return dir;
26854
26992
  }
@@ -26887,10 +27025,10 @@ var init_devMailbox = __esm({
26887
27025
  read: false
26888
27026
  };
26889
27027
  const outboxDir = this.ensureFolder("outbox");
26890
- writeFileSync8(join16(outboxDir, `${id}.json`), JSON.stringify(message, null, 2));
27028
+ writeFileSync8(join17(outboxDir, `${id}.json`), JSON.stringify(message, null, 2));
26891
27029
  const inboxDir = this.ensureFolder("inbox");
26892
27030
  const inboxMessage = { ...message, type: "inbox" };
26893
- writeFileSync8(join16(inboxDir, `${id}.json`), JSON.stringify(inboxMessage, null, 2));
27031
+ writeFileSync8(join17(inboxDir, `${id}.json`), JSON.stringify(inboxMessage, null, 2));
26894
27032
  return { success: true, message: "Email captured to dev mailbox", id };
26895
27033
  }
26896
27034
  /**
@@ -26908,7 +27046,7 @@ var init_devMailbox = __esm({
26908
27046
  const sliced = files.slice(offset, offset + limit);
26909
27047
  for (const file of sliced) {
26910
27048
  try {
26911
- const msg = JSON.parse(readFileSync11(join16(dir, file), "utf-8"));
27049
+ const msg = JSON.parse(readFileSync11(join17(dir, file), "utf-8"));
26912
27050
  results.push(msg);
26913
27051
  } catch {
26914
27052
  }
@@ -26921,8 +27059,8 @@ var init_devMailbox = __esm({
26921
27059
  read(msgId) {
26922
27060
  const folders = ["inbox", "outbox"];
26923
27061
  for (const folder of folders) {
26924
- const filePath = join16(this.mailboxDir, folder, `${msgId}.json`);
26925
- if (existsSync12(filePath)) {
27062
+ const filePath = join17(this.mailboxDir, folder, `${msgId}.json`);
27063
+ if (existsSync13(filePath)) {
26926
27064
  try {
26927
27065
  const msg = JSON.parse(readFileSync11(filePath, "utf-8"));
26928
27066
  msg.read = true;
@@ -26945,7 +27083,7 @@ var init_devMailbox = __esm({
26945
27083
  const files = readdirSync7(dir).filter((f) => f.endsWith(".json"));
26946
27084
  for (const file of files) {
26947
27085
  try {
26948
- const msg = JSON.parse(readFileSync11(join16(dir, file), "utf-8"));
27086
+ const msg = JSON.parse(readFileSync11(join17(dir, file), "utf-8"));
26949
27087
  if (!msg.read) count++;
26950
27088
  } catch {
26951
27089
  }
@@ -26961,8 +27099,8 @@ var init_devMailbox = __esm({
26961
27099
  let deleted = false;
26962
27100
  const folders = ["inbox", "outbox"];
26963
27101
  for (const folder of folders) {
26964
- const filePath = join16(this.mailboxDir, folder, `${msgId}.json`);
26965
- if (existsSync12(filePath)) {
27102
+ const filePath = join17(this.mailboxDir, folder, `${msgId}.json`);
27103
+ if (existsSync13(filePath)) {
26966
27104
  try {
26967
27105
  unlinkSync7(filePath);
26968
27106
  deleted = true;
@@ -26978,12 +27116,12 @@ var init_devMailbox = __esm({
26978
27116
  clear(folder) {
26979
27117
  const folders = folder ? [folder] : ["inbox", "outbox"];
26980
27118
  for (const f of folders) {
26981
- const dir = join16(this.mailboxDir, f);
27119
+ const dir = join17(this.mailboxDir, f);
26982
27120
  try {
26983
- if (existsSync12(dir)) {
27121
+ if (existsSync13(dir)) {
26984
27122
  const files = readdirSync7(dir).filter((file) => file.endsWith(".json"));
26985
27123
  for (const file of files) {
26986
- unlinkSync7(join16(dir, file));
27124
+ unlinkSync7(join17(dir, file));
26987
27125
  }
26988
27126
  }
26989
27127
  } catch {
@@ -27036,7 +27174,7 @@ Generated by DevMailbox.seed() for development purposes.`,
27036
27174
  // first two are unread
27037
27175
  };
27038
27176
  const dir = this.ensureFolder("inbox");
27039
- writeFileSync8(join16(dir, `${id}.json`), JSON.stringify(message, null, 2));
27177
+ writeFileSync8(join17(dir, `${id}.json`), JSON.stringify(message, null, 2));
27040
27178
  }
27041
27179
  }
27042
27180
  /**
@@ -27044,9 +27182,9 @@ Generated by DevMailbox.seed() for development purposes.`,
27044
27182
  */
27045
27183
  count(folder) {
27046
27184
  const countDir = (f) => {
27047
- const dir = join16(this.mailboxDir, f);
27185
+ const dir = join17(this.mailboxDir, f);
27048
27186
  try {
27049
- if (existsSync12(dir)) {
27187
+ if (existsSync13(dir)) {
27050
27188
  return readdirSync7(dir).filter((file) => file.endsWith(".json")).length;
27051
27189
  }
27052
27190
  } catch {
@@ -27087,8 +27225,8 @@ var init_upstreamResponse = __esm({
27087
27225
  // src/metrics.ts
27088
27226
  import * as fs3 from "node:fs";
27089
27227
  import * as path2 from "node:path";
27090
- import { spawnSync } from "node:child_process";
27091
- import { fileURLToPath as fileURLToPath2 } from "node:url";
27228
+ import { spawnSync as spawnSync2 } from "node:child_process";
27229
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
27092
27230
  function containsTypeScript(directory) {
27093
27231
  if (!fs3.existsSync(directory) || !fs3.statSync(directory).isDirectory()) return false;
27094
27232
  for (const entry of fs3.readdirSync(directory, { withFileTypes: true })) {
@@ -27099,7 +27237,7 @@ function containsTypeScript(directory) {
27099
27237
  return false;
27100
27238
  }
27101
27239
  function resolveTarget(root = "src") {
27102
- const resolved = containsTypeScript(root) ? path2.resolve(root) : path2.dirname(fileURLToPath2(import.meta.url));
27240
+ const resolved = containsTypeScript(root) ? path2.resolve(root) : path2.dirname(fileURLToPath3(import.meta.url));
27103
27241
  const mode = containsTypeScript(root) ? "project" : "framework";
27104
27242
  lastScanRoot = resolved;
27105
27243
  return [resolved, mode];
@@ -27127,7 +27265,7 @@ function enginePath() {
27127
27265
  function runEngine(target) {
27128
27266
  const binary = enginePath();
27129
27267
  if (!binary) throw new MetricsEngineError(`tina4 not found on PATH - ${INSTALL_HINT}`);
27130
- const processResult = spawnSync(binary, ["metrics", "--path", target, "--json", "--no-history"], {
27268
+ const processResult = spawnSync2(binary, ["metrics", "--path", target, "--json", "--no-history"], {
27131
27269
  encoding: "utf8",
27132
27270
  timeout: 6e4,
27133
27271
  maxBuffer: 64 * 1024 * 1024
@@ -27220,9 +27358,9 @@ var init_metrics = __esm({
27220
27358
  });
27221
27359
 
27222
27360
  // src/feedback.ts
27223
- import { readFileSync as readFileSync12, existsSync as existsSync14 } from "node:fs";
27224
- import { dirname as dirname8, join as join18, resolve as resolve9 } from "node:path";
27225
- import { fileURLToPath as fileURLToPath3 } from "node:url";
27361
+ import { readFileSync as readFileSync12, existsSync as existsSync15 } from "node:fs";
27362
+ import { dirname as dirname8, join as join19, resolve as resolve9 } from "node:path";
27363
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
27226
27364
  function feedbackEnabled() {
27227
27365
  const raw = (process.env.TINA4_ENABLE_FEEDBACK ?? "").trim().toLowerCase();
27228
27366
  return raw === "1" || raw === "true" || raw === "yes" || raw === "on";
@@ -27271,8 +27409,8 @@ function feedbackRateLimitOk(user) {
27271
27409
  }
27272
27410
  function injectFeedbackWidget(request, html) {
27273
27411
  if (!html) return html;
27274
- const path10 = (request.path ?? "") || "";
27275
- if (path10.startsWith("/__dev") || path10.startsWith("/__feedback")) return html;
27412
+ const path9 = (request.path ?? "") || "";
27413
+ if (path9.startsWith("/__dev") || path9.startsWith("/__feedback")) return html;
27276
27414
  if (html.includes("data-tina4-feedback")) return html;
27277
27415
  const [allowed] = feedbackIsWhitelisted(request);
27278
27416
  if (!allowed) return html;
@@ -27348,11 +27486,11 @@ var init_feedback = __esm({
27348
27486
  clearTimeout(timer);
27349
27487
  await relayUpstreamResponse(res, upstream);
27350
27488
  };
27351
- __feedbackDirname = dirname8(fileURLToPath3(import.meta.url));
27489
+ __feedbackDirname = dirname8(fileURLToPath4(import.meta.url));
27352
27490
  WIDGET_BUNDLE_PATH = resolve9(__feedbackDirname, "__feedback", "widget.js");
27353
27491
  handleFeedbackWidgetJs = (_req, res) => {
27354
27492
  let body;
27355
- if (existsSync14(WIDGET_BUNDLE_PATH)) {
27493
+ if (existsSync15(WIDGET_BUNDLE_PATH)) {
27356
27494
  body = readFileSync12(WIDGET_BUNDLE_PATH);
27357
27495
  } else {
27358
27496
  body = "console.warn('tina4-feedback-widget bundle not built yet');";
@@ -27368,14 +27506,14 @@ var init_feedback = __esm({
27368
27506
  });
27369
27507
 
27370
27508
  // src/version.ts
27371
- import { existsSync as existsSync15, readFileSync as readFileSync13 } from "node:fs";
27372
- import { dirname as dirname9, join as join19 } from "node:path";
27373
- import { fileURLToPath as fileURLToPath4 } from "node:url";
27509
+ import { existsSync as existsSync16, readFileSync as readFileSync13 } from "node:fs";
27510
+ import { dirname as dirname9, join as join20 } from "node:path";
27511
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
27374
27512
  function resolveFrameworkVersion() {
27375
- let dir = dirname9(fileURLToPath4(import.meta.url));
27513
+ let dir = dirname9(fileURLToPath5(import.meta.url));
27376
27514
  for (let i = 0; i < 6; i++) {
27377
- const pkgPath = join19(dir, "package.json");
27378
- if (existsSync15(pkgPath)) {
27515
+ const pkgPath = join20(dir, "package.json");
27516
+ if (existsSync16(pkgPath)) {
27379
27517
  try {
27380
27518
  const pkg = JSON.parse(readFileSync13(pkgPath, "utf-8"));
27381
27519
  if (typeof pkg.version === "string" && pkg.version) return pkg.version;
@@ -27457,27 +27595,27 @@ __export(generate_exports, {
27457
27595
  toSnake: () => toSnake,
27458
27596
  toTableName: () => toTableName
27459
27597
  });
27460
- import { existsSync as existsSync16, mkdirSync as mkdirSync12, writeFileSync as writeFileSync9, readdirSync as readdirSync9, copyFileSync } from "node:fs";
27461
- import { join as join20, relative as relative2, resolve as resolve10, sep as sep5, dirname as dirname10 } from "node:path";
27462
- import { fileURLToPath as fileURLToPath5 } from "node:url";
27598
+ import { existsSync as existsSync17, mkdirSync as mkdirSync12, writeFileSync as writeFileSync9, readdirSync as readdirSync9, copyFileSync } from "node:fs";
27599
+ import { join as join21, relative as relative2, resolve as resolve10, sep as sep5, dirname as dirname10 } from "node:path";
27600
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
27463
27601
  function ensureDir(dir) {
27464
27602
  if (__resolution.dryRun) return;
27465
- if (!existsSync16(dir)) {
27603
+ if (!existsSync17(dir)) {
27466
27604
  mkdirSync12(dir, { recursive: true });
27467
27605
  }
27468
27606
  }
27469
- function writeFileSafe(path10, content) {
27470
- captureEditHints(path10, content);
27607
+ function writeFileSafe(path9, content) {
27608
+ captureEditHints(path9, content);
27471
27609
  if (__resolution.dryRun) {
27472
27610
  return;
27473
27611
  }
27474
- if (existsSync16(path10)) {
27475
- if (!__resolution.jsonMode) console.log(` File already exists: ${path10}`);
27612
+ if (existsSync17(path9)) {
27613
+ if (!__resolution.jsonMode) console.log(` File already exists: ${path9}`);
27476
27614
  return;
27477
27615
  }
27478
- writeFileSync9(path10, content, "utf-8");
27479
- __resolution.actionsTaken.push(`wrote ${path10}`);
27480
- if (!__resolution.jsonMode) console.log(` Created ${path10}`);
27616
+ writeFileSync9(path9, content, "utf-8");
27617
+ __resolution.actionsTaken.push(`wrote ${path9}`);
27618
+ if (!__resolution.jsonMode) console.log(` Created ${path9}`);
27481
27619
  }
27482
27620
  function toSnake(name) {
27483
27621
  return name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
@@ -27569,9 +27707,9 @@ function pushRoute(routePattern) {
27569
27707
  if (!__resolution.body.routes) __resolution.body.routes = [];
27570
27708
  __resolution.body.routes.push(routePattern);
27571
27709
  }
27572
- function pushTestPath(path10) {
27710
+ function pushTestPath(path9) {
27573
27711
  if (!__resolution.body.test_paths) __resolution.body.test_paths = [];
27574
- __resolution.body.test_paths.push(path10);
27712
+ __resolution.body.test_paths.push(path9);
27575
27713
  }
27576
27714
  function pushEditHint(hint) {
27577
27715
  if (!__resolution.body.edit_hints) __resolution.body.edit_hints = [];
@@ -27802,7 +27940,7 @@ function generateModel(name, flags, emitTest = true) {
27802
27940
  const table2 = resolveTable(name, flags, { announce: true });
27803
27941
  const dir = resolve10("src/models");
27804
27942
  ensureDir(dir);
27805
- const path10 = join20(dir, `${name}.ts`);
27943
+ const path9 = join21(dir, `${name}.ts`);
27806
27944
  setResolutionField("class_name", name);
27807
27945
  setResolutionField("table_name", table2);
27808
27946
  setResolutionField("file_path", `src/models/${name}.ts`);
@@ -27825,7 +27963,7 @@ ${fieldLines.join("\n")}
27825
27963
  };
27826
27964
  }
27827
27965
  `;
27828
- writeFileSafe(path10, content);
27966
+ writeFileSafe(path9, content);
27829
27967
  if (!flags["no-migration"]) {
27830
27968
  generateMigration(`create_${table2}`, flags, fields, table2, false);
27831
27969
  }
@@ -27842,7 +27980,7 @@ function generateRoute(name, flags, emitTest = true) {
27842
27980
  const model = flags.model;
27843
27981
  const isPublic = Boolean(flags.public);
27844
27982
  const base = resolve10("src/routes/api", routePath);
27845
- const idDir = join20(base, "[id]");
27983
+ const idDir = join21(base, "[id]");
27846
27984
  ensureDir(base);
27847
27985
  ensureDir(idDir);
27848
27986
  pushRoute(`/api/${routePath}`);
@@ -27858,7 +27996,7 @@ function generateRoute(name, flags, emitTest = true) {
27858
27996
  const writeDoc = isPublic ? "Public (--public): no token required." : "Secure by default: requires a Bearer token (use --public to open).";
27859
27997
  if (model) {
27860
27998
  writeFileSafe(
27861
- join20(base, "get.ts"),
27999
+ join21(base, "get.ts"),
27862
28000
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27863
28001
  ${modelImportBase}
27864
28002
  export const meta = { summary: "List all ${routePath}", tags: ["${routePath}"] };
@@ -27875,7 +28013,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
27875
28013
  );
27876
28014
  } else {
27877
28015
  writeFileSafe(
27878
- join20(base, "get.ts"),
28016
+ join21(base, "get.ts"),
27879
28017
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27880
28018
 
27881
28019
  export const meta = { summary: "List all ${routePath}", tags: ["${routePath}"] };
@@ -27894,7 +28032,7 @@ ${aiFill(`list_${routePath}`, {
27894
28032
  }
27895
28033
  if (model) {
27896
28034
  writeFileSafe(
27897
- join20(base, "post.ts"),
28035
+ join21(base, "post.ts"),
27898
28036
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27899
28037
  ${modelImportBase}${secureOptOut(isPublic)}export const meta = { summary: "Create a new ${singular}", tags: ["${routePath}"] };
27900
28038
 
@@ -27917,7 +28055,7 @@ ${extend(
27917
28055
  );
27918
28056
  } else {
27919
28057
  writeFileSafe(
27920
- join20(base, "post.ts"),
28058
+ join21(base, "post.ts"),
27921
28059
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27922
28060
 
27923
28061
  ${secureOptOut(isPublic)}export const meta = { summary: "Create a new ${singular}", tags: ["${routePath}"] };
@@ -27938,7 +28076,7 @@ ${aiFill(`create_${singular}`, {
27938
28076
  }
27939
28077
  if (model) {
27940
28078
  writeFileSafe(
27941
- join20(idDir, "get.ts"),
28079
+ join21(idDir, "get.ts"),
27942
28080
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27943
28081
  ${modelImportId}
27944
28082
  export const meta = { summary: "Get a ${singular} by ID", tags: ["${routePath}"] };
@@ -27956,7 +28094,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
27956
28094
  );
27957
28095
  } else {
27958
28096
  writeFileSafe(
27959
- join20(idDir, "get.ts"),
28097
+ join21(idDir, "get.ts"),
27960
28098
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27961
28099
 
27962
28100
  export const meta = { summary: "Get a ${singular} by ID", tags: ["${routePath}"] };
@@ -27975,7 +28113,7 @@ ${aiFill(`get_${singular}`, {
27975
28113
  }
27976
28114
  if (model) {
27977
28115
  writeFileSafe(
27978
- join20(idDir, "put.ts"),
28116
+ join21(idDir, "put.ts"),
27979
28117
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
27980
28118
  ${modelImportId}${secureOptOut(isPublic)}export const meta = { summary: "Update a ${singular} by ID", tags: ["${routePath}"] };
27981
28119
 
@@ -28004,7 +28142,7 @@ ${extend(
28004
28142
  );
28005
28143
  } else {
28006
28144
  writeFileSafe(
28007
- join20(idDir, "put.ts"),
28145
+ join21(idDir, "put.ts"),
28008
28146
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28009
28147
 
28010
28148
  ${secureOptOut(isPublic)}export const meta = { summary: "Update a ${singular} by ID", tags: ["${routePath}"] };
@@ -28025,7 +28163,7 @@ ${aiFill(`update_${singular}`, {
28025
28163
  }
28026
28164
  if (model) {
28027
28165
  writeFileSafe(
28028
- join20(idDir, "delete.ts"),
28166
+ join21(idDir, "delete.ts"),
28029
28167
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28030
28168
  ${modelImportId}${secureOptOut(isPublic)}export const meta = { summary: "Delete a ${singular} by ID", tags: ["${routePath}"] };
28031
28169
 
@@ -28044,7 +28182,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28044
28182
  );
28045
28183
  } else {
28046
28184
  writeFileSafe(
28047
- join20(idDir, "delete.ts"),
28185
+ join21(idDir, "delete.ts"),
28048
28186
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28049
28187
 
28050
28188
  ${secureOptOut(isPublic)}export const meta = { summary: "Delete a ${singular} by ID", tags: ["${routePath}"] };
@@ -28121,10 +28259,10 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28121
28259
  return res.html(await Crud.toCrud(req, { model: ${model}, title: "${model} Admin"${publicOpt} }));
28122
28260
  }
28123
28261
  `;
28124
- writeFileSafe(join20(dir, "get.ts"), content);
28262
+ writeFileSafe(join21(dir, "get.ts"), content);
28125
28263
  }
28126
28264
  function frameworkCrudTemplatesDir() {
28127
- const here = dirname10(fileURLToPath5(import.meta.url));
28265
+ const here = dirname10(fileURLToPath6(import.meta.url));
28128
28266
  const candidates = [
28129
28267
  resolve10(here, "../../../core/templates/crud"),
28130
28268
  // monorepo: packages/cli/src/commands -> packages/core/templates/crud
@@ -28133,7 +28271,7 @@ function frameworkCrudTemplatesDir() {
28133
28271
  resolve10(here, "../templates/crud")
28134
28272
  // flattened publish fallback
28135
28273
  ];
28136
- return candidates.find((c) => existsSync16(c)) ?? null;
28274
+ return candidates.find((c) => existsSync17(c)) ?? null;
28137
28275
  }
28138
28276
  function copyCrudTemplates() {
28139
28277
  const sourceDir = frameworkCrudTemplatesDir();
@@ -28144,13 +28282,13 @@ function copyCrudTemplates() {
28144
28282
  const targetDir = resolve10("src/templates/crud");
28145
28283
  ensureDir(targetDir);
28146
28284
  for (const file of readdirSync9(sourceDir).filter((f) => f.endsWith(".twig")).sort()) {
28147
- const dest = join20(targetDir, file);
28148
- if (existsSync16(dest)) {
28285
+ const dest = join21(targetDir, file);
28286
+ if (existsSync17(dest)) {
28149
28287
  if (!__resolution.jsonMode) console.log(` File already exists: ${dest}`);
28150
28288
  continue;
28151
28289
  }
28152
28290
  if (__resolution.dryRun) continue;
28153
- copyFileSync(join20(sourceDir, file), dest);
28291
+ copyFileSync(join21(sourceDir, file), dest);
28154
28292
  __resolution.actionsTaken.push(`wrote ${dest}`);
28155
28293
  if (!__resolution.jsonMode) console.log(` Created ${dest}`);
28156
28294
  }
@@ -28208,7 +28346,7 @@ ${writeCase}
28208
28346
  console.log(\`\\nResults: \${pass} passed, \${fail} failed\`);
28209
28347
  process.exit(fail > 0 ? 1 : 0);
28210
28348
  `;
28211
- writeFileSafe(join20(dir, `${table2}.test.ts`), content);
28349
+ writeFileSafe(join21(dir, `${table2}.test.ts`), content);
28212
28350
  }
28213
28351
  function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest = true) {
28214
28352
  const ts = timestamp();
@@ -28228,7 +28366,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
28228
28366
  const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
28229
28367
  const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
28230
28368
  const fileName = `${ts}_${name}.sql`;
28231
- const path10 = join20(dir, fileName);
28369
+ const path9 = join21(dir, fileName);
28232
28370
  setResolutionField("migration_path", `migrations/${fileName}`);
28233
28371
  if (__resolution.target === "migration") {
28234
28372
  setResolutionField("file_path", `migrations/${fileName}`);
@@ -28269,8 +28407,8 @@ DROP TABLE IF EXISTS ${table2};`;
28269
28407
  -- UP
28270
28408
  ${upSql}
28271
28409
  `;
28272
- writeFileSafe(path10, content);
28273
- const downPath = join20(dir, `${ts}_${name}.down.sql`);
28410
+ writeFileSafe(path9, content);
28411
+ const downPath = join21(dir, `${ts}_${name}.down.sql`);
28274
28412
  const downContent = `-- Rollback: ${name}
28275
28413
  -- Created: ${now}
28276
28414
 
@@ -28283,7 +28421,7 @@ function generateMiddleware(name, _flags) {
28283
28421
  const snake = toSnake(name);
28284
28422
  const dir = resolve10("src/middleware");
28285
28423
  ensureDir(dir);
28286
- const path10 = join20(dir, `${snake}.ts`);
28424
+ const path9 = join21(dir, `${snake}.ts`);
28287
28425
  if (__resolution.target === "middleware") {
28288
28426
  setResolutionField("class_name", name);
28289
28427
  setResolutionField("file_path", `src/middleware/${snake}.ts`);
@@ -28321,7 +28459,7 @@ export async function after${name}(
28321
28459
  await next();
28322
28460
  }
28323
28461
  `;
28324
- writeFileSafe(path10, content);
28462
+ writeFileSafe(path9, content);
28325
28463
  emitMiddlewareTest(name, snake);
28326
28464
  }
28327
28465
  function generateTest(name, flags) {
@@ -28330,7 +28468,7 @@ function generateTest(name, flags) {
28330
28468
  const model = flags.model;
28331
28469
  const dir = resolve10("tests");
28332
28470
  ensureDir(dir);
28333
- const path10 = join20(dir, `${snake}.test.ts`);
28471
+ const path9 = join21(dir, `${snake}.test.ts`);
28334
28472
  if (model && flags["secure-writes"]) {
28335
28473
  const isPublic = Boolean(flags.public);
28336
28474
  const posture = isPublic ? "open (--public)" : "gated";
@@ -28379,7 +28517,7 @@ ${writeCase}
28379
28517
  console.log(\`\\nResults: \${pass} passed, \${fail} failed\`);
28380
28518
  process.exit(fail > 0 ? 1 : 0);
28381
28519
  `;
28382
- writeFileSafe(path10, content2);
28520
+ writeFileSafe(path9, content2);
28383
28521
  return;
28384
28522
  }
28385
28523
  let content;
@@ -28445,7 +28583,7 @@ const test${titleName} = tests(
28445
28583
  void test${titleName};
28446
28584
  `;
28447
28585
  }
28448
- writeFileSafe(path10, content);
28586
+ writeFileSafe(path9, content);
28449
28587
  void singular;
28450
28588
  }
28451
28589
  function generateForm2(name, flags) {
@@ -28468,7 +28606,7 @@ function generateForm2(name, flags) {
28468
28606
  };
28469
28607
  const dir = resolve10("src/templates/forms");
28470
28608
  ensureDir(dir);
28471
- const path10 = join20(dir, `${table2}.twig`);
28609
+ const path9 = join21(dir, `${table2}.twig`);
28472
28610
  let fieldHtml = "";
28473
28611
  for (const [fname, ftype] of fields) {
28474
28612
  const itype = inputTypes[ftype] || "text";
@@ -28512,7 +28650,7 @@ function generateForm2(name, flags) {
28512
28650
  </div>
28513
28651
  {% endblock %}
28514
28652
  `;
28515
- writeFileSafe(path10, content);
28653
+ writeFileSafe(path9, content);
28516
28654
  }
28517
28655
  function generateView(name, flags) {
28518
28656
  const fields = fieldsOrDefault(flags.fields || "");
@@ -28521,7 +28659,7 @@ function generateView(name, flags) {
28521
28659
  const cols = fields.map(([f]) => f);
28522
28660
  const dir = resolve10("src/templates/pages");
28523
28661
  ensureDir(dir);
28524
- const listPath = join20(dir, `${routeName}.twig`);
28662
+ const listPath = join21(dir, `${routeName}.twig`);
28525
28663
  const th = cols.map((c) => ` <th>${c.replace(/_/g, " ").replace(/\b\w/g, (ch) => ch.toUpperCase())}</th>`).join("\n");
28526
28664
  const td = cols.map((c) => ` <td>{{ item.${c} }}</td>`).join("\n");
28527
28665
  const listContent = `{% extends "base.twig" %}
@@ -28558,7 +28696,7 @@ ${td}
28558
28696
  {% endblock %}
28559
28697
  `;
28560
28698
  writeFileSafe(listPath, listContent);
28561
- const detailPath = join20(dir, `${table2}.twig`);
28699
+ const detailPath = join21(dir, `${table2}.twig`);
28562
28700
  const detailFields = cols.map((c) => ` <div class="mb-3"><strong>${c.replace(/_/g, " ").replace(/\b\w/g, (ch) => ch.toUpperCase())}:</strong> {{ item.${c} }}</div>`).join("\n");
28563
28701
  const detailContent = `{% extends "base.twig" %}
28564
28702
  {% block title %}${name} Detail{% endblock %}
@@ -28588,7 +28726,7 @@ function generateAuth(_flags) {
28588
28726
  ensureDir(loginDir);
28589
28727
  ensureDir(meDir);
28590
28728
  writeFileSafe(
28591
- join20(registerDir, "post.ts"),
28729
+ join21(registerDir, "post.ts"),
28592
28730
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28593
28731
  import { hashPassword } from "tina4-nodejs";
28594
28732
  import User from "../../../../models/User.js";
@@ -28620,7 +28758,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28620
28758
  `
28621
28759
  );
28622
28760
  writeFileSafe(
28623
- join20(loginDir, "post.ts"),
28761
+ join21(loginDir, "post.ts"),
28624
28762
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28625
28763
  import { checkPassword, getToken } from "tina4-nodejs";
28626
28764
  import User from "../../../../models/User.js";
@@ -28653,7 +28791,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28653
28791
  `
28654
28792
  );
28655
28793
  writeFileSafe(
28656
- join20(meDir, "get.ts"),
28794
+ join21(meDir, "get.ts"),
28657
28795
  `import type { Tina4Request, Tina4Response } from "tina4-nodejs";
28658
28796
  import { authenticateRequest } from "tina4-nodejs";
28659
28797
 
@@ -28672,7 +28810,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28672
28810
  const formsDir = resolve10("src/templates/forms");
28673
28811
  ensureDir(formsDir);
28674
28812
  writeFileSafe(
28675
- join20(formsDir, "login.twig"),
28813
+ join21(formsDir, "login.twig"),
28676
28814
  `{% extends "base.twig" %}
28677
28815
  {% block title %}Login{% endblock %}
28678
28816
  {% block content %}
@@ -28700,7 +28838,7 @@ export default async function (req: Tina4Request, res: Tina4Response) {
28700
28838
  `
28701
28839
  );
28702
28840
  writeFileSafe(
28703
- join20(formsDir, "register.twig"),
28841
+ join21(formsDir, "register.twig"),
28704
28842
  `{% extends "base.twig" %}
28705
28843
  {% block title %}Register{% endblock %}
28706
28844
  {% block content %}
@@ -28739,7 +28877,7 @@ function generateService(name, flags) {
28739
28877
  const cron = flags.cron;
28740
28878
  const dir = resolve10("src/services");
28741
28879
  ensureDir(dir);
28742
- const path10 = join20(dir, `${snake}.ts`);
28880
+ const path9 = join21(dir, `${snake}.ts`);
28743
28881
  let scheduleField;
28744
28882
  let note;
28745
28883
  if (cron && cron !== true) {
@@ -28782,7 +28920,7 @@ export default {
28782
28920
  ${scheduleField}
28783
28921
  };
28784
28922
  `;
28785
- writeFileSafe(path10, content);
28923
+ writeFileSafe(path9, content);
28786
28924
  emitServiceTest(name, snake, camel);
28787
28925
  }
28788
28926
  function generateQueue(name, _flags) {
@@ -28791,7 +28929,7 @@ function generateQueue(name, _flags) {
28791
28929
  const pascal = toPascal(topic) || "Topic";
28792
28930
  const dir = resolve10("src/services");
28793
28931
  ensureDir(dir);
28794
- const path10 = join20(dir, `${slug}_consumer.ts`);
28932
+ const path9 = join21(dir, `${slug}_consumer.ts`);
28795
28933
  const body = aiFill(`handle${pascal}`, {
28796
28934
  intent: `process ONE ${topic} job payload`,
28797
28935
  given: "payload -> the produced job data (job.payload)",
@@ -28846,13 +28984,13 @@ export default {
28846
28984
  daemon: true,
28847
28985
  };
28848
28986
  `;
28849
- writeFileSafe(path10, content);
28987
+ writeFileSafe(path9, content);
28850
28988
  emitQueueTest(topic, slug, pascal);
28851
28989
  }
28852
28990
  function generateValidator(name, _flags) {
28853
28991
  const dir = resolve10("src/validators");
28854
28992
  ensureDir(dir);
28855
- const path10 = join20(dir, `${toSnake(name)}.ts`);
28993
+ const path9 = join21(dir, `${toSnake(name)}.ts`);
28856
28994
  const rules = extend(
28857
28995
  "add / adjust the validation rules for this payload",
28858
28996
  `e.g. .email("email").minLength("name", 2).integer("age"); ground: tina4_context("validate request body with Validator", "nodejs")`
@@ -28873,14 +29011,14 @@ ${rules} validator.required("name"); // starter rule (matches the model's def
28873
29011
  return validator;
28874
29012
  }
28875
29013
  `;
28876
- writeFileSafe(path10, content);
29014
+ writeFileSafe(path9, content);
28877
29015
  emitValidatorTest(name, toSnake(name), toPascal(name));
28878
29016
  }
28879
29017
  function generateSeeder(name, flags) {
28880
29018
  const table2 = resolveTable(name, flags, { announce: false });
28881
29019
  const dir = resolve10("src/seeds");
28882
29020
  ensureDir(dir);
28883
- const path10 = join20(dir, `${table2}_seeder.ts`);
29021
+ const path9 = join21(dir, `${table2}_seeder.ts`);
28884
29022
  const overrides = extend(
28885
29023
  "override fields that need a specific shape (seedOrm auto-fills the rest)",
28886
29024
  `e.g. return { email: (f) => f.email(), status: "active" }; ground: tina4_context("seed ORM model with FakeData", "nodejs")`
@@ -28914,7 +29052,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
28914
29052
  await run();
28915
29053
  }
28916
29054
  `;
28917
- writeFileSafe(path10, content);
29055
+ writeFileSafe(path9, content);
28918
29056
  emitSeederTest(name, table2);
28919
29057
  }
28920
29058
  function generateWebsocket(name, _flags) {
@@ -28925,7 +29063,7 @@ function generateWebsocket(name, _flags) {
28925
29063
  const handlerName = `${toCamel(toPascal(base))}Ws`;
28926
29064
  const dir = resolve10("src/routes");
28927
29065
  ensureDir(dir);
28928
- const path10 = join20(dir, `ws_${base}.ts`);
29066
+ const path9 = join21(dir, `ws_${base}.ts`);
28929
29067
  const body = aiFill(handlerName, {
28930
29068
  intent: `handle an inbound "message" frame on ${wsPath}`,
28931
29069
  given: "data -> the message payload (string); connection -> WebSocketConnection",
@@ -28967,7 +29105,7 @@ ${body}}
28967
29105
 
28968
29106
  websocket("${wsPath}", ${handlerName});
28969
29107
  `;
28970
- writeFileSafe(path10, content);
29108
+ writeFileSafe(path9, content);
28971
29109
  emitWebsocketTest(wsPath, base, handlerName);
28972
29110
  }
28973
29111
  function generateListener(name, _flags) {
@@ -28976,7 +29114,7 @@ function generateListener(name, _flags) {
28976
29114
  const handlerName = `on${toPascal(slug)}`;
28977
29115
  const dir = resolve10("src/listeners");
28978
29116
  ensureDir(dir);
28979
- const path10 = join20(dir, `${slug}.ts`);
29117
+ const path9 = join21(dir, `${slug}.ts`);
28980
29118
  const body = aiFill(handlerName, {
28981
29119
  intent: `react to the '${event}' event`,
28982
29120
  given: `args -> whatever Events.emit("${event}", ...args) passed`,
@@ -29002,13 +29140,13 @@ ${body}}
29002
29140
 
29003
29141
  Events.on("${event}", ${handlerName});
29004
29142
  `;
29005
- writeFileSafe(path10, content);
29143
+ writeFileSafe(path9, content);
29006
29144
  emitListenerTest(event, slug);
29007
29145
  }
29008
29146
  function writeTest(testName, content) {
29009
29147
  const dir = resolve10("tests");
29010
29148
  ensureDir(dir);
29011
- writeFileSafe(join20(dir, `${testName}.test.ts`), content);
29149
+ writeFileSafe(join21(dir, `${testName}.test.ts`), content);
29012
29150
  }
29013
29151
  function standaloneTest(doc, body) {
29014
29152
  return `${doc}
@@ -29674,7 +29812,6 @@ __export(mcp_exports, {
29674
29812
  import * as fs4 from "node:fs";
29675
29813
  import * as path3 from "node:path";
29676
29814
  import * as os from "node:os";
29677
- import { spawnSync as spawnSync2 } from "node:child_process";
29678
29815
  import { createRequire as createRequire7 } from "node:module";
29679
29816
  import { randomBytes as randomBytes7 } from "node:crypto";
29680
29817
  function reqSibling(pkg) {
@@ -30003,7 +30140,7 @@ function verifyNodeSyntax(absPath, relPath) {
30003
30140
  if (!target) return null;
30004
30141
  const { cmd, args } = syntaxCheckCommand(absPath, target.ext);
30005
30142
  try {
30006
- const proc = spawnSync2(cmd, args, {
30143
+ const proc = spawnSyncAllowingBatch(findExecutable(cmd), args, {
30007
30144
  encoding: "utf-8",
30008
30145
  timeout: 5e3,
30009
30146
  cwd: path3.dirname(path3.dirname(absPath))
@@ -30884,13 +31021,13 @@ function registerDevTools(server) {
30884
31021
  "git_status",
30885
31022
  () => {
30886
31023
  try {
30887
- const { execFileSync: execFileSync6 } = req("node:child_process");
31024
+ const { execFileSync: execFileSync5 } = req("node:child_process");
30888
31025
  const cwd = path3.resolve(process.cwd());
30889
31026
  const run = (args) => {
30890
- return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
31027
+ return execFileSync5("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30891
31028
  };
30892
31029
  try {
30893
- execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
31030
+ execFileSync5("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30894
31031
  } catch {
30895
31032
  return { error: "Not a git repository" };
30896
31033
  }
@@ -31018,6 +31155,7 @@ var init_mcp = __esm({
31018
31155
  "src/mcp.ts"() {
31019
31156
  "use strict";
31020
31157
  init_slashTrim();
31158
+ init_batchSpawn();
31021
31159
  init_version();
31022
31160
  req = createRequire7(import.meta.url);
31023
31161
  PARSE_ERROR = -32700;
@@ -32479,7 +32617,7 @@ function pack(segments, maxLines) {
32479
32617
  }
32480
32618
  return chunks;
32481
32619
  }
32482
- function chunkCode(text, path10 = "", maxLines = 60) {
32620
+ function chunkCode(text, path9 = "", maxLines = 60) {
32483
32621
  const lines = splitLines(text);
32484
32622
  let bounds = [];
32485
32623
  for (let i = 0; i < lines.length; i++) {
@@ -32493,7 +32631,7 @@ function chunkCode(text, path10 = "", maxLines = 60) {
32493
32631
  for (let k = 0; k < bounds.length; k++) {
32494
32632
  segments.push(lines.slice(bounds[k], ends[k]));
32495
32633
  }
32496
- const header = path10 ? `# file: ${path10}` : null;
32634
+ const header = path9 ? `# file: ${path9}` : null;
32497
32635
  const packed = pack(segments, maxLines);
32498
32636
  const out = [];
32499
32637
  for (let i = 0; i < packed.length; i++) {
@@ -32544,8 +32682,8 @@ __export(context_exports, {
32544
32682
  fts5Supported: () => fts5Supported
32545
32683
  });
32546
32684
  import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
32547
- import { existsSync as existsSync18, mkdirSync as mkdirSync14, readFileSync as readFileSync15, readdirSync as readdirSync11, realpathSync as realpathSync5 } from "node:fs";
32548
- import { basename as basename4, dirname as dirname12, extname as extname5, isAbsolute as isAbsolute6, join as join22, relative as relative4, resolve as resolve12 } from "node:path";
32685
+ import { existsSync as existsSync19, mkdirSync as mkdirSync14, readFileSync as readFileSync15, readdirSync as readdirSync11, realpathSync as realpathSync5 } from "node:fs";
32686
+ import { basename as basename4, dirname as dirname12, extname as extname6, isAbsolute as isAbsolute6, join as join23, relative as relative4, resolve as resolve12 } from "node:path";
32549
32687
  function fts5Supported() {
32550
32688
  try {
32551
32689
  const conn = new DatabaseSync4(":memory:");
@@ -32568,13 +32706,13 @@ function realResolve(abs) {
32568
32706
  } catch {
32569
32707
  }
32570
32708
  try {
32571
- return join22(realpathSync5(dirname12(abs)), basename4(abs));
32709
+ return join23(realpathSync5(dirname12(abs)), basename4(abs));
32572
32710
  } catch {
32573
32711
  return abs;
32574
32712
  }
32575
32713
  }
32576
32714
  function dbKey(db) {
32577
- return resolve12(db ? String(db) : join22(process.cwd(), ".tina4", "context.db"));
32715
+ return resolve12(db ? String(db) : join23(process.cwd(), ".tina4", "context.db"));
32578
32716
  }
32579
32717
  function defaultContext(root, db) {
32580
32718
  const key = dbKey(db);
@@ -32680,7 +32818,7 @@ var init_context = __esm({
32680
32818
  }
32681
32819
  // ── indexing ───────────────────────────────────────────────
32682
32820
  static chunksFor(label, text) {
32683
- const ext = extname5(label).toLowerCase();
32821
+ const ext = extname6(label).toLowerCase();
32684
32822
  const special = SPECIAL_FILES.has(basename4(label).toLowerCase());
32685
32823
  if (CODE_EXTS.has(ext) || CONFIG_EXTS.has(ext) || special) {
32686
32824
  return chunkCode(text, label);
@@ -32719,7 +32857,7 @@ var init_context = __esm({
32719
32857
  static eligible(filename) {
32720
32858
  const fn = filename.toLowerCase();
32721
32859
  if (fn.endsWith(".min.js")) return false;
32722
- const ext = extname5(fn);
32860
+ const ext = extname6(fn);
32723
32861
  return CODE_EXTS.has(ext) || DOC_EXTS.has(ext) || CONFIG_EXTS.has(ext) || SPECIAL_FILES.has(fn);
32724
32862
  }
32725
32863
  /**
@@ -32747,11 +32885,11 @@ var init_context = __esm({
32747
32885
  files.sort();
32748
32886
  for (const fn of files) {
32749
32887
  if (!_Context.eligible(fn)) continue;
32750
- const full = join22(dir, fn);
32888
+ const full = join23(dir, fn);
32751
32889
  const rel = relative4(rootAbs, full);
32752
32890
  total += this.indexPath(full, rel);
32753
32891
  }
32754
- for (const d of subdirs) walk2(join22(dir, d));
32892
+ for (const d of subdirs) walk2(join23(dir, d));
32755
32893
  };
32756
32894
  walk2(rootAbs);
32757
32895
  return total;
@@ -32767,7 +32905,7 @@ var init_context = __esm({
32767
32905
  reindexFile(changedPath) {
32768
32906
  if (!this.available || this.root === null) return -1;
32769
32907
  const raw = String(changedPath);
32770
- const abs = isAbsolute6(raw) ? raw : join22(process.cwd(), raw);
32908
+ const abs = isAbsolute6(raw) ? raw : join23(process.cwd(), raw);
32771
32909
  const resolved = realResolve(resolve12(abs));
32772
32910
  const rel = relative4(this.root, resolved);
32773
32911
  if (rel === "" || rel.startsWith("..") || isAbsolute6(rel)) {
@@ -32780,7 +32918,7 @@ var init_context = __esm({
32780
32918
  }
32781
32919
  if (!_Context.eligible(basename4(rel))) return -1;
32782
32920
  const stored = rel;
32783
- if (!existsSync18(abs)) {
32921
+ if (!existsSync19(abs)) {
32784
32922
  this.conn.prepare("DELETE FROM chunks WHERE path = ?").run(stored);
32785
32923
  return 0;
32786
32924
  }
@@ -32798,8 +32936,8 @@ var init_context = __esm({
32798
32936
  const expr = [...toks].sort().map((t) => `"${t}"`).join(" OR ");
32799
32937
  return { expr, toks };
32800
32938
  }
32801
- static isTestlike(path10) {
32802
- const s = (path10 || "").toLowerCase();
32939
+ static isTestlike(path9) {
32940
+ const s = (path9 || "").toLowerCase();
32803
32941
  return ["/test", "test/", "test_", "_test.", ".test.", "/example", "example/"].some((p) => s.includes(p));
32804
32942
  }
32805
32943
  static defines(foldedBody, symbols) {
@@ -33263,7 +33401,7 @@ function parseFrame(data) {
33263
33401
  const payload = data.subarray(offset, offset + payloadLen);
33264
33402
  return { fin: !!fin, opcode, payload: Buffer.from(payload), bytesConsumed: offset + payloadLen };
33265
33403
  }
33266
- function createRouteConnection(socket, path10, headers, params, auth) {
33404
+ function createRouteConnection(socket, path9, headers, params, auth) {
33267
33405
  const id = randomUUID4().slice(0, 8);
33268
33406
  const send = (message) => {
33269
33407
  try {
@@ -33273,14 +33411,14 @@ function createRouteConnection(socket, path10, headers, params, auth) {
33273
33411
  };
33274
33412
  const conn = {
33275
33413
  id,
33276
- path: path10,
33414
+ path: path9,
33277
33415
  ip: socket.remoteAddress ?? "unknown",
33278
33416
  headers,
33279
33417
  params,
33280
33418
  auth,
33281
33419
  send,
33282
33420
  sendJson: (data) => send(JSON.stringify(data)),
33283
- broadcast: (message) => wsRouteManager.broadcastPath(path10, message),
33421
+ broadcast: (message) => wsRouteManager.broadcastPath(path9, message),
33284
33422
  broadcastToRoom: (room, message, excludeSelf = false) => wsRouteManager.broadcastToRoom(room, message, excludeSelf ? id : void 0),
33285
33423
  getRoomConnections: (room) => wsRouteManager.getRoomConnections(room),
33286
33424
  joinRoom: (room) => wsRouteManager.joinRoom(id, room),
@@ -33489,8 +33627,8 @@ var init_websocket = __esm({
33489
33627
  * to the Router's `(conn, event, data)` style and registers it via
33490
33628
  * `Router.websocket()`.
33491
33629
  */
33492
- route(path10, handler, options) {
33493
- this._routeHandlers.set(path10, handler);
33630
+ route(path9, handler, options) {
33631
+ this._routeHandlers.set(path9, handler);
33494
33632
  const adapter = async (conn, event, data) => {
33495
33633
  if (event === "open") {
33496
33634
  const result = handler(conn);
@@ -33513,7 +33651,7 @@ var init_websocket = __esm({
33513
33651
  }
33514
33652
  }
33515
33653
  };
33516
- Router.websocket(path10, adapter, options);
33654
+ Router.websocket(path9, adapter, options);
33517
33655
  }
33518
33656
  /**
33519
33657
  * Broadcast a message to all connected clients.
@@ -33523,18 +33661,18 @@ var init_websocket = __esm({
33523
33661
  * When `path` is omitted/undefined, all clients receive the message
33524
33662
  * (backward compatible).
33525
33663
  */
33526
- broadcast(message, excludeIds, path10) {
33664
+ broadcast(message, excludeIds, path9) {
33527
33665
  this.ensureBackplane();
33528
33666
  const exclude = new Set(excludeIds ?? []);
33529
33667
  for (const [id, client] of Array.from(this.clients)) {
33530
33668
  if (exclude.has(id)) continue;
33531
- if (path10 !== void 0 && client.path !== path10) continue;
33669
+ if (path9 !== void 0 && client.path !== path9) continue;
33532
33670
  this.safeSend(client, message);
33533
33671
  }
33534
33672
  this.backplane.publish(
33535
- path10 !== void 0 ? "path" : "all",
33673
+ path9 !== void 0 ? "path" : "all",
33536
33674
  message,
33537
- { path: path10 ?? null, exclude: excludeIds?.[0] ?? null },
33675
+ { path: path9 ?? null, exclude: excludeIds?.[0] ?? null },
33538
33676
  Log
33539
33677
  );
33540
33678
  }
@@ -34010,10 +34148,10 @@ var init_websocket = __esm({
34010
34148
  }
34011
34149
  }
34012
34150
  /** Broadcast a text frame to every connection on the same path. */
34013
- broadcastPath(path10, message) {
34151
+ broadcastPath(path9, message) {
34014
34152
  const frame = buildFrame(OP_TEXT, Buffer.from(message, "utf-8"));
34015
34153
  for (const state of this.connections.values()) {
34016
- if (state.path !== path10 || state.closed) continue;
34154
+ if (state.path !== path9 || state.closed) continue;
34017
34155
  try {
34018
34156
  state.socket.write(frame);
34019
34157
  } catch {
@@ -35626,8 +35764,8 @@ var init_job = __esm({
35626
35764
  });
35627
35765
 
35628
35766
  // src/queueBackends/liteBackend.ts
35629
- import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync8, existsSync as existsSync19 } from "node:fs";
35630
- import { join as join23 } from "node:path";
35767
+ import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync8, existsSync as existsSync20 } from "node:fs";
35768
+ import { join as join24 } from "node:path";
35631
35769
  import { randomUUID as randomUUID7 } from "node:crypto";
35632
35770
  var LiteBackend;
35633
35771
  var init_liteBackend = __esm({
@@ -35651,22 +35789,22 @@ var init_liteBackend = __esm({
35651
35789
  this.visibilityTimeout = visibilityTimeout;
35652
35790
  }
35653
35791
  ensureDir(queue) {
35654
- const dir = join23(this.basePath, queue);
35792
+ const dir = join24(this.basePath, queue);
35655
35793
  mkdirSync15(dir, { recursive: true });
35656
35794
  return dir;
35657
35795
  }
35658
35796
  ensureFailedDir(queue) {
35659
- const dir = join23(this.basePath, queue, "failed");
35797
+ const dir = join24(this.basePath, queue, "failed");
35660
35798
  mkdirSync15(dir, { recursive: true });
35661
35799
  return dir;
35662
35800
  }
35663
35801
  ensureReservedDir(queue) {
35664
- const dir = join23(this.basePath, queue, "reserved");
35802
+ const dir = join24(this.basePath, queue, "reserved");
35665
35803
  mkdirSync15(dir, { recursive: true });
35666
35804
  return dir;
35667
35805
  }
35668
35806
  reservedPath(queue, jobId) {
35669
- return join23(this.ensureReservedDir(queue), `${jobId}.queue-data`);
35807
+ return join24(this.ensureReservedDir(queue), `${jobId}.queue-data`);
35670
35808
  }
35671
35809
  nowIso() {
35672
35810
  return (/* @__PURE__ */ new Date()).toISOString();
@@ -35709,7 +35847,7 @@ var init_liteBackend = __esm({
35709
35847
  error: void 0
35710
35848
  };
35711
35849
  const prefix = this.nextPrefix();
35712
- writeFileSync11(join23(dir, `${prefix}_${id}.queue-data`), JSON.stringify(job, null, 2));
35850
+ writeFileSync11(join24(dir, `${prefix}_${id}.queue-data`), JSON.stringify(job, null, 2));
35713
35851
  return id;
35714
35852
  }
35715
35853
  /**
@@ -35728,7 +35866,7 @@ var init_liteBackend = __esm({
35728
35866
  }
35729
35867
  const candidates = [];
35730
35868
  for (const filename of filenames) {
35731
- const filePath = join23(dir, filename);
35869
+ const filePath = join24(dir, filename);
35732
35870
  let job;
35733
35871
  try {
35734
35872
  job = JSON.parse(readFileSync16(filePath, "utf-8"));
@@ -35792,7 +35930,7 @@ var init_liteBackend = __esm({
35792
35930
  return;
35793
35931
  }
35794
35932
  for (const filename of filenames) {
35795
- const filePath = join23(reservedDir, filename);
35933
+ const filePath = join24(reservedDir, filename);
35796
35934
  let record2;
35797
35935
  try {
35798
35936
  record2 = JSON.parse(readFileSync16(filePath, "utf-8"));
@@ -35830,7 +35968,7 @@ var init_liteBackend = __esm({
35830
35968
  this.reclaimExpired(queue, bridge.getMaxRetries(), this.nowIso());
35831
35969
  const now = this.nowIso();
35832
35970
  for (const [filename, job] of this.availableCandidates(queue, now)) {
35833
- const filePath = join23(dir, filename);
35971
+ const filePath = join24(dir, filename);
35834
35972
  job.topic = queue;
35835
35973
  job.priority = job.priority ?? 0;
35836
35974
  this.writeReserved(queue, job);
@@ -35855,7 +35993,7 @@ var init_liteBackend = __esm({
35855
35993
  const results = [];
35856
35994
  for (const [filename, job] of this.availableCandidates(queue, now)) {
35857
35995
  if (results.length >= count) break;
35858
- const filePath = join23(dir, filename);
35996
+ const filePath = join24(dir, filename);
35859
35997
  job.topic = queue;
35860
35998
  job.priority = job.priority ?? 0;
35861
35999
  this.writeReserved(queue, job);
@@ -35908,7 +36046,7 @@ var init_liteBackend = __esm({
35908
36046
  let count = 0;
35909
36047
  for (const file of files) {
35910
36048
  try {
35911
- const job = JSON.parse(readFileSync16(join23(scanDir, file), "utf-8"));
36049
+ const job = JSON.parse(readFileSync16(join24(scanDir, file), "utf-8"));
35912
36050
  if (job.status === status2) count++;
35913
36051
  } catch {
35914
36052
  }
@@ -35921,28 +36059,28 @@ var init_liteBackend = __esm({
35921
36059
  try {
35922
36060
  const files = readdirSync12(dir).filter((f) => f.endsWith(".queue-data"));
35923
36061
  for (const file of files) {
35924
- unlinkSync8(join23(dir, file));
36062
+ unlinkSync8(join24(dir, file));
35925
36063
  count++;
35926
36064
  }
35927
36065
  } catch {
35928
36066
  }
35929
- const failedDir = join23(dir, "failed");
36067
+ const failedDir = join24(dir, "failed");
35930
36068
  try {
35931
- if (existsSync19(failedDir)) {
36069
+ if (existsSync20(failedDir)) {
35932
36070
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
35933
36071
  for (const file of files) {
35934
- unlinkSync8(join23(failedDir, file));
36072
+ unlinkSync8(join24(failedDir, file));
35935
36073
  count++;
35936
36074
  }
35937
36075
  }
35938
36076
  } catch {
35939
36077
  }
35940
- const reservedDir = join23(dir, "reserved");
36078
+ const reservedDir = join24(dir, "reserved");
35941
36079
  try {
35942
- if (existsSync19(reservedDir)) {
36080
+ if (existsSync20(reservedDir)) {
35943
36081
  const files = readdirSync12(reservedDir).filter((f) => f.endsWith(".queue-data"));
35944
36082
  for (const file of files) {
35945
- unlinkSync8(join23(reservedDir, file));
36083
+ unlinkSync8(join24(reservedDir, file));
35946
36084
  count++;
35947
36085
  }
35948
36086
  }
@@ -35965,7 +36103,7 @@ var init_liteBackend = __esm({
35965
36103
  const files = readdirSync12(dir).filter((f) => f.endsWith(".queue-data")).sort();
35966
36104
  for (const file of files) {
35967
36105
  try {
35968
- const job = JSON.parse(readFileSync16(join23(dir, file), "utf-8"));
36106
+ const job = JSON.parse(readFileSync16(join24(dir, file), "utf-8"));
35969
36107
  const attempts = job.attempts || 0;
35970
36108
  if (attempts > 0 && attempts < maxRetries) {
35971
36109
  results.push(job);
@@ -35988,9 +36126,9 @@ var init_liteBackend = __esm({
35988
36126
  try {
35989
36127
  const queues = readdirSync12(this.basePath);
35990
36128
  for (const q of queues) {
35991
- const failedDir = join23(this.basePath, q, "failed");
35992
- const filePath = join23(failedDir, `${jobId}.queue-data`);
35993
- if (existsSync19(filePath)) {
36129
+ const failedDir = join24(this.basePath, q, "failed");
36130
+ const filePath = join24(failedDir, `${jobId}.queue-data`);
36131
+ if (existsSync20(filePath)) {
35994
36132
  const job = JSON.parse(readFileSync16(filePath, "utf-8"));
35995
36133
  job.status = "pending";
35996
36134
  job.attempts = (job.attempts || 0) + 1;
@@ -35998,8 +36136,8 @@ var init_liteBackend = __esm({
35998
36136
  job.createdAt = (/* @__PURE__ */ new Date()).toISOString();
35999
36137
  job.delayUntil = delaySeconds ? new Date(Date.now() + delaySeconds * 1e3).toISOString() : null;
36000
36138
  const prefix = this.nextPrefix();
36001
- const queueDir = join23(this.basePath, q);
36002
- writeFileSync11(join23(queueDir, `${prefix}_${jobId}.queue-data`), JSON.stringify(job, null, 2));
36139
+ const queueDir = join24(this.basePath, q);
36140
+ writeFileSync11(join24(queueDir, `${prefix}_${jobId}.queue-data`), JSON.stringify(job, null, 2));
36003
36141
  unlinkSync8(filePath);
36004
36142
  return true;
36005
36143
  }
@@ -36015,7 +36153,7 @@ var init_liteBackend = __esm({
36015
36153
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data")).sort();
36016
36154
  for (const file of files) {
36017
36155
  try {
36018
- const job = JSON.parse(readFileSync16(join23(failedDir, file), "utf-8"));
36156
+ const job = JSON.parse(readFileSync16(join24(failedDir, file), "utf-8"));
36019
36157
  if ((job.attempts || 0) >= maxRetries) {
36020
36158
  job.status = "dead";
36021
36159
  results.push(job);
@@ -36036,7 +36174,7 @@ var init_liteBackend = __esm({
36036
36174
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
36037
36175
  for (const file of files) {
36038
36176
  try {
36039
- unlinkSync8(join23(failedDir, file));
36177
+ unlinkSync8(join24(failedDir, file));
36040
36178
  count++;
36041
36179
  } catch {
36042
36180
  }
@@ -36049,9 +36187,9 @@ var init_liteBackend = __esm({
36049
36187
  const files = readdirSync12(dir).filter((f) => f.endsWith(".queue-data"));
36050
36188
  for (const file of files) {
36051
36189
  try {
36052
- const job = JSON.parse(readFileSync16(join23(dir, file), "utf-8"));
36190
+ const job = JSON.parse(readFileSync16(join24(dir, file), "utf-8"));
36053
36191
  if (job.status === status2) {
36054
- unlinkSync8(join23(dir, file));
36192
+ unlinkSync8(join24(dir, file));
36055
36193
  count++;
36056
36194
  }
36057
36195
  } catch {
@@ -36075,7 +36213,7 @@ var init_liteBackend = __esm({
36075
36213
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
36076
36214
  for (const file of files) {
36077
36215
  try {
36078
- const filePath = join23(failedDir, file);
36216
+ const filePath = join24(failedDir, file);
36079
36217
  const job = JSON.parse(readFileSync16(filePath, "utf-8"));
36080
36218
  if ((job.attempts || 0) >= maxRetries) {
36081
36219
  continue;
@@ -36085,7 +36223,7 @@ var init_liteBackend = __esm({
36085
36223
  job.createdAt = (/* @__PURE__ */ new Date()).toISOString();
36086
36224
  job.delayUntil = null;
36087
36225
  const prefix = this.nextPrefix();
36088
- writeFileSync11(join23(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
36226
+ writeFileSync11(join24(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
36089
36227
  unlinkSync8(filePath);
36090
36228
  count++;
36091
36229
  } catch {
@@ -36105,7 +36243,7 @@ var init_liteBackend = __esm({
36105
36243
  }
36106
36244
  for (const file of files) {
36107
36245
  if (!file.includes(id)) continue;
36108
- const filePath = join23(dir, file);
36246
+ const filePath = join24(dir, file);
36109
36247
  let job;
36110
36248
  try {
36111
36249
  job = JSON.parse(readFileSync16(filePath, "utf-8"));
@@ -36153,7 +36291,7 @@ var init_liteBackend = __esm({
36153
36291
  error: error2
36154
36292
  };
36155
36293
  const prefix = this.nextPrefix();
36156
- writeFileSync11(join23(dir, `${prefix}_${job.id}.queue-data`), JSON.stringify(jobData, null, 2));
36294
+ writeFileSync11(join24(dir, `${prefix}_${job.id}.queue-data`), JSON.stringify(jobData, null, 2));
36157
36295
  }
36158
36296
  /**
36159
36297
  * Move the job to the dead-letter (failed/) directory. Terminal until a
@@ -36173,7 +36311,7 @@ var init_liteBackend = __esm({
36173
36311
  error: error2,
36174
36312
  failedAt: (/* @__PURE__ */ new Date()).toISOString()
36175
36313
  };
36176
- writeFileSync11(join23(failedDir, `${job.id}.queue-data`), JSON.stringify(jobData, null, 2));
36314
+ writeFileSync11(join24(failedDir, `${job.id}.queue-data`), JSON.stringify(jobData, null, 2));
36177
36315
  }
36178
36316
  /**
36179
36317
  * Record a failed attempt.
@@ -36223,7 +36361,7 @@ var init_liteBackend = __esm({
36223
36361
  retryJob(queue, job, delaySeconds) {
36224
36362
  this.clearReservation(queue, job.id);
36225
36363
  try {
36226
- unlinkSync8(join23(this.ensureFailedDir(queue), `${job.id}.queue-data`));
36364
+ unlinkSync8(join24(this.ensureFailedDir(queue), `${job.id}.queue-data`));
36227
36365
  } catch {
36228
36366
  }
36229
36367
  job.attempts = (job.attempts || 0) + 1;
@@ -37363,6 +37501,9 @@ var init_projectIndexExtractors = __esm({
37363
37501
  import * as fs6 from "node:fs";
37364
37502
  import * as path6 from "node:path";
37365
37503
  import * as crypto2 from "node:crypto";
37504
+ function indexKey(root, fullPath) {
37505
+ return path6.relative(root, fullPath).split(path6.sep).join("/");
37506
+ }
37366
37507
  function projectRoot2() {
37367
37508
  return path6.resolve(process.cwd());
37368
37509
  }
@@ -37397,7 +37538,7 @@ function extract2(fullPath) {
37397
37538
  return {};
37398
37539
  }
37399
37540
  const entry = {
37400
- path: path6.relative(projectRoot2(), fullPath),
37541
+ path: indexKey(projectRoot2(), fullPath),
37401
37542
  size: st.size,
37402
37543
  mtime: Math.floor(st.mtimeMs / 1e3),
37403
37544
  language: languageFor(fullPath)
@@ -37504,7 +37645,6 @@ var projectIndex_exports = {};
37504
37645
  __export(projectIndex_exports, {
37505
37646
  ProjectIndex: () => ProjectIndex
37506
37647
  });
37507
- import * as path7 from "node:path";
37508
37648
  import * as fs7 from "node:fs";
37509
37649
  function scoreSearchEntry(query, rel, entry) {
37510
37650
  let score = rel.toLowerCase().includes(query) ? 10 : 0;
@@ -37537,7 +37677,7 @@ var init_projectIndex = __esm({
37537
37677
  const found = [];
37538
37678
  walk(root, found);
37539
37679
  for (const fp of found) {
37540
- const rel = path7.relative(root, fp);
37680
+ const rel = indexKey(root, fp);
37541
37681
  seen.add(rel);
37542
37682
  let mtime;
37543
37683
  try {
@@ -37563,7 +37703,7 @@ var init_projectIndex = __esm({
37563
37703
  updated,
37564
37704
  removed: removed.length,
37565
37705
  total: Object.keys(files).length,
37566
- path: path7.relative(root, indexPath())
37706
+ path: indexKey(root, indexPath())
37567
37707
  };
37568
37708
  },
37569
37709
  search(query, limit = 20) {
@@ -38115,23 +38255,23 @@ __export(docs_exports, {
38115
38255
  returnFromSignature: () => returnFromSignature
38116
38256
  });
38117
38257
  import * as fs8 from "node:fs";
38118
- import * as path8 from "node:path";
38119
- import { fileURLToPath as fileURLToPath6 } from "node:url";
38258
+ import * as path7 from "node:path";
38259
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
38120
38260
  function detectFrameworkRoots() {
38121
- const corePackageRoot = path8.resolve(__DIRNAME, "..");
38122
- const packagesRoot = path8.resolve(corePackageRoot, "..");
38261
+ const corePackageRoot = path7.resolve(__DIRNAME, "..");
38262
+ const packagesRoot = path7.resolve(corePackageRoot, "..");
38123
38263
  const roots = [];
38124
38264
  for (const pkg of ["core", "orm", "swagger", "frond"]) {
38125
- const dir = path8.join(packagesRoot, pkg, "src");
38265
+ const dir = path7.join(packagesRoot, pkg, "src");
38126
38266
  if (fs8.existsSync(dir)) roots.push(dir);
38127
38267
  }
38128
38268
  return roots;
38129
38269
  }
38130
38270
  function detectVersion(projectRoot3) {
38131
38271
  for (const candidate of [
38132
- path8.join(projectRoot3, "package.json"),
38133
- path8.resolve(__DIRNAME, "..", "..", "..", "package.json"),
38134
- path8.resolve(__DIRNAME, "..", "package.json")
38272
+ path7.join(projectRoot3, "package.json"),
38273
+ path7.resolve(__DIRNAME, "..", "..", "..", "package.json"),
38274
+ path7.resolve(__DIRNAME, "..", "package.json")
38135
38275
  ]) {
38136
38276
  try {
38137
38277
  const pkg = JSON.parse(fs8.readFileSync(candidate, "utf-8"));
@@ -38142,16 +38282,16 @@ function detectVersion(projectRoot3) {
38142
38282
  return "0.0.0";
38143
38283
  }
38144
38284
  function relativePath(absPath, projectRoot3, frameworkRoots) {
38145
- const norm = path8.resolve(absPath);
38285
+ const norm = path7.resolve(absPath);
38146
38286
  for (const fw of frameworkRoots) {
38147
- const parent = path8.dirname(fw);
38148
- if (norm.startsWith(parent + path8.sep)) {
38149
- const monorepo = path8.resolve(parent, "..", "..");
38150
- if (norm.startsWith(monorepo + path8.sep)) return path8.relative(monorepo, norm);
38151
- return path8.relative(parent, norm);
38287
+ const parent = path7.dirname(fw);
38288
+ if (norm.startsWith(parent + path7.sep)) {
38289
+ const monorepo = path7.resolve(parent, "..", "..");
38290
+ if (norm.startsWith(monorepo + path7.sep)) return path7.relative(monorepo, norm);
38291
+ return path7.relative(parent, norm);
38152
38292
  }
38153
38293
  }
38154
- if (norm.startsWith(projectRoot3 + path8.sep)) return path8.relative(projectRoot3, norm);
38294
+ if (norm.startsWith(projectRoot3 + path7.sep)) return path7.relative(projectRoot3, norm);
38155
38295
  return norm;
38156
38296
  }
38157
38297
  function tokenise(text) {
@@ -38191,12 +38331,12 @@ function walkTsFiles(root) {
38191
38331
  if (e.name.startsWith(".")) continue;
38192
38332
  if (e.isDirectory()) {
38193
38333
  if (e.name === "node_modules" || e.name === "tests" || e.name === "test" || e.name === "dist" || e.name === "build") continue;
38194
- visit(path8.join(dir, e.name));
38334
+ visit(path7.join(dir, e.name));
38195
38335
  } else if (e.isFile()) {
38196
38336
  if (!e.name.endsWith(".ts") && !e.name.endsWith(".js") && !e.name.endsWith(".mjs")) continue;
38197
38337
  if (e.name.endsWith(".test.ts") || e.name.endsWith(".test.js")) continue;
38198
38338
  if (e.name.endsWith(".d.ts")) continue;
38199
- found.push(path8.join(dir, e.name));
38339
+ found.push(path7.join(dir, e.name));
38200
38340
  }
38201
38341
  }
38202
38342
  }
@@ -38523,8 +38663,8 @@ var init_docs = __esm({
38523
38663
  "hash"
38524
38664
  ]);
38525
38665
  _DOCS_CACHE = /* @__PURE__ */ new Map();
38526
- __FILENAME = fileURLToPath6(import.meta.url);
38527
- __DIRNAME = path8.dirname(__FILENAME);
38666
+ __FILENAME = fileURLToPath7(import.meta.url);
38667
+ __DIRNAME = path7.dirname(__FILENAME);
38528
38668
  USER_DIRS = ["src/orm", "src/routes", "src/app", "src/services", "src/models"];
38529
38669
  FENCE_RE = new RegExp(
38530
38670
  String.fromCharCode(96, 96, 96) + "[a-zA-Z0-9_+-]*\\n([\\s\\S]*?)\\n" + String.fromCharCode(96, 96, 96),
@@ -38542,7 +38682,7 @@ var init_docs = __esm({
38542
38682
  userMtime = 0;
38543
38683
  frameworkMtime = 0;
38544
38684
  constructor(projectRoot3) {
38545
- this.projectRoot = path8.resolve(projectRoot3);
38685
+ this.projectRoot = path7.resolve(projectRoot3);
38546
38686
  this.frameworkRoots = detectFrameworkRoots();
38547
38687
  this.version = detectVersion(this.projectRoot);
38548
38688
  }
@@ -38734,7 +38874,7 @@ var init_docs = __esm({
38734
38874
  // ── Drift detector + sync ────────────────────────────────────────
38735
38875
  static checkDocs(mdPath, projectRoot3) {
38736
38876
  if (!fs8.existsSync(mdPath)) return { drift: [] };
38737
- const docs = _Docs.cached(projectRoot3 ?? path8.dirname(mdPath));
38877
+ const docs = _Docs.cached(projectRoot3 ?? path7.dirname(mdPath));
38738
38878
  const idx = docs.index();
38739
38879
  const known = /* @__PURE__ */ new Set();
38740
38880
  for (const e of idx) known.add(e.name.toLowerCase());
@@ -38761,7 +38901,7 @@ var init_docs = __esm({
38761
38901
  return { drift };
38762
38902
  }
38763
38903
  static syncDocs(mdPath, projectRoot3) {
38764
- const docs = _Docs.cached(projectRoot3 ?? (fs8.existsSync(mdPath) ? path8.dirname(mdPath) : process.cwd()));
38904
+ const docs = _Docs.cached(projectRoot3 ?? (fs8.existsSync(mdPath) ? path7.dirname(mdPath) : process.cwd()));
38765
38905
  const generated = docs.renderGeneratedBlock();
38766
38906
  const begin = "<!-- BEGIN GENERATED API -->";
38767
38907
  const end = "<!-- END GENERATED API -->";
@@ -38785,7 +38925,7 @@ ${end}
38785
38925
  }
38786
38926
  // ── Internals ────────────────────────────────────────────────────
38787
38927
  static cached(projectRoot3) {
38788
- const key = path8.resolve(projectRoot3 ?? process.cwd());
38928
+ const key = path7.resolve(projectRoot3 ?? process.cwd());
38789
38929
  let inst = _DOCS_CACHE.get(key);
38790
38930
  if (!inst) {
38791
38931
  inst = new _Docs(key);
@@ -38812,11 +38952,11 @@ ${end}
38812
38952
  this.frameworkMtime = shared.mtime;
38813
38953
  this.indexCache = null;
38814
38954
  }
38815
- const userMtime = this.maxMtime(USER_DIRS.map((d) => path8.join(this.projectRoot, d)));
38955
+ const userMtime = this.maxMtime(USER_DIRS.map((d) => path7.join(this.projectRoot, d)));
38816
38956
  if (this.indexCache === null || userMtime !== this.userMtime) {
38817
38957
  this.userEntries = /* @__PURE__ */ new Map();
38818
38958
  for (const sub of USER_DIRS) {
38819
- const dir = path8.join(this.projectRoot, sub);
38959
+ const dir = path7.join(this.projectRoot, sub);
38820
38960
  if (!fs8.existsSync(dir)) continue;
38821
38961
  for (const f of walkTsFiles(dir)) {
38822
38962
  buildEntriesForFile(f, "user", this.frameworkRoots, this.projectRoot, this.version, this.userEntries);
@@ -38899,9 +39039,9 @@ ${end}
38899
39039
 
38900
39040
  // src/devAdmin.ts
38901
39041
  import { cpus as osCpus } from "node:os";
38902
- import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync23, readdirSync as readdirSync16, mkdirSync as mkdirSync18, copyFileSync as copyFileSync2, statSync as statSync17, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync3, fchmodSync as fchmodSync2, ftruncateSync as ftruncateSync2, constants as constants4, realpathSync as realpathSync6, lstatSync as lstatSync3 } from "node:fs";
38903
- import { join as join27, dirname as dirname14, resolve as resolve16, relative as relative9, sep as sep8, basename as basename5 } from "node:path";
38904
- import { fileURLToPath as fileURLToPath7 } from "node:url";
39042
+ import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync24, readdirSync as readdirSync16, mkdirSync as mkdirSync18, copyFileSync as copyFileSync2, statSync as statSync18, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync3, fchmodSync as fchmodSync2, ftruncateSync as ftruncateSync2, constants as constants4, realpathSync as realpathSync6, lstatSync as lstatSync3 } from "node:fs";
39043
+ import { join as join28, dirname as dirname14, resolve as resolve16, relative as relative8, sep as sep9, basename as basename5 } from "node:path";
39044
+ import { fileURLToPath as fileURLToPath8 } from "node:url";
38905
39045
  import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
38906
39046
  import net2 from "node:net";
38907
39047
  function escapeHtml2(value) {
@@ -38979,15 +39119,15 @@ function devToolbarAllowed(req2) {
38979
39119
  return devPeerAllowed(peer);
38980
39120
  }
38981
39121
  function devRequestDenial(req2) {
38982
- const path10 = (req2.path ?? "").replace(/\/+/g, "/");
38983
- const isMcp = DEV_MCP_PREFIXES.some((prefix) => path10 === prefix || path10.startsWith(prefix + "/"));
39122
+ const path9 = (req2.path ?? "").replace(/\/+/g, "/");
39123
+ const isMcp = DEV_MCP_PREFIXES.some((prefix) => path9 === prefix || path9.startsWith(prefix + "/"));
38984
39124
  if (!devHostAllowed(req2.header("host"))) {
38985
39125
  return { status: 403, error: "dev-admin: refused (host not allowed)" };
38986
39126
  }
38987
39127
  if (!devSameOriginOk(req2)) {
38988
39128
  return { status: 403, error: "dev-admin: refused (cross-origin request)" };
38989
39129
  }
38990
- if (DEV_PUBLIC_ASSETS.has(path10)) {
39130
+ if (DEV_PUBLIC_ASSETS.has(path9)) {
38991
39131
  return null;
38992
39132
  }
38993
39133
  if (!isMcp) {
@@ -39079,12 +39219,12 @@ function mapQueueJob(job, topic, status2) {
39079
39219
  };
39080
39220
  }
39081
39221
  function readQueueDir(dir, topic, status2) {
39082
- if (!existsSync23(dir)) return [];
39222
+ if (!existsSync24(dir)) return [];
39083
39223
  const jobs = [];
39084
39224
  for (const filename of readdirSync16(dir).sort()) {
39085
39225
  if (!filename.endsWith(".queue-data")) continue;
39086
39226
  try {
39087
- jobs.push(mapQueueJob(JSON.parse(readFileSync20(join27(dir, filename), "utf-8")), topic, status2));
39227
+ jobs.push(mapQueueJob(JSON.parse(readFileSync20(join28(dir, filename), "utf-8")), topic, status2));
39088
39228
  } catch {
39089
39229
  }
39090
39230
  }
@@ -39221,8 +39361,8 @@ async function proxyToSupervisor(req2, res, downstreamPath) {
39221
39361
  function resolveDevEnvVar(key) {
39222
39362
  const live = process.env[key];
39223
39363
  if (live !== void 0 && live !== "") return live;
39224
- const envPath = join27(process.cwd(), ".env");
39225
- if (!existsSync23(envPath)) return "";
39364
+ const envPath = join28(process.cwd(), ".env");
39365
+ if (!existsSync24(envPath)) return "";
39226
39366
  for (const line of readFileSync20(envPath, "utf-8").split("\n")) {
39227
39367
  const t = line.trim();
39228
39368
  if (!t || t.startsWith("#") || !t.includes("=")) continue;
@@ -39232,8 +39372,8 @@ function resolveDevEnvVar(key) {
39232
39372
  return "";
39233
39373
  }
39234
39374
  function upsertDevEnvVar(key, value) {
39235
- const envPath = join27(process.cwd(), ".env");
39236
- const lines = existsSync23(envPath) ? readFileSync20(envPath, "utf-8").split("\n") : [];
39375
+ const envPath = join28(process.cwd(), ".env");
39376
+ const lines = existsSync24(envPath) ? readFileSync20(envPath, "utf-8").split("\n") : [];
39237
39377
  let found = false;
39238
39378
  const out = [];
39239
39379
  for (const line of lines) {
@@ -39263,9 +39403,9 @@ function formatUptime(seconds) {
39263
39403
  return parts.join(" ");
39264
39404
  }
39265
39405
  function parseEnvFile() {
39266
- const envPath = join27(process.cwd(), ".env");
39406
+ const envPath = join28(process.cwd(), ".env");
39267
39407
  const result = {};
39268
- if (!existsSync23(envPath)) return result;
39408
+ if (!existsSync24(envPath)) return result;
39269
39409
  const lines = readFileSync20(envPath, "utf-8").split("\n");
39270
39410
  for (const line of lines) {
39271
39411
  const trimmed = line.trim();
@@ -39277,10 +39417,10 @@ function parseEnvFile() {
39277
39417
  }
39278
39418
  function walkDirRecursive(dir) {
39279
39419
  const results = [];
39280
- if (!existsSync23(dir)) return results;
39420
+ if (!existsSync24(dir)) return results;
39281
39421
  for (const entry of readdirSync16(dir)) {
39282
- const full = join27(dir, entry);
39283
- if (statSync17(full).isDirectory()) {
39422
+ const full = join28(dir, entry);
39423
+ if (statSync18(full).isDirectory()) {
39284
39424
  results.push(...walkDirRecursive(full));
39285
39425
  } else {
39286
39426
  results.push(full);
@@ -39297,8 +39437,8 @@ function handleGalleryDeploy(router) {
39297
39437
  return;
39298
39438
  }
39299
39439
  const galleryDir = resolve16(__devAdminDirname, "..", "gallery");
39300
- const gallerySrc = join27(galleryDir, name, "src");
39301
- if (!existsSync23(gallerySrc)) {
39440
+ const gallerySrc = join28(galleryDir, name, "src");
39441
+ if (!existsSync24(gallerySrc)) {
39302
39442
  res.json({ error: `Gallery item '${name}' not found` }, 404);
39303
39443
  return;
39304
39444
  }
@@ -39306,15 +39446,15 @@ function handleGalleryDeploy(router) {
39306
39446
  const copied = [];
39307
39447
  const allFiles = walkDirRecursive(gallerySrc);
39308
39448
  for (const srcFile of allFiles) {
39309
- const rel = relative9(gallerySrc, srcFile);
39310
- const dest = join27(projectSrc, rel);
39449
+ const rel = relative8(gallerySrc, srcFile);
39450
+ const dest = join28(projectSrc, rel);
39311
39451
  mkdirSync18(dirname14(dest), { recursive: true });
39312
39452
  copyFileSync2(srcFile, dest);
39313
39453
  copied.push(rel);
39314
39454
  }
39315
39455
  try {
39316
39456
  const routesDir = resolve16(process.cwd(), "src", "routes");
39317
- if (existsSync23(routesDir)) {
39457
+ if (existsSync24(routesDir)) {
39318
39458
  const { discoverRoutes: discoverRoutes2 } = await Promise.resolve().then(() => (init_routeDiscovery(), routeDiscovery_exports));
39319
39459
  const routes = await discoverRoutes2(routesDir);
39320
39460
  for (const route of routes) {
@@ -39343,7 +39483,7 @@ function realPathOf2(target) {
39343
39483
  tail.unshift(basename5(existing));
39344
39484
  existing = dirname14(existing);
39345
39485
  }
39346
- return join27(realpathSync6(existing), ...tail);
39486
+ return join28(realpathSync6(existing), ...tail);
39347
39487
  }
39348
39488
  function safeJoin(projectRoot3, rel, extraRoots = []) {
39349
39489
  try {
@@ -39351,14 +39491,14 @@ function safeJoin(projectRoot3, rel, extraRoots = []) {
39351
39491
  const resolved = realPathOf2(resolve16(root, rel));
39352
39492
  const roots = [root, ...extraRoots.filter(Boolean).map((r) => realPathOf2(resolve16(r)))];
39353
39493
  for (const r of roots) {
39354
- if (resolved === r || resolved.startsWith(r.endsWith(sep8) ? r : r + sep8)) return resolved;
39494
+ if (resolved === r || resolved.startsWith(r.endsWith(sep9) ? r : r + sep9)) return resolved;
39355
39495
  }
39356
39496
  } catch {
39357
39497
  }
39358
39498
  return null;
39359
39499
  }
39360
39500
  function resolvedRelative(projectRoot3, resolvedPath) {
39361
- return relative9(realPathOf2(resolve16(projectRoot3)), resolvedPath);
39501
+ return relative8(realPathOf2(resolve16(projectRoot3)), resolvedPath);
39362
39502
  }
39363
39503
  function devFilesHidden(name) {
39364
39504
  if (DEV_FILES_IGNORED.has(name)) return true;
@@ -39374,10 +39514,10 @@ function devGitStatusLabel(code) {
39374
39514
  async function devGitInfo(root) {
39375
39515
  const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
39376
39516
  try {
39377
- const { execFileSync: execFileSync6 } = await import("node:child_process");
39517
+ const { execFileSync: execFileSync5 } = await import("node:child_process");
39378
39518
  const git = (args) => {
39379
39519
  try {
39380
- return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
39520
+ return execFileSync5("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
39381
39521
  } catch {
39382
39522
  return null;
39383
39523
  }
@@ -39429,7 +39569,7 @@ function buildFileEntry(name, full, entryRel, cwdInGit, gitStatus) {
39429
39569
  let isDir = false;
39430
39570
  let size = null;
39431
39571
  try {
39432
- const st = statSync17(full);
39572
+ const st = statSync18(full);
39433
39573
  isDir = st.isDirectory();
39434
39574
  if (!isDir) size = st.size;
39435
39575
  } catch {
@@ -39504,7 +39644,7 @@ function applyMcpOutcome(res, outcome) {
39504
39644
  function renderToolbarHtml(ctx) {
39505
39645
  const nodeVersion = process.version;
39506
39646
  const method = escapeHtml2(ctx.method);
39507
- const path10 = escapeHtml2(ctx.path);
39647
+ const path9 = escapeHtml2(ctx.path);
39508
39648
  const matchedPattern = escapeHtml2(ctx.matchedPattern);
39509
39649
  const reload = ctx.reload === false ? "0" : "1";
39510
39650
  return `<link rel="stylesheet" href="/__dev/toolbar.css">
@@ -39521,7 +39661,7 @@ function renderToolbarHtml(ctx) {
39521
39661
  </div>
39522
39662
  </div>
39523
39663
  <span class="t4-green">${method}</span>
39524
- <span>${path10}</span>
39664
+ <span>${path9}</span>
39525
39665
  <span class="t4-arrow">&rarr; ${matchedPattern}</span>
39526
39666
  <span class="t4-yellow">req:${ctx.requestId}</span>
39527
39667
  <span class="t4-blue">${ctx.routeCount} routes</span>
@@ -39696,6 +39836,7 @@ var init_devAdmin = __esm({
39696
39836
  "src/devAdmin.ts"() {
39697
39837
  "use strict";
39698
39838
  init_slashTrim();
39839
+ init_batchSpawn();
39699
39840
  init_devMailbox();
39700
39841
  init_upstreamResponse();
39701
39842
  init_dotenv();
@@ -39757,12 +39898,12 @@ var init_devAdmin = __esm({
39757
39898
  RequestInspector = class {
39758
39899
  static requests = [];
39759
39900
  static maxRequests = 200;
39760
- static capture(method, path10, status2, duration) {
39901
+ static capture(method, path9, status2, duration) {
39761
39902
  const entry = {
39762
39903
  id: `${Date.now()}_${this.requests.length}`,
39763
39904
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
39764
39905
  method,
39765
- path: path10,
39906
+ path: path9,
39766
39907
  status: status2,
39767
39908
  durationMs: Math.round(duration * 100) / 100
39768
39909
  };
@@ -39951,12 +40092,12 @@ var init_devAdmin = __esm({
39951
40092
  };
39952
40093
  WsTracker = class {
39953
40094
  static connections = [];
39954
- static add(remoteAddress, path10) {
40095
+ static add(remoteAddress, path9) {
39955
40096
  const conn = {
39956
40097
  id: `ws_${Date.now()}_${this.connections.length}`,
39957
40098
  connectedAt: (/* @__PURE__ */ new Date()).toISOString(),
39958
40099
  remoteAddress,
39959
- path: path10
40100
+ path: path9
39960
40101
  };
39961
40102
  this.connections.push(conn);
39962
40103
  return conn.id;
@@ -40066,7 +40207,7 @@ var init_devAdmin = __esm({
40066
40207
  const p = (url.searchParams.get("path") || "").toString();
40067
40208
  const scanRoot = metricsScanRoot();
40068
40209
  let target = p ? safeJoin(process.cwd(), p, [scanRoot]) : "";
40069
- if (target === null && scanRoot) target = safeJoin(process.cwd(), join27(scanRoot, p), [scanRoot]);
40210
+ if (target === null && scanRoot) target = safeJoin(process.cwd(), join28(scanRoot, p), [scanRoot]);
40070
40211
  if (target === null) {
40071
40212
  res.status(403).json({ error: "Path outside project" });
40072
40213
  return;
@@ -40304,6 +40445,7 @@ var init_devAdmin = __esm({
40304
40445
  const mem = process.memoryUsage();
40305
40446
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
40306
40447
  const rssMb = Math.round(mem.rss / 1048576);
40448
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
40307
40449
  let dbTableCount;
40308
40450
  let dbConnected = false;
40309
40451
  try {
@@ -40320,12 +40462,14 @@ var init_devAdmin = __esm({
40320
40462
  architecture: process.arch,
40321
40463
  os: `${process.platform} ${process.arch}`,
40322
40464
  pid: process.pid,
40323
- memory_mb: heapUsedMb,
40465
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
40466
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
40467
+ memory_mb: rssMb,
40324
40468
  db_tables: dbTableCount !== void 0 ? dbTableCount : "N/A",
40325
40469
  db_connected: dbConnected,
40326
40470
  memory: {
40327
- current_mb: heapUsedMb,
40328
- peak_mb: rssMb,
40471
+ current_mb: rssMb,
40472
+ peak_mb: peakRssMb,
40329
40473
  limit: "V8 default",
40330
40474
  rss: `${rssMb} MB`,
40331
40475
  heapUsed: `${heapUsedMb} MB`,
@@ -40384,16 +40528,16 @@ var init_devAdmin = __esm({
40384
40528
  failed: queue.size("failed"),
40385
40529
  reserved: queue.size("reserved")
40386
40530
  };
40387
- const topicDir = join27(queueBasePath2(), topic);
40531
+ const topicDir = join28(queueBasePath2(), topic);
40388
40532
  const jobs = [];
40389
40533
  if (!statusFilter || statusFilter === "pending") {
40390
40534
  jobs.push(...readQueueDir(topicDir, topic, "pending"));
40391
40535
  }
40392
40536
  if (!statusFilter || statusFilter === "reserved") {
40393
- jobs.push(...readQueueDir(join27(topicDir, "reserved"), topic, "reserved"));
40537
+ jobs.push(...readQueueDir(join28(topicDir, "reserved"), topic, "reserved"));
40394
40538
  }
40395
40539
  if (!statusFilter || statusFilter === "failed" || statusFilter === "dead") {
40396
- jobs.push(...readQueueDir(join27(topicDir, "failed"), topic, "dead_letter"));
40540
+ jobs.push(...readQueueDir(join28(topicDir, "failed"), topic, "dead_letter"));
40397
40541
  }
40398
40542
  res.json({ stats, jobs });
40399
40543
  } catch (e) {
@@ -40409,10 +40553,10 @@ var init_devAdmin = __esm({
40409
40553
  const { queueBasePath: queueBasePath2 } = await Promise.resolve().then(() => (init_queue(), queue_exports));
40410
40554
  const queueDir = queueBasePath2();
40411
40555
  let topics = [];
40412
- if (existsSync23(queueDir)) {
40556
+ if (existsSync24(queueDir)) {
40413
40557
  topics = readdirSync16(queueDir).filter((d) => {
40414
40558
  try {
40415
- return statSync17(join27(queueDir, d)).isDirectory();
40559
+ return statSync18(join28(queueDir, d)).isDirectory();
40416
40560
  } catch {
40417
40561
  return false;
40418
40562
  }
@@ -40697,7 +40841,7 @@ var init_devAdmin = __esm({
40697
40841
  const count = parseInt(String(body.count ?? "10"), 10) || 10;
40698
40842
  try {
40699
40843
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
40700
- const dirs = ["src/orm", "src/models"].map((d) => resolve16(process.cwd(), d)).filter((d) => existsSync23(d));
40844
+ const dirs = ["src/orm", "src/models"].map((d) => resolve16(process.cwd(), d)).filter((d) => existsSync24(d));
40701
40845
  const classes = [];
40702
40846
  for (const dir of dirs) {
40703
40847
  for (const m of await orm.discoverModels(dir)) classes.push(m.modelClass);
@@ -40838,7 +40982,7 @@ var init_devAdmin = __esm({
40838
40982
  return;
40839
40983
  }
40840
40984
  try {
40841
- const envPath = join27(process.cwd(), ".env");
40985
+ const envPath = join28(process.cwd(), ".env");
40842
40986
  const fd = openSync5(envPath, constants4.O_RDWR | constants4.O_APPEND | constants4.O_CREAT | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0), 384);
40843
40987
  try {
40844
40988
  const info = fstatSync3(fd);
@@ -40882,29 +41026,29 @@ var init_devAdmin = __esm({
40882
41026
  res.json({ success: false, error: msg });
40883
41027
  }
40884
41028
  };
40885
- __devAdminFilename = fileURLToPath7(import.meta.url);
41029
+ __devAdminFilename = fileURLToPath8(import.meta.url);
40886
41030
  __devAdminDirname = dirname14(__devAdminFilename);
40887
41031
  handleGalleryList = (_req, res) => {
40888
41032
  const galleryDir = resolve16(__devAdminDirname, "..", "gallery");
40889
41033
  const items = [];
40890
- if (existsSync23(galleryDir)) {
41034
+ if (existsSync24(galleryDir)) {
40891
41035
  const entries = readdirSync16(galleryDir).sort();
40892
41036
  for (const entry of entries) {
40893
- const entryPath = join27(galleryDir, entry);
40894
- const metaFile = join27(entryPath, "meta.json");
40895
- if (statSync17(entryPath).isDirectory() && existsSync23(metaFile)) {
41037
+ const entryPath = join28(galleryDir, entry);
41038
+ const metaFile = join28(entryPath, "meta.json");
41039
+ if (statSync18(entryPath).isDirectory() && existsSync24(metaFile)) {
40896
41040
  try {
40897
41041
  const meta = JSON.parse(readFileSync20(metaFile, "utf-8"));
40898
41042
  meta.id = entry;
40899
- const srcDir = join27(entryPath, "src");
40900
- if (existsSync23(srcDir)) {
41043
+ const srcDir = join28(entryPath, "src");
41044
+ if (existsSync24(srcDir)) {
40901
41045
  const allFiles = walkDirRecursive(srcDir);
40902
- meta.files = allFiles.map((f) => relative9(srcDir, f));
41046
+ meta.files = allFiles.map((f) => relative8(srcDir, f));
40903
41047
  }
40904
41048
  const projectSrc = resolve16(process.cwd(), "src");
40905
- if (existsSync23(srcDir) && meta.files) {
41049
+ if (existsSync24(srcDir) && meta.files) {
40906
41050
  meta.deployed = meta.files.every(
40907
- (f) => existsSync23(join27(projectSrc, f))
41051
+ (f) => existsSync24(join28(projectSrc, f))
40908
41052
  );
40909
41053
  } else {
40910
41054
  meta.deployed = false;
@@ -40981,7 +41125,7 @@ var init_devAdmin = __esm({
40981
41125
  const root = resolve16(process.cwd());
40982
41126
  const target = safeJoin(root, rel);
40983
41127
  const { branch, gitRoot, status: gitStatus } = await devGitInfo(root);
40984
- if (!target || !existsSync23(target) || !statSync17(target).isDirectory()) {
41128
+ if (!target || !existsSync24(target) || !statSync18(target).isDirectory()) {
40985
41129
  res.json({ path: rel, branch, entries: [], error: "not a directory" });
40986
41130
  return;
40987
41131
  }
@@ -40994,12 +41138,12 @@ var init_devAdmin = __esm({
40994
41138
  const entries = [];
40995
41139
  for (const name of readdirSync16(target).sort()) {
40996
41140
  if (devFilesHidden(name)) continue;
40997
- const full = join27(target, name);
40998
- const entryRel = relative9(root, full).replace(/\\/g, "/");
41141
+ const full = join28(target, name);
41142
+ const entryRel = relative8(root, full).replace(/\\/g, "/");
40999
41143
  if (isSecretPath(entryRel)) continue;
41000
41144
  entries.push(buildFileEntry(name, full, entryRel, cwdInGit, gitStatus));
41001
41145
  }
41002
- res.json({ path: relative9(root, target).replace(/\\/g, "/") || ".", branch, entries });
41146
+ res.json({ path: relative8(root, target).replace(/\\/g, "/") || ".", branch, entries });
41003
41147
  };
41004
41148
  DEV_ADMIN_LANG_MAP = {
41005
41149
  ".py": "python",
@@ -41057,8 +41201,8 @@ var init_devAdmin = __esm({
41057
41201
  return;
41058
41202
  }
41059
41203
  const content = data.toString("utf-8");
41060
- const path10 = relative9(root, target);
41061
- res.json({ path: path10, content, language: devAdminLanguage(path10), bytes: Buffer.byteLength(content, "utf-8") });
41204
+ const path9 = relative8(root, target);
41205
+ res.json({ path: path9, content, language: devAdminLanguage(path9), bytes: Buffer.byteLength(content, "utf-8") });
41062
41206
  } catch (e) {
41063
41207
  res.json({ error: e.message }, 500);
41064
41208
  }
@@ -41075,14 +41219,14 @@ var init_devAdmin = __esm({
41075
41219
  }
41076
41220
  try {
41077
41221
  mkdirSync18(dirname14(target), { recursive: true });
41078
- const existed = existsSync23(target);
41222
+ const existed = existsSync24(target);
41079
41223
  writeFileSync15(target, content, "utf-8");
41080
41224
  try {
41081
41225
  const { Plan: Plan2 } = await Promise.resolve().then(() => (init_plan(), plan_exports));
41082
- Plan2.recordAction(existed ? "patched" : "created", relative9(root, target));
41226
+ Plan2.recordAction(existed ? "patched" : "created", relative8(root, target));
41083
41227
  } catch {
41084
41228
  }
41085
- res.json({ ok: true, path: relative9(root, target), bytes: Buffer.byteLength(content, "utf-8") });
41229
+ res.json({ ok: true, path: relative8(root, target), bytes: Buffer.byteLength(content, "utf-8") });
41086
41230
  } catch (e) {
41087
41231
  res.json({ error: e.message }, 500);
41088
41232
  }
@@ -41140,7 +41284,7 @@ var init_devAdmin = __esm({
41140
41284
  res.json({ error: "Invalid path" }, 400);
41141
41285
  return;
41142
41286
  }
41143
- if (!existsSync23(src)) {
41287
+ if (!existsSync24(src)) {
41144
41288
  res.json({ error: `Source not found: ${from}` }, 404);
41145
41289
  return;
41146
41290
  }
@@ -41148,7 +41292,7 @@ var init_devAdmin = __esm({
41148
41292
  const { renameSync: renameSync3 } = await import("node:fs");
41149
41293
  mkdirSync18(dirname14(dst), { recursive: true });
41150
41294
  renameSync3(src, dst);
41151
- res.json({ ok: true, from: relative9(root, src), to: relative9(root, dst) });
41295
+ res.json({ ok: true, from: relative8(root, src), to: relative8(root, dst) });
41152
41296
  } catch (e) {
41153
41297
  res.json({ error: e.message }, 500);
41154
41298
  }
@@ -41162,14 +41306,14 @@ var init_devAdmin = __esm({
41162
41306
  res.json({ error: "Invalid path" }, 400);
41163
41307
  return;
41164
41308
  }
41165
- if (!existsSync23(target)) {
41309
+ if (!existsSync24(target)) {
41166
41310
  res.json({ error: `Not found: ${rel}` }, 404);
41167
41311
  return;
41168
41312
  }
41169
41313
  try {
41170
41314
  const { rmSync: rmSync2 } = await import("node:fs");
41171
41315
  rmSync2(target, { recursive: true, force: true });
41172
- res.json({ ok: true, deleted: relative9(root, target) });
41316
+ res.json({ ok: true, deleted: relative8(root, target) });
41173
41317
  } catch (e) {
41174
41318
  res.json({ error: e.message }, 500);
41175
41319
  }
@@ -41204,13 +41348,11 @@ var init_devAdmin = __esm({
41204
41348
  return;
41205
41349
  }
41206
41350
  try {
41207
- const { execFileSync: execFileSync6 } = await import("node:child_process");
41208
41351
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
41209
- const output = execFileSync6("npm", args, {
41352
+ const output = execFileSyncAllowingBatch("npm", args, {
41210
41353
  cwd: resolve16(process.cwd()),
41211
- timeout: 12e4,
41212
- encoding: "utf-8"
41213
- }).toString();
41354
+ timeout: 12e4
41355
+ });
41214
41356
  res.json({ ok: true, package: pkg, output });
41215
41357
  } catch (e) {
41216
41358
  res.json({ error: e.message }, 500);
@@ -41218,15 +41360,15 @@ var init_devAdmin = __esm({
41218
41360
  };
41219
41361
  handleGitStatus = async (_req, res) => {
41220
41362
  try {
41221
- const { execFileSync: execFileSync6 } = await import("node:child_process");
41363
+ const { execFileSync: execFileSync5 } = await import("node:child_process");
41222
41364
  const cwd = resolve16(process.cwd());
41223
41365
  try {
41224
- execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
41366
+ execFileSync5("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
41225
41367
  } catch {
41226
41368
  res.json({ error: "Not a git repository" }, 400);
41227
41369
  return;
41228
41370
  }
41229
- const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
41371
+ const run = (args) => execFileSync5("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
41230
41372
  res.json({
41231
41373
  branch: run(["branch", "--show-current"]),
41232
41374
  status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
@@ -41356,12 +41498,10 @@ var init_devAdmin = __esm({
41356
41498
  return;
41357
41499
  }
41358
41500
  try {
41359
- const { execFileSync: execFileSync6 } = await import("node:child_process");
41360
- const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
41501
+ const output = execFileSyncAllowingBatch("npx", ["tina4nodejs", "generate", kind, name], {
41361
41502
  cwd: resolve16(process.cwd()),
41362
- timeout: 3e4,
41363
- encoding: "utf-8"
41364
- }).toString();
41503
+ timeout: 3e4
41504
+ });
41365
41505
  res.json({ ok: true, kind, name, output });
41366
41506
  } catch (e) {
41367
41507
  res.json({ error: e.message }, 500);
@@ -41503,21 +41643,21 @@ var init_devAdmin = __esm({
41503
41643
  });
41504
41644
  };
41505
41645
  handleDevAdminJs = async (_req, res) => {
41506
- const { readFileSync: readFileSync27, existsSync: existsSync29 } = await import("node:fs");
41507
- const { dirname: dirname17, join: join33, resolve: resolve21 } = await import("node:path");
41508
- const { fileURLToPath: fileURLToPath10 } = await import("node:url");
41509
- const dir = dirname17(fileURLToPath10(import.meta.url));
41646
+ const { readFileSync: readFileSync27, existsSync: existsSync30 } = await import("node:fs");
41647
+ const { dirname: dirname17, join: join34, resolve: resolve21 } = await import("node:path");
41648
+ const { fileURLToPath: fileURLToPath11 } = await import("node:url");
41649
+ const dir = dirname17(fileURLToPath11(import.meta.url));
41510
41650
  const candidates = [
41511
- join33(dir, "..", "public", "js", "tina4-dev-admin.min.js"),
41651
+ join34(dir, "..", "public", "js", "tina4-dev-admin.min.js"),
41512
41652
  // src/../public/js/
41513
- join33(dir, "..", "..", "public", "js", "tina4-dev-admin.min.js"),
41653
+ join34(dir, "..", "..", "public", "js", "tina4-dev-admin.min.js"),
41514
41654
  // deeper nesting
41515
41655
  resolve21(process.cwd(), "node_modules", "tina4-nodejs", "packages", "core", "public", "js", "tina4-dev-admin.min.js"),
41516
41656
  resolve21(process.cwd(), "public", "js", "tina4-dev-admin.min.js")
41517
41657
  // project public/
41518
41658
  ];
41519
41659
  for (const jsPath of candidates) {
41520
- if (existsSync29(jsPath)) {
41660
+ if (existsSync30(jsPath)) {
41521
41661
  try {
41522
41662
  const content = readFileSync27(jsPath, "utf-8");
41523
41663
  res.raw.writeHead(200, { "Content-Type": "application/javascript; charset=utf-8", "Cache-Control": "no-cache" });
@@ -41531,20 +41671,20 @@ var init_devAdmin = __esm({
41531
41671
  res.raw.end("tina4-dev-admin.min.js not found");
41532
41672
  };
41533
41673
  handleDevAdminSplit = async (_req, res) => {
41534
- const { readFileSync: readFileSync27, existsSync: existsSync29 } = await import("node:fs");
41535
- const { dirname: dirname17, join: join33, resolve: resolve21 } = await import("node:path");
41536
- const { fileURLToPath: fileURLToPath10 } = await import("node:url");
41537
- const dir = dirname17(fileURLToPath10(import.meta.url));
41674
+ const { readFileSync: readFileSync27, existsSync: existsSync30 } = await import("node:fs");
41675
+ const { dirname: dirname17, join: join34, resolve: resolve21 } = await import("node:path");
41676
+ const { fileURLToPath: fileURLToPath11 } = await import("node:url");
41677
+ const dir = dirname17(fileURLToPath11(import.meta.url));
41538
41678
  const candidates = [
41539
- join33(dir, "..", "public", "js", "tina4-dev-admin-split.html"),
41540
- join33(dir, "..", "..", "public", "js", "tina4-dev-admin-split.html"),
41679
+ join34(dir, "..", "public", "js", "tina4-dev-admin-split.html"),
41680
+ join34(dir, "..", "..", "public", "js", "tina4-dev-admin-split.html"),
41541
41681
  resolve21(process.cwd(), "node_modules", "tina4-nodejs", "packages", "core", "public", "js", "tina4-dev-admin-split.html"),
41542
41682
  resolve21(process.cwd(), "public", "js", "tina4-dev-admin-split.html")
41543
41683
  ];
41544
- for (const path10 of candidates) {
41545
- if (existsSync29(path10)) {
41684
+ for (const path9 of candidates) {
41685
+ if (existsSync30(path9)) {
41546
41686
  try {
41547
- const content = readFileSync27(path10, "utf-8");
41687
+ const content = readFileSync27(path9, "utf-8");
41548
41688
  res.raw.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache" });
41549
41689
  res.raw.end(content);
41550
41690
  return;
@@ -41567,8 +41707,8 @@ var init_devAdmin = __esm({
41567
41707
  });
41568
41708
 
41569
41709
  // src/i18n.ts
41570
- import { readFileSync as readFileSync21, readdirSync as readdirSync17, existsSync as existsSync24 } from "node:fs";
41571
- import { join as join28, resolve as resolve17 } from "node:path";
41710
+ import { readFileSync as readFileSync21, readdirSync as readdirSync17, existsSync as existsSync25 } from "node:fs";
41711
+ import { join as join29, resolve as resolve17 } from "node:path";
41572
41712
  var I18n;
41573
41713
  var init_i18n = __esm({
41574
41714
  "src/i18n.ts"() {
@@ -41587,9 +41727,9 @@ var init_i18n = __esm({
41587
41727
  * Arg order is (locale, path) to match the Python master `I18n(locale, path)`
41588
41728
  * (BUG-7, BREAKING in 3.13.x — was previously (localeDir, defaultLocale)).
41589
41729
  */
41590
- constructor(locale, path10) {
41730
+ constructor(locale, path9) {
41591
41731
  this._localeDir = resolve17(
41592
- path10 ?? process.env.TINA4_LOCALE_DIR ?? "src/locales"
41732
+ path9 ?? process.env.TINA4_LOCALE_DIR ?? "src/locales"
41593
41733
  );
41594
41734
  this._defaultLocale = locale ?? process.env.TINA4_LOCALE ?? "en";
41595
41735
  this._currentLocale = this._defaultLocale;
@@ -41645,7 +41785,7 @@ var init_i18n = __esm({
41645
41785
  }
41646
41786
  /** List available locale codes based on JSON files in the locale directory. */
41647
41787
  availableLocales() {
41648
- if (!existsSync24(this._localeDir)) {
41788
+ if (!existsSync25(this._localeDir)) {
41649
41789
  return [this._defaultLocale];
41650
41790
  }
41651
41791
  try {
@@ -41661,8 +41801,8 @@ var init_i18n = __esm({
41661
41801
  if (this._translations.has(locale)) {
41662
41802
  return;
41663
41803
  }
41664
- const filePath = join28(this._localeDir, `${locale}.json`);
41665
- if (existsSync24(filePath)) {
41804
+ const filePath = join29(this._localeDir, `${locale}.json`);
41805
+ if (existsSync25(filePath)) {
41666
41806
  try {
41667
41807
  const raw = readFileSync21(filePath, "utf-8");
41668
41808
  const data = JSON.parse(raw);
@@ -41674,8 +41814,8 @@ var init_i18n = __esm({
41674
41814
  }
41675
41815
  }
41676
41816
  for (const ext of [".yml", ".yaml"]) {
41677
- const yamlPath = join28(this._localeDir, `${locale}${ext}`);
41678
- if (existsSync24(yamlPath)) {
41817
+ const yamlPath = join29(this._localeDir, `${locale}${ext}`);
41818
+ if (existsSync25(yamlPath)) {
41679
41819
  try {
41680
41820
  const raw = readFileSync21(yamlPath, "utf-8");
41681
41821
  const data = _I18n._parseSimpleYaml(raw);
@@ -43200,11 +43340,11 @@ __export(docsAutoDiscovery_exports, {
43200
43340
  writeMcpDiscovery: () => writeMcpDiscovery
43201
43341
  });
43202
43342
  import * as fs9 from "node:fs";
43203
- import * as path9 from "node:path";
43343
+ import * as path8 from "node:path";
43204
43344
  function writeMcpDiscovery(projectRoot3, port) {
43205
- const root = path9.resolve(projectRoot3);
43206
- const tinaDir = path9.join(root, TINA4_DIR);
43207
- const mcpPath = path9.join(tinaDir, MCP_FILE);
43345
+ const root = path8.resolve(projectRoot3);
43346
+ const tinaDir = path8.join(root, TINA4_DIR);
43347
+ const mcpPath = path8.join(tinaDir, MCP_FILE);
43208
43348
  const portStr = String(
43209
43349
  port || Number(process.env.TINA4_PORT) || Number(process.env.PORT) || 7148
43210
43350
  );
@@ -43231,9 +43371,9 @@ function writeMcpDiscovery(projectRoot3, port) {
43231
43371
  fs9.writeFileSync(mcpPath, desiredJson, "utf-8");
43232
43372
  wrote = true;
43233
43373
  }
43234
- const gitDir = path9.join(root, ".git");
43374
+ const gitDir = path8.join(root, ".git");
43235
43375
  if (fs9.existsSync(gitDir)) {
43236
- const gitignorePath = path9.join(root, ".gitignore");
43376
+ const gitignorePath = path8.join(root, ".gitignore");
43237
43377
  let contents = "";
43238
43378
  if (fs9.existsSync(gitignorePath)) {
43239
43379
  try {
@@ -43244,8 +43384,8 @@ function writeMcpDiscovery(projectRoot3, port) {
43244
43384
  const lines = contents.split(/\r?\n/);
43245
43385
  const already = lines.some((l) => l.trim() === GITIGNORE_LINE || l.trim() === ".tina4");
43246
43386
  if (!already) {
43247
- const sep9 = contents.endsWith("\n") || contents === "" ? "" : "\n";
43248
- fs9.writeFileSync(gitignorePath, `${contents}${sep9}${GITIGNORE_LINE}
43387
+ const sep10 = contents.endsWith("\n") || contents === "" ? "" : "\n";
43388
+ fs9.writeFileSync(gitignorePath, `${contents}${sep10}${GITIGNORE_LINE}
43249
43389
  `, "utf-8");
43250
43390
  }
43251
43391
  }
@@ -43263,11 +43403,11 @@ var init_docsAutoDiscovery = __esm({
43263
43403
 
43264
43404
  // src/server.ts
43265
43405
  import { randomBytes as randomBytes9 } from "node:crypto";
43266
- import { resolve as resolve19, dirname as dirname15, join as join30, relative as relative10 } from "node:path";
43267
- import { existsSync as existsSync26, readdirSync as readdirSync18, readFileSync as readFileSync23, statSync as statSync18 } from "node:fs";
43406
+ import { resolve as resolve19, dirname as dirname15, join as join31, relative as relative9 } from "node:path";
43407
+ import { existsSync as existsSync27, readdirSync as readdirSync18, readFileSync as readFileSync23, statSync as statSync19 } from "node:fs";
43268
43408
  import { isatty } from "node:tty";
43269
- import { fileURLToPath as fileURLToPath8 } from "node:url";
43270
- import { execFileSync as execFileSync3, execFile } from "node:child_process";
43409
+ import { fileURLToPath as fileURLToPath9 } from "node:url";
43410
+ import { execFile } from "node:child_process";
43271
43411
  import cluster from "node:cluster";
43272
43412
  import os2 from "node:os";
43273
43413
  function isSwaggerAssetPath(pathname) {
@@ -43301,9 +43441,35 @@ function swaggerAdvertised() {
43301
43441
  }
43302
43442
  return TRUTHY3.includes(raw);
43303
43443
  }
43444
+ function stripUrlCredentials(text) {
43445
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
43446
+ }
43447
+ function isModuleNotFound(err) {
43448
+ const code = err?.code;
43449
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
43450
+ }
43451
+ function reportOrmBootFailure(stage, err, dbConfig) {
43452
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
43453
+ if (stage === "connect") {
43454
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
43455
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
43456
+ bootDbConnectError = message;
43457
+ console.warn(`
43458
+ Database could not be reached (${target}): ${message}`);
43459
+ } else if (stage === "import" && isModuleNotFound(err)) {
43460
+ console.warn(`
43461
+ ORM not available (install @tina4/orm to enable): ${message}`);
43462
+ } else if (stage === "import") {
43463
+ console.warn(`
43464
+ ORM failed to load:`, err);
43465
+ } else {
43466
+ console.warn(`
43467
+ ORM model setup failed:`, err);
43468
+ }
43469
+ }
43304
43470
  async function autoMigrateOnStartup(migrationDir = "migrations", base = process.cwd()) {
43305
43471
  const dir = resolve19(base, migrationDir);
43306
- if (!existsSync26(dir)) return;
43472
+ if (!existsSync27(dir)) return;
43307
43473
  let hasSql = false;
43308
43474
  try {
43309
43475
  hasSql = readdirSync18(dir).some((f) => f.endsWith(".sql") && !f.endsWith(".down.sql"));
@@ -43319,9 +43485,20 @@ async function autoMigrateOnStartup(migrationDir = "migrations", base = process.
43319
43485
  let orm;
43320
43486
  try {
43321
43487
  orm = await Promise.resolve().then(() => (init_src(), src_exports));
43488
+ } catch (err) {
43489
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
43490
+ return;
43491
+ }
43492
+ try {
43322
43493
  orm.getAdapter();
43323
43494
  } catch (err) {
43324
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
43495
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
43496
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
43497
+ if (configuredUrl) {
43498
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
43499
+ } else {
43500
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
43501
+ }
43325
43502
  return;
43326
43503
  }
43327
43504
  try {
@@ -43382,17 +43559,8 @@ function killPort(port) {
43382
43559
  }
43383
43560
  }
43384
43561
  function findAvailablePort(start2) {
43385
- try {
43386
- execFileSync3(process.execPath, ["-e", `
43387
- const s = require("net").createServer();
43388
- s.listen(${start2}, "0.0.0.0", () => { s.close(); process.exit(0); });
43389
- s.on("error", () => process.exit(1));
43390
- `], { timeout: 1e3 });
43391
- return start2;
43392
- } catch {
43393
- killPort(start2);
43394
- return start2;
43395
- }
43562
+ if (probeBind("0.0.0.0", start2) === "held") killPort(start2);
43563
+ return start2;
43396
43564
  }
43397
43565
  function shouldOpenBrowser(isDevelopment, noBrowser = false) {
43398
43566
  if (!isDevelopment || isTruthy(process.env.TINA4_PRODUCTION) || cluster.isWorker) return false;
@@ -43454,12 +43622,12 @@ async function renderErrorPage(code, data, templatesDir) {
43454
43622
  }
43455
43623
  return instance;
43456
43624
  };
43457
- const userTemplatePath = join30(templatesDir, templateFile);
43458
- if (existsSync26(userTemplatePath)) {
43625
+ const userTemplatePath = join31(templatesDir, templateFile);
43626
+ if (existsSync27(userTemplatePath)) {
43459
43627
  return getCachedFrond(templatesDir).render(templateFile, data);
43460
43628
  }
43461
- const builtinTemplatePath = join30(BUILTIN_ERROR_TEMPLATES_DIR, templateFile);
43462
- if (existsSync26(builtinTemplatePath)) {
43629
+ const builtinTemplatePath = join31(BUILTIN_ERROR_TEMPLATES_DIR, templateFile);
43630
+ if (existsSync27(builtinTemplatePath)) {
43463
43631
  return getCachedFrond(BUILTIN_ERROR_TEMPLATES_DIR).render(templateFile, data);
43464
43632
  }
43465
43633
  return null;
@@ -43476,10 +43644,10 @@ function injectDevToolbar(html, ctx) {
43476
43644
  }
43477
43645
  function walkGalleryFiles(dir) {
43478
43646
  const results = [];
43479
- if (!existsSync26(dir)) return results;
43647
+ if (!existsSync27(dir)) return results;
43480
43648
  for (const f of readdirSync18(dir)) {
43481
- const full = join30(dir, f);
43482
- if (statSync18(full).isDirectory()) results.push(...walkGalleryFiles(full));
43649
+ const full = join31(dir, f);
43650
+ if (statSync19(full).isDirectory()) results.push(...walkGalleryFiles(full));
43483
43651
  else results.push(full);
43484
43652
  }
43485
43653
  return results;
@@ -43487,18 +43655,18 @@ function walkGalleryFiles(dir) {
43487
43655
  function getGalleryDeployedState() {
43488
43656
  const galleryDir = resolve19(__dirname, "..", "gallery");
43489
43657
  const state = {};
43490
- if (!existsSync26(galleryDir)) return state;
43658
+ if (!existsSync27(galleryDir)) return state;
43491
43659
  try {
43492
43660
  const entries = readdirSync18(galleryDir).sort();
43493
43661
  for (const entry of entries) {
43494
- const entryPath = join30(galleryDir, entry);
43495
- const metaFile = join30(entryPath, "meta.json");
43496
- if (statSync18(entryPath).isDirectory() && existsSync26(metaFile)) {
43497
- const srcDir = join30(entryPath, "src");
43498
- if (existsSync26(srcDir)) {
43662
+ const entryPath = join31(galleryDir, entry);
43663
+ const metaFile = join31(entryPath, "meta.json");
43664
+ if (statSync19(entryPath).isDirectory() && existsSync27(metaFile)) {
43665
+ const srcDir = join31(entryPath, "src");
43666
+ if (existsSync27(srcDir)) {
43499
43667
  const files = walkGalleryFiles(srcDir);
43500
43668
  const projectSrc = resolve19(process.cwd(), "src");
43501
- state[entry] = files.every((f) => existsSync26(join30(projectSrc, relative10(srcDir, f))));
43669
+ state[entry] = files.every((f) => existsSync27(join31(projectSrc, relative9(srcDir, f))));
43502
43670
  } else {
43503
43671
  state[entry] = false;
43504
43672
  }
@@ -43529,7 +43697,7 @@ function resolveTemplate(pathname, templatesDir) {
43529
43697
  if (cleanPath.includes("\\") || cleanPath.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) return null;
43530
43698
  const pagesDir = resolve19(templatesDir, TEMPLATE_PAGES_DIR);
43531
43699
  for (const ext of [".twig", ".html"]) {
43532
- if (existsSync26(resolve19(pagesDir, cleanPath + ext))) {
43700
+ if (existsSync27(resolve19(pagesDir, cleanPath + ext))) {
43533
43701
  return `${TEMPLATE_PAGES_DIR}/${cleanPath}${ext}`;
43534
43702
  }
43535
43703
  }
@@ -43538,7 +43706,7 @@ function resolveTemplate(pathname, templatesDir) {
43538
43706
  if (!templateCache) {
43539
43707
  templateCache = /* @__PURE__ */ new Map();
43540
43708
  const pagesDir = resolve19(templatesDir, TEMPLATE_PAGES_DIR);
43541
- if (existsSync26(pagesDir)) {
43709
+ if (existsSync27(pagesDir)) {
43542
43710
  const scan = (dir, prefix) => {
43543
43711
  for (const entry of readdirSync18(dir, { withFileTypes: true })) {
43544
43712
  if (entry.name.startsWith("_")) continue;
@@ -44006,9 +44174,9 @@ function serveMethodNotAllowed(ctx) {
44006
44174
  }
44007
44175
  function serveStaticAsset(ctx) {
44008
44176
  const custom = process.env.TINA4_PUBLIC_DIR;
44009
- if (custom && existsSync26(custom) && tryServeStatic(custom, ctx.req, ctx.res)) return true;
44010
- if (existsSync26(ctx.staticDir) && tryServeStatic(ctx.staticDir, ctx.req, ctx.res)) return true;
44011
- if (existsSync26(ctx.srcPublicDir) && tryServeStatic(ctx.srcPublicDir, ctx.req, ctx.res)) return true;
44177
+ if (custom && existsSync27(custom) && tryServeStatic(custom, ctx.req, ctx.res)) return true;
44178
+ if (existsSync27(ctx.staticDir) && tryServeStatic(ctx.staticDir, ctx.req, ctx.res)) return true;
44179
+ if (existsSync27(ctx.srcPublicDir) && tryServeStatic(ctx.srcPublicDir, ctx.req, ctx.res)) return true;
44012
44180
  if (ctx.swaggerAssetsEnabled || !isSwaggerAssetPath(ctx.pathname)) {
44013
44181
  if (tryServeStatic(BUILTIN_PUBLIC_DIR, ctx.req, ctx.res)) return true;
44014
44182
  }
@@ -44222,6 +44390,9 @@ function startProductionCluster(port, host) {
44222
44390
  Debug: OFF (Log level: ${logLevel})
44223
44391
  ${reset2}`);
44224
44392
  }
44393
+ if (process.env.NODE_CLUSTER_SCHED_POLICY === void 0) {
44394
+ cluster.schedulingPolicy = cluster.SCHED_RR;
44395
+ }
44225
44396
  for (let i = 0; i < numCPUs; i++) cluster.fork();
44226
44397
  cluster.on("exit", (worker, code) => {
44227
44398
  if (code !== 0) {
@@ -44241,12 +44412,13 @@ ${reset2}`);
44241
44412
  function wireLocaleGlobal(frondEngine, base) {
44242
44413
  if (!frondEngine) return;
44243
44414
  const localeDir = resolve19(base, process.env.TINA4_LOCALE_DIR ?? "src/locales");
44244
- if (!existsSync26(localeDir)) return;
44415
+ if (!existsSync27(localeDir)) return;
44245
44416
  try {
44246
44417
  const localeFiles = readdirSync18(localeDir).filter((file) => file.endsWith(".json"));
44247
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
44418
+ const FrondClass = frondEngine.constructor;
44419
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
44248
44420
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
44249
- frondEngine.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44421
+ FrondClass.addGlobal("t", (key, params) => i18nInstance.t(key, params));
44250
44422
  } catch {
44251
44423
  }
44252
44424
  }
@@ -44313,7 +44485,7 @@ async function startServer(config) {
44313
44485
  middleware.use(requestLogger());
44314
44486
  middleware.use(rateLimiter());
44315
44487
  MiddlewareRunner.use(SecurityHeadersMiddleware);
44316
- if (existsSync26(routesDir)) {
44488
+ if (existsSync27(routesDir)) {
44317
44489
  const routes = await discoverRoutes(routesDir);
44318
44490
  for (const route of routes) {
44319
44491
  router.addRoute(route);
@@ -44576,16 +44748,20 @@ ${reset2}
44576
44748
  });
44577
44749
  }
44578
44750
  async function initializeOrm(config, router, base, ormDir, modelsDir) {
44579
- const hasOrmDir = existsSync26(ormDir);
44580
- const hasModelsDir = existsSync26(modelsDir);
44751
+ const hasOrmDir = existsSync27(ormDir);
44752
+ const hasModelsDir = existsSync27(modelsDir);
44581
44753
  if (hasOrmDir || hasModelsDir) {
44754
+ let ormStage = "import";
44755
+ const dbConfig = config?.database ?? {};
44582
44756
  try {
44583
44757
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
44584
- const dbConfig = config?.database ?? {};
44758
+ ormStage = "connect";
44759
+ bootDbConnectError = null;
44585
44760
  await orm.initDatabase({
44586
44761
  type: dbConfig.type ?? "sqlite",
44587
44762
  path: dbConfig.path ?? "./data/tina4.db"
44588
44763
  });
44764
+ ormStage = "models";
44589
44765
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
44590
44766
  if (hasModelsDir) {
44591
44767
  const extraModels = await orm.discoverModels(modelsDir);
@@ -44620,8 +44796,7 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
44620
44796
  }
44621
44797
  }
44622
44798
  } catch (err) {
44623
- console.warn(`
44624
- ORM not available (install @tina4/orm to enable):`, err);
44799
+ reportOrmBootFailure(ormStage, err, dbConfig);
44625
44800
  }
44626
44801
  await autoMigrateOnStartup("migrations", base);
44627
44802
  }
@@ -44637,7 +44812,7 @@ async function configureSwagger(router, ormDir, modelsDir) {
44637
44812
  let modelDefs = [];
44638
44813
  try {
44639
44814
  const orm = await Promise.resolve().then(() => (init_src(), src_exports));
44640
- const allModelDirs = [ormDir, modelsDir].filter((d) => existsSync26(d));
44815
+ const allModelDirs = [ormDir, modelsDir].filter((d) => existsSync27(d));
44641
44816
  const seenTables = /* @__PURE__ */ new Set();
44642
44817
  for (const dir of allModelDirs) {
44643
44818
  const discovered = await orm.discoverModels(dir);
@@ -44659,7 +44834,7 @@ async function configureSwagger(router, ormDir, modelsDir) {
44659
44834
  }
44660
44835
  return enabled;
44661
44836
  }
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;
44837
+ 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
44838
  var init_server = __esm({
44664
44839
  "src/server.ts"() {
44665
44840
  "use strict";
@@ -44688,12 +44863,13 @@ var init_server = __esm({
44688
44863
  init_background();
44689
44864
  init_tcp();
44690
44865
  init_version();
44691
- __filename = fileURLToPath8(import.meta.url);
44866
+ __filename = fileURLToPath9(import.meta.url);
44692
44867
  __dirname = dirname15(__filename);
44693
44868
  BUILTIN_ERROR_TEMPLATES_DIR = resolve19(__dirname, "..", "templates");
44694
44869
  BUILTIN_PUBLIC_DIR = resolve19(__dirname, "..", "public");
44695
44870
  swaggerAssetsEnabled = false;
44696
44871
  DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;
44872
+ bootDbConnectError = null;
44697
44873
  frondCache2 = /* @__PURE__ */ new Map();
44698
44874
  _LEGACY_ENV_VARS = {
44699
44875
  DATABASE_URL: "TINA4_DATABASE_URL",
@@ -44929,7 +45105,7 @@ var init_mqttMessage = __esm({
44929
45105
  import net3 from "node:net";
44930
45106
  import tls from "node:tls";
44931
45107
  import { randomBytes as randomBytes10 } from "node:crypto";
44932
- import { existsSync as existsSync27, readFileSync as readFileSync24 } from "node:fs";
45108
+ import { existsSync as existsSync28, readFileSync as readFileSync24 } from "node:fs";
44933
45109
  var MqttError, MqttTimeoutError, CONNECT, CONNACK, PUBLISH, PUBACK, SUBSCRIBE, SUBACK, PINGREQ, PINGRESP, DISCONNECT, PROTOCOL_LEVEL, DEFAULT_PORT, DEFAULT_TLS_PORT, DEFAULT_URL, DEFAULT_KEEPALIVE, SUBSCRIPTION_REFUSED, MAX_REMAINING_LENGTH, QOS2_REFUSED_MESSAGE, CONNACK_RETURN_CODES, Mqtt;
44934
45110
  var init_mqtt = __esm({
44935
45111
  "src/mqtt.ts"() {
@@ -45132,7 +45308,7 @@ var init_mqtt = __esm({
45132
45308
  */
45133
45309
  async connect() {
45134
45310
  this.closeSocket();
45135
- if (this.secure && this.tlsVerify && this.caFile && !existsSync27(this.caFile)) {
45311
+ if (this.secure && this.tlsVerify && this.caFile && !existsSync28(this.caFile)) {
45136
45312
  throw new MqttError(
45137
45313
  `MQTT CA file not found: ${this.caFile} -- TINA4_MQTT_CA_FILE (or caFile) must point at the broker's CA certificate in PEM form`
45138
45314
  );
@@ -45614,9 +45790,9 @@ var init_mqtt = __esm({
45614
45790
  });
45615
45791
 
45616
45792
  // src/service.ts
45617
- import { readdirSync as readdirSync19, statSync as statSync19, watchFile, unwatchFile } from "node:fs";
45618
- import { join as join31, extname as extname8 } from "node:path";
45619
- import { pathToFileURL } from "node:url";
45793
+ import { readdirSync as readdirSync19, statSync as statSync20, watchFile, unwatchFile } from "node:fs";
45794
+ import { join as join32, extname as extname9 } from "node:path";
45795
+ import { pathToFileURL as pathToFileURL4 } from "node:url";
45620
45796
  function matchCronField(field, value) {
45621
45797
  if (field === "*") return true;
45622
45798
  if (field.includes("/")) {
@@ -45787,13 +45963,13 @@ var init_service = __esm({
45787
45963
  return discovered;
45788
45964
  }
45789
45965
  for (const entry of entries) {
45790
- const ext = extname8(entry);
45966
+ const ext = extname9(entry);
45791
45967
  if (ext !== ".ts" && ext !== ".js") continue;
45792
- const fullPath = join31(dir, entry);
45793
- const stat = statSync19(fullPath);
45968
+ const fullPath = join32(dir, entry);
45969
+ const stat = statSync20(fullPath);
45794
45970
  if (!stat.isFile()) continue;
45795
45971
  try {
45796
- const fileUrl = pathToFileURL(fullPath).href;
45972
+ const fileUrl = pathToFileURL4(fullPath).href;
45797
45973
  const mod = await import(fileUrl);
45798
45974
  const exp = mod.default ?? mod;
45799
45975
  if (exp.name && typeof exp.handler === "function") {
@@ -45914,13 +46090,13 @@ var init_service = __esm({
45914
46090
  return;
45915
46091
  }
45916
46092
  for (const entry of entries) {
45917
- const ext = extname8(entry);
46093
+ const ext = extname9(entry);
45918
46094
  if (ext !== ".ts" && ext !== ".js") continue;
45919
- const fullPath = join31(dir, entry);
46095
+ const fullPath = join32(dir, entry);
45920
46096
  if (watchedFiles.has(fullPath)) continue;
45921
46097
  watchedFiles.add(fullPath);
45922
46098
  watchFile(fullPath, { interval: 1e3 }, async () => {
45923
- const fileUrl = pathToFileURL(fullPath).href;
46099
+ const fileUrl = pathToFileURL4(fullPath).href;
45924
46100
  try {
45925
46101
  const mod = await import(fileUrl + "?t=" + Date.now());
45926
46102
  const exp = mod.default ?? mod;
@@ -46183,23 +46359,23 @@ function guessContentType(filename) {
46183
46359
  }
46184
46360
  function buildMultipartBody(boundary, fieldName, filename, fileContent, contentType, extraFields) {
46185
46361
  const crlf = "\r\n";
46186
- const delimiter2 = `--${boundary}`;
46362
+ const delimiter3 = `--${boundary}`;
46187
46363
  const parts = [];
46188
46364
  if (extraFields) {
46189
46365
  for (const [key, value] of Object.entries(extraFields)) {
46190
- parts.push(Buffer.from(delimiter2 + crlf, "utf-8"));
46366
+ parts.push(Buffer.from(delimiter3 + crlf, "utf-8"));
46191
46367
  parts.push(Buffer.from(`Content-Disposition: form-data; name="${key}"` + crlf + crlf, "utf-8"));
46192
46368
  parts.push(Buffer.from(String(value) + crlf, "utf-8"));
46193
46369
  }
46194
46370
  }
46195
- parts.push(Buffer.from(delimiter2 + crlf, "utf-8"));
46371
+ parts.push(Buffer.from(delimiter3 + crlf, "utf-8"));
46196
46372
  parts.push(
46197
46373
  Buffer.from(`Content-Disposition: form-data; name="${fieldName}"; filename="${filename}"` + crlf, "utf-8")
46198
46374
  );
46199
46375
  parts.push(Buffer.from(`Content-Type: ${contentType}` + crlf + crlf, "utf-8"));
46200
46376
  parts.push(fileContent);
46201
46377
  parts.push(Buffer.from(crlf, "utf-8"));
46202
- parts.push(Buffer.from(delimiter2 + "--" + crlf, "utf-8"));
46378
+ parts.push(Buffer.from(delimiter3 + "--" + crlf, "utf-8"));
46203
46379
  return Buffer.concat(parts);
46204
46380
  }
46205
46381
  async function* parseLineStream(chunks) {
@@ -46446,8 +46622,8 @@ var init_api = __esm({
46446
46622
  /**
46447
46623
  * HTTP GET request.
46448
46624
  */
46449
- async get(path10, params) {
46450
- let url = this.buildUrl(path10);
46625
+ async get(path9, params) {
46626
+ let url = this.buildUrl(path9);
46451
46627
  if (params && Object.keys(params).length > 0) {
46452
46628
  const qs = new URLSearchParams(params).toString();
46453
46629
  url += (url.includes("?") ? "&" : "?") + qs;
@@ -46457,32 +46633,32 @@ var init_api = __esm({
46457
46633
  /**
46458
46634
  * HTTP POST request.
46459
46635
  */
46460
- async post(path10, body, contentType = "application/json") {
46461
- return this.sendRequest("POST", path10, body, contentType);
46636
+ async post(path9, body, contentType = "application/json") {
46637
+ return this.sendRequest("POST", path9, body, contentType);
46462
46638
  }
46463
46639
  /**
46464
46640
  * HTTP PUT request.
46465
46641
  */
46466
- async put(path10, body, contentType = "application/json") {
46467
- return this.sendRequest("PUT", path10, body, contentType);
46642
+ async put(path9, body, contentType = "application/json") {
46643
+ return this.sendRequest("PUT", path9, body, contentType);
46468
46644
  }
46469
46645
  /**
46470
46646
  * HTTP PATCH request.
46471
46647
  */
46472
- async patch(path10, body, contentType = "application/json") {
46473
- return this.sendRequest("PATCH", path10, body, contentType);
46648
+ async patch(path9, body, contentType = "application/json") {
46649
+ return this.sendRequest("PATCH", path9, body, contentType);
46474
46650
  }
46475
46651
  /**
46476
46652
  * HTTP DELETE request.
46477
46653
  */
46478
- async delete(path10, body) {
46479
- return this.sendRequest("DELETE", path10, body);
46654
+ async delete(path9, body) {
46655
+ return this.sendRequest("DELETE", path9, body);
46480
46656
  }
46481
46657
  /**
46482
46658
  * Generic request method — public entry point for any HTTP method.
46483
46659
  */
46484
- async sendRequest(method, path10, body, contentType = "application/json") {
46485
- const url = this.buildUrl(path10);
46660
+ async sendRequest(method, path9, body, contentType = "application/json") {
46661
+ const url = this.buildUrl(path9);
46486
46662
  return this.execute(method.toUpperCase(), url, body, contentType);
46487
46663
  }
46488
46664
  /**
@@ -46506,7 +46682,7 @@ var init_api = __esm({
46506
46682
  * await api.upload("/avatars", { fileBytes: raw, filename: "me.png",
46507
46683
  * extraFields: { user_id: "42" } });
46508
46684
  */
46509
- async upload(path10, opts = {}) {
46685
+ async upload(path9, opts = {}) {
46510
46686
  const { filePath, fieldName = "file", extraFields, headers, fileBytes, filename } = opts;
46511
46687
  let content;
46512
46688
  let uploadName;
@@ -46541,7 +46717,7 @@ var init_api = __esm({
46541
46717
  const boundary = "----Tina4Boundary" + randomBytes11(16).toString("hex");
46542
46718
  const bodyBuffer = buildMultipartBody(boundary, fieldName, uploadName, content, partContentType, extraFields);
46543
46719
  const contentType = `multipart/form-data; boundary=${boundary}`;
46544
- return this.execute("POST", this.buildUrl(path10), bodyBuffer, contentType, headers);
46720
+ return this.execute("POST", this.buildUrl(path9), bodyBuffer, contentType, headers);
46545
46721
  }
46546
46722
  /**
46547
46723
  * Stream a GET response body to `destPath` in chunks.
@@ -46556,11 +46732,11 @@ var init_api = __esm({
46556
46732
  * dest, HTTP error status, or a transport failure); the destination file is
46557
46733
  * not written on error.
46558
46734
  */
46559
- async download(path10, destPath, params) {
46735
+ async download(path9, destPath, params) {
46560
46736
  if (!destPath) {
46561
46737
  return { http_code: null, headers: {}, error: "download requires destPath", path: null };
46562
46738
  }
46563
- let url = this.buildUrl(path10);
46739
+ let url = this.buildUrl(path9);
46564
46740
  if (params && Object.keys(params).length > 0) {
46565
46741
  const qs = new URLSearchParams(params).toString();
46566
46742
  url += (url.includes("?") ? "&" : "?") + qs;
@@ -46644,8 +46820,8 @@ var init_api = __esm({
46644
46820
  * bounds just the connect + headers phase (default
46645
46821
  * `TINA4_API_CONNECT_TIMEOUT` or 10s).
46646
46822
  */
46647
- async *streamBytes(path10, opts = {}) {
46648
- const url = this.buildUrl(path10);
46823
+ async *streamBytes(path9, opts = {}) {
46824
+ const url = this.buildUrl(path9);
46649
46825
  const method = (opts.method ?? "GET").toUpperCase();
46650
46826
  const contentType = opts.contentType ?? "application/json";
46651
46827
  const { headers, data } = this.buildRequest(method, contentType, opts.body, opts.headers, url);
@@ -46680,8 +46856,8 @@ var init_api = __esm({
46680
46856
  * yields a trailing line without a terminator on EOF. Built on
46681
46857
  * {@link streamBytes} plus the shared {@link parseLineStream}.
46682
46858
  */
46683
- async *streamLines(path10, opts = {}) {
46684
- yield* parseLineStream(this.streamBytes(path10, opts));
46859
+ async *streamLines(path9, opts = {}) {
46860
+ yield* parseLineStream(this.streamBytes(path9, opts));
46685
46861
  }
46686
46862
  /**
46687
46863
  * Stream the response as SSE (Server-Sent Events). Yields one
@@ -46690,8 +46866,8 @@ var init_api = __esm({
46690
46866
  * with `data === "[DONE]"` and the iterator ends on the next EOF.
46691
46867
  * Built on {@link streamLines} plus the shared {@link parseSseStream}.
46692
46868
  */
46693
- async *streamSse(path10, opts = {}) {
46694
- yield* parseSseStream(this.streamLines(path10, opts));
46869
+ async *streamSse(path9, opts = {}) {
46870
+ yield* parseSseStream(this.streamLines(path9, opts));
46695
46871
  }
46696
46872
  // ── Internal helpers ──────────────────────────────────────────────
46697
46873
  /**
@@ -46757,14 +46933,14 @@ var init_api = __esm({
46757
46933
  req2.end();
46758
46934
  });
46759
46935
  }
46760
- buildUrl(path10) {
46761
- if (path10.startsWith("http://") || path10.startsWith("https://")) {
46762
- return path10;
46936
+ buildUrl(path9) {
46937
+ if (path9.startsWith("http://") || path9.startsWith("https://")) {
46938
+ return path9;
46763
46939
  }
46764
- if (!path10) {
46940
+ if (!path9) {
46765
46941
  return this.baseUrl;
46766
46942
  }
46767
- return `${this.baseUrl}/${path10.replace(/^\/+/, "")}`;
46943
+ return `${this.baseUrl}/${path9.replace(/^\/+/, "")}`;
46768
46944
  }
46769
46945
  /**
46770
46946
  * The headers configured on the client, as they may go to `targetUrl`.
@@ -48704,15 +48880,15 @@ var init_htmlElement = __esm({
48704
48880
  });
48705
48881
 
48706
48882
  // src/ai.ts
48707
- import { existsSync as existsSync28, mkdirSync as mkdirSync21, writeFileSync as writeFileSync18, readFileSync as readFileSync26 } from "node:fs";
48883
+ import { existsSync as existsSync29, mkdirSync as mkdirSync21, writeFileSync as writeFileSync18, readFileSync as readFileSync26 } from "node:fs";
48708
48884
  import { homedir } from "node:os";
48709
- import { join as join32, resolve as resolve20, relative as relative11, dirname as dirname16 } from "node:path";
48710
- import { fileURLToPath as fileURLToPath9 } from "node:url";
48711
- import { execSync, execFileSync as execFileSync4 } from "node:child_process";
48885
+ import { join as join33, resolve as resolve20, relative as relative10, dirname as dirname16 } from "node:path";
48886
+ import { fileURLToPath as fileURLToPath10 } from "node:url";
48887
+ import { execSync, execFileSync as execFileSync3 } from "node:child_process";
48712
48888
  import { createInterface } from "node:readline";
48713
48889
  function readVersion() {
48714
48890
  try {
48715
- const thisDir = dirname16(fileURLToPath9(import.meta.url));
48891
+ const thisDir = dirname16(fileURLToPath10(import.meta.url));
48716
48892
  const rootPkg = resolve20(thisDir, "..", "..", "..", "package.json");
48717
48893
  const pkg = JSON.parse(readFileSync26(rootPkg, "utf-8"));
48718
48894
  return pkg.version ?? "0.0.0";
@@ -48764,7 +48940,7 @@ function downloadSkillsSync(jobs) {
48764
48940
  })();
48765
48941
  `;
48766
48942
  try {
48767
- const out = execFileSync4(process.execPath, ["-e", child, JSON.stringify(jobs)], {
48943
+ const out = execFileSync3(process.execPath, ["-e", child, JSON.stringify(jobs)], {
48768
48944
  encoding: "utf-8",
48769
48945
  timeout: 5e4,
48770
48946
  maxBuffer: 8 * 1024 * 1024
@@ -48777,8 +48953,8 @@ function downloadSkillsSync(jobs) {
48777
48953
  function installSkills(root = ".", targets) {
48778
48954
  const ref = skillsRef();
48779
48955
  const dests = targets ?? [
48780
- join32(resolve20(root), ".claude", "skills"),
48781
- join32(homedir(), ".claude", "skills")
48956
+ join33(resolve20(root), ".claude", "skills"),
48957
+ join33(homedir(), ".claude", "skills")
48782
48958
  ];
48783
48959
  const jobs = [];
48784
48960
  const index = /* @__PURE__ */ new Map();
@@ -48796,9 +48972,9 @@ function installSkills(root = ".", targets) {
48796
48972
  const base = `https://raw.githubusercontent.com/tina4stack/${spec.repo}/${ref}/.claude/skills/${skill}`;
48797
48973
  skillMdUrl[skill] = `${base}/SKILL.md`;
48798
48974
  for (const dest of dests) {
48799
- add(`${base}/SKILL.md`, join32(dest, skill, "SKILL.md"));
48975
+ add(`${base}/SKILL.md`, join33(dest, skill, "SKILL.md"));
48800
48976
  for (const r of spec.references) {
48801
- add(`${base}/references/${r}`, join32(dest, skill, "references", r));
48977
+ add(`${base}/references/${r}`, join33(dest, skill, "references", r));
48802
48978
  }
48803
48979
  }
48804
48980
  }
@@ -48810,7 +48986,7 @@ function installSkills(root = ".", targets) {
48810
48986
  return installed;
48811
48987
  }
48812
48988
  function isInstalled(root, tool) {
48813
- return existsSync28(join32(resolve20(root), tool.contextFile));
48989
+ return existsSync29(join33(resolve20(root), tool.contextFile));
48814
48990
  }
48815
48991
  function showMenu(root = ".") {
48816
48992
  const r = resolve20(root);
@@ -48933,7 +49109,7 @@ function looksLikeOldFrameworkInstall(existing) {
48933
49109
  function writeOrMerge(contextPath, contextFile, frameworkGuide) {
48934
49110
  const block = skillBlock(contextFile);
48935
49111
  const [start2, end] = markersFor(contextFile);
48936
- if (!existsSync28(contextPath)) {
49112
+ if (!existsSync29(contextPath)) {
48937
49113
  writeFileSync18(contextPath, frameworkGuide.replace(/\s+$/, "") + "\n\n" + block + "\n", "utf-8");
48938
49114
  return "Installed";
48939
49115
  }
@@ -48954,14 +49130,14 @@ function writeOrMerge(contextPath, contextFile, frameworkGuide) {
48954
49130
  }
48955
49131
  function installForTool(root, tool, context) {
48956
49132
  const created = [];
48957
- const contextPath = join32(root, tool.contextFile);
49133
+ const contextPath = join33(root, tool.contextFile);
48958
49134
  if (tool.configDir) {
48959
- mkdirSync21(join32(root, tool.configDir), { recursive: true });
49135
+ mkdirSync21(join33(root, tool.configDir), { recursive: true });
48960
49136
  }
48961
49137
  const parentDir = dirname16(contextPath);
48962
49138
  mkdirSync21(parentDir, { recursive: true });
48963
49139
  const action = writeOrMerge(contextPath, tool.contextFile, context);
48964
- const rel = relative11(root, contextPath);
49140
+ const rel = relative10(root, contextPath);
48965
49141
  created.push(rel);
48966
49142
  console.log(` ${GREEN2}\u2713${RESET2} ${action} ${rel}`);
48967
49143
  if (tool.name === "claude-code") {
@@ -48994,7 +49170,7 @@ function installTina4Ai() {
48994
49170
  function installClaudeSkills(root) {
48995
49171
  const created = [];
48996
49172
  for (const skill of installSkills(root)) {
48997
- created.push(join32(".claude", "skills", skill));
49173
+ created.push(join33(".claude", "skills", skill));
48998
49174
  console.log(` ${GREEN2}\u2713${RESET2} Installed .claude/skills/${skill} (project + global)`);
48999
49175
  }
49000
49176
  return created;
@@ -49335,10 +49511,10 @@ import { tests, assertEqual, runAll } from "tina4-nodejs";
49335
49511
  }
49336
49512
  function generateClaudeCodeContext() {
49337
49513
  try {
49338
- const thisDir = dirname16(fileURLToPath9(import.meta.url));
49514
+ const thisDir = dirname16(fileURLToPath10(import.meta.url));
49339
49515
  const repoRoot = resolve20(thisDir, "..", "..", "..");
49340
- const claudeMdPath = join32(repoRoot, "CLAUDE.md");
49341
- if (existsSync28(claudeMdPath)) {
49516
+ const claudeMdPath = join33(repoRoot, "CLAUDE.md");
49517
+ if (existsSync29(claudeMdPath)) {
49342
49518
  return readFileSync26(claudeMdPath, "utf-8");
49343
49519
  }
49344
49520
  } catch {
@@ -49999,10 +50175,10 @@ var init_aiClient = __esm({
49999
50175
  throw new AiConfigError("AI URL must be an http or https URL");
50000
50176
  }
50001
50177
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new AiConfigError("AI URL must be an http or https URL");
50002
- const path10 = rtrimSlashes(url.pathname);
50003
- if (path10 === "" || path10 === "/v1" || path10 === "/api" || path10 === "/v1beta/openai") {
50178
+ const path9 = rtrimSlashes(url.pathname);
50179
+ if (path9 === "" || path9 === "/v1" || path9 === "/api" || path9 === "/v1beta/openai") {
50004
50180
  const suffix = provider === "anthropic" ? "/messages" : capability === "embed" ? "/embeddings" : "/chat/completions";
50005
- url.pathname = (path10 || "/v1") + suffix;
50181
+ url.pathname = (path9 || "/v1") + suffix;
50006
50182
  }
50007
50183
  return url.toString();
50008
50184
  }
@@ -50518,7 +50694,7 @@ var init_aiClient = __esm({
50518
50694
  });
50519
50695
 
50520
50696
  // src/queueBackends/rabbitmqBackend.ts
50521
- import { execFileSync as execFileSync5 } from "node:child_process";
50697
+ import { execFileSync as execFileSync4 } from "node:child_process";
50522
50698
  import { randomUUID as randomUUID9 } from "node:crypto";
50523
50699
  function parseAmqpUrl(url) {
50524
50700
  const config = {};
@@ -50939,7 +51115,7 @@ var init_rabbitmqBackend = __esm({
50939
51115
  setTimeout(() => { sock.destroy(); process.exit(1); }, 10000).unref();
50940
51116
  `;
50941
51117
  try {
50942
- const result = execFileSync5(process.execPath, ["-e", script], {
51118
+ const result = execFileSync4(process.execPath, ["-e", script], {
50943
51119
  encoding: "utf-8",
50944
51120
  timeout: 15e3,
50945
51121
  stdio: ["pipe", "pipe", "pipe"]
@@ -51315,27 +51491,27 @@ var init_testClient = __esm({
51315
51491
  return this.ctxPromise;
51316
51492
  }
51317
51493
  /** Send a GET request. */
51318
- async get(path10, options) {
51319
- return this._request("GET", path10, options);
51494
+ async get(path9, options) {
51495
+ return this._request("GET", path9, options);
51320
51496
  }
51321
51497
  /** Send a POST request. */
51322
- async post(path10, options) {
51323
- return this._request("POST", path10, options);
51498
+ async post(path9, options) {
51499
+ return this._request("POST", path9, options);
51324
51500
  }
51325
51501
  /** Send a PUT request. */
51326
- async put(path10, options) {
51327
- return this._request("PUT", path10, options);
51502
+ async put(path9, options) {
51503
+ return this._request("PUT", path9, options);
51328
51504
  }
51329
51505
  /** Send a PATCH request. */
51330
- async patch(path10, options) {
51331
- return this._request("PATCH", path10, options);
51506
+ async patch(path9, options) {
51507
+ return this._request("PATCH", path9, options);
51332
51508
  }
51333
51509
  /** Send a DELETE request. */
51334
- async delete(path10, options) {
51335
- return this._request("DELETE", path10, options);
51510
+ async delete(path9, options) {
51511
+ return this._request("DELETE", path9, options);
51336
51512
  }
51337
51513
  /** Build a mock request/response pair and dispatch it through the REAL pipeline (runDispatch). */
51338
- async _request(method, path10, options) {
51514
+ async _request(method, path9, options) {
51339
51515
  const { json, body, headers } = options ?? {};
51340
51516
  let rawBody = "";
51341
51517
  let contentType = "";
@@ -51361,7 +51537,7 @@ var init_testClient = __esm({
51361
51537
  Object.defineProperty(socket, "remoteAddress", { value: "127.0.0.1" });
51362
51538
  const rawReq = new IncomingMessage2(socket);
51363
51539
  rawReq.method = method.toUpperCase();
51364
- rawReq.url = path10;
51540
+ rawReq.url = path9;
51365
51541
  rawReq.headers = { ...reqHeaders, host: "localhost:7148" };
51366
51542
  if (rawBody) {
51367
51543
  rawReq.push(Buffer.from(rawBody));
@@ -51432,20 +51608,20 @@ var init_test = __esm({
51432
51608
  if (this._client === null) this._client = new TestClient();
51433
51609
  return this._client;
51434
51610
  }
51435
- async get(path10, options) {
51436
- return this.client.get(path10, options);
51611
+ async get(path9, options) {
51612
+ return this.client.get(path9, options);
51437
51613
  }
51438
- async post(path10, options) {
51439
- return this.client.post(path10, options);
51614
+ async post(path9, options) {
51615
+ return this.client.post(path9, options);
51440
51616
  }
51441
- async put(path10, options) {
51442
- return this.client.put(path10, options);
51617
+ async put(path9, options) {
51618
+ return this.client.put(path9, options);
51443
51619
  }
51444
- async patch(path10, options) {
51445
- return this.client.patch(path10, options);
51620
+ async patch(path9, options) {
51621
+ return this.client.patch(path9, options);
51446
51622
  }
51447
- async delete(path10, options) {
51448
- return this.client.delete(path10, options);
51623
+ async delete(path9, options) {
51624
+ return this.client.delete(path9, options);
51449
51625
  }
51450
51626
  // ── Positional assertions — (actual, expected, message) shape ────────
51451
51627
  assertEqual(actual, expected, message) {