tina4-nodejs 3.13.151 → 3.13.152

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.
@@ -4269,6 +4269,9 @@ var init_postgres = __esm({
4269
4269
  await withConnectTimeout(
4270
4270
  () => {
4271
4271
  this.client = typeof this.config === "string" ? new Client({ connectionString: this.config, ...timeoutOption }) : new Client({ ...this.config, ...timeoutOption });
4272
+ this.client.on("error", () => {
4273
+ this.connectionIsDead = true;
4274
+ });
4272
4275
  return this.client.connect();
4273
4276
  },
4274
4277
  budgetMs,
@@ -4292,6 +4295,52 @@ var init_postgres = __esm({
4292
4295
  throw new Error("PostgreSQL adapter not connected. Call connect() first.");
4293
4296
  }
4294
4297
  }
4298
+ // ── Reconnect after a dropped link (parity with the Python master, #236/#242) ──
4299
+ // pg's Client does not reconnect itself: once the server drops the link it must
4300
+ // be rebuilt. A statement that hits a dropped link reconnects and retries once
4301
+ // when nothing uncommitted went down with it; inside an explicit transaction the
4302
+ // error surfaces. A reconnect that itself fails leaves the link dead (not null-
4303
+ // guarded away), so the NEXT statement retries and recovers once a server returns.
4304
+ connectionIsDead = false;
4305
+ isConnectionError(e) {
4306
+ const msg = e instanceof Error ? e.message : String(e);
4307
+ return /connection terminated|terminating connection|server closed the connection|encountered a connection error|connection closed|not queryable|ECONNRESET|EPIPE|socket hang up/i.test(msg);
4308
+ }
4309
+ async reconnect() {
4310
+ void Promise.resolve(this.client?.end()).catch(() => {
4311
+ });
4312
+ this.client = null;
4313
+ this.connectionIsDead = false;
4314
+ await this.connect();
4315
+ }
4316
+ async ensureLiveConnection() {
4317
+ if (!this._inTransaction && (this.client === null || this.connectionIsDead)) {
4318
+ await this.reconnect();
4319
+ }
4320
+ }
4321
+ async runQuery(sql, params) {
4322
+ await this.ensureLiveConnection();
4323
+ this.ensureConnected();
4324
+ try {
4325
+ return await this.client.query(sql, params);
4326
+ } catch (e) {
4327
+ if (!this.isConnectionError(e)) throw e;
4328
+ this.connectionIsDead = true;
4329
+ if (this._inTransaction) throw e;
4330
+ await this.reconnect();
4331
+ return await this.client.query(sql, params);
4332
+ }
4333
+ }
4334
+ // Transaction control (BEGIN/COMMIT/ROLLBACK) runs RAW - no reconnect, no
4335
+ // pre-heal. A failed BEGIN/COMMIT/ROLLBACK must surface so the connection-pool
4336
+ // layer can discard the connection and restore capacity; reconnecting or
4337
+ // retrying here would mask that failure (databasePoolIsolation contract).
4338
+ // Dropped-link recovery stays on the DATA path (runQuery): the next data
4339
+ // statement heals the link.
4340
+ async rawQuery(sql) {
4341
+ this.ensureConnected();
4342
+ await this.client.query(sql);
4343
+ }
4295
4344
  /** Convert ? placeholders to $1, $2, ... for pg. */
4296
4345
  /** Ensure bytea columns are Buffer (already the case with pg). No-op guard. */
4297
4346
  decodeBlobs(row) {
@@ -4341,7 +4390,6 @@ var init_postgres = __esm({
4341
4390
  return null;
4342
4391
  }
4343
4392
  execute(sql, params) {
4344
- this.ensureConnected();
4345
4393
  const convertedSql = this.convertPlaceholders(sql);
4346
4394
  throw new Error("Use executeAsync() for PostgreSQL \u2014 async adapter requires async methods.");
4347
4395
  }
@@ -4376,9 +4424,8 @@ var init_postgres = __esm({
4376
4424
  }
4377
4425
  /** Async execute for real usage. */
4378
4426
  async executeAsync(sql, params) {
4379
- this.ensureConnected();
4380
4427
  const convertedSql = this.bindable(sql, params);
4381
- const result = await this.client.query(convertedSql, params);
4428
+ const result = await this.runQuery(convertedSql, params);
4382
4429
  if (result.rows?.[0]?.id !== void 0) {
4383
4430
  this._lastInsertId = this.normalizeId(result.rows[0].id);
4384
4431
  }
@@ -4389,9 +4436,8 @@ var init_postgres = __esm({
4389
4436
  }
4390
4437
  /** Async query for real usage. */
4391
4438
  async queryAsync(sql, params) {
4392
- this.ensureConnected();
4393
4439
  const convertedSql = this.bindable(sql, params);
4394
- const result = await this.client.query(convertedSql, params);
4440
+ const result = await this.runQuery(convertedSql, params);
4395
4441
  return result.rows.map((row) => this.decodeBlobs(row));
4396
4442
  }
4397
4443
  fetch(sql, params, limit, skip) {
@@ -4419,7 +4465,6 @@ var init_postgres = __esm({
4419
4465
  throw new Error("Use insertAsync() for PostgreSQL.");
4420
4466
  }
4421
4467
  async insertAsync(table2, data) {
4422
- this.ensureConnected();
4423
4468
  if (Array.isArray(data)) {
4424
4469
  const batch = buildInsertRows(ANSI_DIALECT, table2, data);
4425
4470
  if (!batch) return { success: true, affectedRows: 0 };
@@ -4433,7 +4478,7 @@ var init_postgres = __esm({
4433
4478
  }
4434
4479
  const { sql, values } = buildInsertRow(POSTGRES_DIALECT, table2, data, " RETURNING *");
4435
4480
  try {
4436
- const result = await this.client.query(sql, values);
4481
+ const result = await this.runQuery(sql, values);
4437
4482
  const insertedRow = result.rows[0];
4438
4483
  const id = this.normalizeId(insertedRow?.id);
4439
4484
  if (id !== null) this._lastInsertId = id;
@@ -4450,13 +4495,12 @@ var init_postgres = __esm({
4450
4495
  throw new Error("Use updateAsync() for PostgreSQL.");
4451
4496
  }
4452
4497
  async updateAsync(table2, data, filter, params) {
4453
- this.ensureConnected();
4454
4498
  const { sql, values } = buildUpdate(POSTGRES_DIALECT, table2, data, filter, params, {
4455
4499
  startAt: 1,
4456
4500
  convertFragment: (fragment, startAt) => this.convertPlaceholders(fragment, startAt)
4457
4501
  });
4458
4502
  try {
4459
- const result = await this.client.query(sql, values);
4503
+ const result = await this.runQuery(sql, values);
4460
4504
  return { success: true, affectedRows: result.rowCount ?? 0 };
4461
4505
  } catch (e) {
4462
4506
  return { success: false, affectedRows: 0, error: e.message };
@@ -4466,13 +4510,12 @@ var init_postgres = __esm({
4466
4510
  throw new Error("Use deleteAsync() for PostgreSQL.");
4467
4511
  }
4468
4512
  async deleteAsync(table2, filter, params) {
4469
- this.ensureConnected();
4470
4513
  const { sql, values } = buildDelete(POSTGRES_DIALECT, table2, filter, params, {
4471
4514
  startAt: 1,
4472
4515
  convertFragment: (fragment) => this.bindable(fragment, params)
4473
4516
  });
4474
4517
  try {
4475
- const result = await this.client.query(sql, values);
4518
+ const result = await this.runQuery(sql, values);
4476
4519
  return { success: true, affectedRows: result.rowCount ?? 0 };
4477
4520
  } catch (e) {
4478
4521
  return { success: false, affectedRows: 0, error: e.message };
@@ -4482,22 +4525,28 @@ var init_postgres = __esm({
4482
4525
  throw new Error("Use startTransactionAsync() for PostgreSQL.");
4483
4526
  }
4484
4527
  async startTransactionAsync() {
4485
- await this.executeAsync("BEGIN");
4528
+ await this.rawQuery("BEGIN");
4486
4529
  this._inTransaction = true;
4487
4530
  }
4488
4531
  commit() {
4489
4532
  throw new Error("Use commitAsync() for PostgreSQL.");
4490
4533
  }
4491
4534
  async commitAsync() {
4492
- await this.executeAsync("COMMIT");
4493
- this._inTransaction = false;
4535
+ try {
4536
+ await this.rawQuery("COMMIT");
4537
+ } finally {
4538
+ this._inTransaction = false;
4539
+ }
4494
4540
  }
4495
4541
  rollback() {
4496
4542
  throw new Error("Use rollbackAsync() for PostgreSQL.");
4497
4543
  }
4498
4544
  async rollbackAsync() {
4499
- await this.executeAsync("ROLLBACK");
4500
- this._inTransaction = false;
4545
+ try {
4546
+ await this.rawQuery("ROLLBACK");
4547
+ } finally {
4548
+ this._inTransaction = false;
4549
+ }
4501
4550
  }
4502
4551
  getTables() {
4503
4552
  throw new Error("Use tablesAsync() for PostgreSQL.");
@@ -16768,6 +16817,12 @@ import { dirname as dirname6, isAbsolute as isAbsolute4, join as join10 } from "
16768
16817
  function iso(d) {
16769
16818
  return d.toISOString();
16770
16819
  }
16820
+ function setOwn(obj, key, value) {
16821
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
16822
+ }
16823
+ function getOwn(obj, key) {
16824
+ return Object.hasOwn(obj, key) ? obj[key] : void 0;
16825
+ }
16771
16826
  function encodeValue(value) {
16772
16827
  if (value instanceof ObjectId) return value.toString();
16773
16828
  if (value instanceof Date) return iso(value);
@@ -16775,7 +16830,7 @@ function encodeValue(value) {
16775
16830
  if (value !== null && typeof value === "object") {
16776
16831
  const out = {};
16777
16832
  for (const [k, v] of Object.entries(value)) {
16778
- out[k] = encodeValue(v);
16833
+ setOwn(out, k, encodeValue(v));
16779
16834
  }
16780
16835
  return out;
16781
16836
  }
@@ -16794,7 +16849,7 @@ function decodeValue(value) {
16794
16849
  if (value !== null && typeof value === "object") {
16795
16850
  const out = {};
16796
16851
  for (const [k, v] of Object.entries(value)) {
16797
- out[k] = decodeValue(v);
16852
+ setOwn(out, k, decodeValue(v));
16798
16853
  }
16799
16854
  return out;
16800
16855
  }
@@ -16940,31 +16995,32 @@ function project(doc, projection) {
16940
16995
  const exclude = new Set(Object.entries(projection).filter(([, v]) => !v).map(([k]) => k));
16941
16996
  if (include.size > 0) {
16942
16997
  const out2 = {};
16943
- for (const k of include) if (k in doc) out2[k] = doc[k];
16998
+ for (const k of include) if (Object.hasOwn(doc, k)) setOwn(out2, k, doc[k]);
16944
16999
  const idVal = projection._id;
16945
17000
  if ((idVal === void 0 || idVal) && "_id" in doc) out2._id = doc._id;
16946
17001
  return out2;
16947
17002
  }
16948
17003
  const out = {};
16949
- for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) out[k] = v;
17004
+ for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) setOwn(out, k, v);
16950
17005
  return out;
16951
17006
  }
16952
17007
  function setPath(doc, dotted, value) {
16953
17008
  const parts = dotted.split(".");
16954
17009
  let node = doc;
16955
17010
  for (const p of parts.slice(0, -1)) {
16956
- if (node[p] === void 0 || node[p] === null || typeof node[p] !== "object") {
16957
- node[p] = {};
17011
+ const child = getOwn(node, p);
17012
+ if (child === void 0 || child === null || typeof child !== "object") {
17013
+ setOwn(node, p, {});
16958
17014
  }
16959
17015
  node = node[p];
16960
17016
  }
16961
- node[parts[parts.length - 1]] = value;
17017
+ setOwn(node, parts[parts.length - 1], value);
16962
17018
  }
16963
17019
  function unsetPath(doc, dotted) {
16964
17020
  const parts = dotted.split(".");
16965
17021
  let node = doc;
16966
17022
  for (const p of parts.slice(0, -1)) {
16967
- const next = node[p];
17023
+ const next = getOwn(node, p);
16968
17024
  if (next === null || typeof next !== "object") return;
16969
17025
  node = next;
16970
17026
  }
@@ -23384,8 +23440,8 @@ var init_ssoIdentity = __esm({
23384
23440
  });
23385
23441
 
23386
23442
  // ../core/src/authGate.ts
23387
- function enforceRouteAuth(req2, res, match, isDevAdmin) {
23388
- if (!(match.secure === true && match.noAuth !== true && !isDevAdmin)) {
23443
+ function enforceRouteAuth(req2, res, match) {
23444
+ if (!(match.secure === true && match.noAuth !== true)) {
23389
23445
  return false;
23390
23446
  }
23391
23447
  const authHeader = req2.headers.authorization ?? "";
@@ -27145,26 +27201,31 @@ function parseFlags(args, booleanFlags) {
27145
27201
  const positional = [];
27146
27202
  let i = 0;
27147
27203
  while (i < args.length) {
27148
- const arg = args[i];
27149
- if (arg.startsWith("--")) {
27150
- const key = arg.slice(2);
27151
- if (booleanFlags?.has(key)) {
27152
- flags[key] = true;
27153
- i += 1;
27154
- } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
27155
- flags[key] = args[i + 1];
27156
- i += 2;
27157
- } else {
27158
- flags[key] = true;
27159
- i += 1;
27160
- }
27204
+ if (args[i].startsWith("--")) {
27205
+ i += readFlag(args, i, flags, booleanFlags);
27161
27206
  } else {
27162
- positional.push(arg);
27207
+ positional.push(args[i]);
27163
27208
  i += 1;
27164
27209
  }
27165
27210
  }
27166
27211
  return { flags, positional };
27167
27212
  }
27213
+ function readFlag(args, i, flags, booleanFlags) {
27214
+ const arg = args[i];
27215
+ const eq = arg.indexOf("=");
27216
+ if (eq !== -1) {
27217
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
27218
+ return 1;
27219
+ }
27220
+ const key = arg.slice(2);
27221
+ const next = args[i + 1];
27222
+ if (!booleanFlags?.has(key) && next !== void 0 && !next.startsWith("--")) {
27223
+ flags[key] = next;
27224
+ return 2;
27225
+ }
27226
+ flags[key] = true;
27227
+ return 1;
27228
+ }
27168
27229
  function findOnPath(names) {
27169
27230
  for (const dir of (process.env.PATH ?? "").split(delimiter2)) {
27170
27231
  if (!dir) continue;
@@ -27198,6 +27259,7 @@ __export(generate_exports, {
27198
27259
  DEFAULT_FIELDS: () => DEFAULT_FIELDS,
27199
27260
  GENERATORS: () => GENERATORS,
27200
27261
  RESOLUTION_ENVELOPE_VERSION: () => RESOLUTION_ENVELOPE_VERSION,
27262
+ RESOLUTION_FLAGS: () => RESOLUTION_FLAGS,
27201
27263
  SQL_RESERVED_TABLE_NAMES: () => SQL_RESERVED_TABLE_NAMES,
27202
27264
  aiFill: () => aiFill,
27203
27265
  currentResolution: () => currentResolution,
@@ -27514,6 +27576,10 @@ async function generate(what, name, extraArgs = []) {
27514
27576
  extraArgs = [name, ...extraArgs];
27515
27577
  name = "";
27516
27578
  }
27579
+ if (GENERATORS[what] && !noNameGenerators.has(what) && name.startsWith("-")) {
27580
+ console.log(`Invalid ${what} name: '${name}' - names can't start with '-'.`);
27581
+ process.exit(1);
27582
+ }
27517
27583
  if (!noNameGenerators.has(what) && !name) {
27518
27584
  console.error(` Usage: tina4nodejs generate ${what} <name> [options]`);
27519
27585
  process.exit(1);
@@ -27830,7 +27896,7 @@ function generateCrud(name, flags) {
27830
27896
  if (!__resolution.jsonMode) console.log(`
27831
27897
  Generating CRUD for ${name}...
27832
27898
  `);
27833
- generateModel(name, flags, false);
27899
+ if (!flags["skip-model"]) generateModel(name, flags, false);
27834
27900
  generateCrudAdminRoute(name, table2, isPublic);
27835
27901
  if (!flags["no-templates"]) copyCrudTemplates();
27836
27902
  generateCrudGateTest(name, table2, isPublic);
@@ -29140,7 +29206,7 @@ for (const stmt of statements(downSql)) db.execute(stmt);
29140
29206
  assert("DOWN drops the ${table2} table", db.tableExists("${table2}") === false);`;
29141
29207
  writeTest(`${table2}_migration`, standaloneTest(doc, body));
29142
29208
  }
29143
- var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, GENERATOR_LIST, NEXT_STEPS;
29209
+ var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, RESOLUTION_FLAGS, GENERATOR_LIST, NEXT_STEPS;
29144
29210
  var init_generate = __esm({
29145
29211
  "src/commands/generate.ts"() {
29146
29212
  "use strict";
@@ -29253,22 +29319,23 @@ var init_generate = __esm({
29253
29319
  TINA4_EDIT_MARKER = /^\s*(?:\/\/|--|\{#|#)\s*tina4:edit\s+(.+?)(?:\s*#\})?\s*$/;
29254
29320
  DEFAULT_FIELDS = [["name", "string"]];
29255
29321
  GENERATORS = {
29256
- model: { handler: generateModel, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
29257
- route: { handler: generateRoute, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
29258
- crud: { handler: generateCrud, usage: '<Name> [--fields "..."] [--public] [--no-templates]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
29259
- migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
29260
- middleware: { handler: generateMiddleware, usage: "<Name>", summary: "Middleware with before/after hooks" },
29261
- test: { handler: generateTest, usage: "<name> [--model Name]", summary: "Test file" },
29262
- form: { handler: generateForm2, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
29263
- view: { handler: generateView, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
29264
- auth: { handler: (_n, f) => generateAuth(f), usage: "", summary: "Login/register routes (public) + User model + templates" },
29265
- service: { handler: generateService, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
29266
- queue: { handler: generateQueue, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
29267
- validator: { handler: generateValidator, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
29268
- seeder: { handler: generateSeeder, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
29269
- websocket: { handler: generateWebsocket, usage: "<path>", summary: "websocket() handler (src/routes/)" },
29270
- listener: { handler: generateListener, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
29271
- };
29322
+ model: { handler: generateModel, flags: { fields: true, "table-name": true, "no-migration": false }, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
29323
+ route: { handler: generateRoute, flags: { model: true, public: false, "table-name": true }, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
29324
+ crud: { handler: generateCrud, flags: { fields: true, "table-name": true, public: false, "no-templates": false, "no-migration": false, "skip-model": false }, usage: '<Name> [--fields "..."] [--public] [--no-templates] [--skip-model]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
29325
+ migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), flags: { fields: true, "table-name": true, "no-test": false }, usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
29326
+ middleware: { handler: generateMiddleware, flags: {}, usage: "<Name>", summary: "Middleware with before/after hooks" },
29327
+ test: { handler: generateTest, flags: { model: true, public: false, "secure-writes": false }, usage: "<name> [--model Name]", summary: "Test file" },
29328
+ form: { handler: generateForm2, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
29329
+ view: { handler: generateView, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
29330
+ auth: { handler: (_n, f) => generateAuth(f), flags: {}, usage: "", summary: "Login/register routes (public) + User model + templates" },
29331
+ service: { handler: generateService, flags: { every: true, cron: true }, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
29332
+ queue: { handler: generateQueue, flags: {}, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
29333
+ validator: { handler: generateValidator, flags: {}, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
29334
+ seeder: { handler: generateSeeder, flags: { "table-name": true }, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
29335
+ websocket: { handler: generateWebsocket, flags: {}, usage: "<path>", summary: "websocket() handler (src/routes/)" },
29336
+ listener: { handler: generateListener, flags: {}, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
29337
+ };
29338
+ RESOLUTION_FLAGS = { json: false, "dry-run": false };
29272
29339
  GENERATOR_LIST = Object.keys(GENERATORS).join(", ");
29273
29340
  NEXT_STEPS = {
29274
29341
  model: ({ name, table: table2 }) => [
@@ -39083,7 +39150,8 @@ var init_devAdmin = __esm({
39083
39150
  router.addRoute({
39084
39151
  method: route.method,
39085
39152
  pattern: route.pattern,
39086
- handler: route.handler
39153
+ handler: route.handler,
39154
+ noAuth: true
39087
39155
  });
39088
39156
  }
39089
39157
  if (mcpEnabled()) {
@@ -39107,7 +39175,8 @@ var init_devAdmin = __esm({
39107
39175
  router.addRoute({
39108
39176
  method: route.method,
39109
39177
  pattern: route.pattern,
39110
- handler: route.handler
39178
+ handler: route.handler,
39179
+ noAuth: true
39111
39180
  });
39112
39181
  }
39113
39182
  getDefaultDevServer();
@@ -42374,7 +42443,7 @@ async function runMatchedRoute(ctx) {
42374
42443
  const { req: req2, res, match, postMatchMiddleware } = ctx;
42375
42444
  req2.params = match.params;
42376
42445
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
42377
- if (enforceRouteAuth(req2, res, match, ctx.pathname.startsWith("/__dev"))) return;
42446
+ if (enforceRouteAuth(req2, res, match)) return;
42378
42447
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
42379
42448
  let handlerSkipped = false;
42380
42449
  if (match.middlewares && match.middlewares.length > 0) {
@@ -51450,12 +51519,23 @@ async function runMigrations(migrationDir) {
51450
51519
 
51451
51520
  // src/commands/migrateCreate.ts
51452
51521
  init_generate();
51522
+ var MIGRATE_CREATE_FLAGS = {
51523
+ fields: true,
51524
+ "table-name": true,
51525
+ json: false,
51526
+ "dry-run": false
51527
+ };
51453
51528
  async function createMigration2(args = []) {
51454
51529
  const positionals = [];
51455
51530
  const flags = [];
51456
- for (const arg of args) {
51457
- if (arg.startsWith("--")) flags.push(arg);
51458
- else positionals.push(arg);
51531
+ for (let i = 0; i < args.length; i++) {
51532
+ const arg = args[i];
51533
+ if (arg.startsWith("--")) {
51534
+ flags.push(arg);
51535
+ if (!arg.includes("=") && MIGRATE_CREATE_FLAGS[arg.slice(2)] && i + 1 < args.length) flags.push(args[++i]);
51536
+ } else {
51537
+ positionals.push(arg);
51538
+ }
51459
51539
  }
51460
51540
  const description = positionals.join(" ").trim();
51461
51541
  if (!description) {
@@ -52126,6 +52206,12 @@ var QUEUE_SUBCOMMANDS = {
52126
52206
  retry: queueRetry,
52127
52207
  clear: queueClear
52128
52208
  };
52209
+ var QUEUE_FLAGS = {
52210
+ work: { once: false, poll: true, services: true },
52211
+ stats: { json: false },
52212
+ retry: {},
52213
+ clear: {}
52214
+ };
52129
52215
  var QUEUE_SUBCOMMAND_NAMES = Object.keys(QUEUE_SUBCOMMANDS);
52130
52216
  async function queueCommand(args = []) {
52131
52217
  const list = QUEUE_SUBCOMMAND_NAMES.join(", ");
@@ -52329,8 +52415,7 @@ function printHelp() {
52329
52415
  " --no-browser Don't open the browser on serve",
52330
52416
  " --no-reload Disable file watcher / live-reload on serve",
52331
52417
  " --all Install AI context for all tools (with ai command)",
52332
- " --force Overwrite existing AI context files (with ai command)",
52333
- " --help Show this help message",
52418
+ " --help, -h Show this help, or one command's usage (tina4nodejs <command> --help)",
52334
52419
  "",
52335
52420
  " https://tina4.com",
52336
52421
  ""
@@ -52364,7 +52449,7 @@ async function openConsole() {
52364
52449
  }
52365
52450
  async function installAiContext(args) {
52366
52451
  const { showMenu: showMenu2, installSelected: installSelected2, installAll: installAll2 } = await Promise.resolve().then(() => (init_ai(), ai_exports));
52367
- const root = args[0] || ".";
52452
+ const root = args.find((a) => !a.startsWith("-")) || ".";
52368
52453
  if (args.includes("--all")) {
52369
52454
  installAll2(root);
52370
52455
  } else {
@@ -52374,6 +52459,15 @@ async function installAiContext(args) {
52374
52459
  }
52375
52460
  }
52376
52461
  }
52462
+ var SERVE_FLAGS = {
52463
+ port: true,
52464
+ "no-browser": false,
52465
+ "no-reload": false,
52466
+ "no-kill": false,
52467
+ // Not read by serve, but the Dockerfile `init` scaffolds runs
52468
+ // `tina4nodejs serve --production`, so refusing it would break every image.
52469
+ production: false
52470
+ };
52377
52471
  var COMMANDS = {
52378
52472
  init: {
52379
52473
  handler: async (a) => {
@@ -52393,6 +52487,7 @@ var COMMANDS = {
52393
52487
  await killProcessOnPort(port);
52394
52488
  await serveProject({ port, noBrowser, noReload });
52395
52489
  },
52490
+ flags: SERVE_FLAGS,
52396
52491
  usage: "[--port P] [--no-browser] [--no-reload]",
52397
52492
  summary: "Start the dev server with hot-reload (default: 0.0.0.0:7148)"
52398
52493
  },
@@ -52409,6 +52504,7 @@ var COMMANDS = {
52409
52504
  handler: async (a) => {
52410
52505
  await createMigration2(a);
52411
52506
  },
52507
+ flags: MIGRATE_CREATE_FLAGS,
52412
52508
  usage: "<desc>",
52413
52509
  args: ["description"],
52414
52510
  summary: "Create a new migration file (delegates to generate migration)"
@@ -52442,6 +52538,7 @@ var COMMANDS = {
52442
52538
  handler: (a) => {
52443
52539
  runLint(a);
52444
52540
  },
52541
+ flags: { fix: false, "no-install": false },
52445
52542
  usage: "[--fix] [--no-install]",
52446
52543
  summary: "Lint the project (eslint, installed dev-only on demand; else tsc/node --check baseline)"
52447
52544
  },
@@ -52457,6 +52554,7 @@ var COMMANDS = {
52457
52554
  handler: (a) => {
52458
52555
  buildImage(a);
52459
52556
  },
52557
+ flags: { tag: true, file: true },
52460
52558
  usage: "[--tag NAME] [--file PATH]",
52461
52559
  summary: "Build the deployable Docker image"
52462
52560
  },
@@ -52485,6 +52583,7 @@ var COMMANDS = {
52485
52583
  handler: async (a) => {
52486
52584
  await installAiContext(a);
52487
52585
  },
52586
+ flags: { all: false },
52488
52587
  usage: "[--all]",
52489
52588
  summary: "Install AI coding assistant context files"
52490
52589
  },
@@ -52492,6 +52591,7 @@ var COMMANDS = {
52492
52591
  handler: (a) => {
52493
52592
  runCommands(a);
52494
52593
  },
52594
+ flags: { json: false },
52495
52595
  usage: "[--json]",
52496
52596
  summary: "List available commands (add --json for the machine manifest)"
52497
52597
  },
@@ -52499,6 +52599,8 @@ var COMMANDS = {
52499
52599
  handler: () => {
52500
52600
  printHelp();
52501
52601
  },
52602
+ // Not option-checked: `help --help` / `help -h` print the reference too.
52603
+ flags: null,
52502
52604
  summary: "Show this help message"
52503
52605
  }
52504
52606
  };
@@ -52552,6 +52654,114 @@ ${CLIENT_INSTALL_HINT}
52552
52654
  }
52553
52655
  return result.status ?? EXIT_CLIENT_UNAVAILABLE;
52554
52656
  }
52657
+ var HELP_FLAGS = ["--help", "-h"];
52658
+ function printCommandHelp(command, args) {
52659
+ if (command === "generate") {
52660
+ const kind = args.find((a) => !a.startsWith("-"))?.toLowerCase();
52661
+ const gen = kind ? GENERATORS[kind] : void 0;
52662
+ if (gen) {
52663
+ console.log(`Usage: tina4nodejs generate ${kind} ${gen.usage}`.trimEnd());
52664
+ console.log(`
52665
+ ${gen.summary}`);
52666
+ return;
52667
+ }
52668
+ console.log("Usage: tina4nodejs generate <what> <name> [options]\n\nGenerators:");
52669
+ const pad = Math.max(...Object.keys(GENERATORS).map((n) => n.length));
52670
+ for (const [name, g] of Object.entries(GENERATORS)) console.log(` ${name.padEnd(pad)} ${g.summary}`);
52671
+ return;
52672
+ }
52673
+ const spec = COMMANDS[command];
52674
+ console.log(`Usage: tina4nodejs ${command} ${spec.usage ?? ""}`.trimEnd());
52675
+ console.log(`
52676
+ ${spec.summary}`);
52677
+ if (spec.subcommands?.length) console.log(` Subcommands: ${spec.subcommands.join(", ")}`);
52678
+ }
52679
+ function acceptedOptions(command, args) {
52680
+ const sub = (args[0] ?? "").toLowerCase();
52681
+ if (command === "generate") {
52682
+ const gen = GENERATORS[sub];
52683
+ return gen ? { ...gen.flags, ...RESOLUTION_FLAGS } : null;
52684
+ }
52685
+ if (command === "queue") return QUEUE_FLAGS[sub] ?? null;
52686
+ const flags = COMMANDS[command].flags;
52687
+ return flags === void 0 ? {} : flags;
52688
+ }
52689
+ function editDistance(a, b) {
52690
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
52691
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
52692
+ for (let i = 1; i <= a.length; i++) {
52693
+ for (let j = 1; j <= b.length; j++) d[i][j] = distanceCell(d, a, b, i, j);
52694
+ }
52695
+ return d[a.length][b.length];
52696
+ }
52697
+ function distanceCell(d, a, b, i, j) {
52698
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
52699
+ const best = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
52700
+ const swapped = i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1];
52701
+ return swapped ? Math.min(best, d[i - 2][j - 2] + 1) : best;
52702
+ }
52703
+ function closestOption(name, accepted) {
52704
+ let best = null;
52705
+ let bestDistance = Math.max(1, Math.floor(name.length / 3)) + 1;
52706
+ for (const option of accepted) {
52707
+ const distance = editDistance(name, option);
52708
+ if (distance < bestDistance) {
52709
+ best = option;
52710
+ bestDistance = distance;
52711
+ }
52712
+ }
52713
+ return best;
52714
+ }
52715
+ function unknownOptionMessage(option, name, accepted, label) {
52716
+ const close = closestOption(name, Object.keys(accepted));
52717
+ return `Unknown option ${option} for "${label}".${close ? ` Did you mean --${close}?` : ""}
52718
+ Run "tina4nodejs ${label} --help" for its options.`;
52719
+ }
52720
+ function optionProblem(args, i, accepted, label) {
52721
+ const arg = args[i];
52722
+ if (!arg.startsWith("-") || arg === "-") return [null, 1];
52723
+ const [option, inlineValue] = splitOption(arg);
52724
+ const name = option.replace(/^-+/, "");
52725
+ if (!isAccepted(option, name, accepted)) {
52726
+ return [unknownOptionMessage(option, name, accepted, label), 1];
52727
+ }
52728
+ if (inlineValue || !accepted[name]) return [null, 1];
52729
+ if (!hasValueAfter(args, i)) {
52730
+ return [`Option --${name} for "${label}" needs a value: --${name} <value>`, 1];
52731
+ }
52732
+ return [null, 2];
52733
+ }
52734
+ function isAccepted(option, name, accepted) {
52735
+ return option.startsWith("--") && Object.hasOwn(accepted, name);
52736
+ }
52737
+ function splitOption(arg) {
52738
+ const eq = arg.indexOf("=");
52739
+ return eq === -1 ? [arg, false] : [arg.slice(0, eq), true];
52740
+ }
52741
+ function hasValueAfter(args, i) {
52742
+ return i + 1 < args.length && !args[i + 1].startsWith("-");
52743
+ }
52744
+ function checkOptions(command, args) {
52745
+ const accepted = acceptedOptions(command, args);
52746
+ if (accepted === null) return;
52747
+ const label = command === "generate" || command === "queue" ? `${command} ${args[0].toLowerCase()}` : command;
52748
+ for (let i = 0; i < args.length; ) {
52749
+ const [problem, consumed] = optionProblem(args, i, accepted, label);
52750
+ if (problem) {
52751
+ console.log(problem);
52752
+ process.exit(1);
52753
+ }
52754
+ i += consumed;
52755
+ }
52756
+ }
52757
+ async function runCommand(command, spec, cmdArgs) {
52758
+ if (command !== "help" && cmdArgs.some((a) => HELP_FLAGS.includes(a))) {
52759
+ printCommandHelp(command, cmdArgs);
52760
+ return;
52761
+ }
52762
+ checkOptions(command, cmdArgs);
52763
+ await spec.handler(cmdArgs);
52764
+ }
52555
52765
  async function main() {
52556
52766
  const args = process.argv.slice(2);
52557
52767
  let command = args[0];
@@ -52561,7 +52771,7 @@ async function main() {
52561
52771
  }
52562
52772
  const spec = COMMANDS[command];
52563
52773
  if (spec) {
52564
- await spec.handler(cmdArgs);
52774
+ await runCommand(command, spec, cmdArgs);
52565
52775
  return;
52566
52776
  }
52567
52777
  if (command in DELEGATED) {
@@ -52584,7 +52794,10 @@ export {
52584
52794
  DELEGATION_GUARD_ENV,
52585
52795
  EXIT_CLIENT_UNAVAILABLE,
52586
52796
  EXIT_UNKNOWN_COMMAND,
52797
+ acceptedOptions,
52587
52798
  buildCommandManifest,
52799
+ closestOption,
52588
52800
  delegateToClient,
52801
+ optionProblem,
52589
52802
  runCommands
52590
52803
  };