tina4-nodejs 3.13.157 → 3.13.159

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.
@@ -9326,6 +9326,13 @@ function consumeSqlDelimiter(state) {
9326
9326
  }
9327
9327
  return true;
9328
9328
  }
9329
+ function hasExecutableSql(sql) {
9330
+ const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
9331
+ return body.replace(/[;\s]/g, "") !== "";
9332
+ }
9333
+ function isUnappliedScaffold(sql) {
9334
+ return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
9335
+ }
9329
9336
  function splitStatements(sql, delimiter4 = ";") {
9330
9337
  const state = {
9331
9338
  sql: normalizeQuotes(sql),
@@ -9510,6 +9517,12 @@ async function runPendingMigrations(db, dir, delimiter4) {
9510
9517
  result.skipped.push(file);
9511
9518
  continue;
9512
9519
  }
9520
+ if (isUnappliedScaffold(sqlContent)) {
9521
+ console.warn(
9522
+ ` Migration ${file} is still an unedited scaffold (a 'tina4:edit' placeholder with no SQL yet) \u2014 skipped and kept pending. Write the migration and remove the tina4:edit line(s), then run migrate again.`
9523
+ );
9524
+ continue;
9525
+ }
9513
9526
  const statements = splitStatements(sqlContent, delimiter4);
9514
9527
  try {
9515
9528
  await adapterStartTransaction(db);
@@ -9654,7 +9667,7 @@ export class ${className} {
9654
9667
  writeFileSync2(filePath, content, "utf-8");
9655
9668
  return filePath;
9656
9669
  }
9657
- var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
9670
+ var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, TINA4_EDIT_MARKER_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
9658
9671
  var init_migration = __esm({
9659
9672
  "../orm/src/migration.ts"() {
9660
9673
  "use strict";
@@ -9679,6 +9692,7 @@ var init_migration = __esm({
9679
9692
  };
9680
9693
  SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
9681
9694
  SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
9695
+ TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
9682
9696
  MIGRATION_LOCK_NAME = "tina4_migration_lock";
9683
9697
  PG_ADVISORY_KEY = BigInt.asIntN(
9684
9698
  64,
@@ -10303,6 +10317,7 @@ var init_autoCrud = __esm({
10303
10317
  var engine_exports = {};
10304
10318
  __export(engine_exports, {
10305
10319
  Frond: () => Frond,
10320
+ FrondSyntaxError: () => FrondSyntaxError,
10306
10321
  MEMO_CACHE_MAX: () => MEMO_CACHE_MAX,
10307
10322
  TEMPLATE_CACHE_MAX: () => TEMPLATE_CACHE_MAX,
10308
10323
  escapeHtml: () => escapeHtml,
@@ -11435,6 +11450,87 @@ function isEscapableStructured(value) {
11435
11450
  function toOutputString(value) {
11436
11451
  return String(value);
11437
11452
  }
11453
+ function phpDate(dt, fmt) {
11454
+ const pad = (n) => String(n).padStart(2, "0");
11455
+ const hours = dt.getHours();
11456
+ const h12 = hours % 12 || 12;
11457
+ const dow = dt.getDay();
11458
+ const iso2 = dow === 0 ? 7 : dow;
11459
+ let out = "";
11460
+ for (let i = 0; i < fmt.length; i++) {
11461
+ const c = fmt[i];
11462
+ if (c === "\\" && i + 1 < fmt.length) {
11463
+ out += fmt[i + 1];
11464
+ i++;
11465
+ continue;
11466
+ }
11467
+ switch (c) {
11468
+ case "Y":
11469
+ out += String(dt.getFullYear());
11470
+ break;
11471
+ case "y":
11472
+ out += pad(dt.getFullYear() % 100);
11473
+ break;
11474
+ case "m":
11475
+ out += pad(dt.getMonth() + 1);
11476
+ break;
11477
+ case "n":
11478
+ out += String(dt.getMonth() + 1);
11479
+ break;
11480
+ case "d":
11481
+ out += pad(dt.getDate());
11482
+ break;
11483
+ case "j":
11484
+ out += String(dt.getDate());
11485
+ break;
11486
+ case "H":
11487
+ out += pad(hours);
11488
+ break;
11489
+ case "G":
11490
+ out += String(hours);
11491
+ break;
11492
+ case "h":
11493
+ out += pad(h12);
11494
+ break;
11495
+ case "g":
11496
+ out += String(h12);
11497
+ break;
11498
+ case "i":
11499
+ out += pad(dt.getMinutes());
11500
+ break;
11501
+ case "s":
11502
+ out += pad(dt.getSeconds());
11503
+ break;
11504
+ case "A":
11505
+ out += hours < 12 ? "AM" : "PM";
11506
+ break;
11507
+ case "a":
11508
+ out += hours < 12 ? "am" : "pm";
11509
+ break;
11510
+ case "D":
11511
+ out += PHP_DAYS[dow].slice(0, 3);
11512
+ break;
11513
+ case "l":
11514
+ out += PHP_DAYS[dow];
11515
+ break;
11516
+ case "M":
11517
+ out += PHP_MONTHS[dt.getMonth()].slice(0, 3);
11518
+ break;
11519
+ case "F":
11520
+ out += PHP_MONTHS[dt.getMonth()];
11521
+ break;
11522
+ case "N":
11523
+ out += String(iso2);
11524
+ break;
11525
+ case "w":
11526
+ out += String(dow);
11527
+ break;
11528
+ default:
11529
+ out += c;
11530
+ }
11531
+ }
11532
+ return out;
11533
+ }
11438
11534
  function dateFilter(value, fmt) {
11439
11535
  let dt;
11440
11536
  if (value instanceof Date) {
@@ -11447,6 +11543,7 @@ function dateFilter(value, fmt) {
11447
11543
  } else {
11448
11544
  return String(value);
11449
11545
  }
11546
+ if (!fmt.includes("%")) return phpDate(dt, fmt);
11450
11547
  return fmt.replace(/%Y/g, String(dt.getFullYear())).replace(/%m/g, String(dt.getMonth() + 1).padStart(2, "0")).replace(/%d/g, String(dt.getDate()).padStart(2, "0")).replace(/%H/g, String(dt.getHours()).padStart(2, "0")).replace(/%M/g, String(dt.getMinutes()).padStart(2, "0")).replace(/%S/g, String(dt.getSeconds()).padStart(2, "0")).replace(/%I/g, String(dt.getHours() % 12 || 12).padStart(2, "0")).replace(/%p/g, dt.getHours() >= 12 ? "PM" : "AM").replace(/%B/g, dt.toLocaleString("en-US", { month: "long" })).replace(/%b/g, dt.toLocaleString("en-US", { month: "short" })).replace(/%A/g, dt.toLocaleString("en-US", { weekday: "long" })).replace(/%a/g, dt.toLocaleString("en-US", { weekday: "short" }));
11451
11548
  }
11452
11549
  function wordwrap(text, width) {
@@ -11557,7 +11654,7 @@ function _generateFormToken(descriptor = "") {
11557
11654
  function _generateFormTokenValue(descriptor = "") {
11558
11655
  return new SafeString(_buildFormTokenJwt(descriptor));
11559
11656
  }
11560
- var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
11657
+ var SafeString, KNOWN_TAGS, TERMINATOR_TAGS, GATEABLE_TAGS, BLOCK_TAG_ENDS, JSON_UNSAFE_RE, JSON_UNSAFE_MAP, NUMERIC_RE, METHOD_CALL_RE, FN_CALL_RE, IS_NOT_RE, IS_RE, NOT_IN_RE, IN_RE, DIVISIBLE_BY_RE, FILTER_WITH_ARGS_RE, FILTER_COMPARISON_RE, TITLE_WORD_RE, STRIP_TAGS_RE, FAST_FILTERS, FORMAT_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, RAW_OPEN_RE, RAW_CLOSE_RE, TAG_KINDS, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, ARITHMETIC_LEVELS, BARE_KEY_RE, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, FrondSyntaxError, PHP_MONTHS, PHP_DAYS, BUILTIN_FILTERS, _formTokenSessionId, _formTokenSessionProvider, _cspNonceProvider, Frond;
11561
11658
  var init_engine = __esm({
11562
11659
  "../frond/src/engine.ts"() {
11563
11660
  "use strict";
@@ -11754,6 +11851,35 @@ var init_engine = __esm({
11754
11851
  "__defineProperty__",
11755
11852
  "valueOf"
11756
11853
  ]);
11854
+ FrondSyntaxError = class extends Error {
11855
+ constructor(message) {
11856
+ super(message);
11857
+ this.name = "FrondSyntaxError";
11858
+ }
11859
+ };
11860
+ PHP_MONTHS = [
11861
+ "January",
11862
+ "February",
11863
+ "March",
11864
+ "April",
11865
+ "May",
11866
+ "June",
11867
+ "July",
11868
+ "August",
11869
+ "September",
11870
+ "October",
11871
+ "November",
11872
+ "December"
11873
+ ];
11874
+ PHP_DAYS = [
11875
+ "Sunday",
11876
+ "Monday",
11877
+ "Tuesday",
11878
+ "Wednesday",
11879
+ "Thursday",
11880
+ "Friday",
11881
+ "Saturday"
11882
+ ];
11757
11883
  BUILTIN_FILTERS = {
11758
11884
  upper: (v) => String(v).toUpperCase(),
11759
11885
  lower: (v) => String(v).toLowerCase(),
@@ -12277,7 +12403,9 @@ var init_engine = __esm({
12277
12403
  }
12278
12404
  }
12279
12405
  if (depth > 0) {
12280
- pos = contentStart;
12406
+ throw new FrondSyntaxError(
12407
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12408
+ );
12281
12409
  }
12282
12410
  }
12283
12411
  return blocks;
@@ -12344,9 +12472,9 @@ var init_engine = __esm({
12344
12472
  }
12345
12473
  }
12346
12474
  if (!closeMatch) {
12347
- pieces.push(source.slice(mOpen.index));
12348
- pos = source.length;
12349
- break;
12475
+ throw new FrondSyntaxError(
12476
+ `{% block ${name} %} is never closed (missing or malformed {% endblock %})`
12477
+ );
12350
12478
  }
12351
12479
  const parentContent = source.slice(contentStart, closeMatch.index);
12352
12480
  const blockSource = blocks[name] ?? parentContent;
@@ -14116,6 +14244,41 @@ var init_queryBuilder = __esm({
14116
14244
  }
14117
14245
  return this;
14118
14246
  }
14247
+ /**
14248
+ * Set OFFSET (rows to skip) as its own chainable verb.
14249
+ *
14250
+ * `limit(n, offset)` buries the offset as a second positional arg; this
14251
+ * exposes it on its own, so `.offset(20).limit(10)` reads naturally and
14252
+ * matches the SQL keyword.
14253
+ *
14254
+ * @param count - Number of rows to skip.
14255
+ * @returns this for chaining.
14256
+ */
14257
+ offset(count) {
14258
+ this.offsetVal = count;
14259
+ return this;
14260
+ }
14261
+ /**
14262
+ * Alias for `offset()` -- the Mongo/Eloquent name for the same thing.
14263
+ *
14264
+ * Mirrors the DocStore cursor's `skip` and the `skip` key that `toMongo()`
14265
+ * already emits, so a query reads the same whether it targets SQL or MongoDB.
14266
+ *
14267
+ * @param count - Number of rows to skip.
14268
+ * @returns this for chaining.
14269
+ */
14270
+ skip(count) {
14271
+ return this.offset(count);
14272
+ }
14273
+ /**
14274
+ * Alias for `limit()` -- the Eloquent name; pairs with `skip()`.
14275
+ *
14276
+ * @param count - Maximum rows to return.
14277
+ * @returns this for chaining.
14278
+ */
14279
+ take(count) {
14280
+ return this.limit(count);
14281
+ }
14119
14282
  /**
14120
14283
  * Build and return the SQL string without executing.
14121
14284
  *
@@ -22221,6 +22384,9 @@ function attachCsrfFromEnv() {
22221
22384
  }
22222
22385
  return false;
22223
22386
  }
22387
+ function logPath(req2) {
22388
+ return req2.path ?? (req2.url ?? "/").split("?")[0];
22389
+ }
22224
22390
  function requestLogger() {
22225
22391
  return (req2, res, next) => {
22226
22392
  const start2 = Date.now();
@@ -22229,8 +22395,7 @@ function requestLogger() {
22229
22395
  const duration = Date.now() - start2;
22230
22396
  const status2 = res.raw.statusCode;
22231
22397
  const method = req2.method ?? "?";
22232
- const url = req2.url ?? "/";
22233
- Log.info(`${method} ${url} -> ${status2} (${duration}ms)`);
22398
+ Log.info(`${method} ${logPath(req2)} -> ${status2} (${duration}ms)`);
22234
22399
  });
22235
22400
  next();
22236
22401
  };
@@ -22657,9 +22822,9 @@ var init_middleware = __esm({
22657
22822
  const duration = Date.now() - (req2.startTime ?? Date.now());
22658
22823
  const status2 = res.raw.statusCode;
22659
22824
  const method = req2.method ?? "?";
22660
- const url = req2.url ?? "/";
22825
+ const path10 = logPath(req2);
22661
22826
  const color = status2 >= 400 ? "\x1B[31m" : status2 >= 300 ? "\x1B[33m" : "\x1B[32m";
22662
- console.log(` ${color}${status2}\x1B[0m ${method} ${url} \x1B[90m${duration}ms\x1B[0m`);
22827
+ console.log(` ${color}${status2}\x1B[0m ${method} ${path10} \x1B[90m${duration}ms\x1B[0m`);
22663
22828
  return [req2, res];
22664
22829
  }
22665
22830
  };
@@ -28071,6 +28236,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
28071
28236
  }
28072
28237
  const fields = fieldsOverride || parseFields(flags.fields || "");
28073
28238
  const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
28239
+ const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
28074
28240
  const fileName = `${ts}_${name}.sql`;
28075
28241
  const path10 = join22(dir, fileName);
28076
28242
  setResolutionField("migration_path", `migrations/${fileName}`);
@@ -28080,7 +28246,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
28080
28246
  }
28081
28247
  let upSql;
28082
28248
  let downSql;
28083
- if (isCreate) {
28249
+ if (isView) {
28250
+ upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
28251
+ -- tina4:edit lines. For example:
28252
+ -- CREATE VIEW ${table2} AS
28253
+ -- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
28254
+ downSql = `DROP VIEW IF EXISTS ${table2};`;
28255
+ } else if (isCreate) {
28084
28256
  const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
28085
28257
  for (const [fname, ftype] of fields) {
28086
28258
  const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
@@ -28106,9 +28278,6 @@ DROP TABLE IF EXISTS ${table2};`;
28106
28278
 
28107
28279
  -- UP
28108
28280
  ${upSql}
28109
-
28110
- -- DOWN
28111
- ${downSql}
28112
28281
  `;
28113
28282
  writeFileSafe(path10, content);
28114
28283
  const downPath = join22(dir, `${ts}_${name}.down.sql`);
@@ -28118,7 +28287,7 @@ ${downSql}
28118
28287
  ${downSql}
28119
28288
  `;
28120
28289
  writeFileSafe(downPath, downContent);
28121
- if (emitTest && isCreate) emitMigrationTest(name, table2);
28290
+ if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
28122
28291
  }
28123
28292
  function generateMiddleware(name, _flags) {
28124
28293
  const snake = toSnake(name);
@@ -28929,9 +29098,11 @@ function emitRouteStubTest(route) {
28929
29098
  * Routing test for ${route} \u2014 no mocks, real Router + route discovery.
28930
29099
  *
28931
29100
  * Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
28932
- * ${route}\` (no --model). The handlers are AI-FILL stubs that throw until you
28933
- * implement them, so this tests what IS live on generation: all five routes
28934
- * register on the REAL Router, and the list handler fails loud until filled.
29101
+ * ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
29102
+ * you implement them. This tests what is live on generation: all five routes
29103
+ * register on the REAL Router, and the list handler is wired and callable. It
29104
+ * stays GREEN whether the stub still throws OR you have filled it in \u2014
29105
+ * implementing the handler never turns this test red.
28935
29106
  * Run with: npx tsx tests/${route}.test.ts
28936
29107
  */
28937
29108
  import { dirname, resolve } from "node:path";
@@ -28948,9 +29119,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
28948
29119
  assert(\`route registered: \${sig}\`, sigs.includes(sig));
28949
29120
  }
28950
29121
 
28951
- // The scaffolded list handler is a loud AI-FILL stub \u2014 it throws until filled.
28952
- await assertThrows("list handler is a live stub (throws until filled)",
28953
- () => listHandler({} as never, {} as never));`;
29122
+ // The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
29123
+ // stays green whether it still throws OR you have filled it in, so doing the
29124
+ // work never turns the suite red.
29125
+ assert("list handler is callable", typeof listHandler === "function");
29126
+ try {
29127
+ await listHandler({} as never, {} as never);
29128
+ } catch {
29129
+ // still the scaffold stub (throws until filled) \u2014 expected
29130
+ }`;
28954
29131
  writeTest(route, standaloneTest(doc, body));
28955
29132
  }
28956
29133
  function emitMiddlewareTest(name, snake) {
@@ -29034,8 +29211,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
29034
29211
  assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
29035
29212
  ServiceRunner.remove("${snake}");
29036
29213
 
29037
- // The scaffolded task body is an AI-FILL stub \u2014 it throws until filled.
29038
- await assertThrows("task is a live stub (throws until filled)", () => ${camel}Task({} as never));`;
29214
+ // The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
29215
+ // green whether it still throws OR you have filled it in.
29216
+ assert("task is callable", typeof ${camel}Task === "function");
29217
+ try {
29218
+ await ${camel}Task({} as never);
29219
+ } catch {
29220
+ // still the scaffold stub (throws until filled) \u2014 expected
29221
+ }`;
29039
29222
  writeTest(snake, standaloneTest(doc, body));
29040
29223
  }
29041
29224
  function emitQueueTest(topic, slug, pascal) {
@@ -29057,8 +29240,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
29057
29240
  assert("consumer default export is a daemon", worker.daemon === true);
29058
29241
  assert("consumer handler is wired", typeof worker.handler === "function");
29059
29242
 
29060
- // The per-job handler is an AI-FILL stub \u2014 it throws until filled.
29061
- await assertThrows("handle is a live stub (throws until filled)", () => handle${pascal}({}));`;
29243
+ // The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
29244
+ // This stays green whether it still throws OR you have filled it in.
29245
+ assert("handle is callable", typeof handle${pascal} === "function");
29246
+ try {
29247
+ await handle${pascal}({});
29248
+ } catch {
29249
+ // still the scaffold stub (throws until filled) \u2014 expected
29250
+ }`;
29062
29251
  writeTest(slug, standaloneTest(doc, body));
29063
29252
  }
29064
29253
  function emitValidatorTest(name, snake, pascal) {
@@ -29120,9 +29309,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
29120
29309
  const closed = await ${handler}(null as never, "close", "");
29121
29310
  assert("close event handled cleanly", closed === undefined);
29122
29311
 
29123
- // The "message" branch is an AI-FILL stub \u2014 it throws until filled.
29124
- await assertThrows("message branch is a live stub (throws until filled)",
29125
- () => ${handler}(null as never, "message", "hi"));`;
29312
+ // The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
29313
+ // This stays green whether it still throws OR you have filled it in.
29314
+ try {
29315
+ await ${handler}(null as never, "message", "hi");
29316
+ assert("message branch is callable", true);
29317
+ } catch {
29318
+ assert("message branch is callable", true); // still the scaffold stub
29319
+ }`;
29126
29320
  writeTest(`ws_${base}`, standaloneTest(doc, body));
29127
29321
  }
29128
29322
  function emitListenerTest(event, slug) {
@@ -29139,9 +29333,15 @@ import { Events } from "tina4-nodejs";
29139
29333
  import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
29140
29334
  const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
29141
29335
 
29142
- // strict emit re-raises the stub error, proving the listener actually ran.
29143
- await assertThrows("emitting the event reaches the (stub) listener",
29144
- () => Events.emit("${event}", { strict: true }, { id: 1 }));`;
29336
+ // Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
29337
+ // re-raises); once you implement it this test STILL passes, so doing the work
29338
+ // never turns the suite red.
29339
+ try {
29340
+ await Events.emit("${event}", { strict: true }, { id: 1 });
29341
+ assert("emitting reaches the listener", true);
29342
+ } catch {
29343
+ assert("emitting reaches the listener", true); // still the scaffold stub
29344
+ }`;
29145
29345
  writeTest(slug, standaloneTest(doc, body));
29146
29346
  }
29147
29347
  function emitAuthTest() {
@@ -29696,9 +29896,9 @@ function agentLog(projectRoot3, category, message) {
29696
29896
  if (!fs4.existsSync(logDir)) {
29697
29897
  fs4.mkdirSync(logDir, { recursive: true });
29698
29898
  }
29699
- const logPath = path3.join(logDir, "agent.log");
29899
+ const logPath2 = path3.join(logDir, "agent.log");
29700
29900
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/\..+/, "Z");
29701
- fs4.appendFileSync(logPath, `${ts} [${category}] ${message}
29901
+ fs4.appendFileSync(logPath2, `${ts} [${category}] ${message}
29702
29902
  `, "utf-8");
29703
29903
  } catch {
29704
29904
  }
@@ -30694,13 +30894,13 @@ function registerDevTools(server) {
30694
30894
  "git_status",
30695
30895
  () => {
30696
30896
  try {
30697
- const { execFileSync: execFileSync7 } = req("node:child_process");
30897
+ const { execFileSync: execFileSync6 } = req("node:child_process");
30698
30898
  const cwd = path3.resolve(process.cwd());
30699
30899
  const run = (args) => {
30700
- return execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30900
+ return execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
30701
30901
  };
30702
30902
  try {
30703
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30903
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
30704
30904
  } catch {
30705
30905
  return { error: "Not a git repository" };
30706
30906
  }
@@ -34593,6 +34793,753 @@ var init_mongoBackend = __esm({
34593
34793
  }
34594
34794
  });
34595
34795
 
34796
+ // ../core/src/queueBackends/kafkaBackend.ts
34797
+ import { Worker as Worker2 } from "node:worker_threads";
34798
+ import { randomUUID as randomUUID6 } from "node:crypto";
34799
+ function kafkaSecurityConfig(env = process.env) {
34800
+ const mapping = [
34801
+ ["security.protocol", "SECURITY_PROTOCOL"],
34802
+ ["ssl.ca.location", "SSL_CA_LOCATION"],
34803
+ ["sasl.mechanism", "SASL_MECHANISM"],
34804
+ ["sasl.username", "SASL_USERNAME"],
34805
+ ["sasl.password", "SASL_PASSWORD"]
34806
+ ];
34807
+ const config = {};
34808
+ for (const [rdk, suffix] of mapping) {
34809
+ const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
34810
+ if (value) {
34811
+ config[rdk] = value;
34812
+ }
34813
+ }
34814
+ return config;
34815
+ }
34816
+ function kafkaOffsetReset(env = process.env) {
34817
+ return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
34818
+ }
34819
+ var WORKER_SRC, KafkaBackend;
34820
+ var init_kafkaBackend = __esm({
34821
+ "../core/src/queueBackends/kafkaBackend.ts"() {
34822
+ "use strict";
34823
+ WORKER_SRC = `
34824
+ const net = require("node:net");
34825
+ const tls = require("node:tls");
34826
+ const { parentPort, workerData } = require("node:worker_threads");
34827
+
34828
+ const brokers = workerData.brokers;
34829
+ const groupId = workerData.groupId;
34830
+ const security = workerData.security || {};
34831
+ const offsetReset = workerData.offsetReset || "earliest";
34832
+ const header = new Int32Array(workerData.sab, 0, 2); // [0]=flag, [1]=respLen
34833
+ const outBytes = new Uint8Array(workerData.sab, 8);
34834
+
34835
+ // Lowest versions Kafka 4.x still accepts: it REMOVED Produce v0-v2 / Fetch v0-v3
34836
+ // (the old message formats) and answers a removed version by closing the socket,
34837
+ // not with an error code. These are named constants so the source invariant test
34838
+ // (test/kafkaErrorCodes.test.ts) can assert the floors.
34839
+ const PRODUCE_VERSION = 3;
34840
+ const FETCH_VERSION = 4;
34841
+
34842
+ let correlationId = 0;
34843
+ let brokerSock = null;
34844
+ let coordSock = null;
34845
+ const offsets = {}; // topic -> next read offset (in-memory cursor)
34846
+ const inFlight = {}; // job id -> { offset, value, attempts, isEnvelope }
34847
+
34848
+ const COORDINATOR_ERRORS = [14, 15, 16];
34849
+
34850
+ function parseBroker(list) {
34851
+ const first = String(list).split(",")[0].trim();
34852
+ const i = first.lastIndexOf(":");
34853
+ if (i < 0) return { host: first || "localhost", port: 9092 };
34854
+ return { host: first.slice(0, i) || "localhost", port: parseInt(first.slice(i + 1), 10) || 9092 };
34855
+ }
34856
+
34857
+ function connect(host, port) {
34858
+ return new Promise(function (resolve, reject) {
34859
+ const proto = String(security["security.protocol"] || "PLAINTEXT").toUpperCase();
34860
+ const useTls = proto.indexOf("SSL") >= 0;
34861
+ let sock;
34862
+ const onErr = function (e) { reject(e); };
34863
+ if (useTls) {
34864
+ const opts = { host: host, port: port, servername: host };
34865
+ if (security["ssl.ca.location"]) opts.ca = require("node:fs").readFileSync(security["ssl.ca.location"]);
34866
+ sock = tls.connect(opts, function () { sock.removeListener("error", onErr); resolve(sock); });
34867
+ } else {
34868
+ sock = net.createConnection({ host: host, port: port }, function () { sock.removeListener("error", onErr); resolve(sock); });
34869
+ }
34870
+ sock.once("error", onErr);
34871
+ });
34872
+ }
34873
+
34874
+ // One request/response round trip on a socket: write the framed request, read a
34875
+ // 4-byte length then that many bytes, resolve with the payload AFTER the length
34876
+ // (so it starts at correlationId). Serialized \u2014 one in flight per socket.
34877
+ function rpc(sock, reqBuf) {
34878
+ return new Promise(function (resolve, reject) {
34879
+ let buf = Buffer.alloc(0);
34880
+ function onData(chunk) {
34881
+ buf = Buffer.concat([buf, chunk]);
34882
+ if (buf.length < 4) return;
34883
+ const size = buf.readInt32BE(0);
34884
+ if (buf.length < 4 + size) return;
34885
+ sock.removeListener("data", onData);
34886
+ sock.removeListener("error", onErr);
34887
+ resolve(buf.subarray(4, 4 + size));
34888
+ }
34889
+ function onErr(e) {
34890
+ sock.removeListener("data", onData);
34891
+ reject(e);
34892
+ }
34893
+ sock.on("data", onData);
34894
+ sock.once("error", onErr);
34895
+ sock.write(reqBuf);
34896
+ });
34897
+ }
34898
+
34899
+ // \u2500\u2500 encoders \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
34900
+ function kstr(s) {
34901
+ const b = Buffer.from(s, "utf-8");
34902
+ const out = Buffer.alloc(2 + b.length);
34903
+ out.writeInt16BE(b.length, 0);
34904
+ b.copy(out, 2);
34905
+ return out;
34906
+ }
34907
+ function frame(apiKey, apiVersion, body) {
34908
+ correlationId++;
34909
+ const client = Buffer.from("tina4-nodejs", "utf-8");
34910
+ const head = Buffer.alloc(2 + 2 + 4 + 2 + client.length);
34911
+ let p = 0;
34912
+ head.writeInt16BE(apiKey, p); p += 2;
34913
+ head.writeInt16BE(apiVersion, p); p += 2;
34914
+ head.writeInt32BE(correlationId, p); p += 4;
34915
+ head.writeInt16BE(client.length, p); p += 2;
34916
+ client.copy(head, p);
34917
+ const payload = Buffer.concat([head, body]);
34918
+ const out = Buffer.alloc(4 + payload.length);
34919
+ out.writeInt32BE(payload.length, 0);
34920
+ payload.copy(out, 4);
34921
+ return out;
34922
+ }
34923
+
34924
+ // \u2500\u2500 CRC-32C + varints + v2 RecordBatch (produce) \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
34925
+ const CRC32C_TABLE = (function () {
34926
+ const t = new Uint32Array(256);
34927
+ for (let n = 0; n < 256; n++) {
34928
+ let c = n;
34929
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
34930
+ t[n] = c >>> 0;
34931
+ }
34932
+ return t;
34933
+ })();
34934
+ function crc32c(buf) {
34935
+ let crc = 0xffffffff;
34936
+ for (let i = 0; i < buf.length; i++) crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
34937
+ return (crc ^ 0xffffffff) >>> 0;
34938
+ }
34939
+ function zig(n) { return ((n << 1) ^ (n >> 31)) >>> 0; }
34940
+ function varU(u) {
34941
+ const b = [];
34942
+ let v = u >>> 0;
34943
+ for (;;) { if ((v & ~0x7f) === 0) { b.push(v); break; } b.push((v & 0x7f) | 0x80); v >>>= 7; }
34944
+ return Buffer.from(b);
34945
+ }
34946
+ function varint(n) { return varU(zig(n)); }
34947
+ function readVarint(buf, pos) {
34948
+ let result = 0, shift = 0, b;
34949
+ do { b = buf[pos++]; result |= (b & 0x7f) << shift; shift += 7; } while (b & 0x80);
34950
+ result = result >>> 0;
34951
+ return { value: (result >>> 1) ^ -(result & 1), next: pos };
34952
+ }
34953
+ function buildRecordBatch(valueBytes) {
34954
+ const now = BigInt(Date.now());
34955
+ const recBody = Buffer.concat([
34956
+ Buffer.from([0]), varint(0), varint(0), varint(-1),
34957
+ varint(valueBytes.length), valueBytes, varint(0),
34958
+ ]);
34959
+ const record = Buffer.concat([varint(recBody.length), recBody]);
34960
+ const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
34961
+ let c = 0;
34962
+ crcBody.writeInt16BE(0, c); c += 2;
34963
+ crcBody.writeInt32BE(0, c); c += 4;
34964
+ crcBody.writeBigInt64BE(now, c); c += 8;
34965
+ crcBody.writeBigInt64BE(now, c); c += 8;
34966
+ crcBody.writeBigInt64BE(-1n, c); c += 8;
34967
+ crcBody.writeInt16BE(-1, c); c += 2;
34968
+ crcBody.writeInt32BE(-1, c); c += 4;
34969
+ crcBody.writeInt32BE(1, c); c += 4;
34970
+ record.copy(crcBody, c);
34971
+ const crc = crc32c(crcBody);
34972
+ const batchLength = 4 + 1 + 4 + crcBody.length;
34973
+ const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
34974
+ let h = 0;
34975
+ head.writeBigInt64BE(0n, h); h += 8;
34976
+ head.writeInt32BE(batchLength, h); h += 4;
34977
+ head.writeInt32BE(-1, h); h += 4;
34978
+ head.writeInt8(2, h); h += 1;
34979
+ head.writeUInt32BE(crc, h); h += 4;
34980
+ return Buffer.concat([head, crcBody]);
34981
+ }
34982
+
34983
+ // \u2500\u2500 produce \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
34984
+ function produceRequest(topic, valueBytes) {
34985
+ const topicBuf = Buffer.from(topic, "utf-8");
34986
+ const batch = buildRecordBatch(valueBytes);
34987
+ const body = Buffer.alloc(2 + 2 + 4 + 4 + 2 + topicBuf.length + 4 + 4 + 4 + batch.length);
34988
+ let p = 0;
34989
+ body.writeInt16BE(-1, p); p += 2; // transactionalId null
34990
+ body.writeInt16BE(1, p); p += 2; // acks 1
34991
+ body.writeInt32BE(10000, p); p += 4; // timeoutMs
34992
+ body.writeInt32BE(1, p); p += 4; // topics
34993
+ body.writeInt16BE(topicBuf.length, p); p += 2;
34994
+ topicBuf.copy(body, p); p += topicBuf.length;
34995
+ body.writeInt32BE(1, p); p += 4; // partitions
34996
+ body.writeInt32BE(0, p); p += 4; // partition 0
34997
+ body.writeInt32BE(batch.length, p); p += 4;
34998
+ batch.copy(body, p);
34999
+ return frame(0, PRODUCE_VERSION, body);
35000
+ }
35001
+ function parseProduce(resp) {
35002
+ let pos = 4; // correlationId
35003
+ const topicCount = resp.readInt32BE(pos); pos += 4;
35004
+ let err = 0;
35005
+ for (let t = 0; t < topicCount; t++) {
35006
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35007
+ const pc = resp.readInt32BE(pos); pos += 4;
35008
+ for (let pi = 0; pi < pc; pi++) {
35009
+ pos += 4; err = resp.readInt16BE(pos); pos += 2; pos += 8; pos += 8;
35010
+ }
35011
+ }
35012
+ return err;
35013
+ }
35014
+ async function produce(topic, valueBytes) {
35015
+ const sock = await broker();
35016
+ for (let attempt = 1; attempt <= 10; attempt++) {
35017
+ const err = parseProduce(await rpc(sock, produceRequest(topic, valueBytes)));
35018
+ if (err === 0) return;
35019
+ if ((err !== 3 && err !== 5) || attempt === 10) {
35020
+ throw new Error("Kafka rejected the produce for topic " + topic + ": error code " + err);
35021
+ }
35022
+ await sleep(200);
35023
+ }
35024
+ }
35025
+
35026
+ // \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
35027
+ function fetchRequest(topic, offset) {
35028
+ const topicBuf = Buffer.from(topic, "utf-8");
35029
+ const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + 2 + topicBuf.length + 4 + 4 + 8 + 4);
35030
+ let p = 0;
35031
+ buf.writeInt32BE(-1, p); p += 4; // replicaId
35032
+ buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
35033
+ buf.writeInt32BE(1, p); p += 4; // minBytes
35034
+ buf.writeInt32BE(1048576, p); p += 4; // maxBytes
35035
+ buf.writeInt8(0, p); p += 1; // isolation READ_UNCOMMITTED
35036
+ buf.writeInt32BE(1, p); p += 4; // topics
35037
+ buf.writeInt16BE(topicBuf.length, p); p += 2;
35038
+ topicBuf.copy(buf, p); p += topicBuf.length;
35039
+ buf.writeInt32BE(1, p); p += 4; // partitions
35040
+ buf.writeInt32BE(0, p); p += 4; // partition 0
35041
+ buf.writeBigInt64BE(BigInt(offset), p); p += 8;
35042
+ buf.writeInt32BE(1048576, p); p += 4;
35043
+ return frame(1, FETCH_VERSION, buf);
35044
+ }
35045
+ // Decode the first record of the partition's record-set: its value string and
35046
+ // absolute offset (baseOffset + offsetDelta). null = no usable record.
35047
+ function firstRecord(buf, start, end) {
35048
+ let pos = start;
35049
+ while (pos + 12 <= end) {
35050
+ const baseOffset = buf.readBigInt64BE(pos);
35051
+ const batchLength = buf.readInt32BE(pos + 8);
35052
+ const batchStart = pos + 12;
35053
+ const batchEnd = batchStart + batchLength;
35054
+ if (batchLength <= 0 || batchEnd > end) break;
35055
+ const magic = buf.readInt8(batchStart + 4);
35056
+ if (magic !== 2) { pos = batchEnd; continue; }
35057
+ let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
35058
+ const recordsCount = buf.readInt32BE(r); r += 4;
35059
+ for (let i = 0; i < recordsCount && r < batchEnd; i++) {
35060
+ const recLen = readVarint(buf, r);
35061
+ let rp = recLen.next;
35062
+ const recordEnd = rp + recLen.value;
35063
+ rp += 1;
35064
+ rp = readVarint(buf, rp).next; // timestampDelta
35065
+ const offDelta = readVarint(buf, rp); rp = offDelta.next;
35066
+ const keyLen = readVarint(buf, rp); rp = keyLen.next;
35067
+ if (keyLen.value >= 0) rp += keyLen.value;
35068
+ const valLen = readVarint(buf, rp); rp = valLen.next;
35069
+ if (valLen.value >= 0) {
35070
+ return {
35071
+ value: buf.subarray(rp, rp + valLen.value).toString("utf-8"),
35072
+ offset: Number(baseOffset) + offDelta.value,
35073
+ };
35074
+ }
35075
+ r = recordEnd;
35076
+ }
35077
+ pos = batchEnd;
35078
+ }
35079
+ return null;
35080
+ }
35081
+ async function fetchAt(topic, offset) {
35082
+ const sock = await broker();
35083
+ const resp = await rpc(sock, fetchRequest(topic, offset));
35084
+ let pos = 4; // correlationId
35085
+ pos += 4; // throttleTimeMs
35086
+ const topicCount = resp.readInt32BE(pos); pos += 4;
35087
+ let rec = null;
35088
+ for (let t = 0; t < topicCount; t++) {
35089
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35090
+ const pc = resp.readInt32BE(pos); pos += 4;
35091
+ for (let pi = 0; pi < pc; pi++) {
35092
+ pos += 4;
35093
+ const err = resp.readInt16BE(pos); pos += 2;
35094
+ pos += 8; pos += 8;
35095
+ const aborted = resp.readInt32BE(pos); pos += 4;
35096
+ if (aborted > 0) pos += aborted * 16;
35097
+ const recSize = resp.readInt32BE(pos); pos += 4;
35098
+ if (err !== 0 && err !== 3 && err !== 5) {
35099
+ throw new Error("Kafka rejected the fetch for topic " + topic + ": error code " + err);
35100
+ }
35101
+ if (err === 0 && recSize > 0) {
35102
+ const r = firstRecord(resp, pos, pos + recSize);
35103
+ if (r !== null) rec = r;
35104
+ }
35105
+ if (recSize > 0) pos += recSize;
35106
+ }
35107
+ }
35108
+ return rec;
35109
+ }
35110
+
35111
+ // \u2500\u2500 coordinator + offsets \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
35112
+ function readNullableString(buf, pos) {
35113
+ const len = buf.readInt16BE(pos); pos += 2;
35114
+ if (len < 0) return { value: null, next: pos };
35115
+ return { value: buf.toString("utf-8", pos, pos + len), next: pos + len };
35116
+ }
35117
+ async function findCoordinator() {
35118
+ const sock = await broker();
35119
+ for (let attempt = 0; attempt < 30; attempt++) {
35120
+ const body = Buffer.concat([kstr(groupId), Buffer.from([0])]); // key_type 0 = group
35121
+ const resp = await rpc(sock, frame(10, 1, body));
35122
+ let pos = 4; // correlationId
35123
+ pos += 4; // throttle
35124
+ const err = resp.readInt16BE(pos); pos += 2;
35125
+ pos = readNullableString(resp, pos).next; // error_message
35126
+ pos += 4; // node_id
35127
+ const hostRes = readNullableString(resp, pos); pos = hostRes.next;
35128
+ const port = resp.readInt32BE(pos);
35129
+ if (err === 0 && hostRes.value) return { host: hostRes.value, port: port };
35130
+ if (err !== 14 && err !== 15) {
35131
+ throw new Error("Kafka FindCoordinator failed for group " + groupId + ": error code " + err);
35132
+ }
35133
+ await sleep(300);
35134
+ }
35135
+ throw new Error("Kafka group coordinator for " + groupId + " did not become available");
35136
+ }
35137
+ async function coordinator() {
35138
+ if (coordSock) return coordSock;
35139
+ const c = await findCoordinator();
35140
+ coordSock = await connect(c.host, c.port);
35141
+ return coordSock;
35142
+ }
35143
+ function dropCoordinator() {
35144
+ if (coordSock) { try { coordSock.destroy(); } catch (e) { /* ignore */ } }
35145
+ coordSock = null;
35146
+ }
35147
+ function offsetCommitRequest(topic, offset) {
35148
+ const body = Buffer.concat([
35149
+ kstr(groupId),
35150
+ int32(-1), // generation_id -1 (simple consumer)
35151
+ kstr(""), // member_id ""
35152
+ int64(-1n), // retention_time -1
35153
+ int32(1), kstr(topic), int32(1), int32(0), int64(BigInt(offset)), int16(-1),
35154
+ ]);
35155
+ return frame(8, 2, body);
35156
+ }
35157
+ function parseOffsetCommit(resp) {
35158
+ let pos = 4;
35159
+ const tc = resp.readInt32BE(pos); pos += 4;
35160
+ if (tc === 0) return 16;
35161
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35162
+ const pc = resp.readInt32BE(pos); pos += 4;
35163
+ if (pc === 0) return 16;
35164
+ pos += 4;
35165
+ return resp.readInt16BE(pos);
35166
+ }
35167
+ async function offsetCommit(topic, offset) {
35168
+ var err = 0;
35169
+ for (var attempt = 0; attempt < 10; attempt++) {
35170
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (r) { setTimeout(r, 200 * attempt); }); }
35171
+ err = parseOffsetCommit(await rpc(await coordinator(), offsetCommitRequest(topic, offset)));
35172
+ if (COORDINATOR_ERRORS.indexOf(err) < 0) break;
35173
+ }
35174
+ if (err !== 0) throw new Error("Kafka rejected the offset commit for " + topic + ": error code " + err);
35175
+ }
35176
+ function offsetFetchRequest(topic) {
35177
+ const body = Buffer.concat([kstr(groupId), int32(1), kstr(topic), int32(1), int32(0)]);
35178
+ return frame(9, 1, body);
35179
+ }
35180
+ function parseOffsetFetch(resp) {
35181
+ let pos = 4;
35182
+ const tc = resp.readInt32BE(pos); pos += 4;
35183
+ if (tc === 0) return { offset: -1, err: 16 };
35184
+ const tl = resp.readInt16BE(pos); pos += 2 + tl;
35185
+ const pc = resp.readInt32BE(pos); pos += 4;
35186
+ if (pc === 0) return { offset: -1, err: 16 };
35187
+ pos += 4;
35188
+ const offset = Number(resp.readBigInt64BE(pos)); pos += 8;
35189
+ pos = readNullableString(resp, pos).next;
35190
+ const err = resp.readInt16BE(pos);
35191
+ return { offset: offset, err: err };
35192
+ }
35193
+ async function offsetFetch(topic) {
35194
+ var r = { offset: -1, err: 0 };
35195
+ for (var attempt = 0; attempt < 10; attempt++) {
35196
+ if (attempt > 0) { dropCoordinator(); await new Promise(function (res) { setTimeout(res, 200 * attempt); }); }
35197
+ r = parseOffsetFetch(await rpc(await coordinator(), offsetFetchRequest(topic)));
35198
+ if (COORDINATOR_ERRORS.indexOf(r.err) < 0) break;
35199
+ }
35200
+ if (r.err !== 0) throw new Error("Kafka rejected the offset fetch for " + topic + ": error code " + r.err);
35201
+ return r.offset < 0 ? 0 : r.offset;
35202
+ }
35203
+
35204
+ function int16(n) { const b = Buffer.alloc(2); b.writeInt16BE(n, 0); return b; }
35205
+ function int32(n) { const b = Buffer.alloc(4); b.writeInt32BE(n, 0); return b; }
35206
+ function int64(n) { const b = Buffer.alloc(8); b.writeBigInt64BE(BigInt(n), 0); return b; }
35207
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
35208
+
35209
+ async function broker() {
35210
+ if (brokerSock) return brokerSock;
35211
+ const b = parseBroker(brokers);
35212
+ brokerSock = await connect(b.host, b.port);
35213
+ return brokerSock;
35214
+ }
35215
+
35216
+ // Resume from the committed offset on the FIRST read of a topic in this worker,
35217
+ // then advance the in-memory cursor; the committed offset only moves on a
35218
+ // commit, so it lags and a crash before commit replays (at-least-once).
35219
+ async function fetchNext(topic) {
35220
+ if (!(topic in offsets)) offsets[topic] = await offsetFetch(topic);
35221
+ const rec = await fetchAt(topic, offsets[topic]);
35222
+ if (rec === null) return null;
35223
+ offsets[topic] = rec.offset + 1;
35224
+ return rec;
35225
+ }
35226
+
35227
+ function encodeEnvelope(id, payload, attempts) {
35228
+ return JSON.stringify({ id: id, payload: payload, status: "pending", createdAt: new Date().toISOString(), attempts: attempts, delayUntil: null });
35229
+ }
35230
+
35231
+ async function handle(req) {
35232
+ const op = req.op;
35233
+ if (op === "publish") {
35234
+ await produce(req.topic, Buffer.from(req.value, "utf-8"));
35235
+ return { ok: true };
35236
+ }
35237
+ if (op === "dequeueRaw") {
35238
+ // The value exactly as it sits on the wire (a raw record stays its bare
35239
+ // bytes \u2014 tina4-nodejs#264), with no id/offset tracking. For wire
35240
+ // inspection; the facade consumes through "pop", which normalises + tracks.
35241
+ const rec = await fetchNext(req.topic);
35242
+ if (rec === null) return { ok: true, message: null };
35243
+ let decoded;
35244
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = rec.value; }
35245
+ return { ok: true, message: decoded };
35246
+ }
35247
+ if (op === "pop") {
35248
+ let rec;
35249
+ try {
35250
+ rec = await fetchNext(req.topic);
35251
+ } catch (e) {
35252
+ // A malformed/short response runs the parser off the end (a RangeError);
35253
+ // anything else is a transport failure. Both name the topic so the cause
35254
+ // is findable, and neither reads as an empty queue (ADR: a real failure
35255
+ // must never look idle). Wording matches the Python/PHP backends.
35256
+ const range = (e instanceof RangeError) || /out of range|bounds/i.test((e && e.message) || "");
35257
+ if (range) throw new Error("Kafka fetch for topic " + req.topic + " returned an unreadable response: " + ((e && e.message) || e));
35258
+ throw new Error("Kafka fetch for topic " + req.topic + " failed: " + ((e && e.message) || e));
35259
+ }
35260
+ if (rec === null) return { ok: true, message: null };
35261
+ const coordinate = req.topic + ":0:" + rec.offset;
35262
+ let decoded;
35263
+ try { decoded = JSON.parse(rec.value); } catch (e) { decoded = null; }
35264
+ let message;
35265
+ let isEnvelope = false;
35266
+ if (decoded !== null && typeof decoded === "object" && !Array.isArray(decoded) && "payload" in decoded) {
35267
+ message = decoded;
35268
+ isEnvelope = true;
35269
+ if (!message.id) message.id = coordinate;
35270
+ } else {
35271
+ message = { id: coordinate, payload: decoded === null ? rec.value : decoded, status: "pending", attempts: 0 };
35272
+ }
35273
+ // The Job lifecycle (complete/fail/retry) routes by the record's own topic,
35274
+ // so it must be carried back (like the file/mongodb backends do).
35275
+ message.topic = req.topic;
35276
+ inFlight[String(message.id)] = { offset: rec.offset, value: rec.value, attempts: message.attempts || 0, isEnvelope: isEnvelope };
35277
+ return { ok: true, message: message };
35278
+ }
35279
+ if (op === "complete") {
35280
+ const rec = inFlight[String(req.id)];
35281
+ if (rec) { delete inFlight[String(req.id)]; await offsetCommit(req.topic, rec.offset + 1); }
35282
+ return { ok: true };
35283
+ }
35284
+ if (op === "fail") {
35285
+ const rec = inFlight[String(req.id)];
35286
+ if (rec) {
35287
+ delete inFlight[String(req.id)];
35288
+ const attempts = (rec.attempts || 0) + 1;
35289
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35290
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35291
+ if (attempts < req.maxRetries) {
35292
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35293
+ } else {
35294
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: attempts, error: req.error }), "utf-8"));
35295
+ }
35296
+ await offsetCommit(req.topic, rec.offset + 1);
35297
+ }
35298
+ return { ok: true };
35299
+ }
35300
+ if (op === "reject") {
35301
+ const rec = inFlight[String(req.id)];
35302
+ if (rec) {
35303
+ delete inFlight[String(req.id)];
35304
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35305
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35306
+ await produce(req.topic + ".dead_letter", Buffer.from(JSON.stringify({ id: req.id, payload: payload, attempts: req.maxRetries, error: req.reason }), "utf-8"));
35307
+ await offsetCommit(req.topic, rec.offset + 1);
35308
+ }
35309
+ return { ok: true };
35310
+ }
35311
+ if (op === "retry") {
35312
+ const rec = inFlight[String(req.id)];
35313
+ if (rec) {
35314
+ delete inFlight[String(req.id)];
35315
+ const attempts = (rec.attempts || 0) + 1;
35316
+ const parsed = (function () { try { return JSON.parse(rec.value); } catch (e) { return rec.value; } })();
35317
+ const payload = (parsed && typeof parsed === "object" && "payload" in parsed) ? parsed.payload : parsed;
35318
+ await produce(req.topic, Buffer.from(encodeEnvelope(req.id, payload, attempts), "utf-8"));
35319
+ await offsetCommit(req.topic, rec.offset + 1);
35320
+ }
35321
+ return { ok: true };
35322
+ }
35323
+ if (op === "deadLetters") {
35324
+ // Read the <topic>.dead_letter topic from the beginning; every record on it
35325
+ // is a dead letter by construction. A throwaway cursor that never commits,
35326
+ // so it does not disturb the main consume position.
35327
+ const dlq = req.topic + ".dead_letter";
35328
+ const out = [];
35329
+ let off = 0;
35330
+ for (;;) {
35331
+ const rec = await fetchAt(dlq, off);
35332
+ if (rec === null) break;
35333
+ off = rec.offset + 1;
35334
+ try { out.push(JSON.parse(rec.value)); } catch (e) { /* skip */ }
35335
+ if (out.length > 10000) break;
35336
+ }
35337
+ return { ok: true, deadLetters: out };
35338
+ }
35339
+ if (op === "close") {
35340
+ try { if (brokerSock) brokerSock.destroy(); } catch (e) { /* ignore */ }
35341
+ dropCoordinator();
35342
+ return { ok: true, closing: true };
35343
+ }
35344
+ return { ok: false, error: "unknown op " + op };
35345
+ }
35346
+
35347
+ parentPort.on("message", async function (req) {
35348
+ let res;
35349
+ try { res = await handle(req); }
35350
+ catch (e) { res = { ok: false, error: (e && e.message) ? e.message : String(e) }; }
35351
+ const bytes = Buffer.from(JSON.stringify(res), "utf-8");
35352
+ outBytes.set(bytes.subarray(0, outBytes.length), 0);
35353
+ Atomics.store(header, 1, Math.min(bytes.length, outBytes.length));
35354
+ Atomics.store(header, 0, 1);
35355
+ Atomics.notify(header, 0);
35356
+ });
35357
+ `;
35358
+ KafkaBackend = class _KafkaBackend {
35359
+ brokers;
35360
+ groupId;
35361
+ worker = null;
35362
+ sab = null;
35363
+ header = null;
35364
+ outBytes = null;
35365
+ static SAB_SIZE = 1 << 20;
35366
+ // 1 MiB (8-byte header + response bytes)
35367
+ static CALL_TIMEOUT_MS = 2e4;
35368
+ constructor(config) {
35369
+ const url = process.env.TINA4_QUEUE_URL;
35370
+ const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
35371
+ this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
35372
+ this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
35373
+ }
35374
+ /** Resolved connection config — exposed for testing/introspection. */
35375
+ getConfig() {
35376
+ return { brokers: this.brokers, groupId: this.groupId };
35377
+ }
35378
+ securityConfig() {
35379
+ return kafkaSecurityConfig();
35380
+ }
35381
+ producerConfig() {
35382
+ return { "bootstrap.servers": this.brokers, "client.id": "tina4-nodejs", ...this.securityConfig() };
35383
+ }
35384
+ consumerConfig() {
35385
+ return {
35386
+ "bootstrap.servers": this.brokers,
35387
+ "client.id": "tina4-nodejs",
35388
+ "group.id": this.groupId,
35389
+ "auto.offset.reset": kafkaOffsetReset(),
35390
+ "enable.auto.commit": false,
35391
+ ...this.securityConfig()
35392
+ };
35393
+ }
35394
+ /** Lazily start the persistent worker + its shared buffer. */
35395
+ ensureWorker() {
35396
+ if (this.worker) return;
35397
+ this.sab = new SharedArrayBuffer(_KafkaBackend.SAB_SIZE);
35398
+ this.header = new Int32Array(this.sab, 0, 2);
35399
+ this.outBytes = new Uint8Array(this.sab, 8);
35400
+ this.worker = new Worker2(WORKER_SRC, {
35401
+ eval: true,
35402
+ workerData: {
35403
+ brokers: this.brokers,
35404
+ groupId: this.groupId,
35405
+ security: this.securityConfig(),
35406
+ offsetReset: kafkaOffsetReset(),
35407
+ sab: this.sab
35408
+ }
35409
+ });
35410
+ this.worker.unref();
35411
+ }
35412
+ /** One synchronous request to the worker: post, block on Atomics.wait, read. */
35413
+ request(req2) {
35414
+ this.ensureWorker();
35415
+ const header = this.header;
35416
+ const outBytes = this.outBytes;
35417
+ Atomics.store(header, 0, 0);
35418
+ this.worker.postMessage(req2);
35419
+ const waited = Atomics.wait(header, 0, 0, _KafkaBackend.CALL_TIMEOUT_MS);
35420
+ if (waited === "timed-out") {
35421
+ throw new Error(`Kafka ${String(req2.op)} for topic ${String(req2.topic ?? "")} timed out after ${_KafkaBackend.CALL_TIMEOUT_MS}ms`);
35422
+ }
35423
+ const len = Atomics.load(header, 1);
35424
+ const json = Buffer.from(outBytes.buffer, outBytes.byteOffset, len).toString("utf-8");
35425
+ const res = JSON.parse(json);
35426
+ if (res.ok === false) {
35427
+ throw new Error(String(res.error ?? "unknown Kafka worker error"));
35428
+ }
35429
+ return res;
35430
+ }
35431
+ /**
35432
+ * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
35433
+ * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
35434
+ * consumer reading the topic gets the schema it expects; otherwise the Tina4
35435
+ * job envelope. pop() unwraps both shapes (payload ?? the whole record).
35436
+ */
35437
+ static encodeJob(id, payload, raw) {
35438
+ if (raw) return JSON.stringify(payload);
35439
+ return JSON.stringify({
35440
+ id,
35441
+ payload,
35442
+ status: "pending",
35443
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
35444
+ attempts: 0,
35445
+ delayUntil: null
35446
+ });
35447
+ }
35448
+ push(queue, payload, _delay, _priority, raw = false) {
35449
+ const id = randomUUID6();
35450
+ const value = _KafkaBackend.encodeJob(id, payload, raw);
35451
+ this.request({ op: "publish", topic: queue, value });
35452
+ return id;
35453
+ }
35454
+ pop(queue) {
35455
+ const res = this.request({ op: "pop", topic: queue });
35456
+ const message = res.message;
35457
+ return message ?? null;
35458
+ }
35459
+ /**
35460
+ * Read the next record's value exactly as it sits on the wire — a Tina4
35461
+ * envelope as produced, a raw record (tina4-nodejs#264) as its bare bytes —
35462
+ * with no id/offset tracking. For a foreign consumer's view of the schema;
35463
+ * the queue facade consumes through pop(), which also normalises and tracks
35464
+ * the offset so complete()/fail() can commit it.
35465
+ */
35466
+ dequeue(queue) {
35467
+ const res = this.request({ op: "dequeueRaw", topic: queue });
35468
+ return res.message ?? null;
35469
+ }
35470
+ /** Commit the record's offset so a completed job never replays (ADR-0022 d.4). */
35471
+ complete(queue, id) {
35472
+ this.request({ op: "complete", topic: queue, id });
35473
+ }
35474
+ /**
35475
+ * Record a failed attempt: re-produce the job with an incremented attempts
35476
+ * count while it has retries left, else produce it to the dead-letter topic;
35477
+ * commit the original offset either way (ADR-0022 decision 2).
35478
+ */
35479
+ fail(queue, id, error2, maxRetries, _retryBackoff) {
35480
+ this.request({ op: "fail", topic: queue, id, error: error2, maxRetries });
35481
+ }
35482
+ /** Dead-letter the job now, no retry (ADR-0023 reject), then commit the offset. */
35483
+ reject(queue, id, reason, maxRetries) {
35484
+ this.request({ op: "reject", topic: queue, id, reason, maxRetries });
35485
+ }
35486
+ /** Re-produce the job (manual retry) and commit the original offset. */
35487
+ retry(queue, id, delaySeconds) {
35488
+ this.request({ op: "retry", topic: queue, id, delaySeconds: delaySeconds ?? 0 });
35489
+ return true;
35490
+ }
35491
+ /** Read the dead-letter topic for this queue (every record on it is a dead letter). */
35492
+ deadLetters(queue, _maxRetries) {
35493
+ const res = this.request({ op: "deadLetters", topic: queue });
35494
+ return res.deadLetters ?? [];
35495
+ }
35496
+ /**
35497
+ * Refuse rather than silently answer from the local file store. Kafka keeps no
35498
+ * queryable registry of failed jobs: a failed record is re-produced to a
35499
+ * dead-letter TOPIC and the original offset committed past, and a log cannot be
35500
+ * queried by job state. Returning [] would claim nothing has failed.
35501
+ */
35502
+ failed(_queue, _maxRetries) {
35503
+ throw new Error(
35504
+ "The kafka queue backend cannot answer failed(): Kafka keeps no queryable registry of failed or dead jobs. Consume the dead-letter topic directly (deadLetters()), or use the file or mongodb backend."
35505
+ );
35506
+ }
35507
+ /** Refuse for the same reason failed() does (no queryable failed registry). */
35508
+ retryFailed(_queue, _maxRetries) {
35509
+ throw new Error(
35510
+ "The kafka queue backend cannot perform retryFailed(): Kafka keeps no queryable registry of failed or dead jobs. Consume the dead-letter topic directly, or use the file or mongodb backend."
35511
+ );
35512
+ }
35513
+ size(_queue) {
35514
+ return 0;
35515
+ }
35516
+ clear(_queue) {
35517
+ throw new Error(
35518
+ "The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
35519
+ );
35520
+ }
35521
+ purge(_queue, _status) {
35522
+ throw new Error(
35523
+ "The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
35524
+ );
35525
+ }
35526
+ /** Stop the worker and release the connection. Idempotent. */
35527
+ close() {
35528
+ if (!this.worker) return;
35529
+ try {
35530
+ this.request({ op: "close" });
35531
+ } catch {
35532
+ }
35533
+ void this.worker.terminate();
35534
+ this.worker = null;
35535
+ this.sab = null;
35536
+ this.header = null;
35537
+ this.outBytes = null;
35538
+ }
35539
+ };
35540
+ }
35541
+ });
35542
+
34596
35543
  // ../core/src/job.ts
34597
35544
  function createJob(data, queue) {
34598
35545
  const job = {
@@ -34645,7 +35592,7 @@ var init_job = __esm({
34645
35592
  // ../core/src/queueBackends/liteBackend.ts
34646
35593
  import { mkdirSync as mkdirSync16, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync12, unlinkSync as unlinkSync8, existsSync as existsSync20 } from "node:fs";
34647
35594
  import { join as join25 } from "node:path";
34648
- import { randomUUID as randomUUID6 } from "node:crypto";
35595
+ import { randomUUID as randomUUID7 } from "node:crypto";
34649
35596
  var LiteBackend;
34650
35597
  var init_liteBackend = __esm({
34651
35598
  "../core/src/queueBackends/liteBackend.ts"() {
@@ -34712,7 +35659,7 @@ var init_liteBackend = __esm({
34712
35659
  );
34713
35660
  }
34714
35661
  const dir = this.ensureDir(queue);
34715
- const id = randomUUID6();
35662
+ const id = randomUUID7();
34716
35663
  const now = (/* @__PURE__ */ new Date()).toISOString();
34717
35664
  const job = {
34718
35665
  id,
@@ -35268,13 +36215,11 @@ function defaultVisibilityTimeout() {
35268
36215
  return Number.isFinite(parsed) ? parsed : 300;
35269
36216
  }
35270
36217
  function unsupportedBrokerMessage(backendName) {
35271
- const broker = backendName === "kafka" ? "Kafka" : "RabbitMQ";
35272
- const lost = backendName === "kafka" ? "every pop() re-read offset 0, so the topic could never drain" : "pop() destroyed the message with no acknowledgement, so a consumer that died lost the job";
35273
36218
  return `Queue backend "${backendName}" is not available in tina4-nodejs.
35274
36219
 
35275
- Reason: the ${broker} backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and ${lost}. It was losing work silently, so it now refuses instead.
36220
+ Reason: the RabbitMQ backend runs each operation in a separate child process, so no connection survives between pop() and complete(). Acknowledgement is therefore impossible, and pop() destroyed the message with no acknowledgement, so a consumer that died lost the job. It was losing work silently, so it now refuses instead.
35276
36221
 
35277
- Use backend "mongodb" (at-least-once, with a real reservation and visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer ${broker}.
36222
+ Use backend "kafka" (now a persistent connection: at-least-once, drains, survives restarts), "mongodb" (at-least-once, real reservation + visibility timeout) or the default "file" backend. tina4-python, tina4-php and tina4-ruby still offer RabbitMQ.
35278
36223
 
35279
36224
  Tracking: ADR-0022 in tina4-documentation/plan/v3/DECISIONS.md, findings in plan/v3/features/048-queue-backends.md.`;
35280
36225
  }
@@ -35283,6 +36228,7 @@ var init_queue = __esm({
35283
36228
  "../core/src/queue.ts"() {
35284
36229
  "use strict";
35285
36230
  init_mongoBackend();
36231
+ init_kafkaBackend();
35286
36232
  init_liteBackend();
35287
36233
  init_job();
35288
36234
  init_liteBackend();
@@ -35303,7 +36249,7 @@ var init_queue = __esm({
35303
36249
  * - new Queue("mongodb", { path: "data/queue" }) // legacy
35304
36250
  * - new Queue() // file backend, default topic
35305
36251
  *
35306
- * Throws on backend "rabbitmq" or "kafka" (ADR-0022).
36252
+ * Throws on backend "rabbitmq" (ADR-0022); "kafka" is now supported.
35307
36253
  */
35308
36254
  constructor(backendOrConfig, config) {
35309
36255
  let resolvedConfig = {};
@@ -35321,8 +36267,10 @@ var init_queue = __esm({
35321
36267
  this._retryBackoff = resolvedConfig.retryBackoff ?? 0;
35322
36268
  this._visibilityTimeout = resolvedConfig.visibilityTimeout ?? defaultVisibilityTimeout();
35323
36269
  this.liteBackend = new LiteBackend(this.basePath, this._visibilityTimeout);
35324
- if (this.backendName === "rabbitmq" || this.backendName === "kafka") {
36270
+ if (this.backendName === "rabbitmq") {
35325
36271
  throw new Error(unsupportedBrokerMessage(this.backendName));
36272
+ } else if (this.backendName === "kafka") {
36273
+ this.externalBackend = new KafkaBackend({ visibilityTimeout: this._visibilityTimeout });
35326
36274
  } else if (this.backendName === "mongodb" || this.backendName === "mongo") {
35327
36275
  this.externalBackend = new MongoBackend2({ visibilityTimeout: this._visibilityTimeout });
35328
36276
  } else if (!["file", "default", "lite"].includes(this.backendName)) {
@@ -38390,10 +39338,10 @@ function devGitStatusLabel(code) {
38390
39338
  async function devGitInfo(root) {
38391
39339
  const empty = { branch: "", gitRoot: null, status: /* @__PURE__ */ new Map() };
38392
39340
  try {
38393
- const { execFileSync: execFileSync7 } = await import("node:child_process");
39341
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
38394
39342
  const git = (args) => {
38395
39343
  try {
38396
- return execFileSync7("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
39344
+ return execFileSync6("git", args, { cwd: root, timeout: 3e3, encoding: "utf-8" }).toString();
38397
39345
  } catch {
38398
39346
  return null;
38399
39347
  }
@@ -40220,9 +41168,9 @@ var init_devAdmin = __esm({
40220
41168
  return;
40221
41169
  }
40222
41170
  try {
40223
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41171
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40224
41172
  const args = ["install", dev ? "--save-dev" : "--save", pkg];
40225
- const output = execFileSync7("npm", args, {
41173
+ const output = execFileSync6("npm", args, {
40226
41174
  cwd: resolve17(process.cwd()),
40227
41175
  timeout: 12e4,
40228
41176
  encoding: "utf-8"
@@ -40234,15 +41182,15 @@ var init_devAdmin = __esm({
40234
41182
  };
40235
41183
  handleGitStatus = async (_req, res) => {
40236
41184
  try {
40237
- const { execFileSync: execFileSync7 } = await import("node:child_process");
41185
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
40238
41186
  const cwd = resolve17(process.cwd());
40239
41187
  try {
40240
- execFileSync7("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
41188
+ execFileSync6("git", ["rev-parse", "--is-inside-work-tree"], { cwd, timeout: 3e3 });
40241
41189
  } catch {
40242
41190
  res.json({ error: "Not a git repository" }, 400);
40243
41191
  return;
40244
41192
  }
40245
- const run = (args) => execFileSync7("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
41193
+ const run = (args) => execFileSync6("git", args, { cwd, timeout: 3e3, encoding: "utf-8" }).toString().trim();
40246
41194
  res.json({
40247
41195
  branch: run(["branch", "--show-current"]),
40248
41196
  status: run(["status", "--porcelain"]).split(/\r?\n/).filter((l) => l),
@@ -40372,8 +41320,8 @@ var init_devAdmin = __esm({
40372
41320
  return;
40373
41321
  }
40374
41322
  try {
40375
- const { execFileSync: execFileSync7 } = await import("node:child_process");
40376
- const output = execFileSync7("npx", ["tina4nodejs", "generate", kind, name], {
41323
+ const { execFileSync: execFileSync6 } = await import("node:child_process");
41324
+ const output = execFileSync6("npx", ["tina4nodejs", "generate", kind, name], {
40377
41325
  cwd: resolve17(process.cwd()),
40378
41326
  timeout: 3e4,
40379
41327
  encoding: "utf-8"
@@ -40819,6 +41767,359 @@ var init_background = __esm({
40819
41767
  }
40820
41768
  });
40821
41769
 
41770
+ // ../core/src/tcp.ts
41771
+ import { createServer as createServer3 } from "node:net";
41772
+ function resolveMaxBacklog(explicit) {
41773
+ if (explicit !== void 0) return explicit > 0 ? explicit : DEFAULT_MAX_BACKLOG;
41774
+ const raw = (process.env.TINA4_TCP_MAX_BACKLOG ?? "").trim();
41775
+ if (raw === "") return DEFAULT_MAX_BACKLOG;
41776
+ const value = Number.parseInt(raw, 10);
41777
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_BACKLOG;
41778
+ }
41779
+ function tcpService(port, options = {}) {
41780
+ const service = new TcpService(port, options);
41781
+ services.set(service.name, service);
41782
+ return service;
41783
+ }
41784
+ function tcp(name = "default") {
41785
+ const service = services.get(name);
41786
+ if (!service) {
41787
+ const known = services.size === 0 ? "(none registered)" : [...services.keys()].join(", ");
41788
+ throw new Error(`no tcp_service named '${name}' is registered; known services: ${known}`);
41789
+ }
41790
+ return service;
41791
+ }
41792
+ function registeredTcpServices() {
41793
+ return [...services.values()];
41794
+ }
41795
+ function clearTcpRegistry() {
41796
+ services.clear();
41797
+ }
41798
+ async function startAllTcpServices(host = "0.0.0.0") {
41799
+ for (const service of registeredTcpServices()) {
41800
+ try {
41801
+ await service.start(host);
41802
+ } catch (error2) {
41803
+ Log.error(`tcp_service '${service.name}' failed to start: ${String(error2)}`);
41804
+ }
41805
+ }
41806
+ }
41807
+ function stopAcceptingAllTcpServices() {
41808
+ for (const service of registeredTcpServices()) {
41809
+ try {
41810
+ service.stopAccepting();
41811
+ } catch (error2) {
41812
+ Log.error(`tcp_service '${service.name}' stop-accepting failed: ${String(error2)}`);
41813
+ }
41814
+ }
41815
+ }
41816
+ async function drainAllTcpServices() {
41817
+ for (const service of registeredTcpServices()) {
41818
+ try {
41819
+ await service.drain();
41820
+ } catch (error2) {
41821
+ Log.error(`tcp_service '${service.name}' drain failed: ${String(error2)}`);
41822
+ }
41823
+ }
41824
+ }
41825
+ var DEFAULT_MAX_BACKLOG, TcpConnection, TcpService, services;
41826
+ var init_tcp = __esm({
41827
+ "../core/src/tcp.ts"() {
41828
+ "use strict";
41829
+ init_logger();
41830
+ DEFAULT_MAX_BACKLOG = 1 << 20;
41831
+ TcpConnection = class {
41832
+ constructor(socket, service) {
41833
+ this.socket = socket;
41834
+ this.service = service;
41835
+ this.remoteAddr = `${socket.remoteAddress ?? ""}:${socket.remotePort ?? 0}`;
41836
+ }
41837
+ socket;
41838
+ service;
41839
+ /** The registry id (the IMEI), or null until identify() is called. */
41840
+ id = null;
41841
+ /** Per-connection mutable state bag — the app's parse buffer, auth flag. */
41842
+ context = {};
41843
+ /** The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header. */
41844
+ remoteAddr;
41845
+ lastActivity = Date.now();
41846
+ lineBuffer = Buffer.alloc(0);
41847
+ closed = false;
41848
+ closeFired = false;
41849
+ get isClosed() {
41850
+ return this.closed;
41851
+ }
41852
+ /**
41853
+ * Register this live connection under an app-chosen id (the IMEI). A second
41854
+ * connection identifying with the same id SUPERSEDES the first in the
41855
+ * registry — exactly a device that dropped and reconnected.
41856
+ */
41857
+ identify(appId) {
41858
+ this.id = String(appId);
41859
+ this.service._registerId(this.id, this);
41860
+ return this;
41861
+ }
41862
+ /**
41863
+ * Write raw bytes to THIS socket. Returns true when queued/sent, false when
41864
+ * the connection is closed or dropped for backpressure. A stalled reader
41865
+ * (never draining) is bounded: once more than the service's maxBacklog bytes
41866
+ * are outstanding, the connection is dropped rather than buffered without end
41867
+ * (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
41868
+ */
41869
+ send(data) {
41870
+ if (this.closed) return false;
41871
+ const buffer = typeof data === "string" ? Buffer.from(data) : data;
41872
+ this.socket.write(buffer);
41873
+ if (this.socket.writableLength > this.service.maxBacklog) {
41874
+ Log.warning(
41875
+ `tcp_service '${this.service.name}': dropping a stalled reader \u2014 ${this.socket.writableLength} bytes queued exceeds the ${this.service.maxBacklog}-byte backlog limit`
41876
+ );
41877
+ this.close();
41878
+ return false;
41879
+ }
41880
+ return true;
41881
+ }
41882
+ /**
41883
+ * Close this connection. on_close fires exactly once (from the socket's close
41884
+ * event) and the registry entry is removed.
41885
+ */
41886
+ close() {
41887
+ if (this.closed) return;
41888
+ this.closed = true;
41889
+ try {
41890
+ this.socket.end(() => this.socket.destroy());
41891
+ } catch {
41892
+ this.socket.destroy();
41893
+ }
41894
+ }
41895
+ /** @internal mark activity for the idle reaper. */
41896
+ _touch() {
41897
+ this.lastActivity = Date.now();
41898
+ }
41899
+ /** @internal fire on_close exactly once (called from the service removal path). */
41900
+ _fireClose() {
41901
+ if (this.closeFired) return;
41902
+ this.closeFired = true;
41903
+ this.closed = true;
41904
+ const handler = this.service._callbacks.onClose;
41905
+ if (!handler) return;
41906
+ try {
41907
+ void Promise.resolve(handler(this)).catch((error2) => {
41908
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41909
+ });
41910
+ } catch (error2) {
41911
+ Log.error(`tcp_service '${this.service.name}' onClose error: ${String(error2)}`);
41912
+ }
41913
+ }
41914
+ };
41915
+ TcpService = class {
41916
+ name;
41917
+ port;
41918
+ maxBacklog;
41919
+ /** @internal the callback bag, read by TcpConnection. */
41920
+ _callbacks;
41921
+ idleTimeout;
41922
+ maxConnections;
41923
+ connections = /* @__PURE__ */ new Set();
41924
+ byId = /* @__PURE__ */ new Map();
41925
+ server = null;
41926
+ owner = false;
41927
+ boundPortValue = null;
41928
+ reaper = null;
41929
+ constructor(port, options = {}) {
41930
+ this.port = port;
41931
+ this.name = options.name ?? "default";
41932
+ this._callbacks = {
41933
+ onConnect: options.onConnect,
41934
+ onData: options.onData,
41935
+ onClose: options.onClose,
41936
+ onLine: options.onLine
41937
+ };
41938
+ this.idleTimeout = options.idleTimeout ?? 0;
41939
+ this.maxConnections = options.maxConnections ?? null;
41940
+ this.maxBacklog = resolveMaxBacklog(options.maxBacklog);
41941
+ }
41942
+ get isOwner() {
41943
+ return this.owner;
41944
+ }
41945
+ /** The port actually bound (resolves an ephemeral port=0 to the real one). */
41946
+ get boundPort() {
41947
+ return this.boundPortValue ?? this.port;
41948
+ }
41949
+ count() {
41950
+ return this.connections.size;
41951
+ }
41952
+ // ── Registry (D4 — server -> device push) ──────────────────────────────────
41953
+ /** @internal */
41954
+ _registerId(appId, conn) {
41955
+ this.byId.set(appId, conn);
41956
+ }
41957
+ /** The live connection for an app id, or null if unknown or closed. */
41958
+ connection(appId) {
41959
+ const conn = this.byId.get(String(appId));
41960
+ if (!conn || conn.isClosed) return null;
41961
+ return conn;
41962
+ }
41963
+ /**
41964
+ * Write bytes to exactly the connection identified by appId. A send to an
41965
+ * unknown or closed id is a NO-OP that returns false — never a throw.
41966
+ */
41967
+ sendTo(appId, data) {
41968
+ const conn = this.connection(appId);
41969
+ if (!conn) return false;
41970
+ return conn.send(data);
41971
+ }
41972
+ /** Write bytes to every live connection. Returns how many received it. */
41973
+ broadcast(data) {
41974
+ let delivered = 0;
41975
+ for (const conn of [...this.connections]) {
41976
+ if (conn.send(data)) delivered += 1;
41977
+ }
41978
+ return delivered;
41979
+ }
41980
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
41981
+ /**
41982
+ * Bind the listener on host:port on the event loop. SO_REUSEPORT is OFF, so
41983
+ * under a multi-worker deployment exactly ONE worker wins the bind; a worker
41984
+ * that finds the port already bound skips silently (single-owner, D1).
41985
+ * Resolves true when THIS call bound the port.
41986
+ */
41987
+ start(host = "0.0.0.0") {
41988
+ if (this.server) return Promise.resolve(this.owner);
41989
+ return new Promise((resolve29) => {
41990
+ const server = createServer3((socket) => this.handleConnection(socket));
41991
+ this.server = server;
41992
+ const onError = (error2) => {
41993
+ if (error2.code === "EADDRINUSE" || error2.code === "EADDRNOTAVAIL") {
41994
+ this.owner = false;
41995
+ this.server = null;
41996
+ Log.info(
41997
+ `tcp_service '${this.name}' port ${this.port} is already bound by another worker \u2014 single-owner, this worker will not bind (${error2.code})`
41998
+ );
41999
+ resolve29(false);
42000
+ return;
42001
+ }
42002
+ Log.error(`tcp_service '${this.name}' failed to start: ${error2.message}`);
42003
+ this.server = null;
42004
+ resolve29(false);
42005
+ };
42006
+ server.once("error", onError);
42007
+ server.listen(this.port, host, () => {
42008
+ server.off("error", onError);
42009
+ server.on("error", (error2) => Log.error(`tcp_service '${this.name}' error: ${String(error2)}`));
42010
+ this.owner = true;
42011
+ const addr = server.address();
42012
+ this.boundPortValue = typeof addr === "object" && addr ? addr.port : this.port;
42013
+ Log.info(`tcp_service '${this.name}' listening on ${host}:${this.boundPortValue}`);
42014
+ this.startReaper();
42015
+ resolve29(true);
42016
+ });
42017
+ });
42018
+ }
42019
+ handleConnection(socket) {
42020
+ if (this.maxConnections !== null && this.connections.size >= this.maxConnections) {
42021
+ socket.destroy();
42022
+ return;
42023
+ }
42024
+ const conn = new TcpConnection(socket, this);
42025
+ this.connections.add(conn);
42026
+ socket.on("data", (chunk) => {
42027
+ socket.pause();
42028
+ void this.dispatch(conn, chunk).finally(() => {
42029
+ if (!conn.isClosed) socket.resume();
42030
+ });
42031
+ });
42032
+ socket.on("close", () => this.remove(conn));
42033
+ socket.on("error", () => {
42034
+ });
42035
+ const onConnect = this._callbacks.onConnect;
42036
+ if (onConnect) {
42037
+ void Promise.resolve(onConnect(conn)).catch((error2) => {
42038
+ Log.error(`tcp_service '${this.name}' onConnect error: ${String(error2)}`);
42039
+ });
42040
+ }
42041
+ }
42042
+ async dispatch(conn, chunk) {
42043
+ conn._touch();
42044
+ const { onData, onLine } = this._callbacks;
42045
+ if (onData) {
42046
+ try {
42047
+ await onData(conn, chunk);
42048
+ } catch (error2) {
42049
+ Log.error(`tcp_service '${this.name}' onData error: ${String(error2)}`);
42050
+ }
42051
+ }
42052
+ if (onLine) {
42053
+ conn.lineBuffer = Buffer.concat([conn.lineBuffer, chunk]);
42054
+ let newline = conn.lineBuffer.indexOf(10);
42055
+ while (newline !== -1) {
42056
+ let line = conn.lineBuffer.subarray(0, newline);
42057
+ conn.lineBuffer = conn.lineBuffer.subarray(newline + 1);
42058
+ if (line.length > 0 && line[line.length - 1] === 13) {
42059
+ line = line.subarray(0, line.length - 1);
42060
+ }
42061
+ try {
42062
+ await onLine(conn, line);
42063
+ } catch (error2) {
42064
+ Log.error(`tcp_service '${this.name}' onLine error: ${String(error2)}`);
42065
+ }
42066
+ newline = conn.lineBuffer.indexOf(10);
42067
+ }
42068
+ }
42069
+ }
42070
+ /** @internal remove a connection and fire on_close exactly once. */
42071
+ remove(conn) {
42072
+ const existed = this.connections.delete(conn);
42073
+ if (conn.id !== null && this.byId.get(conn.id) === conn) {
42074
+ this.byId.delete(conn.id);
42075
+ }
42076
+ if (existed) conn._fireClose();
42077
+ }
42078
+ // ── Idle reaper (D1 consumer shape — default OFF) ───────────────────────────
42079
+ startReaper() {
42080
+ if (this.idleTimeout <= 0 || this.reaper) return;
42081
+ const intervalMs = Math.max(50, Math.min(1e3, this.idleTimeout / 2 * 1e3));
42082
+ this.reaper = setInterval(() => this.reapIdle(), intervalMs);
42083
+ this.reaper.unref();
42084
+ }
42085
+ reapIdle() {
42086
+ const now = Date.now();
42087
+ const limitMs = this.idleTimeout * 1e3;
42088
+ for (const conn of [...this.connections]) {
42089
+ if (now - conn.lastActivity >= limitMs) conn.close();
42090
+ }
42091
+ }
42092
+ /** Stop accepting new connections (close the listener). Live conns stay. */
42093
+ stopAccepting() {
42094
+ if (this.reaper) {
42095
+ clearInterval(this.reaper);
42096
+ this.reaper = null;
42097
+ }
42098
+ if (this.server && this.owner) {
42099
+ this.server.close();
42100
+ }
42101
+ }
42102
+ /** Close every live connection (firing on_close) and release the listener. */
42103
+ async drain() {
42104
+ this.stopAccepting();
42105
+ for (const conn of [...this.connections]) conn.close();
42106
+ if (this.server) {
42107
+ await new Promise((resolve29) => {
42108
+ this.server.close(() => resolve29());
42109
+ this.server.unref();
42110
+ }).catch(() => void 0);
42111
+ this.server = null;
42112
+ }
42113
+ }
42114
+ /** Stop accepting and drain in one call (used by direct callers/tests). */
42115
+ async stop() {
42116
+ await this.drain();
42117
+ }
42118
+ };
42119
+ services = /* @__PURE__ */ new Map();
42120
+ }
42121
+ });
42122
+
40822
42123
  // ../core/src/events.ts
40823
42124
  var events_exports = {};
40824
42125
  __export(events_exports, {
@@ -42471,6 +43772,12 @@ async function invokeRouteHandler(match, req2, res) {
42471
43772
  if (args.length === 0) return await match.handler();
42472
43773
  return await match.handler(...args);
42473
43774
  }
43775
+ function coerceHandlerResult(res, result) {
43776
+ if (res.raw.writableEnded || res.raw.headersSent) return;
43777
+ if (result === void 0 || result === null) return;
43778
+ if (result === res) return;
43779
+ res(result);
43780
+ }
42474
43781
  async function renderIfTemplateRoute(match, res, result) {
42475
43782
  if (res.raw.writableEnded) return;
42476
43783
  if (!match.template) return;
@@ -42490,7 +43797,9 @@ async function runMatchedRoute(ctx) {
42490
43797
  handlerSkipped = !proceed || res.raw.writableEnded;
42491
43798
  }
42492
43799
  if (!handlerSkipped) {
42493
- await renderIfTemplateRoute(match, res, await invokeRouteHandler(match, req2, res));
43800
+ const result = await invokeRouteHandler(match, req2, res);
43801
+ await renderIfTemplateRoute(match, res, result);
43802
+ coerceHandlerResult(res, result);
42494
43803
  }
42495
43804
  const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
42496
43805
  if (afterMiddleware.length > 0) {
@@ -43027,7 +44336,7 @@ async function startServer(config) {
43027
44336
  server.on("upgrade", (req2, socket, head) => {
43028
44337
  const upPath = (req2.url ?? "/").split("?")[0];
43029
44338
  if (isDevMode() && upPath === "/__dev_reload") {
43030
- if (!devHostAllowed(req2.headers.host)) {
44339
+ if (!devHostAllowed(req2.headers.host) || !devPeerAllowed(socket.remoteAddress)) {
43031
44340
  try {
43032
44341
  socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
43033
44342
  socket.destroy();
@@ -43051,6 +44360,7 @@ async function startServer(config) {
43051
44360
  server.listen(port, host, async () => {
43052
44361
  if (!cluster.isWorker) writePidfile(port);
43053
44362
  const siblingServers = await startLoopbackSiblings(port, host, dispatch);
44363
+ await startAllTcpServices(host);
43054
44364
  const displayHost = host === "0.0.0.0" ? "localhost" : host;
43055
44365
  const isDebug = isTruthy(process.env.TINA4_DEBUG);
43056
44366
  const logLevel = (process.env.TINA4_LOG_LEVEL ?? "DEBUG").toUpperCase();
@@ -43141,6 +44451,8 @@ ${reset2}
43141
44451
  if (wsClosed > 0) {
43142
44452
  Log.info(`Closed ${wsClosed} WebSocket connection(s) with 1001 going away`);
43143
44453
  }
44454
+ stopAcceptingAllTcpServices();
44455
+ await drainAllTcpServices();
43144
44456
  const budgetSeconds = shutdownTimeoutSeconds();
43145
44457
  let timer;
43146
44458
  const outcome = await Promise.race([
@@ -43183,6 +44495,8 @@ ${reset2}
43183
44495
  process.off("SIGTERM", onSigterm);
43184
44496
  process.off("SIGINT", onSigint);
43185
44497
  stopAllBackgroundTasks();
44498
+ stopAcceptingAllTcpServices();
44499
+ void drainAllTcpServices();
43186
44500
  if (aiServer) aiServer.close();
43187
44501
  server.close();
43188
44502
  for (const sibling of siblingServers) {
@@ -43311,6 +44625,7 @@ var init_server = __esm({
43311
44625
  init_feedback();
43312
44626
  init_i18n();
43313
44627
  init_background();
44628
+ init_tcp();
43314
44629
  init_version();
43315
44630
  __filename = fileURLToPath9(import.meta.url);
43316
44631
  __dirname = dirname16(__filename);
@@ -45669,7 +46984,7 @@ import net4 from "node:net";
45669
46984
  import tls2 from "node:tls";
45670
46985
  import { readFileSync as readFileSync25 } from "node:fs";
45671
46986
  import { basename as basename8 } from "node:path";
45672
- import { randomUUID as randomUUID7 } from "node:crypto";
46987
+ import { randomUUID as randomUUID8 } from "node:crypto";
45673
46988
  function normaliseEncryption(value, kind) {
45674
46989
  const normalised = value.trim().toLowerCase();
45675
46990
  if (!MAIL_ENCRYPTION_VALUES.includes(normalised)) {
@@ -46301,7 +47616,7 @@ var init_messenger = __esm({
46301
47616
  );
46302
47617
  }
46303
47618
  const recipients = this.prepareRecipients(options, true);
46304
- const messageId = `${randomUUID7()}@${this.host}`;
47619
+ const messageId = `${randomUUID8()}@${this.host}`;
46305
47620
  if (recipients.allRecipients.length === 0) {
46306
47621
  return { success: false, message: "No recipients specified", id: null };
46307
47622
  }
@@ -49161,7 +50476,7 @@ var init_aiClient = __esm({
49161
50476
 
49162
50477
  // ../core/src/queueBackends/rabbitmqBackend.ts
49163
50478
  import { execFileSync as execFileSync5 } from "node:child_process";
49164
- import { randomUUID as randomUUID8 } from "node:crypto";
50479
+ import { randomUUID as randomUUID9 } from "node:crypto";
49165
50480
  function parseAmqpUrl(url) {
49166
50481
  const config = {};
49167
50482
  let rest = url.replace(/^amqps:\/\//, "").replace(/^amqp:\/\//, "");
@@ -49597,7 +50912,7 @@ var init_rabbitmqBackend = __esm({
49597
50912
  "The rabbitmq queue backend cannot honour push(raw=true): raw emits the message with no Tina4 envelope, which only a message bus consumed by non-Tina4 systems (Kafka) needs. This backend stores an internal envelope (payload/priority/attempts) that pop(), the retry lifecycle and dead-lettering depend on, so there is nothing to omit. Use the kafka backend for raw external messages."
49598
50913
  );
49599
50914
  }
49600
- const id = randomUUID8();
50915
+ const id = randomUUID9();
49601
50916
  const now = (/* @__PURE__ */ new Date()).toISOString();
49602
50917
  const job = {
49603
50918
  id,
@@ -49641,586 +50956,6 @@ var init_rabbitmqBackend = __esm({
49641
50956
  }
49642
50957
  });
49643
50958
 
49644
- // ../core/src/queueBackends/kafkaBackend.ts
49645
- import { execFileSync as execFileSync6 } from "node:child_process";
49646
- import { randomUUID as randomUUID9 } from "node:crypto";
49647
- function kafkaSecurityConfig(env = process.env) {
49648
- const mapping = [
49649
- ["security.protocol", "SECURITY_PROTOCOL"],
49650
- ["ssl.ca.location", "SSL_CA_LOCATION"],
49651
- ["sasl.mechanism", "SASL_MECHANISM"],
49652
- ["sasl.username", "SASL_USERNAME"],
49653
- ["sasl.password", "SASL_PASSWORD"]
49654
- ];
49655
- const config = {};
49656
- for (const [rdk, suffix] of mapping) {
49657
- const value = env[`TINA4_KAFKA_${suffix}`] || env[`KAFKA_${suffix}`];
49658
- if (value) {
49659
- config[rdk] = value;
49660
- }
49661
- }
49662
- return config;
49663
- }
49664
- function kafkaOffsetReset(env = process.env) {
49665
- return env.TINA4_KAFKA_AUTO_OFFSET_RESET || env.KAFKA_AUTO_OFFSET_RESET || "earliest";
49666
- }
49667
- var API_PRODUCE, API_FETCH, KafkaBackend;
49668
- var init_kafkaBackend = __esm({
49669
- "../core/src/queueBackends/kafkaBackend.ts"() {
49670
- "use strict";
49671
- API_PRODUCE = 0;
49672
- API_FETCH = 1;
49673
- KafkaBackend = class _KafkaBackend {
49674
- brokers;
49675
- groupId;
49676
- constructor(config) {
49677
- const url = process.env.TINA4_QUEUE_URL;
49678
- const fromUrl = url ? url.replace(/^kafka:\/\//, "") : void 0;
49679
- this.brokers = config?.brokers ?? process.env.TINA4_KAFKA_BROKERS ?? fromUrl ?? "localhost:9092";
49680
- this.groupId = config?.groupId ?? process.env.TINA4_KAFKA_GROUP_ID ?? "tina4_consumer_group";
49681
- }
49682
- /**
49683
- * Resolved connection config — exposed for testing/introspection.
49684
- */
49685
- getConfig() {
49686
- return { brokers: this.brokers, groupId: this.groupId };
49687
- }
49688
- /**
49689
- * Resolved SSL/SASL client config from the environment (PLAINTEXT default).
49690
- * Mirrors Python's `KafkaConnector._security_config`.
49691
- */
49692
- securityConfig() {
49693
- return kafkaSecurityConfig();
49694
- }
49695
- /**
49696
- * Full producer config — brokers + client id + the resolved security block.
49697
- * The security keys are applied to BOTH producer and consumer (matching
49698
- * Python's `_connect_confluent`).
49699
- */
49700
- producerConfig() {
49701
- return {
49702
- "bootstrap.servers": this.brokers,
49703
- "client.id": "tina4-nodejs",
49704
- ...this.securityConfig()
49705
- };
49706
- }
49707
- /**
49708
- * Full consumer config — brokers + client id + group id + the SAME resolved
49709
- * security block applied to the producer.
49710
- */
49711
- consumerConfig() {
49712
- return {
49713
- "bootstrap.servers": this.brokers,
49714
- "client.id": "tina4-nodejs",
49715
- "group.id": this.groupId,
49716
- "auto.offset.reset": kafkaOffsetReset(),
49717
- "enable.auto.commit": false,
49718
- ...this.securityConfig()
49719
- };
49720
- }
49721
- /**
49722
- * Parse broker string into host:port.
49723
- */
49724
- parseBroker() {
49725
- const parts = this.brokers.split(",")[0].trim().split(":");
49726
- return {
49727
- host: parts[0] ?? "localhost",
49728
- port: parts[1] ? parseInt(parts[1], 10) : 9092
49729
- };
49730
- }
49731
- /**
49732
- * Execute a Kafka operation synchronously via a child process.
49733
- *
49734
- * The wire protocol is hand-rolled (Tina4 is zero-dependency — no npm Kafka
49735
- * library). Produce uses Produce **v3** carrying a Kafka **v2 RecordBatch**
49736
- * (magic byte 2) with a **CRC-32C** (Castagnoli) checksum; Fetch uses Fetch
49737
- * **v4** and parses the v2 RecordBatch out of the response. Both formats are
49738
- * what a modern KRaft broker (apache/kafka 3.7.0) requires — the old
49739
- * Produce-v0 / message-format-v0 / CRC=0 batch is rejected by such brokers.
49740
- */
49741
- execSync(operation, topic, data) {
49742
- const broker = this.parseBroker();
49743
- const script = `
49744
- const net = require("node:net");
49745
- const host = ${JSON.stringify(broker.host)};
49746
- const port = ${broker.port};
49747
- const operation = ${JSON.stringify(operation)};
49748
- const topic = ${JSON.stringify(topic)};
49749
- const groupId = ${JSON.stringify(this.groupId)};
49750
- const data = ${JSON.stringify(data ?? "")};
49751
- const API_PRODUCE = ${API_PRODUCE};
49752
- const API_FETCH = ${API_FETCH};
49753
- const PRODUCE_VERSION = 3; // v3+ requires the v2 RecordBatch format
49754
- const FETCH_VERSION = 4; // v4 returns v2 RecordBatches + isolation_level
49755
- let correlationId = 0;
49756
-
49757
- // \u2500\u2500 CRC-32C (Castagnoli, polynomial 0x1EDC6F41), table-based \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49758
- // Node has no built-in CRC-32C; the v2 RecordBatch mandates it over the
49759
- // bytes from \`attributes\` to the end of the batch. A wrong CRC makes the
49760
- // broker drop the connection, so this must be exact.
49761
- const CRC32C_TABLE = (() => {
49762
- const table = new Uint32Array(256);
49763
- for (let n = 0; n < 256; n++) {
49764
- let c = n;
49765
- for (let k = 0; k < 8; k++) {
49766
- c = (c & 1) ? (0x82f63b78 ^ (c >>> 1)) : (c >>> 1);
49767
- }
49768
- table[n] = c >>> 0;
49769
- }
49770
- return table;
49771
- })();
49772
- function crc32c(buf) {
49773
- let crc = 0xffffffff;
49774
- for (let i = 0; i < buf.length; i++) {
49775
- crc = (CRC32C_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8)) >>> 0;
49776
- }
49777
- return (crc ^ 0xffffffff) >>> 0;
49778
- }
49779
-
49780
- // \u2500\u2500 Kafka protocol varints (zigzag-encoded signed varints) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
49781
- function encodeZigZag(n) {
49782
- // 32-bit zigzag: (n << 1) ^ (n >> 31)
49783
- return ((n << 1) ^ (n >> 31)) >>> 0;
49784
- }
49785
- function encodeVarintUnsigned(u) {
49786
- const bytes = [];
49787
- let v = u >>> 0;
49788
- while (true) {
49789
- if ((v & ~0x7f) === 0) { bytes.push(v); break; }
49790
- bytes.push((v & 0x7f) | 0x80);
49791
- v >>>= 7;
49792
- }
49793
- return Buffer.from(bytes);
49794
- }
49795
- function encodeVarint(n) {
49796
- // signed varint = zigzag then unsigned-varint
49797
- return encodeVarintUnsigned(encodeZigZag(n));
49798
- }
49799
- function decodeVarint(buf, pos) {
49800
- // returns { value, next } \u2014 signed (zigzag-decoded)
49801
- let result = 0, shift = 0, b;
49802
- do {
49803
- b = buf[pos++];
49804
- result |= (b & 0x7f) << shift;
49805
- shift += 7;
49806
- } while (b & 0x80);
49807
- result = result >>> 0;
49808
- // zigzag decode
49809
- const value = (result >>> 1) ^ -(result & 1);
49810
- return { value, next: pos };
49811
- }
49812
-
49813
- // \u2500\u2500 v2 RecordBatch builder \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
49814
- function buildRecordBatch(valueBytes) {
49815
- const now = BigInt(Date.now());
49816
-
49817
- // Build the single record body.
49818
- // record = attributes:int8(0), timestampDelta:varint(0),
49819
- // offsetDelta:varint(0), keyLen:varint(-1 null),
49820
- // valueLen:varint(len), value, headerCount:varint(0)
49821
- const recBody = Buffer.concat([
49822
- Buffer.from([0]), // attributes (int8)
49823
- encodeVarint(0), // timestampDelta
49824
- encodeVarint(0), // offsetDelta
49825
- encodeVarint(-1), // keyLen (-1 = null key)
49826
- encodeVarint(valueBytes.length), // valueLen
49827
- valueBytes, // value (JSON payload bytes)
49828
- encodeVarint(0), // headerCount
49829
- ]);
49830
- // record length prefix = signed varint of recBody length
49831
- const record = Buffer.concat([encodeVarint(recBody.length), recBody]);
49832
- const recordsCount = 1;
49833
-
49834
- // The portion the CRC covers starts at \`attributes\` and runs to end.
49835
- // crcBody = attributes:int16(0), lastOffsetDelta:int32(count-1),
49836
- // firstTimestamp:int64, maxTimestamp:int64,
49837
- // producerId:int64(-1), producerEpoch:int16(-1),
49838
- // baseSequence:int32(-1), recordsCount:int32, records
49839
- const crcBody = Buffer.alloc(2 + 4 + 8 + 8 + 8 + 2 + 4 + 4 + record.length);
49840
- let c = 0;
49841
- crcBody.writeInt16BE(0, c); c += 2; // attributes
49842
- crcBody.writeInt32BE(recordsCount - 1, c); c += 4; // lastOffsetDelta
49843
- crcBody.writeBigInt64BE(now, c); c += 8; // firstTimestamp
49844
- crcBody.writeBigInt64BE(now, c); c += 8; // maxTimestamp
49845
- crcBody.writeBigInt64BE(-1n, c); c += 8; // producerId
49846
- crcBody.writeInt16BE(-1, c); c += 2; // producerEpoch
49847
- crcBody.writeInt32BE(-1, c); c += 4; // baseSequence
49848
- crcBody.writeInt32BE(recordsCount, c); c += 4; // recordsCount
49849
- record.copy(crcBody, c);
49850
-
49851
- const crc = crc32c(crcBody);
49852
-
49853
- // Header before the CRC-covered region:
49854
- // baseOffset:int64(0), batchLength:int32, partitionLeaderEpoch:int32(-1),
49855
- // magic:int8(2), crc:uint32. batchLength counts everything AFTER itself
49856
- // (partitionLeaderEpoch through end of records) = 4 + 1 + 4 + crcBody.
49857
- const batchLength = 4 + 1 + 4 + crcBody.length;
49858
- const head = Buffer.alloc(8 + 4 + 4 + 1 + 4);
49859
- let h = 0;
49860
- head.writeBigInt64BE(0n, h); h += 8; // baseOffset
49861
- head.writeInt32BE(batchLength, h); h += 4; // batchLength
49862
- head.writeInt32BE(-1, h); h += 4; // partitionLeaderEpoch
49863
- head.writeInt8(2, h); h += 1; // magic = 2
49864
- head.writeUInt32BE(crc, h); h += 4; // crc (CRC-32C)
49865
-
49866
- return Buffer.concat([head, crcBody]);
49867
- }
49868
-
49869
- // \u2500\u2500 Produce v3 request \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
49870
- function buildProduceRequest(topicName, valueBytes) {
49871
- correlationId++;
49872
- const clientBuf = Buffer.from("tina4", "utf-8");
49873
- const topicBuf = Buffer.from(topicName, "utf-8");
49874
- const recordBatch = buildRecordBatch(valueBytes);
49875
-
49876
- const body = Buffer.alloc(
49877
- 2 + // transactionalId (-1 null nullable_string)
49878
- 2 + // acks
49879
- 4 + // timeoutMs
49880
- 4 + // topics array count
49881
- 2 + topicBuf.length + // topic name
49882
- 4 + // partitions array count
49883
- 4 + // partition index
49884
- 4 + recordBatch.length // recordSetBytes (int32 size) + batch
49885
- );
49886
- let p = 0;
49887
- body.writeInt16BE(-1, p); p += 2; // transactionalId = null
49888
- body.writeInt16BE(1, p); p += 2; // acks = 1
49889
- body.writeInt32BE(10000, p); p += 4; // timeoutMs
49890
- body.writeInt32BE(1, p); p += 4; // topics count
49891
- body.writeInt16BE(topicBuf.length, p); p += 2;
49892
- topicBuf.copy(body, p); p += topicBuf.length;
49893
- body.writeInt32BE(1, p); p += 4; // partitions count
49894
- body.writeInt32BE(0, p); p += 4; // partition index 0
49895
- body.writeInt32BE(recordBatch.length, p); p += 4; // recordSetBytes size
49896
- recordBatch.copy(body, p);
49897
-
49898
- return frameRequest(API_PRODUCE, PRODUCE_VERSION, clientBuf, body);
49899
- }
49900
-
49901
- // \u2500\u2500 Fetch v4 request \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
49902
- function buildFetchRequest(topicName, fetchOffset) {
49903
- correlationId++;
49904
- const clientBuf = Buffer.from("tina4", "utf-8");
49905
- const topicBuf = Buffer.from(topicName, "utf-8");
49906
-
49907
- // Fetch v4 request body (NO logStartOffset \u2014 that arrives in v5+):
49908
- // replicaId(4), maxWaitMs(4), minBytes(4), maxBytes(4 v3+),
49909
- // isolationLevel(1 v4+), topics[count]: name, partitions[count]:
49910
- // partition(4), fetchOffset(8), partitionMaxBytes(4).
49911
- const buf = Buffer.alloc(4 + 4 + 4 + 4 + 1 + 4 + (2 + topicBuf.length) + 4 + 4 + 8 + 4);
49912
- let p = 0;
49913
- buf.writeInt32BE(-1, p); p += 4; // replicaId (-1 consumer)
49914
- buf.writeInt32BE(1000, p); p += 4; // maxWaitMs
49915
- buf.writeInt32BE(1, p); p += 4; // minBytes
49916
- buf.writeInt32BE(1048576, p); p += 4; // maxBytes
49917
- buf.writeInt8(0, p); p += 1; // isolationLevel = READ_UNCOMMITTED
49918
- buf.writeInt32BE(1, p); p += 4; // topics count
49919
- buf.writeInt16BE(topicBuf.length, p); p += 2;
49920
- topicBuf.copy(buf, p); p += topicBuf.length;
49921
- buf.writeInt32BE(1, p); p += 4; // partitions count
49922
- buf.writeInt32BE(0, p); p += 4; // partition 0
49923
- buf.writeBigInt64BE(BigInt(fetchOffset), p); p += 8; // fetchOffset
49924
- buf.writeInt32BE(1048576, p); p += 4; // partitionMaxBytes
49925
-
49926
- return frameRequest(API_FETCH, FETCH_VERSION, clientBuf, buf);
49927
- }
49928
-
49929
- // Frame a request with header v1: apiKey, apiVersion, correlationId,
49930
- // clientId (nullable string) + body.
49931
- function frameRequest(apiKey, apiVersion, clientBuf, body) {
49932
- const header = Buffer.alloc(2 + 2 + 4 + 2 + clientBuf.length);
49933
- let p = 0;
49934
- header.writeInt16BE(apiKey, p); p += 2;
49935
- header.writeInt16BE(apiVersion, p); p += 2;
49936
- header.writeInt32BE(correlationId, p); p += 4;
49937
- header.writeInt16BE(clientBuf.length, p); p += 2;
49938
- clientBuf.copy(header, p);
49939
- const payload = Buffer.concat([header, body]);
49940
- const framed = Buffer.alloc(4 + payload.length);
49941
- framed.writeInt32BE(payload.length, 0);
49942
- payload.copy(framed, 4);
49943
- return framed;
49944
- }
49945
-
49946
- // \u2500\u2500 Parse a v2 RecordBatch region, return the FIRST record value \u2500\u2500\u2500\u2500\u2500\u2500\u2500
49947
- // \`buf\` is the whole fetch response; [start, end) bounds the partition's
49948
- // record-set bytes (may contain one or more concatenated batches).
49949
- function firstRecordValue(buf, start, end) {
49950
- let pos = start;
49951
- while (pos + 12 <= end) {
49952
- // baseOffset(8) + batchLength(4) then batchLength bytes follow.
49953
- const batchLength = buf.readInt32BE(pos + 8);
49954
- const batchStart = pos + 12; // first byte of partitionLeaderEpoch
49955
- const batchEnd = batchStart + batchLength;
49956
- if (batchLength <= 0 || batchEnd > end) break;
49957
- // partitionLeaderEpoch(4), magic(1), crc(4), attributes(2),
49958
- // lastOffsetDelta(4), firstTimestamp(8), maxTimestamp(8),
49959
- // producerId(8), producerEpoch(2), baseSequence(4), recordsCount(4)
49960
- const magic = buf.readInt8(batchStart + 4);
49961
- if (magic !== 2) { pos = batchEnd; continue; }
49962
- let r = batchStart + 4 + 1 + 4 + 2 + 4 + 8 + 8 + 8 + 2 + 4;
49963
- const recordsCount = buf.readInt32BE(r); r += 4;
49964
- for (let i = 0; i < recordsCount && r < batchEnd; i++) {
49965
- const recLen = decodeVarint(buf, r); // record length (signed varint)
49966
- let rp = recLen.next;
49967
- const recordEnd = rp + recLen.value;
49968
- rp += 1; // attributes (int8)
49969
- const tsDelta = decodeVarint(buf, rp); rp = tsDelta.next;
49970
- const offDelta = decodeVarint(buf, rp); rp = offDelta.next;
49971
- const keyLen = decodeVarint(buf, rp); rp = keyLen.next;
49972
- if (keyLen.value >= 0) rp += keyLen.value;
49973
- const valLen = decodeVarint(buf, rp); rp = valLen.next;
49974
- if (valLen.value >= 0) {
49975
- return buf.subarray(rp, rp + valLen.value).toString("utf-8");
49976
- }
49977
- r = recordEnd;
49978
- }
49979
- pos = batchEnd;
49980
- }
49981
- return null;
49982
- }
49983
-
49984
- let finished = false;
49985
- function finish(out, code) {
49986
- if (finished) return;
49987
- finished = true;
49988
- clearTimeout(timer);
49989
- try { sock.destroy(); } catch (e) { /* ignore */ }
49990
- if (out) process.stdout.write(out);
49991
- // Flush stdout before exiting so execFileSync captures it.
49992
- process.stdout.write("", () => process.exit(code));
49993
- }
49994
-
49995
- const sock = net.createConnection({ host, port }, () => {
49996
- if (operation === "publish") {
49997
- const req = buildProduceRequest(topic, Buffer.from(data, "utf-8"));
49998
- sock.write(req);
49999
- } else if (operation === "get") {
50000
- sock.write(buildFetchRequest(topic, 0));
50001
- } else {
50002
- finish("__UNSUPPORTED__", 0);
50003
- }
50004
- });
50005
-
50006
- let buffer = Buffer.alloc(0);
50007
- sock.on("data", (chunk) => {
50008
- buffer = Buffer.concat([buffer, chunk]);
50009
- if (buffer.length < 4) return;
50010
- const respSize = buffer.readInt32BE(0);
50011
- if (buffer.length < 4 + respSize) return;
50012
-
50013
- if (operation === "publish") {
50014
- // Produce v3 response (after the 4-byte frame size): correlationId(4),
50015
- // topics[count]: name, partitions[count]: partition(4), errorCode(2),
50016
- // baseOffset(8), logAppendTime(8); then throttleTimeMs(4) at the END.
50017
- // Only the per-partition error code matters here.
50018
- try {
50019
- let pos = 4 + 4; // skip frame size + correlationId
50020
- const topicCount = buffer.readInt32BE(pos); pos += 4;
50021
- let errCode = 0;
50022
- for (let t = 0; t < topicCount; t++) {
50023
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
50024
- const pc = buffer.readInt32BE(pos); pos += 4;
50025
- for (let pi = 0; pi < pc; pi++) {
50026
- pos += 4; // partition index
50027
- errCode = buffer.readInt16BE(pos); pos += 2; // error code
50028
- pos += 8; // baseOffset
50029
- pos += 8; // logAppendTime (v2+)
50030
- }
50031
- }
50032
- if (errCode === 0) {
50033
- finish("__PUBLISHED__", 0);
50034
- } else {
50035
- // Report the CODE, not just "it failed" \u2014 the caller decides
50036
- // whether it is retriable (3/5, the async topic-creation race)
50037
- // or fatal (e.g. 29 TOPIC_AUTHORIZATION_FAILED).
50038
- process.stderr.write("Produce error code " + errCode);
50039
- finish("__PRODUCEERROR__" + errCode, 0);
50040
- }
50041
- } catch (e) {
50042
- process.stderr.write("produce parse: " + e.message);
50043
- finish("__PARSEERROR__produce: " + e.message, 0);
50044
- }
50045
- return;
50046
- } else if (operation === "get") {
50047
- // Fetch v4 response (after the 4-byte frame size): correlationId(4),
50048
- // throttleTimeMs(4), topics[count]: name, partitions[count]:
50049
- // partition(4), errorCode(2), highWatermark(8), lastStableOffset(8),
50050
- // abortedTxns[count](producerId(8)+firstOffset(8)),
50051
- // recordSetBytes(int32)+batch.
50052
- try {
50053
- let pos = 4 + 4; // frame size + correlationId
50054
- pos += 4; // throttleTimeMs (v1+)
50055
- const topicCount = buffer.readInt32BE(pos); pos += 4;
50056
- let out = "__EMPTY__";
50057
- let fatalCode = 0;
50058
- for (let t = 0; t < topicCount; t++) {
50059
- const tl = buffer.readInt16BE(pos); pos += 2 + tl;
50060
- const pc = buffer.readInt32BE(pos); pos += 4;
50061
- for (let pi = 0; pi < pc; pi++) {
50062
- pos += 4; // partition index
50063
- const errCode = buffer.readInt16BE(pos); pos += 2;
50064
- pos += 8; // highWatermark
50065
- pos += 8; // lastStableOffset (v4+)
50066
- const abortedCount = buffer.readInt32BE(pos); pos += 4;
50067
- if (abortedCount > 0) pos += abortedCount * 16; // (-1 => none, skip)
50068
- const recSetSize = buffer.readInt32BE(pos); pos += 4;
50069
- // 3 = UNKNOWN_TOPIC_OR_PARTITION, 5 = LEADER_NOT_AVAILABLE:
50070
- // "nothing to read here yet", which a consumer that starts
50071
- // before its producer hits on every cold start. Any OTHER code
50072
- // (29 TOPIC_AUTHORIZATION_FAILED, 13 STALE_CONTROLLER_EPOCH, \u2026)
50073
- // is a real failure and must NOT be reported as an empty queue.
50074
- if (errCode !== 0 && errCode !== 3 && errCode !== 5) {
50075
- fatalCode = errCode;
50076
- }
50077
- if (errCode === 0 && recSetSize > 0) {
50078
- const val = firstRecordValue(buffer, pos, pos + recSetSize);
50079
- if (val !== null) out = val;
50080
- }
50081
- pos += recSetSize > 0 ? recSetSize : 0;
50082
- }
50083
- }
50084
- if (fatalCode !== 0) {
50085
- process.stderr.write("Fetch error code " + fatalCode);
50086
- finish("__FETCHERROR__" + fatalCode, 0);
50087
- return;
50088
- }
50089
- finish(out, 0);
50090
- } catch (e) {
50091
- // A parse failure is NOT an empty queue either \u2014 say so.
50092
- process.stderr.write("fetch parse: " + e.message);
50093
- finish("__PARSEERROR__fetch: " + e.message, 0);
50094
- }
50095
- return;
50096
- }
50097
- });
50098
-
50099
- // Report the reason on STDOUT and exit 0. Writing it to stderr and
50100
- // exiting non-zero LOST it: stderr to a pipe is an async write and
50101
- // process.exit() truncates it, so the parent saw an empty stderr and fell
50102
- // back to execFileSync's message -- which embeds this entire script.
50103
- // stdout is flushed by finish()'s write callback, so it survives.
50104
- sock.on("error", (err) => {
50105
- finish("__TRANSPORTERROR__" + err.message, 0);
50106
- });
50107
-
50108
- var timer = setTimeout(() => {
50109
- finish("__TRANSPORTERROR__timed out after 10s talking to " + host + ":" + port, 0);
50110
- }, 10000);
50111
- `;
50112
- try {
50113
- const result = execFileSync6(process.execPath, ["-e", script], {
50114
- encoding: "utf-8",
50115
- timeout: 15e3,
50116
- stdio: ["pipe", "pipe", "pipe"]
50117
- });
50118
- return result;
50119
- } catch (err) {
50120
- const e = err;
50121
- const reason = String(e.stderr ?? "").trim() || e.message || "unknown error";
50122
- const firstLine = reason.split("\n", 1)[0].slice(0, 200);
50123
- return "__TRANSPORTERROR__" + firstLine;
50124
- }
50125
- }
50126
- /**
50127
- * Sleep synchronously between produce retries.
50128
- *
50129
- * `push()` is synchronous (the whole backend drives its socket through a child
50130
- * process), so there is no event loop to await on. `Atomics.wait` on a
50131
- * SharedArrayBuffer is the stdlib way to block a thread for a fixed time --
50132
- * no dependency, no busy-wait burning CPU.
50133
- */
50134
- static sleepSync(ms) {
50135
- const shared = new Int32Array(new SharedArrayBuffer(4));
50136
- Atomics.wait(shared, 0, 0, ms);
50137
- }
50138
- /**
50139
- * Turn a sentinel from the protocol child into a thrown error, or return.
50140
- *
50141
- * The wording matches the Python and PHP backends exactly -- the parity rule
50142
- * covers user-visible error messages, not just behaviour.
50143
- */
50144
- static assertNoError(result, operation, topic) {
50145
- const fatal = /^__(PRODUCEERROR|FETCHERROR)__(\d+)/.exec(result);
50146
- if (fatal) {
50147
- throw new Error(
50148
- `Kafka rejected the ${operation} for topic ${topic}: error code ${fatal[2]}`
50149
- );
50150
- }
50151
- if (result.startsWith("__TRANSPORTERROR__")) {
50152
- throw new Error(
50153
- `Kafka ${operation} for topic ${topic} failed: ` + result.slice("__TRANSPORTERROR__".length)
50154
- );
50155
- }
50156
- if (result.startsWith("__PARSEERROR__")) {
50157
- throw new Error(
50158
- `Kafka ${operation} for topic ${topic} returned an unreadable response: ` + result.slice("__PARSEERROR__".length)
50159
- );
50160
- }
50161
- }
50162
- /**
50163
- * Serialize the record value. raw (tina4-nodejs#264) emits the payload exactly
50164
- * as given — no {id, payload, status, attempts, ...} envelope — so a non-Tina4
50165
- * consumer reading the topic gets the schema it expects; otherwise the Tina4 job
50166
- * envelope. pop() unwraps both shapes (payload ?? the whole record).
50167
- */
50168
- static encodeJob(id, payload, raw) {
50169
- if (raw) return JSON.stringify(payload);
50170
- return JSON.stringify({
50171
- id,
50172
- payload,
50173
- status: "pending",
50174
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
50175
- attempts: 0,
50176
- delayUntil: null
50177
- });
50178
- }
50179
- push(queue, payload, _delay, _priority, raw = false) {
50180
- const id = randomUUID9();
50181
- const body = _KafkaBackend.encodeJob(id, payload, raw);
50182
- let result = "";
50183
- for (let attempt = 1; attempt <= 10; attempt++) {
50184
- result = this.execSync("publish", queue, body);
50185
- if (result.includes("__PUBLISHED__")) {
50186
- return id;
50187
- }
50188
- const retriable = /^__PRODUCEERROR__(3|5)\b/.test(result);
50189
- if (!retriable || attempt === 10) {
50190
- break;
50191
- }
50192
- _KafkaBackend.sleepSync(200);
50193
- }
50194
- _KafkaBackend.assertNoError(result, "produce", queue);
50195
- throw new Error(`Kafka publish failed for topic ${queue}: ${result || "no response"}`);
50196
- }
50197
- pop(queue) {
50198
- const result = this.execSync("get", queue);
50199
- _KafkaBackend.assertNoError(result, "fetch", queue);
50200
- if (!result || result === "__EMPTY__" || result === "__UNSUPPORTED__") return null;
50201
- try {
50202
- return JSON.parse(result);
50203
- } catch {
50204
- return null;
50205
- }
50206
- }
50207
- size(_queue) {
50208
- return 0;
50209
- }
50210
- clear(_queue) {
50211
- throw new Error(
50212
- "The kafka queue backend cannot perform clear(): Kafka has no notion of job status and cannot delete records on demand. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
50213
- );
50214
- }
50215
- purge(_queue, _status) {
50216
- throw new Error(
50217
- "The kafka queue backend cannot perform purge(): Kafka has no notion of job status to purge by. A log is read in offset order and records leave only by retention. Use the file or mongodb backend."
50218
- );
50219
- }
50220
- };
50221
- }
50222
- });
50223
-
50224
50959
  // ../core/src/testing.ts
50225
50960
  function expectEqual(args, expected) {
50226
50961
  return { type: "equal", args, expected };
@@ -50996,6 +51731,8 @@ __export(src_exports3, {
50996
51731
  TEXT_PLAIN: () => TEXT_PLAIN,
50997
51732
  TEXT_XML: () => TEXT_XML,
50998
51733
  TINA4_VERSION: () => TINA4_VERSION,
51734
+ TcpConnection: () => TcpConnection,
51735
+ TcpService: () => TcpService,
50999
51736
  TestClient: () => TestClient,
51000
51737
  TestResponse: () => TestResponse,
51001
51738
  Tina4AssertionError: () => AssertionError,
@@ -51038,6 +51775,7 @@ __export(src_exports3, {
51038
51775
  checkPassword: () => checkPassword,
51039
51776
  clearCache: () => clearCache,
51040
51777
  clearCurrentNonce: () => clearCurrentNonce,
51778
+ clearTcpRegistry: () => clearTcpRegistry,
51041
51779
  computeAcceptKey: () => computeAcceptKey,
51042
51780
  container: () => container,
51043
51781
  cors: () => cors,
@@ -51059,6 +51797,7 @@ __export(src_exports3, {
51059
51797
  devAdminLanguage: () => devAdminLanguage,
51060
51798
  devReloadWs: () => devReloadWs,
51061
51799
  discoverRoutes: () => discoverRoutes,
51800
+ drainAllTcpServices: () => drainAllTcpServices,
51062
51801
  encodeError: () => encodeError,
51063
51802
  encodeNotification: () => encodeNotification,
51064
51803
  encodeResponse: () => encodeResponse,
@@ -51146,6 +51885,7 @@ __export(src_exports3, {
51146
51885
  refreshToken: () => refreshToken,
51147
51886
  registerDevTools: () => registerDevTools,
51148
51887
  registerFeedbackRoutes: () => registerFeedbackRoutes,
51888
+ registeredTcpServices: () => registeredTcpServices,
51149
51889
  removePidfile: () => removePidfile,
51150
51890
  renderErrorOverlay: () => renderErrorOverlay,
51151
51891
  requestLogger: () => requestLogger,
@@ -51176,12 +51916,16 @@ __export(src_exports3, {
51176
51916
  setFrond: () => setFrond,
51177
51917
  showMenu: () => showMenu,
51178
51918
  start: () => start,
51919
+ startAllTcpServices: () => startAllTcpServices,
51179
51920
  startServer: () => startServer,
51180
51921
  stop: () => stop,
51922
+ stopAcceptingAllTcpServices: () => stopAcceptingAllTcpServices,
51181
51923
  stopAllBackgroundTasks: () => stopAllBackgroundTasks,
51182
51924
  supervisorBaseUrl: () => supervisorBaseUrl,
51183
51925
  sweep: () => sweep,
51184
51926
  takeOverPort: () => takeOverPort,
51927
+ tcp: () => tcp,
51928
+ tcpService: () => tcpService,
51185
51929
  templateAutoRoutingEnabled: () => templateAutoRoutingEnabled,
51186
51930
  tests: () => tests,
51187
51931
  trustedProxyNetworks: () => trustedProxyNetworks,
@@ -51201,6 +51945,7 @@ var init_src3 = __esm({
51201
51945
  "use strict";
51202
51946
  init_server();
51203
51947
  init_background();
51948
+ init_tcp();
51204
51949
  init_router();
51205
51950
  init_router();
51206
51951
  init_routeDiscovery();