tina4-nodejs 3.13.162 → 3.13.164

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7288,8 +7288,14 @@ var init_engine = __esm({
7288
7288
  // and every future ``new Frond()`` inherits it automatically.
7289
7289
  // Mirrors Python's _class_globals / _class_filters / _class_tests.
7290
7290
  static classFilters = /* @__PURE__ */ new Map();
7291
- static classGlobals = /* @__PURE__ */ new Map();
7291
+ // Globals are read LIVE at render time (not copied at construction), so a
7292
+ // Frond.addGlobal() made after an engine exists still reaches it. A plain
7293
+ // object rather than a Map so render() can spread it in one step.
7294
+ static classGlobals = {};
7292
7295
  static classTests = /* @__PURE__ */ new Map();
7296
+ // Bumped on every class-level filter/test change, so an engine knows when
7297
+ // to rebuild its merged filter/test maps (see syncRegistries).
7298
+ static classRegistryVersion = 0;
7293
7299
  // ── Live-block registries (server-rendered {% live %} regions) ──
7294
7300
  // A {% live %} block registers three things when its page first renders:
7295
7301
  // liveFragments[name] -> the raw body source, re-rendered on every
@@ -7309,20 +7315,27 @@ var init_engine = __esm({
7309
7315
  static liveBroadcaster = null;
7310
7316
  /**
7311
7317
  * Register a custom filter at the class level — available to every
7312
- * future ``new Frond()`` instance. Callable as ``Frond.addFilter()``
7318
+ * instance, existing ones included: an engine merges the class filters
7319
+ * again at its next render (ADR-0107). Callable as ``Frond.addFilter()``
7313
7320
  * (static) or ``frond.addFilter()`` (instance). See instance method
7314
7321
  * below for the dual-call semantics.
7315
7322
  */
7316
7323
  static addFilter(name, fn) {
7317
7324
  _Frond.classFilters.set(name, fn);
7325
+ _Frond.classRegistryVersion++;
7318
7326
  }
7319
7327
  /**
7320
7328
  * Register a global variable available in all templates of every
7321
- * future instance. Callable as ``Frond.addGlobal()`` (static) or
7329
+ * instance, existing ones included: class globals are read at render time
7330
+ * (ADR-0106). Callable as ``Frond.addGlobal()`` (static) or
7322
7331
  * ``frond.addGlobal()`` (instance).
7323
7332
  */
7324
7333
  static addGlobal(name, value) {
7325
- _Frond.classGlobals.set(name, value);
7334
+ _Frond.classGlobals[name] = value;
7335
+ }
7336
+ /** True when a class-level global with this name is registered. */
7337
+ static hasGlobal(name) {
7338
+ return Object.prototype.hasOwnProperty.call(_Frond.classGlobals, name);
7326
7339
  }
7327
7340
  /**
7328
7341
  * Register a custom test (``{% if x is positive %}``) at the class
@@ -7331,6 +7344,7 @@ var init_engine = __esm({
7331
7344
  */
7332
7345
  static addTest(name, fn) {
7333
7346
  _Frond.classTests.set(name, fn);
7347
+ _Frond.classRegistryVersion++;
7334
7348
  }
7335
7349
  /**
7336
7350
  * Clear the class-level globals/filters/tests registries.
@@ -7340,15 +7354,25 @@ var init_engine = __esm({
7340
7354
  */
7341
7355
  static clearRegistry() {
7342
7356
  _Frond.classFilters.clear();
7343
- _Frond.classGlobals.clear();
7357
+ _Frond.classGlobals = {};
7344
7358
  _Frond.classTests.clear();
7359
+ _Frond.classRegistryVersion++;
7345
7360
  _Frond.liveFragments.clear();
7346
7361
  _Frond.liveSources.clear();
7347
7362
  _Frond.liveWsPaths.clear();
7348
7363
  }
7349
7364
  templateDir;
7350
- filters;
7365
+ /** Effective filters: built-in < class < instance (see syncRegistries). */
7366
+ filters = {};
7367
+ /** Filters / tests registered on THIS instance only (ADR-0052). */
7368
+ localFilters = {};
7369
+ localTests = {};
7370
+ /** The class-registry version `filters` / `tests` were last merged at. */
7371
+ registryVersion = -1;
7372
+ /** Globals registered on THIS instance only (ADR-0052). */
7351
7373
  globals;
7374
+ /** Built-in globals (formToken, range, dump, csp_nonce, ...). */
7375
+ builtinGlobals;
7352
7376
  tests;
7353
7377
  _sandbox;
7354
7378
  _allowedFilters;
@@ -7378,9 +7402,10 @@ var init_engine = __esm({
7378
7402
  }
7379
7403
  constructor(templateDir = "src/templates") {
7380
7404
  this.templateDir = resolve2(templateDir);
7381
- this.filters = { ...BUILTIN_FILTERS };
7382
7405
  this.globals = {};
7406
+ this.builtinGlobals = {};
7383
7407
  this.tests = {};
7408
+ this.syncRegistries();
7384
7409
  this._sandbox = false;
7385
7410
  this._allowedFilters = null;
7386
7411
  this._allowedTags = null;
@@ -7428,16 +7453,25 @@ var init_engine = __esm({
7428
7453
  return { output, next };
7429
7454
  }
7430
7455
  };
7431
- this.globals.formToken = (descriptor) => _generateFormToken(descriptor || "");
7432
- this.globals.form_token = (descriptor) => _generateFormToken(descriptor || "");
7433
- this.globals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
7434
- this.globals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
7435
- this.globals.range = frondRange;
7436
- this.globals.dump = (value) => renderDump(value);
7437
- this.globals.csp_nonce = () => _cspNonceProvider();
7438
- for (const [k, v] of _Frond.classFilters) this.filters[k] = v;
7439
- for (const [k, v] of _Frond.classGlobals) this.globals[k] = v;
7440
- for (const [k, v] of _Frond.classTests) this.tests[k] = v;
7456
+ this.builtinGlobals.formToken = (descriptor) => _generateFormToken(descriptor || "");
7457
+ this.builtinGlobals.form_token = (descriptor) => _generateFormToken(descriptor || "");
7458
+ this.builtinGlobals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
7459
+ this.builtinGlobals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
7460
+ this.builtinGlobals.range = frondRange;
7461
+ this.builtinGlobals.dump = (value) => renderDump(value);
7462
+ this.builtinGlobals.csp_nonce = () => _cspNonceProvider();
7463
+ }
7464
+ /**
7465
+ * Rebuild the merged filter/test maps when the class registry changed.
7466
+ * Same layering as globals -- built-ins < class < this instance. Filter
7467
+ * lookup is on the hot path, so the merge is a plain object rebuilt only
7468
+ * when the class-registry version moves, never a per-lookup chain.
7469
+ */
7470
+ syncRegistries() {
7471
+ if (this.registryVersion === _Frond.classRegistryVersion) return;
7472
+ this.filters = { ...BUILTIN_FILTERS, ...Object.fromEntries(_Frond.classFilters), ...this.localFilters };
7473
+ this.tests = { ...Object.fromEntries(_Frond.classTests), ...this.localTests };
7474
+ this.registryVersion = _Frond.classRegistryVersion;
7441
7475
  }
7442
7476
  sandbox(filters, tags, vars) {
7443
7477
  this._sandbox = true;
@@ -7458,6 +7492,7 @@ var init_engine = __esm({
7458
7492
  * for process-global registration. tina4: ADR-0052.
7459
7493
  */
7460
7494
  addFilter(name, fn) {
7495
+ this.localFilters[name] = fn;
7461
7496
  this.filters[name] = fn;
7462
7497
  }
7463
7498
  /**
@@ -7470,6 +7505,7 @@ var init_engine = __esm({
7470
7505
  * Register a custom test on this instance only.
7471
7506
  */
7472
7507
  addTest(name, fn) {
7508
+ this.localTests[name] = fn;
7473
7509
  this.tests[name] = fn;
7474
7510
  }
7475
7511
  /**
@@ -7485,8 +7521,19 @@ var init_engine = __esm({
7485
7521
  const n = parseInt(raw, 10);
7486
7522
  return isNaN(n) || n < 0 ? 0 : n;
7487
7523
  }
7524
+ /**
7525
+ * Layer the globals under the render data: built-ins < class globals (read
7526
+ * live, so registration order never matters) < this instance's own globals
7527
+ * < the data passed to render(). Every render starts here, so this is also
7528
+ * where the filter/test maps catch up with any class registration made
7529
+ * since the last render.
7530
+ */
7531
+ withGlobals(data) {
7532
+ this.syncRegistries();
7533
+ return { ...this.builtinGlobals, ..._Frond.classGlobals, ...this.globals, ...data || {} };
7534
+ }
7488
7535
  render(template, data) {
7489
- const context = { ...this.globals, ...data || {} };
7536
+ const context = this.withGlobals(data);
7490
7537
  const filePath = join5(this.templateDir, template);
7491
7538
  if (!existsSync5(filePath)) {
7492
7539
  throw new Error(`Template not found: ${filePath}`);
@@ -7509,7 +7556,7 @@ var init_engine = __esm({
7509
7556
  return this.executeWithSource(source, tokens, context);
7510
7557
  }
7511
7558
  renderString(source, data) {
7512
- const context = { ...this.globals, ...data || {} };
7559
+ const context = this.withGlobals(data);
7513
7560
  const key = createHash3("md5").update(source).digest("hex");
7514
7561
  const ttlMs = this.cacheTtlSeconds() * 1e3;
7515
7562
  const cached = this.compiledStrings.get(key);
@@ -10856,27 +10903,33 @@ function sleepSync(ms) {
10856
10903
  if (ms <= 0) return;
10857
10904
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
10858
10905
  }
10859
- function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
10906
+ function bindable(host, port) {
10907
+ try {
10908
+ execFileSync(process.execPath, ["-e", BIND_PROBE, host, String(port)], { stdio: "ignore", timeout: 5e3 });
10909
+ return true;
10910
+ } catch {
10911
+ return false;
10912
+ }
10913
+ }
10914
+ function refusal(port, dev, noTakeover, host) {
10915
+ if (dev && !noTakeover) return null;
10916
+ if (host !== void 0 && bindable(host, port)) {
10917
+ return { status: TAKEOVER_NOTHING, port, killed: [], message: "" };
10918
+ }
10919
+ if (noTakeover) {
10920
+ 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.` };
10921
+ }
10922
+ 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.` };
10923
+ }
10924
+ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500, host) {
10860
10925
  const make = (status2, killed2 = [], message = "") => ({
10861
10926
  status: status2,
10862
10927
  port,
10863
10928
  killed: killed2,
10864
10929
  message
10865
10930
  });
10866
- if (noTakeover) {
10867
- return make(
10868
- TAKEOVER_REFUSED_OPTOUT,
10869
- [],
10870
- `Port ${port} is in use and takeover is disabled (TINA4_NO_TAKEOVER/--no-kill) -- free it or choose another port.`
10871
- );
10872
- }
10873
- if (!dev) {
10874
- return make(
10875
- TAKEOVER_REFUSED_PROD,
10876
- [],
10877
- `Port ${port} is in use; takeover is disabled outside dev mode -- free it or choose another port.`
10878
- );
10879
- }
10931
+ const early = refusal(port, dev, noTakeover, host);
10932
+ if (early !== null) return early;
10880
10933
  if (inContainer()) return make(TAKEOVER_SKIPPED_CONTAINER);
10881
10934
  const tokens = portHolders(port);
10882
10935
  if (tokens.length === 0) return make(TAKEOVER_NOTHING);
@@ -10908,7 +10961,7 @@ function takeOverPort(port, dev, noTakeover, baseDir, grace = 500) {
10908
10961
  `Reclaimed port ${port} from Tina4 dev server (PID: ${killed.join(", ")}).`
10909
10962
  );
10910
10963
  }
10911
- var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS;
10964
+ var TAKEOVER_NOTHING, TAKEOVER_KILLED, TAKEOVER_REFUSED_FOREIGN, TAKEOVER_REFUSED_OPTOUT, TAKEOVER_REFUSED_PROD, TAKEOVER_SKIPPED_CONTAINER, TAKEOVER_REFUSALS, BIND_PROBE;
10912
10965
  var init_portTakeover = __esm({
10913
10966
  "../core/src/portTakeover.ts"() {
10914
10967
  "use strict";
@@ -10923,6 +10976,7 @@ var init_portTakeover = __esm({
10923
10976
  TAKEOVER_REFUSED_OPTOUT,
10924
10977
  TAKEOVER_REFUSED_PROD
10925
10978
  ];
10979
+ BIND_PROBE = 'const s = require("node:net").createServer();s.on("error", () => process.exit(1));s.listen({ host: process.argv[1], port: Number(process.argv[2]) }, () => s.close(() => process.exit(0)));';
10926
10980
  }
10927
10981
  });
10928
10982
 
@@ -12973,7 +13027,7 @@ var init_session = __esm({
12973
13027
  save() {
12974
13028
  if (!this.sessionId || !this.data) return true;
12975
13029
  if (this.isFresh()) return true;
12976
- let record = this.data;
13030
+ let record2 = this.data;
12977
13031
  if (this.stored) {
12978
13032
  const current = this.safeRead(this.sessionId);
12979
13033
  if (this.lastReadFailed) return false;
@@ -12982,9 +13036,9 @@ var init_session = __esm({
12982
13036
  this.ended = true;
12983
13037
  return true;
12984
13038
  }
12985
- if (!this.cleared) record = this.merged(current);
13039
+ if (!this.cleared) record2 = this.merged(current);
12986
13040
  }
12987
- if (this.safeWrite(this.sessionId, record, this.ttl)) {
13041
+ if (this.safeWrite(this.sessionId, record2, this.ttl)) {
12988
13042
  this.dirty = false;
12989
13043
  this.stored = true;
12990
13044
  this.cleared = false;
@@ -13001,19 +13055,19 @@ var init_session = __esm({
13001
13055
  */
13002
13056
  merged(current) {
13003
13057
  const data = this.data;
13004
- const record = { ...current };
13058
+ const record2 = { ...current };
13005
13059
  for (const [key, value] of Object.entries(data)) {
13006
13060
  const print = fingerprint(value);
13007
13061
  if (print === void 0 || !this.loaded.has(key) || this.loaded.get(key) !== print) {
13008
- record[key] = value;
13062
+ record2[key] = value;
13009
13063
  }
13010
13064
  }
13011
13065
  for (const key of this.loaded.keys()) {
13012
13066
  if (!Object.prototype.hasOwnProperty.call(data, key)) {
13013
- delete record[key];
13067
+ delete record2[key];
13014
13068
  }
13015
13069
  }
13016
- return record;
13070
+ return record2;
13017
13071
  }
13018
13072
  /**
13019
13073
  * End the session for this request without touching the store: no id and
@@ -18168,7 +18222,7 @@ data: ${channel.buffer.shift()}
18168
18222
  }
18169
18223
  return { resources };
18170
18224
  }
18171
- _handleResourcesRead(params) {
18225
+ async _handleResourcesRead(params) {
18172
18226
  const uri = params.uri;
18173
18227
  if (!uri) {
18174
18228
  throw new Error("Missing resource URI");
@@ -18177,7 +18231,7 @@ data: ${channel.buffer.shift()}
18177
18231
  if (!resource) {
18178
18232
  throw new Error(`Unknown resource: ${uri}`);
18179
18233
  }
18180
- const result = resource.handler();
18234
+ const result = await resource.handler();
18181
18235
  let text;
18182
18236
  if (typeof result === "string") {
18183
18237
  text = result;
@@ -21711,6 +21765,12 @@ const outBytes = new Uint8Array(workerData.sab, 8);
21711
21765
  // (test/kafkaErrorCodes.test.ts) can assert the floors.
21712
21766
  const PRODUCE_VERSION = 3;
21713
21767
  const FETCH_VERSION = 4;
21768
+ // How long the broker long-polls an empty partition before answering (ms).
21769
+ // Deliberately 1000, not tina4-php / tina4-python's 5000: Node's pop() is
21770
+ // synchronous (Atomics.wait on this worker), so the long-poll blocks the whole
21771
+ // event loop, not one request. The tombstone-skip deadline caps it further while
21772
+ // stepping so a stream of tombstones cannot hold pop() past ~1s.
21773
+ const FETCH_MAX_WAIT_MS = 1000;
21714
21774
 
21715
21775
  let correlationId = 0;
21716
21776
  let brokerSock = null;
@@ -21897,12 +21957,13 @@ async function produce(topic, valueBytes) {
21897
21957
  }
21898
21958
 
21899
21959
  // \u2500\u2500 fetch \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
21900
- function fetchRequest(topic, offset) {
21960
+ function fetchRequest(topic, offset, maxWaitMs) {
21961
+ if (maxWaitMs === undefined) maxWaitMs = FETCH_MAX_WAIT_MS;
21901
21962
  const topicBuf = Buffer.from(topic, "utf-8");
21902
21963
  const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
21903
21964
  let p = 0;
21904
21965
  buf.writeInt32BE(-1, p); p += 4; // replicaId
21905
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
21966
+ buf.writeInt32BE(maxWaitMs, p); p += 4; // maxWaitMs (long-poll bound; capped by the tombstone-skip deadline)
21906
21967
  buf.writeInt32BE(1, p); p += 4; // minBytes
21907
21968
  buf.writeInt32BE(1048576, p); p += 4; // maxBytes
21908
21969
  buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
@@ -21915,8 +21976,12 @@ function fetchRequest(topic, offset) {
21915
21976
  buf.writeInt32BE(1048576, p); p += 4;
21916
21977
  return frame(1, FETCH_VERSION, buf);
21917
21978
  }
21918
- // Decode the first record of the partition's record-set: its value string and
21919
- // absolute offset (baseOffset + offsetDelta). null = no usable record.
21979
+ // Decode the FIRST record of the partition's record-set (the cross-framework
21980
+ // contract: only a batch's first record is decoded -- the Tina4 producer writes
21981
+ // one record per batch). Returns its value and absolute offset (baseOffset +
21982
+ // offsetDelta); a tombstone (null value) comes back with value null and its
21983
+ // offset so the caller can step past it. null = no usable record at all (empty /
21984
+ // old-format / short response).
21920
21985
  function firstRecord(buf, start, end) {
21921
21986
  let pos = start;
21922
21987
  while (pos + 12 <= end) {
@@ -21932,8 +21997,7 @@ function firstRecord(buf, start, end) {
21932
21997
  for (let i = 0; i < recordsCount && r < batchEnd; i++) {
21933
21998
  const recLen = readVarint(buf, r);
21934
21999
  let rp = recLen.next;
21935
- const recordEnd = rp + recLen.value;
21936
- rp += 1;
22000
+ rp += 1; // record attributes byte
21937
22001
  rp = readVarint(buf, rp).next; // timestampDelta
21938
22002
  const offDelta = readVarint(buf, rp); rp = offDelta.next;
21939
22003
  const keyLen = readVarint(buf, rp); rp = keyLen.next;
@@ -21945,15 +22009,23 @@ function firstRecord(buf, start, end) {
21945
22009
  offset: Number(baseOffset) + offDelta.value,
21946
22010
  };
21947
22011
  }
21948
- r = recordEnd;
22012
+ // Tombstone (null value) or empty value: hand back a marker carrying its
22013
+ // offset instead of null. Returning null here used to mean "no record", so
22014
+ // pop() never advanced and re-fetched the tombstone for ever -- nothing
22015
+ // after it was delivered. The caller (fetchPastTombstones) steps the
22016
+ // offset on and re-fetches.
22017
+ return {
22018
+ value: null,
22019
+ offset: Number(baseOffset) + offDelta.value,
22020
+ };
21949
22021
  }
21950
22022
  pos = batchEnd;
21951
22023
  }
21952
22024
  return null;
21953
22025
  }
21954
- async function fetchAt(topic, offset) {
22026
+ async function fetchAt(topic, offset, maxWaitMs) {
21955
22027
  const sock = await broker();
21956
- const resp = await rpc(sock, fetchRequest(topic, offset));
22028
+ const resp = await rpc(sock, fetchRequest(topic, offset, maxWaitMs));
21957
22029
  let pos = 4; // correlationId
21958
22030
  pos += 4; // throttleTimeMs
21959
22031
  const topicCount = resp.readInt32BE(pos); pos += 4;
@@ -22089,9 +22161,37 @@ async function broker() {
22089
22161
  // Resume from the committed offset on the FIRST read of a topic in this worker,
22090
22162
  // then advance the in-memory cursor; the committed offset only moves on a
22091
22163
  // commit, so it lags and a crash before commit replays (at-least-once).
22164
+ // Fetch from the cursor, stepping past tombstones, until a record with a value
22165
+ // arrives, the topic is exhausted, or the deadline passes. A tombstone (null
22166
+ // value: Debezium deletes, compacted-topic delete markers) carries no job;
22167
+ // returning "nothing" without moving the offset re-fetched it for ever, so
22168
+ // nothing after it was ever delivered. The 1 s deadline holds while skipping
22169
+ // (the same steady-state bound as tina4-php/tina4-python), and the whole loop
22170
+ // stays inside this one worker round-trip (ADR-0022) -- well under
22171
+ // CALL_TIMEOUT_MS. Nothing is committed here: acknowledging the next record
22172
+ // commits past the skipped tombstones, as before.
22173
+ async function fetchPastTombstones(topic) {
22174
+ const deadline = Date.now() + 1000;
22175
+ let maxWaitMs = FETCH_MAX_WAIT_MS;
22176
+ while (true) {
22177
+ const offset = offsets[topic];
22178
+ const rec = await fetchAt(topic, offset, maxWaitMs);
22179
+ if (rec === null || rec.value !== null) return rec; // nothing, or a real record
22180
+ // Anti-spin: the decoder reads only a batch's first record, so a tombstone
22181
+ // sharing a batch with later records comes back at an offset already passed.
22182
+ // That must never loop this fetch.
22183
+ const next = rec.offset + 1;
22184
+ if (next <= offset) return null;
22185
+ offsets[topic] = next;
22186
+ const remaining = deadline - Date.now();
22187
+ if (remaining <= 0) return null;
22188
+ maxWaitMs = remaining;
22189
+ }
22190
+ }
22191
+
22092
22192
  async function fetchNext(topic) {
22093
22193
  if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
22094
- const rec = await fetchAt(topic, offsets[topic]);
22194
+ const rec = await fetchPastTombstones(topic);
22095
22195
  if (rec === null) return null;
22096
22196
  offsets[topic] = rec.offset + 1;
22097
22197
  return rec;
@@ -22596,7 +22696,7 @@ var init_liteBackend = __esm({
22596
22696
  writeReserved(queue, job) {
22597
22697
  const now = this.nowIso();
22598
22698
  const vt = this.visibilityTimeout || 0;
22599
- const record = {
22699
+ const record2 = {
22600
22700
  id: job.id,
22601
22701
  payload: job.payload,
22602
22702
  status: "reserved",
@@ -22608,7 +22708,7 @@ var init_liteBackend = __esm({
22608
22708
  createdAt: job.createdAt ?? now,
22609
22709
  topic: job.topic ?? queue
22610
22710
  };
22611
- writeFileSync9(this.reservedPath(queue, record.id), JSON.stringify(record, null, 2));
22711
+ writeFileSync9(this.reservedPath(queue, record2.id), JSON.stringify(record2, null, 2));
22612
22712
  }
22613
22713
  /**
22614
22714
  * Return expired reservations to the queue (at-least-once delivery).
@@ -22630,29 +22730,29 @@ var init_liteBackend = __esm({
22630
22730
  }
22631
22731
  for (const filename of filenames) {
22632
22732
  const filePath = join18(reservedDir, filename);
22633
- let record;
22733
+ let record2;
22634
22734
  try {
22635
- record = JSON.parse(readFileSync14(filePath, "utf-8"));
22735
+ record2 = JSON.parse(readFileSync14(filePath, "utf-8"));
22636
22736
  } catch {
22637
22737
  continue;
22638
22738
  }
22639
- if (record.availableAt && record.availableAt > now) continue;
22739
+ if (record2.availableAt && record2.availableAt > now) continue;
22640
22740
  try {
22641
22741
  unlinkSync7(filePath);
22642
22742
  } catch {
22643
22743
  continue;
22644
22744
  }
22645
- const attempts = (record.attempts ?? 0) + 1;
22745
+ const attempts = (record2.attempts ?? 0) + 1;
22646
22746
  const error2 = "reservation timed out \u2014 consumer did not acknowledge within the visibility timeout";
22647
22747
  const job = {
22648
- id: record.id,
22649
- payload: record.payload,
22748
+ id: record2.id,
22749
+ payload: record2.payload,
22650
22750
  status: "reserved",
22651
- createdAt: record.createdAt ?? now,
22751
+ createdAt: record2.createdAt ?? now,
22652
22752
  attempts,
22653
22753
  delayUntil: null,
22654
- priority: record.priority ?? 0,
22655
- topic: record.topic ?? queue,
22754
+ priority: record2.priority ?? 0,
22755
+ topic: record2.topic ?? queue,
22656
22756
  error: error2
22657
22757
  };
22658
22758
  if (attempts >= maxRetries) {
@@ -27141,6 +27241,7 @@ var init_devAdmin = __esm({
27141
27241
  const mem = process.memoryUsage();
27142
27242
  const heapUsedMb = Math.round(mem.heapUsed / 1048576);
27143
27243
  const rssMb = Math.round(mem.rss / 1048576);
27244
+ const peakRssMb = Math.round(process.resourceUsage().maxRSS / 1024);
27144
27245
  let dbTableCount;
27145
27246
  let dbConnected = false;
27146
27247
  try {
@@ -27157,12 +27258,14 @@ var init_devAdmin = __esm({
27157
27258
  architecture: process.arch,
27158
27259
  os: `${process.platform} ${process.arch}`,
27159
27260
  pid: process.pid,
27160
- memory_mb: heapUsedMb,
27261
+ // The dashboard's "Memory": the process's current RSS, as tina4-python
27262
+ // reports it. V8's heapUsed (below) leaves out Buffers and native memory.
27263
+ memory_mb: rssMb,
27161
27264
  db_tables: dbTableCount !== void 0 ? dbTableCount : "N/A",
27162
27265
  db_connected: dbConnected,
27163
27266
  memory: {
27164
- current_mb: heapUsedMb,
27165
- peak_mb: rssMb,
27267
+ current_mb: rssMb,
27268
+ peak_mb: peakRssMb,
27166
27269
  limit: "V8 default",
27167
27270
  rss: `${rssMb} MB`,
27168
27271
  heapUsed: `${heapUsedMb} MB`,
@@ -30138,6 +30241,32 @@ function swaggerAdvertised() {
30138
30241
  }
30139
30242
  return TRUTHY3.includes(raw);
30140
30243
  }
30244
+ function stripUrlCredentials(text) {
30245
+ return text.replace(/:\/\/[^/\s]*@/g, "://");
30246
+ }
30247
+ function isModuleNotFound(err) {
30248
+ const code = err?.code;
30249
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND";
30250
+ }
30251
+ function reportOrmBootFailure(stage, err, dbConfig) {
30252
+ const message = stripUrlCredentials(err instanceof Error ? err.message : String(err));
30253
+ if (stage === "connect") {
30254
+ const url = (process.env.TINA4_DATABASE_URL ?? "").trim();
30255
+ const target = url ? stripUrlCredentials(url) : `${dbConfig.type ?? "sqlite"} ${dbConfig.path ?? "./data/tina4.db"}`;
30256
+ bootDbConnectError = message;
30257
+ console.warn(`
30258
+ Database could not be reached (${target}): ${message}`);
30259
+ } else if (stage === "import" && isModuleNotFound(err)) {
30260
+ console.warn(`
30261
+ ORM not available (install @tina4/orm to enable): ${message}`);
30262
+ } else if (stage === "import") {
30263
+ console.warn(`
30264
+ ORM failed to load:`, err);
30265
+ } else {
30266
+ console.warn(`
30267
+ ORM model setup failed:`, err);
30268
+ }
30269
+ }
30141
30270
  async function autoMigrateOnStartup(migrationDir = "migrations", base = process.cwd()) {
30142
30271
  const dir = resolve15(base, migrationDir);
30143
30272
  if (!existsSync23(dir)) return;
@@ -30156,9 +30285,20 @@ async function autoMigrateOnStartup(migrationDir = "migrations", base = process.
30156
30285
  let orm;
30157
30286
  try {
30158
30287
  orm = await Promise.resolve().then(() => (init_index(), index_exports));
30288
+ } catch (err) {
30289
+ Log.debug(`Startup migrations skipped (ORM not available): ${stripUrlCredentials(err instanceof Error ? err.message : String(err))}`);
30290
+ return;
30291
+ }
30292
+ try {
30159
30293
  orm.getAdapter();
30160
30294
  } catch (err) {
30161
- Log.debug(`Startup migrations skipped (no database configured): ${err instanceof Error ? err.message : String(err)}`);
30295
+ const configuredUrl = (process.env.TINA4_DATABASE_URL ?? "").trim();
30296
+ const cause = stripUrlCredentials(bootDbConnectError ?? (err instanceof Error ? err.message : String(err)));
30297
+ if (configuredUrl) {
30298
+ Log.debug(`Startup migrations skipped (database configured but could not connect to ${stripUrlCredentials(configuredUrl)}): ${cause}`);
30299
+ } else {
30300
+ Log.debug(`Startup migrations skipped (no database configured): ${cause}`);
30301
+ }
30162
30302
  return;
30163
30303
  }
30164
30304
  try {
@@ -31081,9 +31221,10 @@ function wireLocaleGlobal(frondEngine, base) {
31081
31221
  if (!existsSync23(localeDir)) return;
31082
31222
  try {
31083
31223
  const localeFiles = readdirSync15(localeDir).filter((file) => file.endsWith(".json"));
31084
- if (localeFiles.length === 0 || frondEngine.globals?.t) return;
31224
+ const FrondClass = frondEngine.constructor;
31225
+ if (localeFiles.length === 0 || FrondClass.hasGlobal("t") || frondEngine.globals?.t) return;
31085
31226
  const i18nInstance = new I18n(process.env.TINA4_LOCALE ?? "en", localeDir);
31086
- frondEngine.addGlobal("t", (key, params) => i18nInstance.t(key, params));
31227
+ FrondClass.addGlobal("t", (key, params) => i18nInstance.t(key, params));
31087
31228
  } catch {
31088
31229
  }
31089
31230
  }
@@ -31416,13 +31557,17 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
31416
31557
  const hasOrmDir = existsSync23(ormDir);
31417
31558
  const hasModelsDir = existsSync23(modelsDir);
31418
31559
  if (hasOrmDir || hasModelsDir) {
31560
+ let ormStage = "import";
31561
+ const dbConfig = config?.database ?? {};
31419
31562
  try {
31420
31563
  const orm = await Promise.resolve().then(() => (init_index(), index_exports));
31421
- const dbConfig = config?.database ?? {};
31564
+ ormStage = "connect";
31565
+ bootDbConnectError = null;
31422
31566
  await orm.initDatabase({
31423
31567
  type: dbConfig.type ?? "sqlite",
31424
31568
  path: dbConfig.path ?? "./data/tina4.db"
31425
31569
  });
31570
+ ormStage = "models";
31426
31571
  let models = hasOrmDir ? await orm.discoverModels(ormDir) : [];
31427
31572
  if (hasModelsDir) {
31428
31573
  const extraModels = await orm.discoverModels(modelsDir);
@@ -31457,8 +31602,7 @@ async function initializeOrm(config, router, base, ormDir, modelsDir) {
31457
31602
  }
31458
31603
  }
31459
31604
  } catch (err) {
31460
- console.warn(`
31461
- ORM not available (install @tina4/orm to enable):`, err);
31605
+ reportOrmBootFailure(ormStage, err, dbConfig);
31462
31606
  }
31463
31607
  await autoMigrateOnStartup("migrations", base);
31464
31608
  }
@@ -31496,7 +31640,7 @@ async function configureSwagger(router, ormDir, modelsDir) {
31496
31640
  }
31497
31641
  return enabled;
31498
31642
  }
31499
- var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swaggerAssetsEnabled, DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, frondCache, _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;
31643
+ var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swaggerAssetsEnabled, DEFAULT_SHUTDOWN_TIMEOUT_SECONDS, bootDbConnectError, frondCache, _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;
31500
31644
  var init_server = __esm({
31501
31645
  "../core/src/server.ts"() {
31502
31646
  "use strict";
@@ -31531,6 +31675,7 @@ var init_server = __esm({
31531
31675
  BUILTIN_PUBLIC_DIR = resolve15(__dirname, "..", "public");
31532
31676
  swaggerAssetsEnabled = false;
31533
31677
  DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;
31678
+ bootDbConnectError = null;
31534
31679
  frondCache = /* @__PURE__ */ new Map();
31535
31680
  _LEGACY_ENV_VARS = {
31536
31681
  DATABASE_URL: "TINA4_DATABASE_URL",
@@ -37254,26 +37399,26 @@ var init_aiClient = __esm({
37254
37399
  if (!part || typeof part !== "object" || Array.isArray(part)) {
37255
37400
  throw new AiConfigError("AI content part must be an object with type and text/source");
37256
37401
  }
37257
- const record = part;
37258
- switch (record.type) {
37402
+ const record2 = part;
37403
+ switch (record2.type) {
37259
37404
  case "text":
37260
- this.validateTextPart(record);
37405
+ this.validateTextPart(record2);
37261
37406
  return;
37262
37407
  case "image":
37263
- this.validateImagePart(record);
37408
+ this.validateImagePart(record2);
37264
37409
  return;
37265
37410
  case "tool_result":
37266
- this.validateToolResultPart(record);
37411
+ this.validateToolResultPart(record2);
37267
37412
  return;
37268
37413
  default:
37269
- throw new AiConfigError(`AI content part has unknown type '${String(record.type)}'`);
37414
+ throw new AiConfigError(`AI content part has unknown type '${String(record2.type)}'`);
37270
37415
  }
37271
37416
  }
37272
- static validateTextPart(record) {
37273
- if (typeof record.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
37417
+ static validateTextPart(record2) {
37418
+ if (typeof record2.text !== "string") throw new AiConfigError("AI text content part requires a string 'text' field");
37274
37419
  }
37275
- static validateImagePart(record) {
37276
- const source = record.source;
37420
+ static validateImagePart(record2) {
37421
+ const source = record2.source;
37277
37422
  if (typeof source !== "string" || source.length === 0) {
37278
37423
  throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
37279
37424
  }
@@ -37284,11 +37429,11 @@ var init_aiClient = __esm({
37284
37429
  throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
37285
37430
  }
37286
37431
  }
37287
- static validateToolResultPart(record) {
37288
- if (typeof record.tool_use_id !== "string" || record.tool_use_id.length === 0) {
37432
+ static validateToolResultPart(record2) {
37433
+ if (typeof record2.tool_use_id !== "string" || record2.tool_use_id.length === 0) {
37289
37434
  throw new AiConfigError("AI tool_result part requires a non-empty string 'tool_use_id'");
37290
37435
  }
37291
- if (typeof record.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
37436
+ if (typeof record2.content !== "string") throw new AiConfigError("AI tool_result part requires a string 'content'");
37292
37437
  }
37293
37438
  /**
37294
37439
  * Validate the outbound tool declarations (ADR-0061). Each tool needs a
@@ -37304,14 +37449,14 @@ var init_aiClient = __esm({
37304
37449
  if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
37305
37450
  throw new AiConfigError("AI tool must be an object with name, description, parameters");
37306
37451
  }
37307
- const record = tool;
37308
- if (typeof record.name !== "string" || record.name.length === 0) {
37452
+ const record2 = tool;
37453
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
37309
37454
  throw new AiConfigError("AI tool requires a non-empty string 'name'");
37310
37455
  }
37311
- if (typeof record.description !== "string") {
37456
+ if (typeof record2.description !== "string") {
37312
37457
  throw new AiConfigError("AI tool requires a string 'description'");
37313
37458
  }
37314
- if (!record.parameters || typeof record.parameters !== "object" || Array.isArray(record.parameters)) {
37459
+ if (!record2.parameters || typeof record2.parameters !== "object" || Array.isArray(record2.parameters)) {
37315
37460
  throw new AiConfigError("AI tool requires a JSON-Schema object 'parameters'");
37316
37461
  }
37317
37462
  }
@@ -37328,8 +37473,8 @@ var init_aiClient = __esm({
37328
37473
  return;
37329
37474
  }
37330
37475
  if (choice && typeof choice === "object" && !Array.isArray(choice)) {
37331
- const record = choice;
37332
- if (typeof record.name !== "string" || record.name.length === 0) {
37476
+ const record2 = choice;
37477
+ if (typeof record2.name !== "string" || record2.name.length === 0) {
37333
37478
  throw new AiConfigError("AI toolChoice object requires a non-empty string 'name'");
37334
37479
  }
37335
37480
  return;
@@ -38394,38 +38539,37 @@ function runAll(options = {}) {
38394
38539
  const { quiet = false, failfast = false } = options;
38395
38540
  const results = { passed: 0, failed: 0, errors: 0, details: [] };
38396
38541
  for (const entry of registry2) {
38397
- if (!quiet) {
38398
- console.log(`
38542
+ if (!quiet) console.log(`
38399
38543
  ${entry.name}`);
38544
+ for (const assertion of entry.assertions) {
38545
+ const label = assertionLabel(assertion, entry.name);
38546
+ const ok = record(results, label, quiet, () => judge(assertion, callSync(entry.fn, assertion.args)));
38547
+ if (!ok && failfast) {
38548
+ printSummary(results, quiet);
38549
+ return results;
38550
+ }
38400
38551
  }
38552
+ }
38553
+ printSummary(results, quiet);
38554
+ return results;
38555
+ }
38556
+ async function runAllAsync(options = {}) {
38557
+ const { quiet = false, failfast = false, timeoutMs = 3e4 } = options;
38558
+ checkTimeout(timeoutMs);
38559
+ const results = { passed: 0, failed: 0, errors: 0, details: [] };
38560
+ for (const entry of registry2) {
38561
+ if (!quiet) console.log(`
38562
+ ${entry.name}`);
38401
38563
  for (const assertion of entry.assertions) {
38402
38564
  const label = assertionLabel(assertion, entry.name);
38403
- try {
38404
- runAssertion(entry.fn, assertion);
38405
- results.passed++;
38406
- results.details.push({ name: label, status: "passed" });
38407
- if (!quiet) {
38408
- console.log(` \x1B[32m+\x1B[0m ${label}`);
38409
- }
38410
- } catch (err) {
38411
- if (err instanceof TestAssertionError) {
38412
- results.failed++;
38413
- results.details.push({ name: label, status: "failed", message: err.message });
38414
- if (!quiet) {
38415
- console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
38416
- }
38417
- } else {
38418
- results.errors++;
38419
- const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
38420
- results.details.push({ name: label, status: "error", message: msg });
38421
- if (!quiet) {
38422
- console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
38423
- }
38424
- }
38425
- if (failfast) {
38426
- printSummary(results, quiet);
38427
- return results;
38428
- }
38565
+ const outcome = await callAsync(entry.fn, assertion.args, timeoutMs);
38566
+ const ok = record(results, label, quiet, () => {
38567
+ if (outcome instanceof TestRunError) throw outcome;
38568
+ judge(assertion, outcome);
38569
+ });
38570
+ if (!ok && failfast) {
38571
+ printSummary(results, quiet);
38572
+ return results;
38429
38573
  }
38430
38574
  }
38431
38575
  }
@@ -38435,47 +38579,103 @@ function runAll(options = {}) {
38435
38579
  function reset() {
38436
38580
  registry2.length = 0;
38437
38581
  }
38438
- function runAssertion(fn, assertion) {
38439
- const { type: type2, args } = assertion;
38582
+ function isThenable(value) {
38583
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
38584
+ }
38585
+ function callSync(fn, args) {
38586
+ let value;
38587
+ try {
38588
+ value = fn(...args);
38589
+ } catch (error2) {
38590
+ return { threw: true, error: error2 };
38591
+ }
38592
+ if (isThenable(value)) {
38593
+ Promise.resolve(value).then(void 0, () => void 0);
38594
+ throw new TestRunError(
38595
+ "returned a Promise (async test function): runAll() cannot judge it, use await runAllAsync()"
38596
+ );
38597
+ }
38598
+ return { threw: false, value };
38599
+ }
38600
+ function checkTimeout(timeoutMs) {
38601
+ if (timeoutMs === Infinity) return;
38602
+ if (!(timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {
38603
+ throw new RangeError(
38604
+ `timeoutMs must be Infinity or a number of milliseconds in (0, ${MAX_TIMER_MS}], got ${timeoutMs}`
38605
+ );
38606
+ }
38607
+ }
38608
+ async function callAsync(fn, args, timeoutMs) {
38609
+ let timer;
38610
+ try {
38611
+ const value = fn(...args);
38612
+ if (!isThenable(value)) return { threw: false, value };
38613
+ if (timeoutMs === Infinity) return { threw: false, value: await value };
38614
+ const timeout = new Promise((_, reject) => {
38615
+ timer = setTimeout(
38616
+ () => reject(new TestRunError(`did not settle within ${timeoutMs} ms`)),
38617
+ timeoutMs
38618
+ );
38619
+ });
38620
+ return { threw: false, value: await Promise.race([Promise.resolve(value), timeout]) };
38621
+ } catch (error2) {
38622
+ if (error2 instanceof TestRunError) return error2;
38623
+ return { threw: true, error: error2 };
38624
+ } finally {
38625
+ if (timer !== void 0) clearTimeout(timer);
38626
+ }
38627
+ }
38628
+ function record(results, label, quiet, check) {
38629
+ try {
38630
+ check();
38631
+ results.passed++;
38632
+ results.details.push({ name: label, status: "passed" });
38633
+ if (!quiet) console.log(` \x1B[32m+\x1B[0m ${label}`);
38634
+ return true;
38635
+ } catch (err) {
38636
+ if (err instanceof TestAssertionError) {
38637
+ results.failed++;
38638
+ results.details.push({ name: label, status: "failed", message: err.message });
38639
+ if (!quiet) console.log(` \x1B[31mx\x1B[0m ${label}: ${err.message}`);
38640
+ } else {
38641
+ results.errors++;
38642
+ const msg = err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err);
38643
+ results.details.push({ name: label, status: "error", message: msg });
38644
+ if (!quiet) console.log(` \x1B[33m!\x1B[0m ${label}: ${msg}`);
38645
+ }
38646
+ return false;
38647
+ }
38648
+ }
38649
+ function judgeRaises(assertion, outcome) {
38650
+ const ExcClass = assertion.exception;
38651
+ if (!outcome.threw) throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
38652
+ const err = outcome.error;
38653
+ if (err instanceof ExcClass) return;
38654
+ throw new TestAssertionError(
38655
+ `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
38656
+ );
38657
+ }
38658
+ function judge(assertion, outcome) {
38659
+ const { type: type2 } = assertion;
38660
+ if (type2 === "raises") return judgeRaises(assertion, outcome);
38661
+ if (outcome.threw) throw outcome.error;
38662
+ const result = outcome.value;
38440
38663
  switch (type2) {
38441
38664
  case "equal": {
38442
- const result = fn(...args);
38443
38665
  const expected = assertion.expected;
38444
38666
  if (result !== expected) {
38445
38667
  throw new TestAssertionError(
38446
38668
  `expected ${JSON.stringify(expected)}, got ${JSON.stringify(result)}`
38447
38669
  );
38448
38670
  }
38449
- break;
38450
- }
38451
- case "raises": {
38452
- const ExcClass = assertion.exception;
38453
- try {
38454
- fn(...args);
38455
- } catch (err) {
38456
- if (err instanceof ExcClass) {
38457
- return;
38458
- }
38459
- throw new TestAssertionError(
38460
- `expected ${ExcClass.name}, got ${err instanceof Error ? err.constructor.name : typeof err}: ${err}`
38461
- );
38462
- }
38463
- throw new TestAssertionError(`expected ${ExcClass.name} to be raised`);
38464
- }
38465
- case "true": {
38466
- const result = fn(...args);
38467
- if (!result) {
38468
- throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
38469
- }
38470
- break;
38471
- }
38472
- case "false": {
38473
- const result = fn(...args);
38474
- if (result) {
38475
- throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
38476
- }
38477
- break;
38671
+ return;
38478
38672
  }
38673
+ case "true":
38674
+ if (!result) throw new TestAssertionError(`expected truthy, got ${JSON.stringify(result)}`);
38675
+ return;
38676
+ case "false":
38677
+ if (result) throw new TestAssertionError(`expected falsy, got ${JSON.stringify(result)}`);
38678
+ return;
38479
38679
  default:
38480
38680
  throw new Error(`unknown assertion type: ${type2}`);
38481
38681
  }
@@ -38504,7 +38704,7 @@ function printSummary(results, quiet) {
38504
38704
  `
38505
38705
  );
38506
38706
  }
38507
- var registry2, TestAssertionError;
38707
+ var registry2, TestAssertionError, TestRunError, MAX_TIMER_MS;
38508
38708
  var init_testing = __esm({
38509
38709
  "../core/src/testing.ts"() {
38510
38710
  "use strict";
@@ -38515,6 +38715,13 @@ var init_testing = __esm({
38515
38715
  this.name = "TestAssertionError";
38516
38716
  }
38517
38717
  };
38718
+ TestRunError = class extends Error {
38719
+ constructor(message) {
38720
+ super(message);
38721
+ this.name = "TestRunError";
38722
+ }
38723
+ };
38724
+ MAX_TIMER_MS = 2147483647;
38518
38725
  }
38519
38726
  });
38520
38727
 
@@ -39330,6 +39537,7 @@ __export(src_exports2, {
39330
39537
  resolveTemplate: () => resolveTemplate,
39331
39538
  responseCache: () => responseCache,
39332
39539
  runAll: () => runAll,
39540
+ runAllAsync: () => runAllAsync,
39333
39541
  runRouteMiddlewares: () => runRouteMiddlewares,
39334
39542
  runWithCspNonce: () => runWithCspNonce,
39335
39543
  runtimeDir: () => runtimeDir,
@@ -42343,11 +42551,11 @@ var init_firebird = __esm({
42343
42551
  */
42344
42552
  async decodeBlobs(row) {
42345
42553
  if (row === null || typeof row !== "object") return row;
42346
- const record = row;
42347
- for (const key of Object.keys(record)) {
42348
- if (typeof record[key] === "function") {
42349
- record[key] = await this.readBlob(
42350
- record[key]
42554
+ const record2 = row;
42555
+ for (const key of Object.keys(record2)) {
42556
+ if (typeof record2[key] === "function") {
42557
+ record2[key] = await this.readBlob(
42558
+ record2[key]
42351
42559
  );
42352
42560
  }
42353
42561
  }
@@ -46721,12 +46929,12 @@ function crudSortProp(model, requested, pkProp) {
46721
46929
  }
46722
46930
  return pkProp;
46723
46931
  }
46724
- function cellValue(record, col) {
46725
- return record[col];
46932
+ function cellValue(record2, col) {
46933
+ return record2[col];
46726
46934
  }
46727
- function buildCells(columns, record, editable, aligns) {
46935
+ function buildCells(columns, record2, editable, aligns) {
46728
46936
  return columns.map((col, index) => {
46729
- const raw = cellValue(record, col);
46937
+ const raw = cellValue(record2, col);
46730
46938
  const value = h(raw === null || raw === void 0 ? "" : raw);
46731
46939
  const css = aligns[index];
46732
46940
  return editable ? `<td class="${css}" contenteditable="true" data-field="${h(col)}">${value}</td>` : `<td class="${css}">${value}</td>`;
@@ -46889,9 +47097,9 @@ function headerCell(opts, col, align) {
46889
47097
  function tableData(opts) {
46890
47098
  const aligns = opts.columns.map((col) => columnAlignment(opts.model, col));
46891
47099
  const headers = opts.columns.map((col, index) => headerCell(opts, col, aligns[index]));
46892
- const rows = opts.records.map((record) => ({
46893
- id: h(cellValue(record, opts.pk) ?? ""),
46894
- cells: buildCells(opts.columns, record, opts.editable, aligns)
47100
+ const rows = opts.records.map((record2) => ({
47101
+ id: h(cellValue(record2, opts.pk) ?? ""),
47102
+ cells: buildCells(opts.columns, record2, opts.editable, aligns)
46895
47103
  }));
46896
47104
  return {
46897
47105
  headers,
@@ -48020,9 +48228,9 @@ async function eagerLoadHasRelation(instances, model, relatedClass, relationName
48020
48228
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
48021
48229
  const fkProp = reverseMappedColumn(relatedClass, relation.foreignKey);
48022
48230
  const grouped = {};
48023
- for (const record of related) {
48024
- const key = _joinKey(record[fkProp]);
48025
- (grouped[key] ??= []).push(record);
48231
+ for (const record2 of related) {
48232
+ const key = _joinKey(record2[fkProp]);
48233
+ (grouped[key] ??= []).push(record2);
48026
48234
  }
48027
48235
  for (const instance of instances) {
48028
48236
  const records = grouped[_joinKey(instance[pk])] ?? [];
@@ -48038,7 +48246,7 @@ async function eagerLoadBelongsToRelation(instances, model, relatedClass, relati
48038
48246
  const related = await eagerQueryRelated(relatedClass, relatedPkColumn, values);
48039
48247
  if (nested.length > 0 && related.length > 0) await relatedClass._eagerLoad(related, nested);
48040
48248
  const lookup2 = {};
48041
- for (const record of related) lookup2[_joinKey(record[relatedPk])] = record;
48249
+ for (const record2 of related) lookup2[_joinKey(record2[relatedPk])] = record2;
48042
48250
  for (const instance of instances) {
48043
48251
  const value = instance[fkProp];
48044
48252
  relationshipCache(instance)[relationName] = value !== void 0 && value !== null ? lookup2[_joinKey(value)] ?? null : null;
@@ -50753,7 +50961,7 @@ var init_bolt = __esm({
50753
50961
  const session = this.database ? this.driver.session({ database: this.database }) : this.driver.session();
50754
50962
  try {
50755
50963
  const result = await session.run(cypher, params ?? {});
50756
- return result.records.map((record) => record.toObject());
50964
+ return result.records.map((record2) => record2.toObject());
50757
50965
  } catch (exc) {
50758
50966
  this.lastError = errorMessage(exc);
50759
50967
  const code = exc?.code ?? "";