tina4-nodejs 3.13.150 → 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.
Files changed (71) hide show
  1. package/CLAUDE.md +2 -2
  2. package/package.json +5 -9
  3. package/packages/cli/dist/bin.js +1326 -586
  4. package/packages/cli/src/bin.ts +179 -7
  5. package/packages/cli/src/commands/generate.ts +36 -17
  6. package/packages/cli/src/commands/migrateCreate.ts +15 -3
  7. package/packages/cli/src/commands/queue.ts +8 -0
  8. package/packages/cli/src/util.ts +25 -15
  9. package/packages/core/dist/index.js +1172 -574
  10. package/packages/core/src/aiClient.ts +2 -1
  11. package/packages/core/src/api.ts +2 -1
  12. package/packages/core/src/auth.ts +1 -1
  13. package/packages/core/src/authGate.ts +3 -4
  14. package/packages/core/src/cache.ts +6 -1
  15. package/packages/core/src/devAdmin.ts +180 -123
  16. package/packages/core/src/dispatchPipeline.ts +4 -0
  17. package/packages/core/src/docs.ts +5 -3
  18. package/packages/core/src/errorOverlay.ts +18 -9
  19. package/packages/core/src/index.ts +2 -1
  20. package/packages/core/src/mcp.ts +53 -16
  21. package/packages/core/src/messenger.ts +22 -30
  22. package/packages/core/src/middleware.ts +8 -1
  23. package/packages/core/src/optionalPackage.ts +2 -2
  24. package/packages/core/src/plan.ts +3 -3
  25. package/packages/core/src/push.ts +1 -1
  26. package/packages/core/src/request.ts +185 -25
  27. package/packages/core/src/router.ts +3 -2
  28. package/packages/core/src/server.ts +36 -12
  29. package/packages/core/src/session.ts +44 -0
  30. package/packages/core/src/slashTrim.ts +39 -0
  31. package/packages/core/src/wsdl.ts +66 -48
  32. package/packages/core/templates/crud/form.twig +5 -5
  33. package/packages/core/templates/crud/table.twig +2 -2
  34. package/packages/core/templates/errors/302.twig +4 -3
  35. package/packages/frond/dist/index.js +206 -64
  36. package/packages/frond/src/engine.ts +278 -69
  37. package/packages/frond/src/index.ts +1 -1
  38. package/packages/orm/dist/index.js +1156 -560
  39. package/packages/orm/src/adapters/postgres.ts +79 -19
  40. package/packages/orm/src/crudRender.ts +5 -5
  41. package/packages/orm/src/crudTable.ts +1 -1
  42. package/packages/orm/src/database.ts +15 -29
  43. package/packages/orm/src/databaseResult.ts +11 -1
  44. package/packages/orm/src/docstore.ts +24 -8
  45. package/packages/orm/src/realtime/index.ts +1 -0
  46. package/packages/orm/src/realtime/realtime.ts +2 -1
  47. package/packages/orm/src/realtime/s3Client.ts +276 -0
  48. package/packages/orm/src/realtime/storage.ts +19 -60
  49. package/packages/orm/src/sqlTranslator.ts +58 -42
  50. package/packages/swagger/dist/index.js +25 -4
  51. package/packages/swagger/src/generator.ts +7 -4
  52. package/packages/swagger/src/ui.ts +2 -1
  53. package/types/cli/src/bin.d.ts +16 -0
  54. package/types/cli/src/commands/generate.d.ts +11 -0
  55. package/types/cli/src/commands/migrateCreate.d.ts +2 -0
  56. package/types/cli/src/commands/queue.d.ts +2 -0
  57. package/types/cli/src/util.d.ts +2 -1
  58. package/types/core/src/authGate.d.ts +3 -3
  59. package/types/core/src/devAdmin.d.ts +40 -0
  60. package/types/core/src/index.d.ts +2 -1
  61. package/types/core/src/middleware.d.ts +1 -0
  62. package/types/core/src/optionalPackage.d.ts +2 -2
  63. package/types/core/src/request.d.ts +5 -1
  64. package/types/core/src/session.d.ts +25 -0
  65. package/types/core/src/slashTrim.d.ts +6 -0
  66. package/types/frond/src/engine.d.ts +11 -0
  67. package/types/frond/src/index.d.ts +1 -1
  68. package/types/orm/src/adapters/postgres.d.ts +6 -0
  69. package/types/orm/src/realtime/index.d.ts +1 -0
  70. package/types/orm/src/realtime/s3Client.d.ts +48 -0
  71. package/types/orm/src/realtime/storage.d.ts +9 -7
@@ -13,6 +13,30 @@ var __export = (target, all) => {
13
13
  __defProp(target, name, { get: all[name], enumerable: true });
14
14
  };
15
15
 
16
+ // src/slashTrim.ts
17
+ function rtrimSlashes(s) {
18
+ let end = s.length;
19
+ while (end > 0 && s.charCodeAt(end - 1) === SLASH) end--;
20
+ return end === s.length ? s : s.slice(0, end);
21
+ }
22
+ function trimChar(s, code) {
23
+ let start2 = 0;
24
+ let end = s.length;
25
+ while (start2 < end && s.charCodeAt(start2) === code) start2++;
26
+ while (end > start2 && s.charCodeAt(end - 1) === code) end--;
27
+ return start2 === 0 && end === s.length ? s : s.slice(start2, end);
28
+ }
29
+ function trimSlashes(s) {
30
+ return trimChar(s, SLASH);
31
+ }
32
+ var SLASH;
33
+ var init_slashTrim = __esm({
34
+ "src/slashTrim.ts"() {
35
+ "use strict";
36
+ SLASH = 47;
37
+ }
38
+ });
39
+
16
40
  // src/constants.ts
17
41
  var HTTP_OK, HTTP_CREATED, HTTP_ACCEPTED, HTTP_NO_CONTENT, HTTP_MOVED, HTTP_REDIRECT, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_CONFLICT, HTTP_GONE, HTTP_UNPROCESSABLE, HTTP_TOO_MANY, HTTP_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_UNAVAILABLE, APPLICATION_JSON, APPLICATION_XML, APPLICATION_FORM, APPLICATION_OCTET, TEXT_HTML, TEXT_PLAIN, TEXT_CSV, TEXT_XML;
18
42
  var init_constants = __esm({
@@ -1101,7 +1125,7 @@ function resolveAlgorithm(algorithm) {
1101
1125
  return chosen;
1102
1126
  }
1103
1127
  function base64urlEncode(data) {
1104
- return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1128
+ return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
1105
1129
  }
1106
1130
  function base64urlDecode(str) {
1107
1131
  let s = str.replace(/-/g, "+").replace(/_/g, "/");
@@ -1380,6 +1404,12 @@ var init_types = __esm({
1380
1404
  });
1381
1405
 
1382
1406
  // ../orm/src/databaseResult.ts
1407
+ function stripTypeArgs(colType) {
1408
+ const open = colType.indexOf("(");
1409
+ if (open < 0) return colType;
1410
+ const close = colType.indexOf(")", open);
1411
+ return close < 0 ? colType : colType.slice(0, open) + colType.slice(close + 1);
1412
+ }
1383
1413
  var DatabaseResult;
1384
1414
  var init_databaseResult = __esm({
1385
1415
  "../orm/src/databaseResult.ts"() {
@@ -1562,7 +1592,7 @@ var init_databaseResult = __esm({
1562
1592
  const [size, decimals] = this._parseTypeSize(colType);
1563
1593
  return {
1564
1594
  name: col.name,
1565
- type: colType.replace(/\(.*\)/, ""),
1595
+ type: stripTypeArgs(colType),
1566
1596
  size,
1567
1597
  decimals,
1568
1598
  nullable: col.nullable ?? true,
@@ -2119,12 +2149,49 @@ var init_point = __esm({
2119
2149
  });
2120
2150
 
2121
2151
  // ../orm/src/sqlTranslator.ts
2122
- var SQLTranslator, QueryCache;
2152
+ function skipQuoted(sql, i, backslashEscapes) {
2153
+ const c = sql[i];
2154
+ const escapeString = c === "'" && (sql[i - 1] === "E" || sql[i - 1] === "e") && !isIdentChar(sql[i - 2]);
2155
+ const backslash = c !== "`" && (escapeString || backslashEscapes);
2156
+ const n = sql.length;
2157
+ i++;
2158
+ while (i < n) {
2159
+ if (backslash && sql[i] === "\\") {
2160
+ i += 2;
2161
+ continue;
2162
+ }
2163
+ if (sql[i] === c) {
2164
+ if (sql[i + 1] === c) {
2165
+ i += 2;
2166
+ continue;
2167
+ }
2168
+ return i + 1;
2169
+ }
2170
+ i++;
2171
+ }
2172
+ return i;
2173
+ }
2174
+ function skipLineComment(sql, i) {
2175
+ while (i < sql.length && sql[i] !== "\n") i++;
2176
+ return i;
2177
+ }
2178
+ function skipBlockComment(sql, i) {
2179
+ const end = sql.indexOf("*/", i + 2);
2180
+ return end === -1 ? sql.length : end + 2;
2181
+ }
2182
+ function skipDollarQuote(sql, i) {
2183
+ const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
2184
+ if (!tag) return i;
2185
+ const end = sql.indexOf(tag[0], i + tag[0].length);
2186
+ return end === -1 ? sql.length : end + tag[0].length;
2187
+ }
2188
+ var isIdentChar, SQLTranslator, QueryCache;
2123
2189
  var init_sqlTranslator = __esm({
2124
2190
  "../orm/src/sqlTranslator.ts"() {
2125
2191
  "use strict";
2126
2192
  init_databaseUrl();
2127
2193
  init_point();
2194
+ isIdentChar = (ch) => !!ch && /[A-Za-z0-9_]/.test(ch);
2128
2195
  SQLTranslator = class _SQLTranslator {
2129
2196
  static SPATIAL_ENGINES = /* @__PURE__ */ new Set(["postgres", "postgresql"]);
2130
2197
  static SPATIAL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;
@@ -2405,47 +2472,26 @@ var init_sqlTranslator = __esm({
2405
2472
  static placeholderPositions(sql, options = {}) {
2406
2473
  const positions = [];
2407
2474
  const n = sql.length;
2408
- const isIdent = (ch) => !!ch && /[A-Za-z0-9_]/.test(ch);
2409
2475
  let i = 0;
2410
2476
  while (i < n) {
2411
2477
  const c = sql[i];
2412
2478
  const next = sql[i + 1];
2413
2479
  if (c === "'" || c === '"' || c === "`") {
2414
- const prev = sql[i - 1];
2415
- const escapeString = c === "'" && (prev === "E" || prev === "e") && !isIdent(sql[i - 2]);
2416
- const backslash = c !== "`" && (escapeString || options.backslashEscapes === true);
2417
- i++;
2418
- while (i < n) {
2419
- if (backslash && sql[i] === "\\") {
2420
- i += 2;
2421
- continue;
2422
- }
2423
- if (sql[i] === c) {
2424
- if (sql[i + 1] === c) {
2425
- i += 2;
2426
- continue;
2427
- }
2428
- i++;
2429
- break;
2430
- }
2431
- i++;
2432
- }
2480
+ i = skipQuoted(sql, i, options.backslashEscapes === true);
2433
2481
  continue;
2434
2482
  }
2435
2483
  if (c === "-" && next === "-") {
2436
- while (i < n && sql[i] !== "\n") i++;
2484
+ i = skipLineComment(sql, i);
2437
2485
  continue;
2438
2486
  }
2439
2487
  if (c === "/" && next === "*") {
2440
- const end = sql.indexOf("*/", i + 2);
2441
- i = end === -1 ? n : end + 2;
2488
+ i = skipBlockComment(sql, i);
2442
2489
  continue;
2443
2490
  }
2444
- if (c === "$" && !isIdent(sql[i - 1])) {
2445
- const tag = sql.slice(i).match(/^\$([A-Za-z_][A-Za-z0-9_]*)?\$/);
2446
- if (tag) {
2447
- const end = sql.indexOf(tag[0], i + tag[0].length);
2448
- i = end === -1 ? n : end + tag[0].length;
2491
+ if (c === "$" && !isIdentChar(sql[i - 1])) {
2492
+ const past = skipDollarQuote(sql, i);
2493
+ if (past !== i) {
2494
+ i = past;
2449
2495
  continue;
2450
2496
  }
2451
2497
  }
@@ -2478,7 +2524,7 @@ var init_sqlTranslator = __esm({
2478
2524
  * → { sql: "INSERT INTO t (x) VALUES (1)", columns: ["id", "name"] }
2479
2525
  */
2480
2526
  static parseReturning(sql) {
2481
- const m = sql.match(/\bRETURNING\s+(.+)$/i);
2527
+ const m = sql.match(/\bRETURNING\s+(\S.*)$/i);
2482
2528
  if (!m) return { sql, columns: [] };
2483
2529
  const columns = m[1].split(",").map((c) => c.trim());
2484
2530
  return {
@@ -2532,7 +2578,12 @@ var init_sqlTranslator = __esm({
2532
2578
  // The `d` flag records group indices, so the head can be sliced at the exact
2533
2579
  // start of the VALUES group rather than by hunting for a parenthesis (the
2534
2580
  // column list has parentheses too).
2535
- static INSERT_VALUES = /^\s*INSERT\s+INTO\s+.+?\s+VALUES\s*\(([^()]*)\)\s*$/dis;
2581
+ static INSERT_VALUES = (
2582
+ // ReDoS-safe: the table ref matches `\S(?:[\s\S]*?\S)?` (bounded by non-space
2583
+ // at both ends) so the separator `\s+` before VALUES can't overlap it the way
2584
+ // the old `.+?\s+` did (polynomial on `INSERT INTO ` + a long space run).
2585
+ /^\s*INSERT\s+INTO\s+\S(?:[\s\S]*?\S)?\s+VALUES\s*\(([^()]*)\)\s*$/dis
2586
+ );
2536
2587
  /**
2537
2588
  * Engines whose lastInsertId reports the FIRST generated id of a multi-row
2538
2589
  * INSERT rather than the last. Verified live, not assumed: a 3-row insert
@@ -4217,6 +4268,9 @@ var init_postgres = __esm({
4217
4268
  await withConnectTimeout(
4218
4269
  () => {
4219
4270
  this.client = typeof this.config === "string" ? new Client({ connectionString: this.config, ...timeoutOption }) : new Client({ ...this.config, ...timeoutOption });
4271
+ this.client.on("error", () => {
4272
+ this.connectionIsDead = true;
4273
+ });
4220
4274
  return this.client.connect();
4221
4275
  },
4222
4276
  budgetMs,
@@ -4240,6 +4294,52 @@ var init_postgres = __esm({
4240
4294
  throw new Error("PostgreSQL adapter not connected. Call connect() first.");
4241
4295
  }
4242
4296
  }
4297
+ // ── Reconnect after a dropped link (parity with the Python master, #236/#242) ──
4298
+ // pg's Client does not reconnect itself: once the server drops the link it must
4299
+ // be rebuilt. A statement that hits a dropped link reconnects and retries once
4300
+ // when nothing uncommitted went down with it; inside an explicit transaction the
4301
+ // error surfaces. A reconnect that itself fails leaves the link dead (not null-
4302
+ // guarded away), so the NEXT statement retries and recovers once a server returns.
4303
+ connectionIsDead = false;
4304
+ isConnectionError(e) {
4305
+ const msg = e instanceof Error ? e.message : String(e);
4306
+ 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);
4307
+ }
4308
+ async reconnect() {
4309
+ void Promise.resolve(this.client?.end()).catch(() => {
4310
+ });
4311
+ this.client = null;
4312
+ this.connectionIsDead = false;
4313
+ await this.connect();
4314
+ }
4315
+ async ensureLiveConnection() {
4316
+ if (!this._inTransaction && (this.client === null || this.connectionIsDead)) {
4317
+ await this.reconnect();
4318
+ }
4319
+ }
4320
+ async runQuery(sql, params) {
4321
+ await this.ensureLiveConnection();
4322
+ this.ensureConnected();
4323
+ try {
4324
+ return await this.client.query(sql, params);
4325
+ } catch (e) {
4326
+ if (!this.isConnectionError(e)) throw e;
4327
+ this.connectionIsDead = true;
4328
+ if (this._inTransaction) throw e;
4329
+ await this.reconnect();
4330
+ return await this.client.query(sql, params);
4331
+ }
4332
+ }
4333
+ // Transaction control (BEGIN/COMMIT/ROLLBACK) runs RAW - no reconnect, no
4334
+ // pre-heal. A failed BEGIN/COMMIT/ROLLBACK must surface so the connection-pool
4335
+ // layer can discard the connection and restore capacity; reconnecting or
4336
+ // retrying here would mask that failure (databasePoolIsolation contract).
4337
+ // Dropped-link recovery stays on the DATA path (runQuery): the next data
4338
+ // statement heals the link.
4339
+ async rawQuery(sql) {
4340
+ this.ensureConnected();
4341
+ await this.client.query(sql);
4342
+ }
4243
4343
  /** Convert ? placeholders to $1, $2, ... for pg. */
4244
4344
  /** Ensure bytea columns are Buffer (already the case with pg). No-op guard. */
4245
4345
  decodeBlobs(row) {
@@ -4289,7 +4389,6 @@ var init_postgres = __esm({
4289
4389
  return null;
4290
4390
  }
4291
4391
  execute(sql, params) {
4292
- this.ensureConnected();
4293
4392
  const convertedSql = this.convertPlaceholders(sql);
4294
4393
  throw new Error("Use executeAsync() for PostgreSQL \u2014 async adapter requires async methods.");
4295
4394
  }
@@ -4324,9 +4423,8 @@ var init_postgres = __esm({
4324
4423
  }
4325
4424
  /** Async execute for real usage. */
4326
4425
  async executeAsync(sql, params) {
4327
- this.ensureConnected();
4328
4426
  const convertedSql = this.bindable(sql, params);
4329
- const result = await this.client.query(convertedSql, params);
4427
+ const result = await this.runQuery(convertedSql, params);
4330
4428
  if (result.rows?.[0]?.id !== void 0) {
4331
4429
  this._lastInsertId = this.normalizeId(result.rows[0].id);
4332
4430
  }
@@ -4337,9 +4435,8 @@ var init_postgres = __esm({
4337
4435
  }
4338
4436
  /** Async query for real usage. */
4339
4437
  async queryAsync(sql, params) {
4340
- this.ensureConnected();
4341
4438
  const convertedSql = this.bindable(sql, params);
4342
- const result = await this.client.query(convertedSql, params);
4439
+ const result = await this.runQuery(convertedSql, params);
4343
4440
  return result.rows.map((row) => this.decodeBlobs(row));
4344
4441
  }
4345
4442
  fetch(sql, params, limit, skip) {
@@ -4367,7 +4464,6 @@ var init_postgres = __esm({
4367
4464
  throw new Error("Use insertAsync() for PostgreSQL.");
4368
4465
  }
4369
4466
  async insertAsync(table2, data) {
4370
- this.ensureConnected();
4371
4467
  if (Array.isArray(data)) {
4372
4468
  const batch = buildInsertRows(ANSI_DIALECT, table2, data);
4373
4469
  if (!batch) return { success: true, affectedRows: 0 };
@@ -4381,7 +4477,7 @@ var init_postgres = __esm({
4381
4477
  }
4382
4478
  const { sql, values } = buildInsertRow(POSTGRES_DIALECT, table2, data, " RETURNING *");
4383
4479
  try {
4384
- const result = await this.client.query(sql, values);
4480
+ const result = await this.runQuery(sql, values);
4385
4481
  const insertedRow = result.rows[0];
4386
4482
  const id = this.normalizeId(insertedRow?.id);
4387
4483
  if (id !== null) this._lastInsertId = id;
@@ -4398,13 +4494,12 @@ var init_postgres = __esm({
4398
4494
  throw new Error("Use updateAsync() for PostgreSQL.");
4399
4495
  }
4400
4496
  async updateAsync(table2, data, filter, params) {
4401
- this.ensureConnected();
4402
4497
  const { sql, values } = buildUpdate(POSTGRES_DIALECT, table2, data, filter, params, {
4403
4498
  startAt: 1,
4404
4499
  convertFragment: (fragment, startAt) => this.convertPlaceholders(fragment, startAt)
4405
4500
  });
4406
4501
  try {
4407
- const result = await this.client.query(sql, values);
4502
+ const result = await this.runQuery(sql, values);
4408
4503
  return { success: true, affectedRows: result.rowCount ?? 0 };
4409
4504
  } catch (e) {
4410
4505
  return { success: false, affectedRows: 0, error: e.message };
@@ -4414,13 +4509,12 @@ var init_postgres = __esm({
4414
4509
  throw new Error("Use deleteAsync() for PostgreSQL.");
4415
4510
  }
4416
4511
  async deleteAsync(table2, filter, params) {
4417
- this.ensureConnected();
4418
4512
  const { sql, values } = buildDelete(POSTGRES_DIALECT, table2, filter, params, {
4419
4513
  startAt: 1,
4420
4514
  convertFragment: (fragment) => this.bindable(fragment, params)
4421
4515
  });
4422
4516
  try {
4423
- const result = await this.client.query(sql, values);
4517
+ const result = await this.runQuery(sql, values);
4424
4518
  return { success: true, affectedRows: result.rowCount ?? 0 };
4425
4519
  } catch (e) {
4426
4520
  return { success: false, affectedRows: 0, error: e.message };
@@ -4430,22 +4524,28 @@ var init_postgres = __esm({
4430
4524
  throw new Error("Use startTransactionAsync() for PostgreSQL.");
4431
4525
  }
4432
4526
  async startTransactionAsync() {
4433
- await this.executeAsync("BEGIN");
4527
+ await this.rawQuery("BEGIN");
4434
4528
  this._inTransaction = true;
4435
4529
  }
4436
4530
  commit() {
4437
4531
  throw new Error("Use commitAsync() for PostgreSQL.");
4438
4532
  }
4439
4533
  async commitAsync() {
4440
- await this.executeAsync("COMMIT");
4441
- this._inTransaction = false;
4534
+ try {
4535
+ await this.rawQuery("COMMIT");
4536
+ } finally {
4537
+ this._inTransaction = false;
4538
+ }
4442
4539
  }
4443
4540
  rollback() {
4444
4541
  throw new Error("Use rollbackAsync() for PostgreSQL.");
4445
4542
  }
4446
4543
  async rollbackAsync() {
4447
- await this.executeAsync("ROLLBACK");
4448
- this._inTransaction = false;
4544
+ try {
4545
+ await this.rawQuery("ROLLBACK");
4546
+ } finally {
4547
+ this._inTransaction = false;
4548
+ }
4449
4549
  }
4450
4550
  getTables() {
4451
4551
  throw new Error("Use tablesAsync() for PostgreSQL.");
@@ -7272,7 +7372,7 @@ __export(database_exports, {
7272
7372
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
7273
7373
  function stripTrailingSemicolons(sql) {
7274
7374
  if (!sql) return sql;
7275
- let stripped = sql.replace(/\s+$/, "");
7375
+ let stripped = sql.trimEnd();
7276
7376
  while (stripped.endsWith(";")) {
7277
7377
  stripped = stripped.slice(0, -1).replace(/\s+$/, "");
7278
7378
  }
@@ -7439,6 +7539,13 @@ async function createAdapterFromUrl(url, username, password) {
7439
7539
  }
7440
7540
  async function buildAdapterFromUrl(url, username, password) {
7441
7541
  const parsed = parseDatabaseUrl(url, username, password);
7542
+ const serverConfig = {
7543
+ host: parsed.host ?? void 0,
7544
+ port: parsed.port ?? void 0,
7545
+ user: parsed.username ?? void 0,
7546
+ password: parsed.password ?? void 0,
7547
+ database: parsed.database || void 0
7548
+ };
7442
7549
  switch (parsed.engine) {
7443
7550
  case "sqlite": {
7444
7551
  const { SQLiteAdapter: SQLiteAdapter2 } = await Promise.resolve().then(() => (init_sqlite(), sqlite_exports));
@@ -7446,49 +7553,25 @@ async function buildAdapterFromUrl(url, username, password) {
7446
7553
  }
7447
7554
  case "postgres": {
7448
7555
  const { PostgresAdapter: PostgresAdapter2 } = await Promise.resolve().then(() => (init_postgres(), postgres_exports));
7449
- const adapter = new PostgresAdapter2({
7450
- host: parsed.host ?? void 0,
7451
- port: parsed.port ?? void 0,
7452
- user: parsed.username ?? void 0,
7453
- password: parsed.password ?? void 0,
7454
- database: parsed.database || void 0
7455
- });
7556
+ const adapter = new PostgresAdapter2(serverConfig);
7456
7557
  await adapter.connect();
7457
7558
  return adapter;
7458
7559
  }
7459
7560
  case "mysql": {
7460
7561
  const { MysqlAdapter: MysqlAdapter2 } = await Promise.resolve().then(() => (init_mysql(), mysql_exports));
7461
- const adapter = new MysqlAdapter2({
7462
- host: parsed.host ?? void 0,
7463
- port: parsed.port ?? void 0,
7464
- user: parsed.username ?? void 0,
7465
- password: parsed.password ?? void 0,
7466
- database: parsed.database || void 0
7467
- });
7562
+ const adapter = new MysqlAdapter2(serverConfig);
7468
7563
  await adapter.connect();
7469
7564
  return adapter;
7470
7565
  }
7471
7566
  case "mssql": {
7472
7567
  const { MssqlAdapter: MssqlAdapter2 } = await Promise.resolve().then(() => (init_mssql(), mssql_exports));
7473
- const adapter = new MssqlAdapter2({
7474
- host: parsed.host ?? void 0,
7475
- port: parsed.port ?? void 0,
7476
- user: parsed.username ?? void 0,
7477
- password: parsed.password ?? void 0,
7478
- database: parsed.database || void 0
7479
- });
7568
+ const adapter = new MssqlAdapter2(serverConfig);
7480
7569
  await adapter.connect();
7481
7570
  return adapter;
7482
7571
  }
7483
7572
  case "firebird": {
7484
7573
  const { FirebirdAdapter: FirebirdAdapter2 } = await Promise.resolve().then(() => (init_firebird(), firebird_exports));
7485
- const adapter = new FirebirdAdapter2({
7486
- host: parsed.host ?? void 0,
7487
- port: parsed.port ?? void 0,
7488
- user: parsed.username ?? void 0,
7489
- password: parsed.password ?? void 0,
7490
- database: parsed.database || void 0
7491
- });
7574
+ const adapter = new FirebirdAdapter2(serverConfig);
7492
7575
  await adapter.connect();
7493
7576
  return adapter;
7494
7577
  }
@@ -10224,9 +10307,11 @@ __export(engine_exports, {
10224
10307
  escapeHtml: () => escapeHtml,
10225
10308
  expressionFormCache: () => expressionFormCache,
10226
10309
  filterChainCache: () => filterChainCache,
10310
+ frondRange: () => frondRange,
10227
10311
  pathParseCache: () => pathParseCache,
10228
10312
  setCspNonceProvider: () => setCspNonceProvider,
10229
- setFormTokenSessionId: () => setFormTokenSessionId
10313
+ setFormTokenSessionId: () => setFormTokenSessionId,
10314
+ setFormTokenSessionProvider: () => setFormTokenSessionProvider
10230
10315
  });
10231
10316
  import { createHash as createHash3, createHmac as createHmac2, randomBytes as randomBytes2 } from "node:crypto";
10232
10317
  import { readFileSync as readFileSync4, existsSync as existsSync5, statSync as statSync4, realpathSync } from "node:fs";
@@ -10311,6 +10396,14 @@ function renderDump(value) {
10311
10396
  const escaped = dumped.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
10312
10397
  return new SafeString(`<pre>${escaped}</pre>`);
10313
10398
  }
10399
+ function stripTags(input) {
10400
+ let s = input, prev;
10401
+ do {
10402
+ prev = s;
10403
+ s = s.replace(STRIP_TAGS_RE, "");
10404
+ } while (s !== prev);
10405
+ return s;
10406
+ }
10314
10407
  function liveAttr(value) {
10315
10408
  return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
10316
10409
  }
@@ -10328,35 +10421,58 @@ function sweepExpiredCache(cache) {
10328
10421
  if (expiresAt2 <= now) cache.delete(key);
10329
10422
  }
10330
10423
  }
10331
- function tokenize(source) {
10424
+ function extractRawBlocks(source) {
10332
10425
  const rawBlocks = [];
10333
- source = source.replace(RAW_BLOCK_RE, (_match, content) => {
10426
+ let out = "";
10427
+ let pos = 0;
10428
+ RAW_OPEN_RE.lastIndex = 0;
10429
+ let om;
10430
+ while ((om = RAW_OPEN_RE.exec(source)) !== null) {
10431
+ const openStart = om.index;
10432
+ const openEnd = RAW_OPEN_RE.lastIndex;
10433
+ RAW_CLOSE_RE.lastIndex = openEnd;
10434
+ const cm = RAW_CLOSE_RE.exec(source);
10435
+ if (cm === null) break;
10334
10436
  const idx = rawBlocks.length;
10335
- rawBlocks.push(content);
10336
- return `\0RAW_${idx}\0`;
10337
- });
10437
+ rawBlocks.push(source.slice(openEnd, cm.index));
10438
+ out += source.slice(pos, openStart) + `\0RAW_${idx}\0`;
10439
+ pos = RAW_CLOSE_RE.lastIndex;
10440
+ RAW_OPEN_RE.lastIndex = pos;
10441
+ }
10442
+ out += source.slice(pos);
10443
+ return { source: out, rawBlocks };
10444
+ }
10445
+ function tokenize(rawSource) {
10446
+ const { source, rawBlocks } = extractRawBlocks(rawSource);
10338
10447
  const tokens = [];
10448
+ const n = source.length;
10339
10449
  let pos = 0;
10340
- TOKEN_RE.lastIndex = 0;
10341
- let m;
10342
- while ((m = TOKEN_RE.exec(source)) !== null) {
10343
- const start2 = m.index;
10344
- if (start2 > pos) {
10345
- tokens.push(["TEXT", source.slice(pos, start2)]);
10450
+ let scan = 0;
10451
+ const exhausted = { "%}": false, "}}": false, "#}": false };
10452
+ while (scan < n) {
10453
+ const brace = source.indexOf("{", scan);
10454
+ if (brace === -1) break;
10455
+ const kind = TAG_KINDS[source[brace + 1]];
10456
+ if (!kind) {
10457
+ scan = brace + 1;
10458
+ continue;
10346
10459
  }
10347
- const raw = m[0];
10348
- if (raw.startsWith("{#")) {
10349
- tokens.push(["COMMENT", raw]);
10350
- } else if (raw.startsWith("{{")) {
10351
- tokens.push(["VAR", raw]);
10352
- } else if (raw.startsWith("{%")) {
10353
- tokens.push(["BLOCK", raw]);
10460
+ if (exhausted[kind.close]) {
10461
+ scan = brace + 1;
10462
+ continue;
10354
10463
  }
10355
- pos = m.index + raw.length;
10356
- }
10357
- if (pos < source.length) {
10358
- tokens.push(["TEXT", source.slice(pos)]);
10464
+ const close = source.indexOf(kind.close, brace + 2);
10465
+ if (close === -1) {
10466
+ exhausted[kind.close] = true;
10467
+ scan = brace + 1;
10468
+ continue;
10469
+ }
10470
+ if (brace > pos) tokens.push(["TEXT", source.slice(pos, brace)]);
10471
+ tokens.push([kind.type, source.slice(brace, close + 2)]);
10472
+ pos = close + 2;
10473
+ scan = close + 2;
10359
10474
  }
10475
+ if (pos < n) tokens.push(["TEXT", source.slice(pos)]);
10360
10476
  if (rawBlocks.length > 0) {
10361
10477
  for (let i = 0; i < tokens.length; i++) {
10362
10478
  if (tokens[i][0] === "TEXT" && tokens[i][1].includes("\0RAW_")) {
@@ -10682,26 +10798,123 @@ function evalConcatOrComparison(expr, context) {
10682
10798
  }
10683
10799
  return EXPR_NOT_MATCHED;
10684
10800
  }
10801
+ function topLevelPositions(expr) {
10802
+ const positions = [];
10803
+ let inQuote = null;
10804
+ let depth = 0;
10805
+ for (let pos = 0; pos < expr.length; pos++) {
10806
+ const ch = expr[pos];
10807
+ if (inQuote) {
10808
+ if (ch === inQuote) inQuote = null;
10809
+ } else if (ch === '"' || ch === "'") {
10810
+ inQuote = ch;
10811
+ } else if ("([{".includes(ch)) {
10812
+ depth++;
10813
+ } else if (")]}".includes(ch)) {
10814
+ depth--;
10815
+ } else if (depth === 0) {
10816
+ positions.push(pos);
10817
+ }
10818
+ }
10819
+ return positions;
10820
+ }
10821
+ function followsOperand(expr, pos) {
10822
+ return /[\w)\]'"]$/.test(expr.slice(0, pos).trimEnd());
10823
+ }
10824
+ function topLevelArithmeticOperators(expr) {
10825
+ const operators = [];
10826
+ let skipUntil = -1;
10827
+ for (const pos of topLevelPositions(expr)) {
10828
+ if (pos < skipUntil || !"+-*/%".includes(expr[pos])) continue;
10829
+ const pair = expr.slice(pos, pos + 2);
10830
+ const op = pair === "**" || pair === "//" ? pair : expr[pos];
10831
+ skipUntil = pos + op.length;
10832
+ if (followsOperand(expr, pos)) operators.push([pos, op]);
10833
+ }
10834
+ return operators;
10835
+ }
10836
+ function splitArithmetic(expr) {
10837
+ const operators = topLevelArithmeticOperators(expr);
10838
+ for (const level of ARITHMETIC_LEVELS) {
10839
+ const matches = operators.filter(([, op]) => level.includes(op));
10840
+ if (matches.length > 0) return level[0] === "**" ? matches[0] : matches[matches.length - 1];
10841
+ }
10842
+ return null;
10843
+ }
10685
10844
  function evalArithmeticExpression(expr, context) {
10686
- for (const op of [" + ", " - ", " * ", " // ", " / ", " % ", " ** "]) {
10687
- const pos = findOutsideQuotes(expr, op);
10688
- if (pos >= 0) {
10689
- const left = expr.slice(0, pos).trim();
10690
- const right = expr.slice(pos + op.length).trim();
10691
- const lVal = evalExpr(left, context);
10692
- const rVal = evalExpr(right, context);
10693
- try {
10694
- let lNum = lVal != null ? Number(lVal) : 0;
10695
- let rNum = rVal != null ? Number(rVal) : 0;
10696
- if (isNaN(lNum)) lNum = 0;
10697
- if (isNaN(rNum)) rNum = 0;
10698
- return ARITHMETIC_OPERATIONS[op.trim()](lNum, rNum);
10699
- } catch {
10700
- return null;
10701
- }
10845
+ const split = splitArithmetic(expr);
10846
+ if (!split) return EXPR_NOT_MATCHED;
10847
+ const [pos, op] = split;
10848
+ const lVal = evalExpr(expr.slice(0, pos).trim(), context);
10849
+ const rVal = evalExpr(expr.slice(pos + op.length).trim(), context);
10850
+ let lNum = lVal != null ? Number(lVal) : 0;
10851
+ let rNum = rVal != null ? Number(rVal) : 0;
10852
+ if (isNaN(lNum)) lNum = 0;
10853
+ if (isNaN(rNum)) rNum = 0;
10854
+ return ARITHMETIC_OPERATIONS[op](lNum, rNum);
10855
+ }
10856
+ function frondRange(start2, end, step = 1) {
10857
+ const numeric = (value) => typeof value === "number" || typeof value === "string" && NUMERIC_RE.test(value);
10858
+ if (!numeric(start2) || !numeric(end) || !numeric(step)) return [];
10859
+ const first = Math.trunc(Number(start2));
10860
+ const last = Math.trunc(Number(end));
10861
+ const stride = Math.abs(Math.trunc(Number(step)));
10862
+ if (stride === 0) return [];
10863
+ const values = [];
10864
+ if (first <= last) for (let value = first; value <= last; value += stride) values.push(value);
10865
+ else for (let value = first; value >= last; value -= stride) values.push(value);
10866
+ return values;
10867
+ }
10868
+ function findRangeOperator(expr) {
10869
+ let pos = findOutsideQuotes(expr, "..");
10870
+ while (pos >= 0) {
10871
+ const partOfEllipsis = expr.startsWith("...", pos) || pos > 0 && expr[pos - 1] === ".";
10872
+ if (pos > 0 && !partOfEllipsis) return findOutsideQuotes(expr.slice(pos + 2), "|") >= 0 ? -1 : pos;
10873
+ const next = findOutsideQuotes(expr.slice(pos + 2), "..");
10874
+ pos = next >= 0 ? pos + 2 + next : -1;
10875
+ }
10876
+ return -1;
10877
+ }
10878
+ function evalRangeExpression(expr, context) {
10879
+ const pos = findRangeOperator(expr);
10880
+ if (pos < 0) return EXPR_NOT_MATCHED;
10881
+ return frondRange(evalExpr(expr.slice(0, pos).trim(), context), evalExpr(expr.slice(pos + 2).trim(), context));
10882
+ }
10883
+ function closingBracketIndex(expr) {
10884
+ let depth = 0;
10885
+ let inQuote = null;
10886
+ for (let i = 0; i < expr.length; i++) {
10887
+ const ch = expr[i];
10888
+ if (inQuote) {
10889
+ if (ch === inQuote) inQuote = null;
10890
+ } else if (ch === '"' || ch === "'") {
10891
+ inQuote = ch;
10892
+ } else if ("([{".includes(ch)) {
10893
+ depth++;
10894
+ } else if (")]}".includes(ch) && --depth === 0) {
10895
+ return i;
10702
10896
  }
10703
10897
  }
10704
- return EXPR_NOT_MATCHED;
10898
+ return -1;
10899
+ }
10900
+ function mapLiteralKey(rawKey, context) {
10901
+ const quoted = rawKey.length >= 2 && (rawKey[0] === '"' || rawKey[0] === "'") && rawKey.endsWith(rawKey[0]);
10902
+ if (quoted) return rawKey.slice(1, -1);
10903
+ return BARE_KEY_RE.test(rawKey) ? rawKey : String(evalExpr(rawKey, context));
10904
+ }
10905
+ function evalMapLiteral(inner, context) {
10906
+ const map = {};
10907
+ for (const pair of inner === "" ? [] : splitArgs(inner)) {
10908
+ const colon = findOutsideQuotes(pair, ":");
10909
+ if (colon > 0) map[mapLiteralKey(pair.slice(0, colon).trim(), context)] = evalExpr(pair.slice(colon + 1).trim(), context);
10910
+ }
10911
+ return map;
10912
+ }
10913
+ function evalCollectionLiteral(expr, context) {
10914
+ if (expr[0] !== "[" && expr[0] !== "{" || closingBracketIndex(expr) !== expr.length - 1) return EXPR_NOT_MATCHED;
10915
+ const inner = expr.slice(1, -1).trim();
10916
+ if (expr[0] === "{") return evalMapLiteral(inner, context);
10917
+ return inner === "" ? [] : splitArgs(inner).map((item) => evalExpr(item.trim(), context));
10705
10918
  }
10706
10919
  function evalFilterExpression(expr, context) {
10707
10920
  if (findOutsideQuotes(expr, "|") >= 0) {
@@ -11123,12 +11336,12 @@ function splitArgs(raw) {
11123
11336
  current += ch;
11124
11337
  continue;
11125
11338
  }
11126
- if (ch === "(" || ch === "[") {
11339
+ if (ch === "(" || ch === "[" || ch === "{") {
11127
11340
  depth++;
11128
11341
  current += ch;
11129
11342
  continue;
11130
11343
  }
11131
- if (ch === ")" || ch === "]") {
11344
+ if (ch === ")" || ch === "]" || ch === "}") {
11132
11345
  depth--;
11133
11346
  current += ch;
11134
11347
  continue;
@@ -11293,11 +11506,14 @@ function formatMatch(match, flags, width, prec, type2, arg) {
11293
11506
  return padFormattedValue(formatValue(type2, precision, arg), flags, width);
11294
11507
  }
11295
11508
  function _b64url(data) {
11296
- return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
11509
+ return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
11297
11510
  }
11298
11511
  function setFormTokenSessionId(sessionId) {
11299
11512
  _formTokenSessionId = sessionId || "";
11300
11513
  }
11514
+ function setFormTokenSessionProvider(fn) {
11515
+ _formTokenSessionProvider = fn;
11516
+ }
11301
11517
  function setCspNonceProvider(fn) {
11302
11518
  _cspNonceProvider = fn;
11303
11519
  }
@@ -11322,8 +11538,9 @@ function _buildFormTokenJwt(descriptor = "") {
11322
11538
  payload.context = descriptor;
11323
11539
  }
11324
11540
  }
11325
- if (_formTokenSessionId) {
11326
- payload.session_id = _formTokenSessionId;
11541
+ const sessionId = _formTokenSessionProvider() || _formTokenSessionId;
11542
+ if (sessionId) {
11543
+ payload.session_id = sessionId;
11327
11544
  }
11328
11545
  const h2 = _b64url(Buffer.from(JSON.stringify(header)));
11329
11546
  const p = _b64url(Buffer.from(JSON.stringify(payload)));
@@ -11339,7 +11556,7 @@ function _generateFormToken(descriptor = "") {
11339
11556
  function _generateFormTokenValue(descriptor = "") {
11340
11557
  return new SafeString(_buildFormTokenJwt(descriptor));
11341
11558
  }
11342
- 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, LEADING_WS_RE, TRAILING_WS_RE, THOUSANDS_RE, LIVE_RE, LIVE_WS_RE, LIVE_SRC_RE, EXTENDS_RE, EXTENDS_RE_GLOBAL, filterChainCache, pathParseCache, TEMPLATE_CACHE_MAX, MEMO_CACHE_MAX, TOKEN_RE, RAW_BLOCK_RE, EXPR_NOT_MATCHED, ARITHMETIC_OPERATIONS, EXPR_EVALUATORS, expressionFormCache, VarRef, JS_SAFE_RE, MEDIA_TYPE_RE, SANDBOX_EXPR_KEYWORDS, SANDBOX_IDENT_RE, SANDBOX_STRING_RE, UNSAFE_KEYS, BUILTIN_FILTERS, _formTokenSessionId, _cspNonceProvider, Frond;
11559
+ 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;
11343
11560
  var init_engine = __esm({
11344
11561
  "../frond/src/engine.ts"() {
11345
11562
  "use strict";
@@ -11441,7 +11658,7 @@ var init_engine = __esm({
11441
11658
  int: (value) => value ? parseInt(String(value), 10) || 0 : 0,
11442
11659
  float: (value) => value ? parseFloat(String(value)) || 0 : 0,
11443
11660
  abs: (value) => typeof value === "number" ? Math.abs(value) : value,
11444
- striptags: (value) => String(value).replace(STRIP_TAGS_RE, ""),
11661
+ striptags: (value) => stripTags(String(value)),
11445
11662
  first: (value) => Array.isArray(value) ? value[0] ?? null : null,
11446
11663
  last: (value) => Array.isArray(value) ? value[value.length - 1] ?? null : null,
11447
11664
  keys: (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? Object.keys(value) : [],
@@ -11455,20 +11672,23 @@ var init_engine = __esm({
11455
11672
  filter: (value) => Array.isArray(value) ? value.filter(Boolean) : value
11456
11673
  };
11457
11674
  FORMAT_RE = /%%|%([-+ 0]*)(\d+)?(?:\.(\d+))?([sdifFeEgGxXob])/g;
11458
- LEADING_WS_RE = /^\s+/;
11459
- TRAILING_WS_RE = /\s+$/;
11460
11675
  THOUSANDS_RE = /\B(?=(\d{3})+(?!\d))/g;
11461
11676
  LIVE_RE = /^live\s+["']([^"']+)["']([\s\S]*)$/;
11462
11677
  LIVE_WS_RE = /ws\s+["']([^"']+)["']/;
11463
11678
  LIVE_SRC_RE = /src\s+["']([^"']+)["']/;
11464
- EXTENDS_RE = /\{%[-\s]*extends\s+["'](.+?)["']\s*[-]?%\}/;
11465
- EXTENDS_RE_GLOBAL = /\{%[-\s]*extends\s+["'](.+?)["']\s*[-]?%\}/g;
11679
+ EXTENDS_RE = /\{%[-\s]*extends\s+["']([^"']+)["']\s*[-]?%\}/;
11680
+ EXTENDS_RE_GLOBAL = /\{%[-\s]*extends\s+["']([^"']+)["']\s*[-]?%\}/g;
11466
11681
  filterChainCache = /* @__PURE__ */ new Map();
11467
11682
  pathParseCache = /* @__PURE__ */ new Map();
11468
11683
  TEMPLATE_CACHE_MAX = 256;
11469
11684
  MEMO_CACHE_MAX = 1024;
11470
- TOKEN_RE = /(\{%-?\s*[\s\S]*?\s*-?%\})|(\{\{-?\s*[\s\S]*?\s*-?\}\})|(\{#[\s\S]*?#\})/g;
11471
- RAW_BLOCK_RE = /\{%-?\s*raw\s*-?%\}([\s\S]*?)\{%-?\s*endraw\s*-?%\}/g;
11685
+ RAW_OPEN_RE = /\{%-?\s*raw\s*-?%\}/g;
11686
+ RAW_CLOSE_RE = /\{%-?\s*endraw\s*-?%\}/g;
11687
+ TAG_KINDS = {
11688
+ "%": { close: "%}", type: "BLOCK" },
11689
+ "{": { close: "}}", type: "VAR" },
11690
+ "#": { close: "#}", type: "COMMENT" }
11691
+ };
11472
11692
  EXPR_NOT_MATCHED = /* @__PURE__ */ Symbol("frond-expression-not-matched");
11473
11693
  ARITHMETIC_OPERATIONS = {
11474
11694
  "+": (left, right) => left + right,
@@ -11479,10 +11699,14 @@ var init_engine = __esm({
11479
11699
  "%": (left, right) => right !== 0 ? left % right : 0,
11480
11700
  "**": (left, right) => left ** right
11481
11701
  };
11702
+ ARITHMETIC_LEVELS = [["+", "-"], ["*", "//", "/", "%"], ["**"]];
11703
+ BARE_KEY_RE = /^[A-Za-z_]\w*$/;
11482
11704
  EXPR_EVALUATORS = [
11705
+ evalCollectionLiteral,
11483
11706
  evalPrimary,
11484
11707
  evalConditional,
11485
11708
  evalConcatOrComparison,
11709
+ evalRangeExpression,
11486
11710
  evalArithmeticExpression,
11487
11711
  evalFilterExpression,
11488
11712
  evalFunctionExpression
@@ -11538,8 +11762,8 @@ var init_engine = __esm({
11538
11762
  },
11539
11763
  title: (v) => String(v).replace(TITLE_WORD_RE, (c) => c.toUpperCase()),
11540
11764
  trim: (v) => String(v).trim(),
11541
- ltrim: (v) => String(v).replace(LEADING_WS_RE, ""),
11542
- rtrim: (v) => String(v).replace(TRAILING_WS_RE, ""),
11765
+ ltrim: (v) => String(v).trimStart(),
11766
+ rtrim: (v) => String(v).trimEnd(),
11543
11767
  length: (v) => {
11544
11768
  if (Array.isArray(v)) return v.length;
11545
11769
  if (typeof v === "string") return v.length;
@@ -11580,7 +11804,7 @@ var init_engine = __esm({
11580
11804
  safe: (v) => v,
11581
11805
  escape: (v, ...a) => escapeStrategy(v, a[0] ?? "html"),
11582
11806
  e: (v, ...a) => escapeStrategy(v, a[0] ?? "html"),
11583
- striptags: (v) => String(v).replace(STRIP_TAGS_RE, ""),
11807
+ striptags: (v) => stripTags(String(v)),
11584
11808
  nl2br: (v) => new SafeString(htmlEscape(String(v)).replace(/\n/g, "<br />\n")),
11585
11809
  abs: (v) => typeof v === "number" ? Math.abs(v) : v,
11586
11810
  round: (v, decimals) => {
@@ -11693,6 +11917,7 @@ var init_engine = __esm({
11693
11917
  js_escape: (v) => new SafeString(jsEscape(v))
11694
11918
  };
11695
11919
  _formTokenSessionId = "";
11920
+ _formTokenSessionProvider = () => "";
11696
11921
  _cspNonceProvider = () => "";
11697
11922
  Frond = class _Frond {
11698
11923
  // ── Class-level registries ──────────────────────────────────
@@ -11846,6 +12071,7 @@ var init_engine = __esm({
11846
12071
  this.globals.form_token = (descriptor) => _generateFormToken(descriptor || "");
11847
12072
  this.globals.formTokenValue = (descriptor) => _generateFormTokenValue(descriptor || "");
11848
12073
  this.globals.form_token_value = (descriptor) => _generateFormTokenValue(descriptor || "");
12074
+ this.globals.range = frondRange;
11849
12075
  this.globals.dump = (value) => renderDump(value);
11850
12076
  this.globals.csp_nonce = () => _cspNonceProvider();
11851
12077
  for (const [k, v] of _Frond.classFilters) this.filters[k] = v;
@@ -12182,20 +12408,20 @@ var init_engine = __esm({
12182
12408
  }
12183
12409
  renderVarToken(tokens, index, context, output) {
12184
12410
  const [content, stripB, stripA] = stripTag(tokens[index][1]);
12185
- if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].replace(TRAILING_WS_RE, "");
12411
+ if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].trimEnd();
12186
12412
  const result = this.evalVar(content, context);
12187
12413
  output.push(result !== null && result !== void 0 ? String(result) : "");
12188
12414
  if (stripA && index + 1 < tokens.length && tokens[index + 1][0] === "TEXT") {
12189
- tokens[index + 1] = ["TEXT", tokens[index + 1][1].replace(LEADING_WS_RE, "")];
12415
+ tokens[index + 1] = ["TEXT", tokens[index + 1][1].trimStart()];
12190
12416
  }
12191
12417
  return index + 1;
12192
12418
  }
12193
12419
  renderBlockToken(tokens, index, context, output) {
12194
12420
  const [content, stripB, stripA] = stripTag(tokens[index][1]);
12195
- if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].replace(TRAILING_WS_RE, "");
12421
+ if (stripB && output.length > 0) output[output.length - 1] = output[output.length - 1].trimEnd();
12196
12422
  const tag = content.split(/\s+/)[0] || "";
12197
12423
  if (stripA && index + 1 < tokens.length && tokens[index + 1][0] === "TEXT") {
12198
- tokens[index + 1] = ["TEXT", tokens[index + 1][1].replace(LEADING_WS_RE, "")];
12424
+ tokens[index + 1] = ["TEXT", tokens[index + 1][1].trimStart()];
12199
12425
  }
12200
12426
  let next;
12201
12427
  if (tag === "if" && this.tagPermitted(tag)) {
@@ -12212,7 +12438,7 @@ var init_engine = __esm({
12212
12438
  next = block.next;
12213
12439
  }
12214
12440
  if (stripA && next < tokens.length && tokens[next][0] === "TEXT") {
12215
- tokens[next] = ["TEXT", tokens[next][1].replace(LEADING_WS_RE, "")];
12441
+ tokens[next] = ["TEXT", tokens[next][1].trimStart()];
12216
12442
  }
12217
12443
  return next;
12218
12444
  }
@@ -12471,7 +12697,7 @@ var init_engine = __esm({
12471
12697
  pushIfBranch(branches, condition, branchTokens, stripBefore) {
12472
12698
  if (stripBefore && branchTokens.length > 0 && branchTokens[branchTokens.length - 1][0] === "TEXT") {
12473
12699
  const last = branchTokens[branchTokens.length - 1];
12474
- branchTokens[branchTokens.length - 1] = ["TEXT", last[1].replace(TRAILING_WS_RE, "")];
12700
+ branchTokens[branchTokens.length - 1] = ["TEXT", last[1].trimEnd()];
12475
12701
  }
12476
12702
  branches.push([condition, branchTokens]);
12477
12703
  }
@@ -12499,7 +12725,7 @@ var init_engine = __esm({
12499
12725
  } else if (tag === "endif") {
12500
12726
  this.pushIfBranch(branches, currentCond, currentTokens, tagStripB);
12501
12727
  if (tagStripA && i + 1 < tokens.length && tokens[i + 1][0] === "TEXT") {
12502
- tokens[i + 1] = ["TEXT", tokens[i + 1][1].replace(LEADING_WS_RE, "")];
12728
+ tokens[i + 1] = ["TEXT", tokens[i + 1][1].trimStart()];
12503
12729
  }
12504
12730
  return { branches, next: i + 1 };
12505
12731
  } else if ((tag === "elseif" || tag === "elif") && depth === 0) {
@@ -13285,7 +13511,7 @@ function tableData(opts) {
13285
13511
  readonly: !opts.editable,
13286
13512
  inline_script: opts.inlineScript,
13287
13513
  table_name: h(opts.tableName),
13288
- table_id_attr: opts.tableId ? ` id="${h(opts.tableId)}"` : ""
13514
+ table_id: opts.tableId ? String(opts.tableId) : ""
13289
13515
  };
13290
13516
  }
13291
13517
  var init_crudTable = __esm({
@@ -13393,13 +13619,13 @@ function renderModalForm(mode, columns, pk, edit) {
13393
13619
  value: "",
13394
13620
  placeholder: h(`Enter ${label.toLowerCase()}`),
13395
13621
  type: "text",
13396
- required_attr: "",
13622
+ required: false,
13397
13623
  input: true
13398
13624
  };
13399
13625
  });
13400
13626
  return renderCrudTemplate("form", {
13401
13627
  wrap: true,
13402
- form_id_attr: ` id="form-${mode}"`,
13628
+ form_id: `form-${mode}`,
13403
13629
  action: "",
13404
13630
  form_method: "POST",
13405
13631
  method_override: null,
@@ -13456,7 +13682,7 @@ function fieldInputShape(field, base) {
13456
13682
  case "text":
13457
13683
  return { ...base, textarea: true };
13458
13684
  case "boolean":
13459
- return { ...base, checkbox: true, checked_attr: value ? " checked" : "" };
13685
+ return { ...base, checkbox: true, checked: !!value };
13460
13686
  case "select":
13461
13687
  return { ...base, select: true, options_html: buildOptions(field.options, value) };
13462
13688
  case "date":
@@ -13479,7 +13705,7 @@ function buildCustomField(field) {
13479
13705
  label: h(String(label)),
13480
13706
  value: h(field.value ?? ""),
13481
13707
  placeholder: "",
13482
- required_attr: field.required ? " required" : ""
13708
+ required: !!field.required
13483
13709
  };
13484
13710
  return fieldInputShape(field, base);
13485
13711
  }
@@ -13487,7 +13713,7 @@ function generateForm(fields, options = {}) {
13487
13713
  const verb = String(options.method ?? "POST").toUpperCase();
13488
13714
  return renderCrudTemplate("form", {
13489
13715
  wrap: true,
13490
- form_id_attr: "",
13716
+ form_id: "",
13491
13717
  action: h(options.action ?? "/"),
13492
13718
  form_method: h(verb),
13493
13719
  method_override: ["PUT", "PATCH", "DELETE"].includes(verb) ? verb : null,
@@ -16590,6 +16816,12 @@ import { dirname as dirname5, isAbsolute as isAbsolute4, join as join9 } from "n
16590
16816
  function iso(d) {
16591
16817
  return d.toISOString();
16592
16818
  }
16819
+ function setOwn(obj, key, value) {
16820
+ Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });
16821
+ }
16822
+ function getOwn(obj, key) {
16823
+ return Object.hasOwn(obj, key) ? obj[key] : void 0;
16824
+ }
16593
16825
  function encodeValue(value) {
16594
16826
  if (value instanceof ObjectId) return value.toString();
16595
16827
  if (value instanceof Date) return iso(value);
@@ -16597,7 +16829,7 @@ function encodeValue(value) {
16597
16829
  if (value !== null && typeof value === "object") {
16598
16830
  const out = {};
16599
16831
  for (const [k, v] of Object.entries(value)) {
16600
- out[k] = encodeValue(v);
16832
+ setOwn(out, k, encodeValue(v));
16601
16833
  }
16602
16834
  return out;
16603
16835
  }
@@ -16616,7 +16848,7 @@ function decodeValue(value) {
16616
16848
  if (value !== null && typeof value === "object") {
16617
16849
  const out = {};
16618
16850
  for (const [k, v] of Object.entries(value)) {
16619
- out[k] = decodeValue(v);
16851
+ setOwn(out, k, decodeValue(v));
16620
16852
  }
16621
16853
  return out;
16622
16854
  }
@@ -16762,31 +16994,32 @@ function project(doc, projection) {
16762
16994
  const exclude = new Set(Object.entries(projection).filter(([, v]) => !v).map(([k]) => k));
16763
16995
  if (include.size > 0) {
16764
16996
  const out2 = {};
16765
- for (const k of include) if (k in doc) out2[k] = doc[k];
16997
+ for (const k of include) if (Object.hasOwn(doc, k)) setOwn(out2, k, doc[k]);
16766
16998
  const idVal = projection._id;
16767
16999
  if ((idVal === void 0 || idVal) && "_id" in doc) out2._id = doc._id;
16768
17000
  return out2;
16769
17001
  }
16770
17002
  const out = {};
16771
- for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) out[k] = v;
17003
+ for (const [k, v] of Object.entries(doc)) if (!exclude.has(k)) setOwn(out, k, v);
16772
17004
  return out;
16773
17005
  }
16774
17006
  function setPath(doc, dotted, value) {
16775
17007
  const parts = dotted.split(".");
16776
17008
  let node = doc;
16777
17009
  for (const p of parts.slice(0, -1)) {
16778
- if (node[p] === void 0 || node[p] === null || typeof node[p] !== "object") {
16779
- node[p] = {};
17010
+ const child = getOwn(node, p);
17011
+ if (child === void 0 || child === null || typeof child !== "object") {
17012
+ setOwn(node, p, {});
16780
17013
  }
16781
17014
  node = node[p];
16782
17015
  }
16783
- node[parts[parts.length - 1]] = value;
17016
+ setOwn(node, parts[parts.length - 1], value);
16784
17017
  }
16785
17018
  function unsetPath(doc, dotted) {
16786
17019
  const parts = dotted.split(".");
16787
17020
  let node = doc;
16788
17021
  for (const p of parts.slice(0, -1)) {
16789
- const next = node[p];
17022
+ const next = getOwn(node, p);
16790
17023
  if (next === null || typeof next !== "object") return;
16791
17024
  node = next;
16792
17025
  }
@@ -18138,20 +18371,210 @@ var init_attachment = __esm({
18138
18371
  }
18139
18372
  });
18140
18373
 
18374
+ // ../orm/src/realtime/s3Client.ts
18375
+ import { createHash as createHash4, createHmac as createHmac3 } from "node:crypto";
18376
+ function retryAfterSeconds(raw) {
18377
+ if (raw == null) return null;
18378
+ const n = Number(raw);
18379
+ return Number.isFinite(n) ? Math.max(0, n) : null;
18380
+ }
18381
+ function uriEncode(value, isPath) {
18382
+ let out = "";
18383
+ for (const byte of Buffer.from(value, "utf8")) {
18384
+ const ch = String.fromCharCode(byte);
18385
+ if (UNRESERVED.test(ch) || isPath && ch === "/") out += ch;
18386
+ else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
18387
+ }
18388
+ return out;
18389
+ }
18390
+ function sha256Hex2(data) {
18391
+ return createHash4("sha256").update(data).digest("hex");
18392
+ }
18393
+ function hmac(key, msg) {
18394
+ return createHmac3("sha256", key).update(msg, "utf8").digest();
18395
+ }
18396
+ var ALGORITHM, SERVICE, UNRESERVED, MAX_RETRIES, BACKOFF_BASE, BACKOFF_CAP, S3Error, S3ConfigError, sleep, S3Client;
18397
+ var init_s3Client = __esm({
18398
+ "../orm/src/realtime/s3Client.ts"() {
18399
+ "use strict";
18400
+ ALGORITHM = "AWS4-HMAC-SHA256";
18401
+ SERVICE = "s3";
18402
+ UNRESERVED = /[A-Za-z0-9\-_.~]/;
18403
+ MAX_RETRIES = 2;
18404
+ BACKOFF_BASE = 0.5;
18405
+ BACKOFF_CAP = 20;
18406
+ S3Error = class extends Error {
18407
+ constructor(status2, message) {
18408
+ super(message);
18409
+ this.status = status2;
18410
+ this.name = "S3Error";
18411
+ }
18412
+ status;
18413
+ /** Seconds from a Retry-After header in its delta-seconds form, else null. */
18414
+ retryAfter = null;
18415
+ };
18416
+ S3ConfigError = class extends Error {
18417
+ constructor(message) {
18418
+ super(message);
18419
+ this.name = "S3ConfigError";
18420
+ }
18421
+ };
18422
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18423
+ S3Client = class {
18424
+ scheme;
18425
+ host;
18426
+ // authority (host[:port]) — matches the Host header
18427
+ prefix;
18428
+ // path an endpoint carries (https://host/s3 -> "/s3"), "" if none
18429
+ region;
18430
+ accessKey;
18431
+ secretKey;
18432
+ timeout;
18433
+ constructor(opts = {}) {
18434
+ this.region = opts.region || "us-east-1";
18435
+ this.accessKey = opts.accessKey || "";
18436
+ this.secretKey = opts.secretKey || "";
18437
+ this.timeout = opts.timeout ?? 3e4;
18438
+ let base = opts.endpoint || `https://s3.${this.region}.amazonaws.com`;
18439
+ while (base.endsWith("/")) base = base.slice(0, -1);
18440
+ const m = /^([a-z][a-z0-9+.-]*):\/\/([^/]+)(\/.*)?$/i.exec(base);
18441
+ this.scheme = m ? m[1] : "https";
18442
+ this.host = m ? m[2] : base;
18443
+ let p = m && m[3] ? m[3] : "";
18444
+ while (p.endsWith("/")) p = p.slice(0, -1);
18445
+ this.prefix = p;
18446
+ }
18447
+ // -- public API (the subset S3Storage uses) --------------------------------
18448
+ async putObject(bucket, key, data, contentType = "application/octet-stream") {
18449
+ const body = Buffer.isBuffer(data) ? data : Buffer.from(data);
18450
+ await this.request("PUT", this.canonicalUri(bucket, key), body, { "content-type": contentType });
18451
+ }
18452
+ async getObject(bucket, key) {
18453
+ return (await this.request("GET", this.canonicalUri(bucket, key), Buffer.alloc(0))).body;
18454
+ }
18455
+ async deleteObject(bucket, key) {
18456
+ await this.request("DELETE", this.canonicalUri(bucket, key), Buffer.alloc(0));
18457
+ }
18458
+ async headObject(bucket, key) {
18459
+ await this.request("HEAD", this.canonicalUri(bucket, key), Buffer.alloc(0));
18460
+ }
18461
+ /** Create the bucket (path-style `PUT /<bucket>`); an already-owned bucket (409) is success. */
18462
+ async createBucket(bucket) {
18463
+ try {
18464
+ await this.request("PUT", `${this.prefix}/${uriEncode(bucket, true)}`, Buffer.alloc(0));
18465
+ } catch (e) {
18466
+ if (!(e instanceof S3Error) || e.status !== 409) throw e;
18467
+ }
18468
+ }
18469
+ /** A URL that fetches the object directly, signed via SigV4 query params. */
18470
+ presignedGetUrl(bucket, key, expires = 3600) {
18471
+ this.requireCredentials();
18472
+ const { amzDate, dateStamp } = this.now();
18473
+ const uri = this.canonicalUri(bucket, key);
18474
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
18475
+ const query = {
18476
+ "X-Amz-Algorithm": ALGORITHM,
18477
+ "X-Amz-Credential": `${this.accessKey}/${scope}`,
18478
+ "X-Amz-Date": amzDate,
18479
+ "X-Amz-Expires": String(expires),
18480
+ "X-Amz-SignedHeaders": "host"
18481
+ };
18482
+ const canonicalQs = this.canonicalQuery(query);
18483
+ const canonicalRequest = ["GET", uri, canonicalQs, `host:${this.host}
18484
+ `, "host", "UNSIGNED-PAYLOAD"].join("\n");
18485
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
18486
+ return `${this.scheme}://${this.host}${uri}?${canonicalQs}&X-Amz-Signature=${signature}`;
18487
+ }
18488
+ // -- signing + transport ----------------------------------------------------
18489
+ requireCredentials() {
18490
+ if (!this.accessKey || !this.secretKey) {
18491
+ throw new S3ConfigError(
18492
+ "S3 credentials are not set: set TINA4_STORAGE_KEY and TINA4_STORAGE_SECRET"
18493
+ );
18494
+ }
18495
+ }
18496
+ now() {
18497
+ const iso2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:-]|\.\d{3}/g, "");
18498
+ return { amzDate: iso2, dateStamp: iso2.slice(0, 8) };
18499
+ }
18500
+ canonicalUri(bucket, key) {
18501
+ return `${this.prefix}/${uriEncode(bucket, true)}/${uriEncode(key, true)}`;
18502
+ }
18503
+ canonicalQuery(query) {
18504
+ return Object.keys(query).sort().map((k) => `${uriEncode(k, false)}=${uriEncode(query[k], false)}`).join("&");
18505
+ }
18506
+ signingKey(dateStamp) {
18507
+ const kDate = hmac(`AWS4${this.secretKey}`, dateStamp);
18508
+ const kRegion = hmac(kDate, this.region);
18509
+ const kService = hmac(kRegion, SERVICE);
18510
+ return hmac(kService, "aws4_request");
18511
+ }
18512
+ sign(canonicalRequest, amzDate, dateStamp, scope) {
18513
+ const stringToSign = [ALGORITHM, amzDate, scope, sha256Hex2(canonicalRequest)].join("\n");
18514
+ return createHmac3("sha256", this.signingKey(dateStamp)).update(stringToSign, "utf8").digest("hex");
18515
+ }
18516
+ async request(method, uri, body, extraHeaders = {}) {
18517
+ this.requireCredentials();
18518
+ for (let attempt = 0; ; attempt++) {
18519
+ const last = attempt === MAX_RETRIES;
18520
+ let delay2 = null;
18521
+ try {
18522
+ return await this.send(method, uri, body, extraHeaders);
18523
+ } catch (e) {
18524
+ if (e instanceof S3Error) {
18525
+ if (last || !(e.status === 429 || e.status >= 500)) throw e;
18526
+ delay2 = e.retryAfter;
18527
+ } else {
18528
+ if (last) throw e;
18529
+ delay2 = null;
18530
+ }
18531
+ }
18532
+ if (delay2 == null) delay2 = Math.random() * (BACKOFF_BASE * 2 ** attempt);
18533
+ await sleep(Math.min(delay2, BACKOFF_CAP) * 1e3);
18534
+ }
18535
+ }
18536
+ async send(method, uri, body, extraHeaders = {}) {
18537
+ const { amzDate, dateStamp } = this.now();
18538
+ const payloadHash = sha256Hex2(body);
18539
+ const signed = {
18540
+ host: this.host,
18541
+ "x-amz-content-sha256": payloadHash,
18542
+ "x-amz-date": amzDate
18543
+ };
18544
+ const signedKeys = Object.keys(signed).sort();
18545
+ const canonicalHeaders = signedKeys.map((k) => `${k}:${signed[k]}
18546
+ `).join("");
18547
+ const signedHeaders = signedKeys.join(";");
18548
+ const canonicalRequest = [method, uri, "", canonicalHeaders, signedHeaders, payloadHash].join("\n");
18549
+ const scope = `${dateStamp}/${this.region}/${SERVICE}/aws4_request`;
18550
+ const signature = this.sign(canonicalRequest, amzDate, dateStamp, scope);
18551
+ const authorization = `${ALGORITHM} Credential=${this.accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
18552
+ const headers = {
18553
+ Authorization: authorization,
18554
+ "x-amz-content-sha256": payloadHash,
18555
+ "x-amz-date": amzDate,
18556
+ ...extraHeaders
18557
+ };
18558
+ const url = `${this.scheme}://${this.host}${uri}`;
18559
+ const init = { method, headers, redirect: "manual" };
18560
+ if (method === "PUT" || method === "POST") init.body = body;
18561
+ if (AbortSignal.timeout) init.signal = AbortSignal.timeout(this.timeout);
18562
+ const response = await fetch(url, init);
18563
+ if (response.status < 200 || response.status >= 300) {
18564
+ const err = new S3Error(response.status, `${method} ${uri}: HTTP ${response.status}`);
18565
+ err.retryAfter = retryAfterSeconds(response.headers.get("retry-after"));
18566
+ throw err;
18567
+ }
18568
+ return { status: response.status, body: Buffer.from(await response.arrayBuffer()) };
18569
+ }
18570
+ };
18571
+ }
18572
+ });
18573
+
18141
18574
  // ../orm/src/realtime/storage.ts
18142
18575
  import { randomBytes as randomBytes5 } from "node:crypto";
18143
18576
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync2, unlinkSync as unlinkSync2, statSync as statSync5 } from "node:fs";
18144
18577
  import { resolve as resolve6, sep as sep3 } from "node:path";
18145
- import { createRequire as createRequire6 } from "node:module";
18146
- function loadAwsSdk(packageName) {
18147
- try {
18148
- return require2(packageName);
18149
- } catch (error2) {
18150
- const missing = error2?.code === "MODULE_NOT_FOUND" && String(error2?.message ?? "").includes(`'${packageName}'`);
18151
- if (!missing) throw error2;
18152
- throw optionalPackageMissing("S3Storage", S3_PACKAGES);
18153
- }
18154
- }
18155
18578
  function storageKey(filename = "") {
18156
18579
  let ext = "";
18157
18580
  if (filename && filename.includes(".")) {
@@ -18176,14 +18599,12 @@ function selectStorage(storage) {
18176
18599
  }
18177
18600
  return new LocalStorage();
18178
18601
  }
18179
- var require2, S3_PACKAGES, UNSAFE, LocalStorage, S3Storage;
18602
+ var UNSAFE, LocalStorage, S3Storage;
18180
18603
  var init_storage = __esm({
18181
18604
  "../orm/src/realtime/storage.ts"() {
18182
18605
  "use strict";
18183
18606
  init_index();
18184
- init_optionalPackage();
18185
- require2 = createRequire6(import.meta.url);
18186
- S3_PACKAGES = ["@aws-sdk/client-s3", "@aws-sdk/s3-request-presigner"];
18607
+ init_s3Client();
18187
18608
  UNSAFE = /[^A-Za-z0-9]/g;
18188
18609
  LocalStorage = class {
18189
18610
  directory;
@@ -18233,51 +18654,36 @@ var init_storage = __esm({
18233
18654
  constructor(opts = {}) {
18234
18655
  this.bucket = opts.bucket || process.env.TINA4_STORAGE_BUCKET || "";
18235
18656
  if (!this.bucket) throw new Error("S3Storage requires TINA4_STORAGE_BUCKET");
18236
- const { S3Client } = loadAwsSdk("@aws-sdk/client-s3");
18237
- loadAwsSdk("@aws-sdk/s3-request-presigner");
18238
- const endpoint = opts.endpoint || process.env.TINA4_STORAGE_URL;
18239
18657
  this.client = new S3Client({
18240
- endpoint: endpoint || void 0,
18241
- forcePathStyle: true,
18658
+ endpoint: opts.endpoint || process.env.TINA4_STORAGE_URL || void 0,
18242
18659
  region: opts.region || process.env.TINA4_STORAGE_REGION || "us-east-1",
18243
- credentials: {
18244
- accessKeyId: opts.key || process.env.TINA4_STORAGE_KEY || "",
18245
- secretAccessKey: opts.secret || process.env.TINA4_STORAGE_SECRET || ""
18246
- }
18660
+ accessKey: opts.key || process.env.TINA4_STORAGE_KEY || "",
18661
+ secretKey: opts.secret || process.env.TINA4_STORAGE_SECRET || ""
18247
18662
  });
18248
18663
  }
18249
18664
  async put(key, data, mime = "application/octet-stream") {
18250
- const { PutObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
18251
- await this.client.send(new PutObjectCommand({ Bucket: this.bucket, Key: key, Body: data, ContentType: mime }));
18665
+ await this.client.putObject(this.bucket, key, data, mime);
18252
18666
  }
18253
18667
  async get(key) {
18254
18668
  try {
18255
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
18256
- const res = await this.client.send(new GetObjectCommand({ Bucket: this.bucket, Key: key }));
18257
- const chunks = [];
18258
- for await (const chunk of res.Body) chunks.push(Buffer.from(chunk));
18259
- return Buffer.concat(chunks);
18669
+ return await this.client.getObject(this.bucket, key);
18260
18670
  } catch {
18261
18671
  return null;
18262
18672
  }
18263
18673
  }
18264
18674
  async url(key, ttl = 3600) {
18265
- const { GetObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
18266
- const { getSignedUrl } = loadAwsSdk("@aws-sdk/s3-request-presigner");
18267
- return getSignedUrl(this.client, new GetObjectCommand({ Bucket: this.bucket, Key: key }), { expiresIn: ttl });
18675
+ return this.client.presignedGetUrl(this.bucket, key, ttl);
18268
18676
  }
18269
18677
  async delete(key) {
18270
18678
  try {
18271
- const { DeleteObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
18272
- await this.client.send(new DeleteObjectCommand({ Bucket: this.bucket, Key: key }));
18679
+ await this.client.deleteObject(this.bucket, key);
18273
18680
  } catch (e) {
18274
18681
  Log.error(`S3Storage delete failed for ${key}: ${e.message}`);
18275
18682
  }
18276
18683
  }
18277
18684
  async exists(key) {
18278
18685
  try {
18279
- const { HeadObjectCommand } = loadAwsSdk("@aws-sdk/client-s3");
18280
- await this.client.send(new HeadObjectCommand({ Bucket: this.bucket, Key: key }));
18686
+ await this.client.headObject(this.bucket, key);
18281
18687
  return true;
18282
18688
  } catch {
18283
18689
  return false;
@@ -18288,7 +18694,7 @@ var init_storage = __esm({
18288
18694
  });
18289
18695
 
18290
18696
  // ../orm/src/realtime/realtime.ts
18291
- import { createHmac as createHmac3 } from "node:crypto";
18697
+ import { createHmac as createHmac4 } from "node:crypto";
18292
18698
  function iceServers() {
18293
18699
  const stun = process.env.TINA4_RTC_STUN_URLS || DEFAULT_STUN;
18294
18700
  const servers = [{ urls: splitUrls(stun) }];
@@ -18297,14 +18703,14 @@ function iceServers() {
18297
18703
  if (turnUrl && secret) {
18298
18704
  const ttl = parseInt(process.env.TINA4_RTC_TURN_TTL || "3600", 10);
18299
18705
  const username = String(Math.floor(Date.now() / 1e3) + ttl);
18300
- const credential = createHmac3("sha1", secret).update(username).digest("base64");
18706
+ const credential = createHmac4("sha1", secret).update(username).digest("base64");
18301
18707
  servers.push({ urls: splitUrls(turnUrl), username, credential });
18302
18708
  }
18303
18709
  return servers;
18304
18710
  }
18305
18711
  async function realtime(options = {}) {
18306
18712
  const features = options.features ?? ["calls"];
18307
- const raw = (options.prefix ?? "").replace(/^\/+|\/+$/g, "");
18713
+ const raw = trimSlashes(options.prefix ?? "");
18308
18714
  const p = raw ? `/${raw}` : "";
18309
18715
  _authorize = options.authorize;
18310
18716
  if (features.includes("chat") || features.includes("files")) {
@@ -18576,6 +18982,7 @@ var DEFAULT_STUN, _authorize;
18576
18982
  var init_realtime = __esm({
18577
18983
  "../orm/src/realtime/realtime.ts"() {
18578
18984
  "use strict";
18985
+ init_slashTrim();
18579
18986
  init_index();
18580
18987
  init_workspace();
18581
18988
  init_channel();
@@ -18593,6 +19000,7 @@ var init_realtime2 = __esm({
18593
19000
  "use strict";
18594
19001
  init_realtime();
18595
19002
  init_storage();
19003
+ init_s3Client();
18596
19004
  init_workspace();
18597
19005
  init_channel();
18598
19006
  init_channelMember();
@@ -18958,6 +19366,7 @@ function mayStore(req2, vary, cacheControl, setCookie) {
18958
19366
  if (requestHeader(req2, "authorization") !== void 0) return sharedCacheAllowed(cacheControl);
18959
19367
  if (requestHeader(req2, "cookie") !== void 0) return sharedCacheAllowed(cacheControl);
18960
19368
  if (hasSetCookie(setCookie)) return sharedCacheAllowed(cacheControl);
19369
+ if (req2.session?.isFresh && !req2.session.isFresh()) return sharedCacheAllowed(cacheControl);
18961
19370
  return true;
18962
19371
  }
18963
19372
  function varyMatches(entry, req2) {
@@ -20310,7 +20719,7 @@ function coerceParam(raw, type2) {
20310
20719
  }
20311
20720
  function joinGroupPath(prefix, path10) {
20312
20721
  const full = `${prefix}/${path10.replace(/^\/+/, "")}`;
20313
- const trimmed = `/${full.replace(/^\/+|\/+$/g, "")}`;
20722
+ const trimmed = `/${trimSlashes(full)}`;
20314
20723
  return trimmed.replace(/\/+/g, "/");
20315
20724
  }
20316
20725
  async function resolveStringMiddleware(spec) {
@@ -20375,6 +20784,7 @@ var WsRouteRef, RouteRef, Router, RouteGroup, TINA4_DEFAULT_ROUTER, globalRouter
20375
20784
  var init_router = __esm({
20376
20785
  "src/router.ts"() {
20377
20786
  "use strict";
20787
+ init_slashTrim();
20378
20788
  init_dotenv();
20379
20789
  init_middleware();
20380
20790
  WsRouteRef = class {
@@ -20584,7 +20994,7 @@ var init_router = __esm({
20584
20994
  const direct = this.matchRoute(routes, path10);
20585
20995
  if (direct) return direct;
20586
20996
  if (isTrailingSlashRedirectEnabled() && path10.length > 1 && path10.endsWith("/")) {
20587
- const stripped = path10.replace(/\/+$/, "");
20997
+ const stripped = rtrimSlashes(path10);
20588
20998
  if (stripped.length > 0) {
20589
20999
  const retry = this.matchRoute(routes, stripped);
20590
21000
  if (retry) return retry;
@@ -22260,7 +22670,8 @@ var init_middleware = __esm({
22260
22670
  "Content-Security-Policy": resolveCspHeader(currentCspNonce()),
22261
22671
  "Referrer-Policy": process.env.TINA4_REFERRER_POLICY ?? "strict-origin-when-cross-origin",
22262
22672
  "X-XSS-Protection": "0",
22263
- "Permissions-Policy": process.env.TINA4_PERMISSIONS_POLICY ?? "camera=(), microphone=(), geolocation=()"
22673
+ "Permissions-Policy": process.env.TINA4_PERMISSIONS_POLICY ?? "camera=(), microphone=(), geolocation=()",
22674
+ "Cross-Origin-Opener-Policy": process.env.TINA4_COOP ?? "same-origin-allow-popups"
22264
22675
  };
22265
22676
  }
22266
22677
  static beforeSecurity(req2, res) {
@@ -22277,7 +22688,7 @@ var init_middleware = __esm({
22277
22688
  if (process.env.TINA4_CSP === void 0) {
22278
22689
  _SecurityHeadersMiddleware.warnCspDefaultOnce();
22279
22690
  }
22280
- for (const name of ["Content-Security-Policy", "Referrer-Policy", "X-XSS-Protection", "Permissions-Policy"]) {
22691
+ for (const name of ["Content-Security-Policy", "Referrer-Policy", "X-XSS-Protection", "Permissions-Policy", "Cross-Origin-Opener-Policy"]) {
22281
22692
  res.header(name, canonical[name]);
22282
22693
  }
22283
22694
  return [req2, res];
@@ -22361,7 +22772,7 @@ var init_middleware = __esm({
22361
22772
  });
22362
22773
 
22363
22774
  // src/request.ts
22364
- import { mkdirSync as mkdirSync7, realpathSync as realpathSync2, writeFileSync as writeFileSync4 } from "node:fs";
22775
+ import { closeSync as closeSync3, constants as constants2, fstatSync as fstatSync2, ftruncateSync, lstatSync, mkdirSync as mkdirSync7, openSync as openSync3, realpathSync as realpathSync2, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
22365
22776
  import { dirname as dirname6, join as join11 } from "node:path";
22366
22777
  function makeCaseInsensitiveHeaders(raw) {
22367
22778
  return new Proxy(raw, {
@@ -22397,7 +22808,8 @@ function createRequest(req2) {
22397
22808
  try {
22398
22809
  const url = new URL(req2.url ?? "/", `${proto}://${host}`);
22399
22810
  for (const [key, value] of url.searchParams) {
22400
- query[key] = value;
22811
+ if (isUnsafeFieldName(key)) continue;
22812
+ Reflect.set(query, key, value);
22401
22813
  }
22402
22814
  path10 = url.pathname;
22403
22815
  queryString = url.search.replace(/^\?/, "");
@@ -22409,7 +22821,8 @@ function createRequest(req2) {
22409
22821
  queryString = questionIdx >= 0 ? rawTarget.slice(questionIdx + 1) : "";
22410
22822
  try {
22411
22823
  for (const [key, value] of new URLSearchParams(queryString)) {
22412
- query[key] = value;
22824
+ if (isUnsafeFieldName(key)) continue;
22825
+ Reflect.set(query, key, value);
22413
22826
  }
22414
22827
  } catch {
22415
22828
  }
@@ -22428,7 +22841,8 @@ function createRequest(req2) {
22428
22841
  if (cookieHeader) {
22429
22842
  for (const pair of cookieHeader.split(";")) {
22430
22843
  const [k, ...v] = pair.trim().split("=");
22431
- if (k) cookies[k.trim()] = v.join("=").trim();
22844
+ const name = k ? k.trim() : "";
22845
+ if (name && !isUnsafeFieldName(name)) Reflect.set(cookies, name, v.join("=").trim());
22432
22846
  }
22433
22847
  }
22434
22848
  w.cookies = cookies;
@@ -22519,13 +22933,7 @@ async function parseBody(req2) {
22519
22933
  req2.body = str;
22520
22934
  }
22521
22935
  } else if (contentType.includes("application/x-www-form-urlencoded")) {
22522
- const str = raw.toString("utf-8");
22523
- const params = new URLSearchParams(str);
22524
- const obj = {};
22525
- for (const [key, value] of params) {
22526
- obj[key] = value;
22527
- }
22528
- req2.body = obj;
22936
+ req2.body = nestFormFields([...new URLSearchParams(raw.toString("utf-8"))]);
22529
22937
  } else {
22530
22938
  req2.body = raw.toString("utf-8");
22531
22939
  }
@@ -22535,7 +22943,7 @@ function extractBoundary(contentType) {
22535
22943
  return match ? match[1] ?? match[2] : null;
22536
22944
  }
22537
22945
  function parseMultipart(body, boundary) {
22538
- const fields = {};
22946
+ const pairs = [];
22539
22947
  const files = {};
22540
22948
  const delimiter2 = Buffer.from(`--${boundary}`);
22541
22949
  const closeDelimiter = Buffer.from(`--${boundary}--`);
@@ -22543,7 +22951,7 @@ function parseMultipart(body, boundary) {
22543
22951
  const doubleCrlf = Buffer.from("\r\n\r\n");
22544
22952
  let offset = 0;
22545
22953
  const firstIdx = bufferIndexOf(body, delimiter2, offset);
22546
- if (firstIdx === -1) return { fields, files };
22954
+ if (firstIdx === -1) return { fields: {}, files };
22547
22955
  offset = firstIdx + delimiter2.length;
22548
22956
  if (body[offset] === 13 && body[offset + 1] === 10) {
22549
22957
  offset += 2;
@@ -22567,14 +22975,15 @@ function parseMultipart(body, boundary) {
22567
22975
  content: Buffer.from(content),
22568
22976
  size: content.length
22569
22977
  };
22570
- if (files[disposition.name]) {
22978
+ if (isUnsafeFieldName(disposition.name)) {
22979
+ } else if (files[disposition.name]) {
22571
22980
  const existing = files[disposition.name];
22572
- files[disposition.name] = Array.isArray(existing) ? [...existing, file] : [existing, file];
22981
+ Reflect.set(files, disposition.name, Array.isArray(existing) ? [...existing, file] : [existing, file]);
22573
22982
  } else {
22574
- files[disposition.name] = file;
22983
+ Reflect.set(files, disposition.name, file);
22575
22984
  }
22576
22985
  } else if (disposition.name) {
22577
- fields[disposition.name] = content.toString("utf-8");
22986
+ pairs.push([disposition.name, content.toString("utf-8")]);
22578
22987
  }
22579
22988
  offset = nextDelimIdx + delimiter2.length;
22580
22989
  if (body[offset] === 45 && body[offset + 1] === 45) {
@@ -22584,7 +22993,7 @@ function parseMultipart(body, boundary) {
22584
22993
  offset += 2;
22585
22994
  }
22586
22995
  }
22587
- return { fields, files };
22996
+ return { fields: nestFormFields(pairs), files };
22588
22997
  }
22589
22998
  function saveUpload(file, targetDir, filename) {
22590
22999
  const raw = String(filename ?? file.filename ?? "");
@@ -22600,7 +23009,21 @@ function saveUpload(file, targetDir, filename) {
22600
23009
  if (realParent !== realDir) {
22601
23010
  throw new Error(`refusing to write outside ${targetDir}: ${JSON.stringify(raw)}`);
22602
23011
  }
22603
- writeFileSync4(dest, file.content);
23012
+ if (lstatSync(dest, { throwIfNoEntry: false })?.isSymbolicLink()) unlinkSync4(dest);
23013
+ const flags = constants2.O_WRONLY | constants2.O_CREAT | (constants2.O_NOFOLLOW ?? 0);
23014
+ let fd = openSync3(dest, flags, 384);
23015
+ try {
23016
+ if (fstatSync2(fd).nlink > 1) {
23017
+ closeSync3(fd);
23018
+ fd = -1;
23019
+ unlinkSync4(dest);
23020
+ fd = openSync3(dest, flags | constants2.O_EXCL, 384);
23021
+ }
23022
+ ftruncateSync(fd, 0);
23023
+ writeFileSync4(fd, file.content);
23024
+ } finally {
23025
+ if (fd >= 0) closeSync3(fd);
23026
+ }
22604
23027
  return dest;
22605
23028
  }
22606
23029
  function bufferIndexOf(haystack, needle, offset) {
@@ -22625,10 +23048,98 @@ function parseDisposition(headers) {
22625
23048
  };
22626
23049
  }
22627
23050
  function parsePartContentType(headers) {
22628
- const match = headers.match(/Content-Type:\s*(.+?)(?:\r?\n|$)/i);
22629
- return match?.[1]?.trim() ?? null;
23051
+ const match = headers.match(/Content-Type:([^\r\n]*)/i);
23052
+ const value = match?.[1]?.trim();
23053
+ return value ? value : null;
23054
+ }
23055
+ function nestFormFields(pairs) {
23056
+ const kept = pairs.filter(([name]) => !/(^|[[\]])__proto__([[\]]|$)/.test(name));
23057
+ if (kept.length > FORM_FIELD_LIMIT) return Object.fromEntries(kept);
23058
+ const nested = /* @__PURE__ */ new WeakSet();
23059
+ const node = () => {
23060
+ const created = /* @__PURE__ */ Object.create(null);
23061
+ nested.add(created);
23062
+ return created;
23063
+ };
23064
+ const isNode = (value) => typeof value === "object" && value !== null && nested.has(value);
23065
+ const own = (params, key) => Object.prototype.hasOwnProperty.call(params, key) ? params[key] : void 0;
23066
+ const list = (params, key) => {
23067
+ let current = own(params, key);
23068
+ if (current === void 0) {
23069
+ current = [];
23070
+ Reflect.set(params, key, current);
23071
+ }
23072
+ if (!Array.isArray(current)) throw new RangeError(`expected an array for '${key}'`);
23073
+ return current;
23074
+ };
23075
+ const object = (params, key) => {
23076
+ let current = own(params, key);
23077
+ if (current === void 0) {
23078
+ current = node();
23079
+ Reflect.set(params, key, current);
23080
+ }
23081
+ if (!isNode(current)) throw new RangeError(`expected an object for '${key}'`);
23082
+ return current;
23083
+ };
23084
+ const hasKey = (params, key) => {
23085
+ if (key.includes("[]")) return false;
23086
+ let level = params;
23087
+ for (const part of key.split(/[[\]]+/).filter(Boolean)) {
23088
+ if (!isNode(level) || own(level, part) === void 0) return false;
23089
+ level = level[part];
23090
+ }
23091
+ return true;
23092
+ };
23093
+ const splitName = (name, depth) => {
23094
+ if (depth === 0) {
23095
+ const start2 = name.indexOf("[", 1);
23096
+ return start2 === -1 ? [name, ""] : [name.slice(0, start2), name.slice(start2)];
23097
+ }
23098
+ if (name.startsWith("[]")) return ["[]", name.slice(2)];
23099
+ const close = name.indexOf("]", 1);
23100
+ return name.startsWith("[") && close !== -1 ? [name.slice(1, close), name.slice(close + 1)] : [name, ""];
23101
+ };
23102
+ const putListItem = (items, after, value, depth) => {
23103
+ let childKey = after[2] === "[" && after.endsWith("]") ? after.slice(3, -1) : "";
23104
+ if (childKey === "" || childKey.includes("[") || childKey.includes("]")) childKey = after.slice(2);
23105
+ const last = items[items.length - 1];
23106
+ if (isNode(last) && !hasKey(last, childKey)) put2(last, childKey, value, depth + 1);
23107
+ else items.push(put2(node(), childKey, value, depth + 1));
23108
+ };
23109
+ const put2 = (params, name, value, depth) => {
23110
+ const [key, after] = splitName(name, depth);
23111
+ if (key === "") return void 0;
23112
+ if (after === "" && key === "[]" && depth !== 0) return [value];
23113
+ if (after === "") Reflect.set(params, key, value);
23114
+ else if (after === "[") Reflect.set(params, name, value);
23115
+ else if (after === "[]") list(params, key).push(value);
23116
+ else if (after.startsWith("[]")) putListItem(list(params, key), after, value, depth);
23117
+ else put2(object(params, key), after, value, depth + 1);
23118
+ return params;
23119
+ };
23120
+ const tooDeep = (name) => {
23121
+ let count = 0;
23122
+ for (let at = name.indexOf("["); at !== -1; at = name.indexOf("[", at + 1)) {
23123
+ if (++count >= FORM_DEPTH_LIMIT) return true;
23124
+ }
23125
+ return false;
23126
+ };
23127
+ const fields = node();
23128
+ for (const [name, value] of kept) {
23129
+ if (name.length > FORM_NAME_LIMIT || tooDeep(name)) {
23130
+ Reflect.set(fields, name, value);
23131
+ continue;
23132
+ }
23133
+ try {
23134
+ put2(fields, name, value, 0);
23135
+ } catch (error2) {
23136
+ if (!(error2 instanceof RangeError)) throw error2;
23137
+ Reflect.set(fields, name, value);
23138
+ }
23139
+ }
23140
+ return fields;
22630
23141
  }
22631
- var DEFAULT_MAX_UPLOAD_SIZE, warnedLimits, PayloadTooLargeError;
23142
+ var DEFAULT_MAX_UPLOAD_SIZE, warnedLimits, PayloadTooLargeError, FORM_DEPTH_LIMIT, FORM_FIELD_LIMIT, FORM_NAME_LIMIT, isUnsafeFieldName;
22632
23143
  var init_request = __esm({
22633
23144
  "src/request.ts"() {
22634
23145
  "use strict";
@@ -22643,6 +23154,10 @@ var init_request = __esm({
22643
23154
  this.name = "PayloadTooLargeError";
22644
23155
  }
22645
23156
  };
23157
+ FORM_DEPTH_LIMIT = 32;
23158
+ FORM_FIELD_LIMIT = 4096;
23159
+ FORM_NAME_LIMIT = 1024;
23160
+ isUnsafeFieldName = (key) => key === "__proto__" || key === "constructor" || key === "prototype";
22646
23161
  }
22647
23162
  });
22648
23163
 
@@ -22924,8 +23439,8 @@ var init_ssoIdentity = __esm({
22924
23439
  });
22925
23440
 
22926
23441
  // src/authGate.ts
22927
- function enforceRouteAuth(req2, res, match, isDevAdmin) {
22928
- if (!(match.secure === true && match.noAuth !== true && !isDevAdmin)) {
23442
+ function enforceRouteAuth(req2, res, match) {
23443
+ if (!(match.secure === true && match.noAuth !== true)) {
22929
23444
  return false;
22930
23445
  }
22931
23446
  const authHeader = req2.headers.authorization ?? "";
@@ -23149,7 +23664,7 @@ var init_routeDiscovery = __esm({
23149
23664
 
23150
23665
  // src/portTakeover.ts
23151
23666
  import { execFileSync } from "node:child_process";
23152
- import { existsSync as existsSync10, readFileSync as readFileSync7, writeFileSync as writeFileSync6, mkdirSync as mkdirSync9, unlinkSync as unlinkSync4 } from "node:fs";
23667
+ import { existsSync as existsSync10, readFileSync as readFileSync7, writeFileSync as writeFileSync6, mkdirSync as mkdirSync9, unlinkSync as unlinkSync5 } from "node:fs";
23153
23668
  import { join as join13 } from "node:path";
23154
23669
  function isTruthy3(value) {
23155
23670
  return ["true", "1", "yes", "on"].includes(String(value ?? "").trim().toLowerCase());
@@ -23203,7 +23718,7 @@ function readPidfile(port, baseDir) {
23203
23718
  }
23204
23719
  function removePidfile(port, baseDir) {
23205
23720
  try {
23206
- unlinkSync4(pidfilePath(port, baseDir));
23721
+ unlinkSync5(pidfilePath(port, baseDir));
23207
23722
  } catch {
23208
23723
  }
23209
23724
  }
@@ -23304,21 +23819,6 @@ var init_portTakeover = __esm({
23304
23819
  }
23305
23820
  });
23306
23821
 
23307
- // src/etag.ts
23308
- function etagMatches(ifNoneMatch, etag) {
23309
- const strip = (tag) => tag.trim().replace(/^W\//, "");
23310
- const target = strip(etag);
23311
- return ifNoneMatch.split(",").some((candidate) => {
23312
- const trimmed = candidate.trim();
23313
- return trimmed === "*" || strip(trimmed) === target;
23314
- });
23315
- }
23316
- var init_etag = __esm({
23317
- "src/etag.ts"() {
23318
- "use strict";
23319
- }
23320
- });
23321
-
23322
23822
  // src/sessionHandlers/syncBridge.ts
23323
23823
  import { Worker } from "node:worker_threads";
23324
23824
  function getBridge(key, workerSource, workerData) {
@@ -23678,7 +24178,7 @@ var init_valkeyHandler = __esm({
23678
24178
  });
23679
24179
 
23680
24180
  // src/sessionHandlers/memcachedHandler.ts
23681
- import { createHash as createHash5 } from "node:crypto";
24181
+ import { createHash as createHash6 } from "node:crypto";
23682
24182
  var MAX_KEY_BYTES, MAX_RELATIVE_EXPTIME, MemcachedSessionHandler;
23683
24183
  var init_memcachedHandler = __esm({
23684
24184
  "src/sessionHandlers/memcachedHandler.ts"() {
@@ -23700,7 +24200,7 @@ var init_memcachedHandler = __esm({
23700
24200
  key(sessionId) {
23701
24201
  const candidate = `${this.prefix}${sessionId}`;
23702
24202
  if (Buffer.byteLength(candidate) > MAX_KEY_BYTES || /[\x00-\x20\x7f]/.test(candidate)) {
23703
- return `${this.prefix}${createHash5("sha256").update(sessionId).digest("hex")}`;
24203
+ return `${this.prefix}${createHash6("sha256").update(sessionId).digest("hex")}`;
23704
24204
  }
23705
24205
  return candidate;
23706
24206
  }
@@ -24166,7 +24666,7 @@ var init_mongoHandler = __esm({
24166
24666
  });
24167
24667
 
24168
24668
  // src/sessionHandlers/sqlClient.ts
24169
- import { createRequire as createRequire7 } from "node:module";
24669
+ import { createRequire as createRequire6 } from "node:module";
24170
24670
  function driverPath(engine) {
24171
24671
  const packageName = DRIVER_PACKAGE4[engine];
24172
24672
  try {
@@ -24205,7 +24705,7 @@ var init_sqlClient = __esm({
24205
24705
  mssql: "tedious",
24206
24706
  firebird: "node-firebird"
24207
24707
  };
24208
- requireFromHere = createRequire7(import.meta.url);
24708
+ requireFromHere = createRequire6(import.meta.url);
24209
24709
  SQL_WORKER = `
24210
24710
  const target = workerData.target;
24211
24711
  const engine = target.engine;
@@ -24687,14 +25187,18 @@ __export(session_exports, {
24687
25187
  Session: () => Session,
24688
25188
  VALID_SESSION_BACKENDS: () => VALID_SESSION_BACKENDS,
24689
25189
  buildSessionCookie: () => buildSessionCookie,
25190
+ currentFormTokenSessionId: () => currentFormTokenSessionId,
24690
25191
  isSecureScheme: () => isSecureScheme,
24691
25192
  isValidSessionId: () => isValidSessionId,
25193
+ runWithFormTokenSession: () => runWithFormTokenSession,
24692
25194
  sessionCookieName: () => sessionCookieName,
24693
25195
  sessionCookieToSend: () => sessionCookieToSend,
24694
- sessionStrictMode: () => sessionStrictMode
25196
+ sessionStrictMode: () => sessionStrictMode,
25197
+ setFormTokenSession: () => setFormTokenSession
24695
25198
  });
24696
- import { createHash as createHash6, randomBytes as randomBytes6 } from "node:crypto";
24697
- import { existsSync as existsSync11, mkdirSync as mkdirSync10, readFileSync as readFileSync8, writeFileSync as writeFileSync7, unlinkSync as unlinkSync5, readdirSync as readdirSync6 } from "node:fs";
25199
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
25200
+ import { createHash as createHash7, randomBytes as randomBytes6 } from "node:crypto";
25201
+ import { existsSync as existsSync11, mkdirSync as mkdirSync10, readFileSync as readFileSync8, writeFileSync as writeFileSync7, unlinkSync as unlinkSync6, readdirSync as readdirSync6 } from "node:fs";
24698
25202
  import { join as join14 } from "node:path";
24699
25203
  function isValidSessionId(sessionId) {
24700
25204
  return typeof sessionId === "string" && SESSION_ID_PATTERN.test(sessionId);
@@ -24760,7 +25264,21 @@ function sessionCookieToSend(sess, existingSid, rawReq, rawRes) {
24760
25264
  const socketEncrypted = rawReq.socket?.encrypted === true;
24761
25265
  return buildSessionCookie(newSid, ttl, void 0, forwardedProto, socketEncrypted);
24762
25266
  }
24763
- var SESSION_ID_PATTERN, VALID_SESSION_BACKENDS, CANONICAL_SESSION_BACKENDS, RETIRED_SESSION_BACKENDS, FileSessionHandler, RedisSessionHandler, FLASH_PREFIX, Session;
25267
+ function runWithFormTokenSession(fn) {
25268
+ return sessionStore.run({ session: null }, fn);
25269
+ }
25270
+ function setFormTokenSession(session) {
25271
+ const store = sessionStore.getStore();
25272
+ if (store) store.session = session;
25273
+ }
25274
+ function currentFormTokenSessionId() {
25275
+ const session = sessionStore.getStore()?.session;
25276
+ const sid = session?.getSessionId();
25277
+ if (!session || !sid) return "";
25278
+ if (session.isFresh()) session.set("_tina4_csrf", true);
25279
+ return sid;
25280
+ }
25281
+ var SESSION_ID_PATTERN, VALID_SESSION_BACKENDS, CANONICAL_SESSION_BACKENDS, RETIRED_SESSION_BACKENDS, FileSessionHandler, RedisSessionHandler, FLASH_PREFIX, Session, sessionStore;
24764
25282
  var init_session = __esm({
24765
25283
  "src/session.ts"() {
24766
25284
  "use strict";
@@ -24834,7 +25352,7 @@ var init_session = __esm({
24834
25352
  `Invalid session id ${JSON.stringify(id)} \u2014 a session id is opaque and must match ${SESSION_ID_PATTERN.source}. It is never a path, so it is refused rather than resolved to a file.`
24835
25353
  );
24836
25354
  }
24837
- return join14(this.storagePath, `${createHash6("sha256").update(id).digest("hex")}.json`);
25355
+ return join14(this.storagePath, `${createHash7("sha256").update(id).digest("hex")}.json`);
24838
25356
  }
24839
25357
  read(sessionId) {
24840
25358
  const filePath = this.filePath(sessionId);
@@ -24844,7 +25362,7 @@ var init_session = __esm({
24844
25362
  const wrapper = JSON.parse(raw);
24845
25363
  if (wrapper._expires && wrapper._expires > 0 && Date.now() / 1e3 > wrapper._expires) {
24846
25364
  try {
24847
- unlinkSync5(filePath);
25365
+ unlinkSync6(filePath);
24848
25366
  } catch {
24849
25367
  }
24850
25368
  return null;
@@ -24863,7 +25381,7 @@ var init_session = __esm({
24863
25381
  destroy(sessionId) {
24864
25382
  const filePath = this.filePath(sessionId);
24865
25383
  try {
24866
- if (existsSync11(filePath)) unlinkSync5(filePath);
25384
+ if (existsSync11(filePath)) unlinkSync6(filePath);
24867
25385
  } catch {
24868
25386
  }
24869
25387
  }
@@ -24879,11 +25397,11 @@ var init_session = __esm({
24879
25397
  const raw = readFileSync8(fullPath, "utf-8");
24880
25398
  const wrapper = JSON.parse(raw);
24881
25399
  if (wrapper._expires && wrapper._expires > 0 && now > wrapper._expires) {
24882
- unlinkSync5(fullPath);
25400
+ unlinkSync6(fullPath);
24883
25401
  }
24884
25402
  } catch {
24885
25403
  try {
24886
- unlinkSync5(fullPath);
25404
+ unlinkSync6(fullPath);
24887
25405
  } catch {
24888
25406
  }
24889
25407
  }
@@ -25403,12 +25921,28 @@ var init_session = __esm({
25403
25921
  this.loaded = /* @__PURE__ */ new Map();
25404
25922
  }
25405
25923
  };
25924
+ sessionStore = new AsyncLocalStorage4();
25925
+ }
25926
+ });
25927
+
25928
+ // src/etag.ts
25929
+ function etagMatches(ifNoneMatch, etag) {
25930
+ const strip = (tag) => tag.trim().replace(/^W\//, "");
25931
+ const target = strip(etag);
25932
+ return ifNoneMatch.split(",").some((candidate) => {
25933
+ const trimmed = candidate.trim();
25934
+ return trimmed === "*" || strip(trimmed) === target;
25935
+ });
25936
+ }
25937
+ var init_etag = __esm({
25938
+ "src/etag.ts"() {
25939
+ "use strict";
25406
25940
  }
25407
25941
  });
25408
25942
 
25409
25943
  // src/dispatchPipeline.ts
25410
25944
  import { gzipSync } from "node:zlib";
25411
- import { createHash as createHash7 } from "node:crypto";
25945
+ import { createHash as createHash8 } from "node:crypto";
25412
25946
  async function resetRequestCaches2() {
25413
25947
  if (_resetRequestCaches === void 0) {
25414
25948
  _resetRequestCaches = Promise.resolve().then(() => (init_src(), src_exports)).then((orm) => orm.resetRequestCaches).catch(() => null);
@@ -25481,7 +26015,7 @@ function applyResponseValidator(rawReq, rawRes, body) {
25481
26015
  if ((rawRes.statusCode || 200) !== 200 || body.length === 0) return false;
25482
26016
  let etag = rawRes.getHeader("etag");
25483
26017
  if (!etag) {
25484
- etag = `"${createHash7("md5").update(body).digest("hex").slice(0, 16)}"`;
26018
+ etag = `"${createHash8("md5").update(body).digest("hex").slice(0, 16)}"`;
25485
26019
  rawRes.setHeader("ETag", etag);
25486
26020
  }
25487
26021
  if (!responseIsNotModified(rawReq, rawRes, String(etag))) return false;
@@ -25556,6 +26090,7 @@ async function sessionAutoStart(rawReq, rawRes, req2) {
25556
26090
  return;
25557
26091
  }
25558
26092
  req2.session = sess;
26093
+ setFormTokenSession(sess);
25559
26094
  const origEnd = rawRes.end.bind(rawRes);
25560
26095
  let finalised = false;
25561
26096
  rawRes.end = function(...args) {
@@ -25584,6 +26119,7 @@ var _resetRequestCaches, COMPRESSIBLE_PREFIXES;
25584
26119
  var init_dispatchPipeline = __esm({
25585
26120
  "src/dispatchPipeline.ts"() {
25586
26121
  "use strict";
26122
+ init_session();
25587
26123
  init_logger();
25588
26124
  init_etag();
25589
26125
  COMPRESSIBLE_PREFIXES = [
@@ -25733,14 +26269,21 @@ function parseStack(stack) {
25733
26269
  const frames = [];
25734
26270
  const lines = stack.split("\n");
25735
26271
  for (const line of lines) {
25736
- let match = line.match(/^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);
25737
- if (match) {
25738
- frames.push({ func: match[1], file: match[2], line: parseInt(match[3], 10), column: parseInt(match[4], 10) });
25739
- continue;
26272
+ const t = line.trim();
26273
+ if (!t.startsWith("at ")) continue;
26274
+ const rest = t.slice(3);
26275
+ let func = "{anonymous}";
26276
+ let loc = rest;
26277
+ if (rest.endsWith(")")) {
26278
+ const open = rest.lastIndexOf(" (");
26279
+ if (open >= 0) {
26280
+ func = rest.slice(0, open);
26281
+ loc = rest.slice(open + 2, -1);
26282
+ }
25740
26283
  }
25741
- match = line.match(/^\s*at\s+(.+?):(\d+):(\d+)/);
25742
- if (match) {
25743
- frames.push({ func: "{anonymous}", file: match[1], line: parseInt(match[2], 10), column: parseInt(match[3], 10) });
26284
+ const lc = loc.match(/:(\d+):(\d+)$/);
26285
+ if (lc && lc.index !== void 0) {
26286
+ frames.push({ func, file: loc.slice(0, lc.index), line: parseInt(lc[1], 10), column: parseInt(lc[2], 10) });
25744
26287
  }
25745
26288
  }
25746
26289
  return frames;
@@ -26065,7 +26608,7 @@ var init_rateLimiter = __esm({
26065
26608
  });
26066
26609
 
26067
26610
  // src/devMailbox.ts
26068
- import { mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync8, unlinkSync as unlinkSync6, existsSync as existsSync12 } from "node:fs";
26611
+ import { mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync11, writeFileSync as writeFileSync8, unlinkSync as unlinkSync7, existsSync as existsSync12 } from "node:fs";
26069
26612
  import { join as join16 } from "node:path";
26070
26613
  import { randomUUID as randomUUID2 } from "node:crypto";
26071
26614
  var DevMailbox;
@@ -26197,7 +26740,7 @@ var init_devMailbox = __esm({
26197
26740
  const filePath = join16(this.mailboxDir, folder, `${msgId}.json`);
26198
26741
  if (existsSync12(filePath)) {
26199
26742
  try {
26200
- unlinkSync6(filePath);
26743
+ unlinkSync7(filePath);
26201
26744
  deleted = true;
26202
26745
  } catch {
26203
26746
  }
@@ -26216,7 +26759,7 @@ var init_devMailbox = __esm({
26216
26759
  if (existsSync12(dir)) {
26217
26760
  const files = readdirSync7(dir).filter((file) => file.endsWith(".json"));
26218
26761
  for (const file of files) {
26219
- unlinkSync6(join16(dir, file));
26762
+ unlinkSync7(join16(dir, file));
26220
26763
  }
26221
26764
  }
26222
26765
  } catch {
@@ -26635,26 +27178,31 @@ function parseFlags(args, booleanFlags) {
26635
27178
  const positional = [];
26636
27179
  let i = 0;
26637
27180
  while (i < args.length) {
26638
- const arg = args[i];
26639
- if (arg.startsWith("--")) {
26640
- const key = arg.slice(2);
26641
- if (booleanFlags?.has(key)) {
26642
- flags[key] = true;
26643
- i += 1;
26644
- } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
26645
- flags[key] = args[i + 1];
26646
- i += 2;
26647
- } else {
26648
- flags[key] = true;
26649
- i += 1;
26650
- }
27181
+ if (args[i].startsWith("--")) {
27182
+ i += readFlag(args, i, flags, booleanFlags);
26651
27183
  } else {
26652
- positional.push(arg);
27184
+ positional.push(args[i]);
26653
27185
  i += 1;
26654
27186
  }
26655
27187
  }
26656
27188
  return { flags, positional };
26657
27189
  }
27190
+ function readFlag(args, i, flags, booleanFlags) {
27191
+ const arg = args[i];
27192
+ const eq = arg.indexOf("=");
27193
+ if (eq !== -1) {
27194
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
27195
+ return 1;
27196
+ }
27197
+ const key = arg.slice(2);
27198
+ const next = args[i + 1];
27199
+ if (!booleanFlags?.has(key) && next !== void 0 && !next.startsWith("--")) {
27200
+ flags[key] = next;
27201
+ return 2;
27202
+ }
27203
+ flags[key] = true;
27204
+ return 1;
27205
+ }
26658
27206
  var init_util = __esm({
26659
27207
  "../cli/src/util.ts"() {
26660
27208
  "use strict";
@@ -26667,6 +27215,7 @@ __export(generate_exports, {
26667
27215
  DEFAULT_FIELDS: () => DEFAULT_FIELDS,
26668
27216
  GENERATORS: () => GENERATORS,
26669
27217
  RESOLUTION_ENVELOPE_VERSION: () => RESOLUTION_ENVELOPE_VERSION,
27218
+ RESOLUTION_FLAGS: () => RESOLUTION_FLAGS,
26670
27219
  SQL_RESERVED_TABLE_NAMES: () => SQL_RESERVED_TABLE_NAMES,
26671
27220
  aiFill: () => aiFill,
26672
27221
  currentResolution: () => currentResolution,
@@ -26983,6 +27532,10 @@ async function generate(what, name, extraArgs = []) {
26983
27532
  extraArgs = [name, ...extraArgs];
26984
27533
  name = "";
26985
27534
  }
27535
+ if (GENERATORS[what] && !noNameGenerators.has(what) && name.startsWith("-")) {
27536
+ console.log(`Invalid ${what} name: '${name}' - names can't start with '-'.`);
27537
+ process.exit(1);
27538
+ }
26986
27539
  if (!noNameGenerators.has(what) && !name) {
26987
27540
  console.error(` Usage: tina4nodejs generate ${what} <name> [options]`);
26988
27541
  process.exit(1);
@@ -27299,7 +27852,7 @@ function generateCrud(name, flags) {
27299
27852
  if (!__resolution.jsonMode) console.log(`
27300
27853
  Generating CRUD for ${name}...
27301
27854
  `);
27302
- generateModel(name, flags, false);
27855
+ if (!flags["skip-model"]) generateModel(name, flags, false);
27303
27856
  generateCrudAdminRoute(name, table2, isPublic);
27304
27857
  if (!flags["no-templates"]) copyCrudTemplates();
27305
27858
  generateCrudGateTest(name, table2, isPublic);
@@ -28609,7 +29162,7 @@ for (const stmt of statements(downSql)) db.execute(stmt);
28609
29162
  assert("DOWN drops the ${table2} table", db.tableExists("${table2}") === false);`;
28610
29163
  writeTest(`${table2}_migration`, standaloneTest(doc, body));
28611
29164
  }
28612
- var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, GENERATOR_LIST, NEXT_STEPS;
29165
+ var FIELD_TYPE_MAP, SQL_RESERVED_TABLE_NAMES, RESOLUTION_ENVELOPE_VERSION, __resolution, TINA4_EDIT_MARKER, DEFAULT_FIELDS, GENERATORS, RESOLUTION_FLAGS, GENERATOR_LIST, NEXT_STEPS;
28613
29166
  var init_generate = __esm({
28614
29167
  "../cli/src/commands/generate.ts"() {
28615
29168
  "use strict";
@@ -28722,22 +29275,23 @@ var init_generate = __esm({
28722
29275
  TINA4_EDIT_MARKER = /^\s*(?:\/\/|--|\{#|#)\s*tina4:edit\s+(.+?)(?:\s*#\})?\s*$/;
28723
29276
  DEFAULT_FIELDS = [["name", "string"]];
28724
29277
  GENERATORS = {
28725
- model: { handler: generateModel, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
28726
- route: { handler: generateRoute, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
28727
- crud: { handler: generateCrud, usage: '<Name> [--fields "..."] [--public] [--no-templates]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
28728
- migration: { handler: (n, f) => generateMigration(n, f, void 0, void 0, !f["no-test"]), usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
28729
- middleware: { handler: generateMiddleware, usage: "<Name>", summary: "Middleware with before/after hooks" },
28730
- test: { handler: generateTest, usage: "<name> [--model Name]", summary: "Test file" },
28731
- form: { handler: generateForm2, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
28732
- view: { handler: generateView, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
28733
- auth: { handler: (_n, f) => generateAuth(f), usage: "", summary: "Login/register routes (public) + User model + templates" },
28734
- service: { handler: generateService, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
28735
- queue: { handler: generateQueue, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
28736
- validator: { handler: generateValidator, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
28737
- seeder: { handler: generateSeeder, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
28738
- websocket: { handler: generateWebsocket, usage: "<path>", summary: "websocket() handler (src/routes/)" },
28739
- listener: { handler: generateListener, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
28740
- };
29278
+ 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" },
29279
+ 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)" },
29280
+ 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" },
29281
+ 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)" },
29282
+ middleware: { handler: generateMiddleware, flags: {}, usage: "<Name>", summary: "Middleware with before/after hooks" },
29283
+ test: { handler: generateTest, flags: { model: true, public: false, "secure-writes": false }, usage: "<name> [--model Name]", summary: "Test file" },
29284
+ form: { handler: generateForm2, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
29285
+ view: { handler: generateView, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
29286
+ auth: { handler: (_n, f) => generateAuth(f), flags: {}, usage: "", summary: "Login/register routes (public) + User model + templates" },
29287
+ service: { handler: generateService, flags: { every: true, cron: true }, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
29288
+ queue: { handler: generateQueue, flags: {}, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
29289
+ validator: { handler: generateValidator, flags: {}, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
29290
+ seeder: { handler: generateSeeder, flags: { "table-name": true }, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
29291
+ websocket: { handler: generateWebsocket, flags: {}, usage: "<path>", summary: "websocket() handler (src/routes/)" },
29292
+ listener: { handler: generateListener, flags: {}, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" }
29293
+ };
29294
+ RESOLUTION_FLAGS = { json: false, "dry-run": false };
28741
29295
  GENERATOR_LIST = Object.keys(GENERATORS).join(", ");
28742
29296
  NEXT_STEPS = {
28743
29297
  model: ({ name, table: table2 }) => [
@@ -28862,7 +29416,7 @@ import * as fs4 from "node:fs";
28862
29416
  import * as path3 from "node:path";
28863
29417
  import * as os from "node:os";
28864
29418
  import { spawnSync as spawnSync2 } from "node:child_process";
28865
- import { createRequire as createRequire8 } from "node:module";
29419
+ import { createRequire as createRequire7 } from "node:module";
28866
29420
  import { randomBytes as randomBytes7 } from "node:crypto";
28867
29421
  function reqSibling(pkg) {
28868
29422
  return req(`../../${pkg}/src/index.ts`);
@@ -29021,21 +29575,45 @@ function safePath(projectRoot3, relPath) {
29021
29575
  if (resolved !== projectRoot3 && !resolved.startsWith(rootPrefix)) {
29022
29576
  throw new Error(`Path escapes project directory: ${relPath}`);
29023
29577
  }
29024
- let real = null;
29578
+ let realRoot;
29025
29579
  try {
29026
- real = fs4.realpathSync(resolved);
29580
+ realRoot = fs4.realpathSync(projectRoot3);
29027
29581
  } catch {
29028
- real = null;
29582
+ return resolved;
29029
29583
  }
29030
- if (real !== null) {
29031
- const realRoot = fs4.realpathSync(projectRoot3);
29032
- const realPrefix = realRoot.endsWith(path3.sep) ? realRoot : realRoot + path3.sep;
29033
- if (real !== realRoot && !real.startsWith(realPrefix)) {
29034
- throw new Error(`Path escapes project directory: ${relPath}`);
29035
- }
29584
+ const real = realPathOf(resolved);
29585
+ const realPrefix = realRoot.endsWith(path3.sep) ? realRoot : realRoot + path3.sep;
29586
+ if (real === null || real !== realRoot && !real.startsWith(realPrefix)) {
29587
+ throw new Error(`Path escapes project directory: ${relPath}`);
29036
29588
  }
29037
29589
  return resolved;
29038
29590
  }
29591
+ function realPathOf(p, hops = 0) {
29592
+ let probe = p;
29593
+ while (!fs4.existsSync(probe) && !isSymlink(probe) && path3.dirname(probe) !== probe) {
29594
+ probe = path3.dirname(probe);
29595
+ }
29596
+ try {
29597
+ return fs4.realpathSync.native(probe);
29598
+ } catch {
29599
+ if (hops >= 40) return null;
29600
+ let target;
29601
+ try {
29602
+ target = fs4.readlinkSync(probe);
29603
+ } catch {
29604
+ return null;
29605
+ }
29606
+ const base = path3.isAbsolute(target) ? target : path3.dirname(probe) + path3.sep + target;
29607
+ return realPathOf(base + p.slice(probe.length), hops + 1);
29608
+ }
29609
+ }
29610
+ function isSymlink(p) {
29611
+ try {
29612
+ return fs4.lstatSync(p).isSymbolicLink();
29613
+ } catch {
29614
+ return false;
29615
+ }
29616
+ }
29039
29617
  function redactEnv(key, value) {
29040
29618
  const sensitive = ["secret", "password", "token", "key", "credential", "api_key"];
29041
29619
  if (sensitive.some((s) => key.toLowerCase().includes(s))) {
@@ -29880,8 +30458,10 @@ function registerDevTools(server) {
29880
30458
  return { error: `Invalid path ${JSON.stringify(rel)}: ${proseErr}` };
29881
30459
  }
29882
30460
  rel = normalizeCoderPath(projectRoot4, rel);
29883
- const resolved = path3.resolve(projectRoot4, rel);
29884
- if (!resolved.startsWith(projectRoot4)) {
30461
+ let resolved;
30462
+ try {
30463
+ resolved = safePath(projectRoot4, rel);
30464
+ } catch {
29885
30465
  return { error: `Path escapes project directory: ${rel}` };
29886
30466
  }
29887
30467
  if (!fs4.existsSync(resolved) || !fs4.statSync(resolved).isFile()) {
@@ -30178,8 +30758,9 @@ var req, PARSE_ERROR, INVALID_REQUEST, METHOD_NOT_FOUND, INVALID_PARAMS, INTERNA
30178
30758
  var init_mcp = __esm({
30179
30759
  "src/mcp.ts"() {
30180
30760
  "use strict";
30761
+ init_slashTrim();
30181
30762
  init_version();
30182
- req = createRequire8(import.meta.url);
30763
+ req = createRequire7(import.meta.url);
30183
30764
  PARSE_ERROR = -32700;
30184
30765
  INVALID_REQUEST = -32600;
30185
30766
  METHOD_NOT_FOUND = -32601;
@@ -30204,7 +30785,7 @@ var init_mcp = __esm({
30204
30785
  // threaded, so this in-process map is the whole coordination mechanism.
30205
30786
  _sseChannels = /* @__PURE__ */ new Map();
30206
30787
  constructor(mcpPath, name = "Tina4 MCP", version = "1.0.0") {
30207
- this.path = mcpPath.replace(/\/+$/, "");
30788
+ this.path = rtrimSlashes(mcpPath);
30208
30789
  this.name = name;
30209
30790
  this.version = version;
30210
30791
  _McpServer._instances.push(this);
@@ -32287,7 +32868,7 @@ __export(websocket_exports, {
32287
32868
  wsToken: () => wsToken
32288
32869
  });
32289
32870
  import { createServer as createServer2 } from "node:http";
32290
- import { createHash as createHash8 } from "node:crypto";
32871
+ import { createHash as createHash9 } from "node:crypto";
32291
32872
  import { randomUUID as randomUUID4 } from "node:crypto";
32292
32873
  function buildCloseFrame(code, reason = "") {
32293
32874
  const reasonBytes = Buffer.from(reason, "utf-8");
@@ -32297,7 +32878,7 @@ function buildCloseFrame(code, reason = "") {
32297
32878
  return buildFrame(OP_CLOSE, payload);
32298
32879
  }
32299
32880
  function computeAcceptKey(key) {
32300
- return createHash8("sha1").update(key + MAGIC_STRING).digest("base64");
32881
+ return createHash9("sha1").update(key + MAGIC_STRING).digest("base64");
32301
32882
  }
32302
32883
  function originAllowed(headers) {
32303
32884
  const raw = (process.env.TINA4_WS_ALLOWED_ORIGINS ?? "").trim();
@@ -33988,7 +34569,7 @@ var init_job = __esm({
33988
34569
  });
33989
34570
 
33990
34571
  // src/queueBackends/liteBackend.ts
33991
- import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync7, existsSync as existsSync19 } from "node:fs";
34572
+ import { mkdirSync as mkdirSync15, readdirSync as readdirSync12, readFileSync as readFileSync16, writeFileSync as writeFileSync11, unlinkSync as unlinkSync8, existsSync as existsSync19 } from "node:fs";
33992
34573
  import { join as join23 } from "node:path";
33993
34574
  import { randomUUID as randomUUID6 } from "node:crypto";
33994
34575
  var LiteBackend;
@@ -34158,7 +34739,7 @@ var init_liteBackend = __esm({
34158
34739
  }
34159
34740
  if (record.availableAt && record.availableAt > now) continue;
34160
34741
  try {
34161
- unlinkSync7(filePath);
34742
+ unlinkSync8(filePath);
34162
34743
  } catch {
34163
34744
  continue;
34164
34745
  }
@@ -34192,10 +34773,10 @@ var init_liteBackend = __esm({
34192
34773
  job.priority = job.priority ?? 0;
34193
34774
  this.writeReserved(queue, job);
34194
34775
  try {
34195
- unlinkSync7(filePath);
34776
+ unlinkSync8(filePath);
34196
34777
  } catch {
34197
34778
  try {
34198
- unlinkSync7(this.reservedPath(queue, job.id));
34779
+ unlinkSync8(this.reservedPath(queue, job.id));
34199
34780
  } catch {
34200
34781
  }
34201
34782
  continue;
@@ -34217,10 +34798,10 @@ var init_liteBackend = __esm({
34217
34798
  job.priority = job.priority ?? 0;
34218
34799
  this.writeReserved(queue, job);
34219
34800
  try {
34220
- unlinkSync7(filePath);
34801
+ unlinkSync8(filePath);
34221
34802
  } catch {
34222
34803
  try {
34223
- unlinkSync7(this.reservedPath(queue, job.id));
34804
+ unlinkSync8(this.reservedPath(queue, job.id));
34224
34805
  } catch {
34225
34806
  }
34226
34807
  continue;
@@ -34235,7 +34816,7 @@ var init_liteBackend = __esm({
34235
34816
  */
34236
34817
  clearReservation(queue, jobId) {
34237
34818
  try {
34238
- unlinkSync7(this.reservedPath(queue, jobId));
34819
+ unlinkSync8(this.reservedPath(queue, jobId));
34239
34820
  } catch {
34240
34821
  }
34241
34822
  }
@@ -34278,7 +34859,7 @@ var init_liteBackend = __esm({
34278
34859
  try {
34279
34860
  const files = readdirSync12(dir).filter((f) => f.endsWith(".queue-data"));
34280
34861
  for (const file of files) {
34281
- unlinkSync7(join23(dir, file));
34862
+ unlinkSync8(join23(dir, file));
34282
34863
  count++;
34283
34864
  }
34284
34865
  } catch {
@@ -34288,7 +34869,7 @@ var init_liteBackend = __esm({
34288
34869
  if (existsSync19(failedDir)) {
34289
34870
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
34290
34871
  for (const file of files) {
34291
- unlinkSync7(join23(failedDir, file));
34872
+ unlinkSync8(join23(failedDir, file));
34292
34873
  count++;
34293
34874
  }
34294
34875
  }
@@ -34299,7 +34880,7 @@ var init_liteBackend = __esm({
34299
34880
  if (existsSync19(reservedDir)) {
34300
34881
  const files = readdirSync12(reservedDir).filter((f) => f.endsWith(".queue-data"));
34301
34882
  for (const file of files) {
34302
- unlinkSync7(join23(reservedDir, file));
34883
+ unlinkSync8(join23(reservedDir, file));
34303
34884
  count++;
34304
34885
  }
34305
34886
  }
@@ -34357,7 +34938,7 @@ var init_liteBackend = __esm({
34357
34938
  const prefix = this.nextPrefix();
34358
34939
  const queueDir = join23(this.basePath, q);
34359
34940
  writeFileSync11(join23(queueDir, `${prefix}_${jobId}.queue-data`), JSON.stringify(job, null, 2));
34360
- unlinkSync7(filePath);
34941
+ unlinkSync8(filePath);
34361
34942
  return true;
34362
34943
  }
34363
34944
  }
@@ -34393,7 +34974,7 @@ var init_liteBackend = __esm({
34393
34974
  const files = readdirSync12(failedDir).filter((f) => f.endsWith(".queue-data"));
34394
34975
  for (const file of files) {
34395
34976
  try {
34396
- unlinkSync7(join23(failedDir, file));
34977
+ unlinkSync8(join23(failedDir, file));
34397
34978
  count++;
34398
34979
  } catch {
34399
34980
  }
@@ -34408,7 +34989,7 @@ var init_liteBackend = __esm({
34408
34989
  try {
34409
34990
  const job = JSON.parse(readFileSync16(join23(dir, file), "utf-8"));
34410
34991
  if (job.status === status2) {
34411
- unlinkSync7(join23(dir, file));
34992
+ unlinkSync8(join23(dir, file));
34412
34993
  count++;
34413
34994
  }
34414
34995
  } catch {
@@ -34443,7 +35024,7 @@ var init_liteBackend = __esm({
34443
35024
  job.delayUntil = null;
34444
35025
  const prefix = this.nextPrefix();
34445
35026
  writeFileSync11(join23(queueDir, `${prefix}_${job.id}.queue-data`), JSON.stringify(job, null, 2));
34446
- unlinkSync7(filePath);
35027
+ unlinkSync8(filePath);
34447
35028
  count++;
34448
35029
  } catch {
34449
35030
  }
@@ -34475,10 +35056,10 @@ var init_liteBackend = __esm({
34475
35056
  job.priority = job.priority ?? 0;
34476
35057
  this.writeReserved(queue, job);
34477
35058
  try {
34478
- unlinkSync7(filePath);
35059
+ unlinkSync8(filePath);
34479
35060
  } catch {
34480
35061
  try {
34481
- unlinkSync7(this.reservedPath(queue, job.id));
35062
+ unlinkSync8(this.reservedPath(queue, job.id));
34482
35063
  } catch {
34483
35064
  }
34484
35065
  continue;
@@ -34580,7 +35161,7 @@ var init_liteBackend = __esm({
34580
35161
  retryJob(queue, job, delaySeconds) {
34581
35162
  this.clearReservation(queue, job.id);
34582
35163
  try {
34583
- unlinkSync7(join23(this.ensureFailedDir(queue), `${job.id}.queue-data`));
35164
+ unlinkSync8(join23(this.ensureFailedDir(queue), `${job.id}.queue-data`));
34584
35165
  } catch {
34585
35166
  }
34586
35167
  job.attempts = (job.attempts || 0) + 1;
@@ -35130,7 +35711,8 @@ function archiveDir() {
35130
35711
  return p;
35131
35712
  }
35132
35713
  function slugify(title) {
35133
- const slug = (title || "").trim().toLowerCase().replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
35714
+ const dashed = (title || "").trim().toLowerCase().replace(/[^A-Za-z0-9_-]+/g, "-");
35715
+ const slug = trimChar(dashed, 45);
35134
35716
  return slug.slice(0, 80) || `plan-${Math.floor(Date.now() / 1e3)}`;
35135
35717
  }
35136
35718
  function parse(text) {
@@ -35267,6 +35849,7 @@ var PLAN_DIR, CURRENT_FILE, ARCHIVE_SUBDIR, STEP_RE, Plan;
35267
35849
  var init_plan = __esm({
35268
35850
  "src/plan.ts"() {
35269
35851
  "use strict";
35852
+ init_slashTrim();
35270
35853
  PLAN_DIR = "plan";
35271
35854
  CURRENT_FILE = ".current";
35272
35855
  ARCHIVE_SUBDIR = "done";
@@ -36506,7 +37089,7 @@ function relativePath(absPath, projectRoot3, frameworkRoots) {
36506
37089
  }
36507
37090
  function tokenise(text) {
36508
37091
  if (!text) return [];
36509
- const expanded = text.replace(CAMEL_SPLIT, (_m, a, b, c, d) => a ? `${a} ${b}` : `${c} ${d}`).toLowerCase();
37092
+ const expanded = text.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z])(?=[A-Z][a-z])/g, "$1 ").toLowerCase();
36510
37093
  return expanded.split(/[\s_\-./:,;()\[\]{}\\]+/).filter((p) => p.length > 0);
36511
37094
  }
36512
37095
  function summariseDoc(doc) {
@@ -36737,7 +37320,7 @@ function returnFromSignature(signature) {
36737
37320
  const rest = signature.slice(close + 1).trim();
36738
37321
  return rest.startsWith(":") ? rest.slice(1).trim() : "";
36739
37322
  }
36740
- var STDLIB_ALLOWLIST, _DOCS_CACHE, __FILENAME, __DIRNAME, USER_DIRS, CAMEL_SPLIT, FENCE_RE, CALL_RE, sharedFrameworkIndex, Docs;
37323
+ var STDLIB_ALLOWLIST, _DOCS_CACHE, __FILENAME, __DIRNAME, USER_DIRS, FENCE_RE, CALL_RE, sharedFrameworkIndex, Docs;
36741
37324
  var init_docs = __esm({
36742
37325
  "src/docs.ts"() {
36743
37326
  "use strict";
@@ -36876,7 +37459,6 @@ var init_docs = __esm({
36876
37459
  __FILENAME = fileURLToPath6(import.meta.url);
36877
37460
  __DIRNAME = path8.dirname(__FILENAME);
36878
37461
  USER_DIRS = ["src/orm", "src/routes", "src/app", "src/services", "src/models"];
36879
- CAMEL_SPLIT = /([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])/g;
36880
37462
  FENCE_RE = new RegExp(
36881
37463
  String.fromCharCode(96, 96, 96) + "[a-zA-Z0-9_+-]*\\n([\\s\\S]*?)\\n" + String.fromCharCode(96, 96, 96),
36882
37464
  "g"
@@ -37250,7 +37832,7 @@ ${end}
37250
37832
 
37251
37833
  // src/devAdmin.ts
37252
37834
  import { cpus as osCpus } from "node:os";
37253
- import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync23, readdirSync as readdirSync16, mkdirSync as mkdirSync18, copyFileSync as copyFileSync2, statSync as statSync17, openSync as openSync4, closeSync as closeSync4, fstatSync as fstatSync2, fchmodSync as fchmodSync2, ftruncateSync, constants as constants3, realpathSync as realpathSync6, lstatSync } from "node:fs";
37835
+ import { readFileSync as readFileSync20, writeFileSync as writeFileSync15, existsSync as existsSync23, readdirSync as readdirSync16, mkdirSync as mkdirSync18, copyFileSync as copyFileSync2, statSync as statSync17, openSync as openSync5, closeSync as closeSync5, fstatSync as fstatSync3, fchmodSync as fchmodSync2, ftruncateSync as ftruncateSync2, constants as constants4, realpathSync as realpathSync6, lstatSync as lstatSync3 } from "node:fs";
37254
37836
  import { join as join27, dirname as dirname14, resolve as resolve16, relative as relative9, sep as sep8, basename as basename5 } from "node:path";
37255
37837
  import { fileURLToPath as fileURLToPath7 } from "node:url";
37256
37838
  import { timingSafeEqual as timingSafeEqual2 } from "node:crypto";
@@ -37449,8 +38031,41 @@ function quoteTableRef(name) {
37449
38031
  }
37450
38032
  return parts.map((p) => `"${p}"`).join(".");
37451
38033
  }
38034
+ function parseSeedRequest(url, body) {
38035
+ const b = body ?? {};
38036
+ const table2 = String(url.searchParams.get("table") ?? b.table ?? "");
38037
+ const count = parseInt(String(url.searchParams.get("count") ?? b.count ?? "10"), 10) || 10;
38038
+ const seedRaw = url.searchParams.get("seed") ?? b.seed;
38039
+ const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
38040
+ const clear = String(url.searchParams.get("clear") ?? b.clear ?? "") === "true" || b.clear === true;
38041
+ const strict = String(url.searchParams.get("strict") ?? b.strict ?? "") === "true" || b.strict === true;
38042
+ return { table: table2, count, seed, clear, strict };
38043
+ }
38044
+ function buildSeedFieldMap(columns, fake) {
38045
+ const rules = [
38046
+ [(n) => n.includes("email"), () => fake.email()],
38047
+ [(n) => n.includes("name"), () => fake.name()],
38048
+ [(n) => n.includes("phone"), () => fake.phone()],
38049
+ [(n) => n.includes("address") || n.includes("city") || n.includes("country"), () => fake.address()],
38050
+ [(n) => n.includes("url") || n.includes("website"), () => fake.url()],
38051
+ [(_n, t) => t.includes("int"), () => fake.integer(1, 1e3)],
38052
+ [(_n, t) => /real|float|double|numeric|decimal/.test(t), () => fake.numeric(0, 1e3, 2)],
38053
+ [(_n, t) => t.includes("bool"), () => fake.boolean()],
38054
+ [(_n, t) => t.includes("date") || t.includes("time"), () => fake.date()]
38055
+ ];
38056
+ const sentence = () => fake.sentence(3);
38057
+ const fieldMap = {};
38058
+ for (const col of columns) {
38059
+ if (col.name.toLowerCase() === "id" || col.primaryKey === true) continue;
38060
+ const name = col.name.toLowerCase();
38061
+ const type2 = col.type.toLowerCase();
38062
+ const rule = rules.find(([matches]) => matches(name, type2));
38063
+ fieldMap[col.name] = rule ? rule[1] : sentence;
38064
+ }
38065
+ return fieldMap;
38066
+ }
37452
38067
  function supervisorBaseUrl() {
37453
- const explicit = (process.env.TINA4_SUPERVISOR_URL ?? "").replace(/\/+$/, "");
38068
+ const explicit = rtrimSlashes(process.env.TINA4_SUPERVISOR_URL ?? "");
37454
38069
  if (explicit) return explicit;
37455
38070
  const agentPort = (process.env.TINA4_AGENT_PORT ?? "").trim();
37456
38071
  if (/^\d+$/.test(agentPort)) return `http://127.0.0.1:${parseInt(agentPort, 10)}`;
@@ -37458,6 +38073,42 @@ function supervisorBaseUrl() {
37458
38073
  if (/^\d+$/.test(fwPort)) return `http://127.0.0.1:${parseInt(fwPort, 10) + 2e3}`;
37459
38074
  return "http://127.0.0.1:9145";
37460
38075
  }
38076
+ function buildSupervisorBody(method, body) {
38077
+ if (method !== "POST" && method !== "PUT" && method !== "PATCH" && method !== "DELETE") return void 0;
38078
+ if (body === void 0 || body === null) return void 0;
38079
+ if (typeof body === "string") return body;
38080
+ if (typeof body !== "object") return void 0;
38081
+ let outBody = body;
38082
+ if (!Array.isArray(body)) {
38083
+ const pf = body.plan_file;
38084
+ if (typeof pf === "string" && pf && !pf.includes("/")) outBody = { ...body, plan_file: `plan/${pf}` };
38085
+ }
38086
+ return JSON.stringify(outBody);
38087
+ }
38088
+ async function streamEventStream(res, upstream, timer) {
38089
+ res.raw.writeHead(upstream.status || 200, {
38090
+ "Content-Type": upstream.headers.get("content-type") ?? "text/event-stream",
38091
+ "Cache-Control": "no-cache",
38092
+ Connection: "keep-alive"
38093
+ });
38094
+ if (typeof res.raw.flushHeaders === "function") res.raw.flushHeaders();
38095
+ if (!upstream.body) {
38096
+ res.raw.end();
38097
+ clearTimeout(timer);
38098
+ return;
38099
+ }
38100
+ const reader = upstream.body.getReader();
38101
+ try {
38102
+ while (true) {
38103
+ const { done, value } = await reader.read();
38104
+ if (done) break;
38105
+ if (value) res.raw.write(Buffer.from(value));
38106
+ }
38107
+ } finally {
38108
+ clearTimeout(timer);
38109
+ res.raw.end();
38110
+ }
38111
+ }
37461
38112
  async function proxyToSupervisor(req2, res, downstreamPath) {
37462
38113
  const base = supervisorBaseUrl();
37463
38114
  let qs = "";
@@ -37468,24 +38119,7 @@ async function proxyToSupervisor(req2, res, downstreamPath) {
37468
38119
  }
37469
38120
  const target = `${base}${downstreamPath}${qs}`;
37470
38121
  const method = (req2.method ?? "GET").toUpperCase();
37471
- let bodyText;
37472
- if (method === "POST" || method === "PUT" || method === "PATCH" || method === "DELETE") {
37473
- const body = req2.body;
37474
- if (body !== void 0 && body !== null) {
37475
- if (typeof body === "string") {
37476
- bodyText = body;
37477
- } else if (typeof body === "object") {
37478
- let outBody = body;
37479
- if (!Array.isArray(body)) {
37480
- const pf = body.plan_file;
37481
- if (typeof pf === "string" && pf && !pf.includes("/")) {
37482
- outBody = { ...body, plan_file: `plan/${pf}` };
37483
- }
37484
- }
37485
- bodyText = JSON.stringify(outBody);
37486
- }
37487
- }
37488
- }
38122
+ const bodyText = buildSupervisorBody(method, req2.body);
37489
38123
  const timeoutMs = downstreamPath === "/execute" || downstreamPath === "/chat" ? 6e5 : 3e4;
37490
38124
  const ctrl = new AbortController();
37491
38125
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
@@ -37511,30 +38145,7 @@ async function proxyToSupervisor(req2, res, downstreamPath) {
37511
38145
  }
37512
38146
  const ct = (upstream.headers.get("content-type") ?? "").toLowerCase();
37513
38147
  if (ct.includes("text/event-stream")) {
37514
- res.raw.writeHead(upstream.status || 200, {
37515
- "Content-Type": upstream.headers.get("content-type") ?? "text/event-stream",
37516
- "Cache-Control": "no-cache",
37517
- Connection: "keep-alive"
37518
- });
37519
- if (typeof res.raw.flushHeaders === "function") {
37520
- res.raw.flushHeaders();
37521
- }
37522
- if (!upstream.body) {
37523
- res.raw.end();
37524
- clearTimeout(timer);
37525
- return;
37526
- }
37527
- const reader = upstream.body.getReader();
37528
- try {
37529
- while (true) {
37530
- const { done, value } = await reader.read();
37531
- if (done) break;
37532
- if (value) res.raw.write(Buffer.from(value));
37533
- }
37534
- } finally {
37535
- clearTimeout(timer);
37536
- res.raw.end();
37537
- }
38148
+ await streamEventStream(res, upstream, timer);
37538
38149
  return;
37539
38150
  }
37540
38151
  clearTimeout(timer);
@@ -37651,13 +38262,13 @@ function handleGalleryDeploy(router) {
37651
38262
  res.json({ deployed: name, files: copied });
37652
38263
  };
37653
38264
  }
37654
- function realPathOf(target) {
38265
+ function realPathOf2(target) {
37655
38266
  let existing = target;
37656
38267
  const tail = [];
37657
38268
  for (; ; ) {
37658
38269
  let present = false;
37659
38270
  try {
37660
- lstatSync(existing);
38271
+ lstatSync3(existing);
37661
38272
  present = true;
37662
38273
  } catch {
37663
38274
  }
@@ -37669,9 +38280,9 @@ function realPathOf(target) {
37669
38280
  }
37670
38281
  function safeJoin(projectRoot3, rel, extraRoots = []) {
37671
38282
  try {
37672
- const root = realPathOf(resolve16(projectRoot3));
37673
- const resolved = realPathOf(resolve16(root, rel));
37674
- const roots = [root, ...extraRoots.filter(Boolean).map((r) => realPathOf(resolve16(r)))];
38283
+ const root = realPathOf2(resolve16(projectRoot3));
38284
+ const resolved = realPathOf2(resolve16(root, rel));
38285
+ const roots = [root, ...extraRoots.filter(Boolean).map((r) => realPathOf2(resolve16(r)))];
37675
38286
  for (const r of roots) {
37676
38287
  if (resolved === r || resolved.startsWith(r.endsWith(sep8) ? r : r + sep8)) return resolved;
37677
38288
  }
@@ -37680,7 +38291,7 @@ function safeJoin(projectRoot3, rel, extraRoots = []) {
37680
38291
  return null;
37681
38292
  }
37682
38293
  function resolvedRelative(projectRoot3, resolvedPath) {
37683
- return relative9(realPathOf(resolve16(projectRoot3)), resolvedPath);
38294
+ return relative9(realPathOf2(resolve16(projectRoot3)), resolvedPath);
37684
38295
  }
37685
38296
  function devFilesHidden(name) {
37686
38297
  if (DEV_FILES_IGNORED.has(name)) return true;
@@ -37708,7 +38319,7 @@ async function devGitInfo(root) {
37708
38319
  if (!inside || inside.trim() !== "true") return empty;
37709
38320
  const branch = (git(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "").trim();
37710
38321
  const topRaw = git(["rev-parse", "--show-toplevel"]);
37711
- const gitRoot = topRaw && topRaw.trim() !== "" ? topRaw.trim().replace(/\\/g, "/").replace(/\/+$/, "") : null;
38322
+ const gitRoot = topRaw && topRaw.trim() !== "" ? rtrimSlashes(topRaw.trim().replace(/\\/g, "/")) : null;
37712
38323
  const status2 = /* @__PURE__ */ new Map();
37713
38324
  const porcelain = git(["status", "--porcelain", "-uall"]);
37714
38325
  if (porcelain) {
@@ -37727,6 +38338,44 @@ async function devGitInfo(root) {
37727
38338
  return empty;
37728
38339
  }
37729
38340
  }
38341
+ function devGitLabel(gitPath, isDir, gitStatus) {
38342
+ const code = gitStatus.get(gitPath);
38343
+ if (code !== void 0) return devGitStatusLabel(code);
38344
+ if (isDir) {
38345
+ const prefix = gitPath + "/";
38346
+ for (const [gf, gc] of gitStatus) {
38347
+ if (gf.startsWith(prefix)) return gc === "??" ? "untracked" : "modified";
38348
+ }
38349
+ }
38350
+ return "clean";
38351
+ }
38352
+ function devDirHasVisibleChild(full) {
38353
+ try {
38354
+ for (const c of readdirSync16(full)) {
38355
+ if (!devFilesHidden(c)) return true;
38356
+ }
38357
+ } catch {
38358
+ }
38359
+ return false;
38360
+ }
38361
+ function buildFileEntry(name, full, entryRel, cwdInGit, gitStatus) {
38362
+ let isDir = false;
38363
+ let size = null;
38364
+ try {
38365
+ const st = statSync17(full);
38366
+ isDir = st.isDirectory();
38367
+ if (!isDir) size = st.size;
38368
+ } catch {
38369
+ }
38370
+ return {
38371
+ name,
38372
+ path: entryRel,
38373
+ is_dir: isDir,
38374
+ has_children: isDir ? devDirHasVisibleChild(full) : null,
38375
+ git_status: devGitLabel(cwdInGit + entryRel, isDir, gitStatus),
38376
+ size
38377
+ };
38378
+ }
37730
38379
  function devAdminLanguage(rel) {
37731
38380
  const base = (rel.split(/[\\/]/).pop() ?? "").toLowerCase();
37732
38381
  if (base === "dockerfile" || base === "dockerfile.dev" || base === "dockerfile.prod") {
@@ -37741,14 +38390,14 @@ function devAdminLanguage(rel) {
37741
38390
  function readDevFile(target) {
37742
38391
  let fd;
37743
38392
  try {
37744
- fd = openSync4(target, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
37745
- if (!fstatSync2(fd).isFile()) return null;
38393
+ fd = openSync5(target, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
38394
+ if (!fstatSync3(fd).isFile()) return null;
37746
38395
  return readFileSync20(fd);
37747
38396
  } catch (error2) {
37748
38397
  if (["ENOENT", "ENOTDIR", "ELOOP"].includes(error2.code ?? "")) return null;
37749
38398
  throw error2;
37750
38399
  } finally {
37751
- if (fd !== void 0) closeSync4(fd);
38400
+ if (fd !== void 0) closeSync5(fd);
37752
38401
  }
37753
38402
  }
37754
38403
  function mcpSecureEqual(expected, provided) {
@@ -37979,6 +38628,7 @@ var cpuCount, DEV_MCP_PREFIXES, DEV_PUBLIC_ASSETS, DEV_SECRET_BASENAMES, DEV_SEC
37979
38628
  var init_devAdmin = __esm({
37980
38629
  "src/devAdmin.ts"() {
37981
38630
  "use strict";
38631
+ init_slashTrim();
37982
38632
  init_devMailbox();
37983
38633
  init_upstreamResponse();
37984
38634
  init_dotenv();
@@ -38456,7 +39106,8 @@ var init_devAdmin = __esm({
38456
39106
  router.addRoute({
38457
39107
  method: route.method,
38458
39108
  pattern: route.pattern,
38459
- handler: route.handler
39109
+ handler: route.handler,
39110
+ noAuth: true
38460
39111
  });
38461
39112
  }
38462
39113
  if (mcpEnabled()) {
@@ -38480,7 +39131,8 @@ var init_devAdmin = __esm({
38480
39131
  router.addRoute({
38481
39132
  method: route.method,
38482
39133
  pattern: route.pattern,
38483
- handler: route.handler
39134
+ handler: route.handler,
39135
+ noAuth: true
38484
39136
  });
38485
39137
  }
38486
39138
  getDefaultDevServer();
@@ -38812,13 +39464,7 @@ var init_devAdmin = __esm({
38812
39464
  };
38813
39465
  handleSeed = async (req2, res) => {
38814
39466
  const url = new URL(req2.url ?? "/", "http://localhost");
38815
- const body = req2.body ?? {};
38816
- const table2 = url.searchParams.get("table") ?? body?.table ?? "";
38817
- const count = parseInt(String(url.searchParams.get("count") ?? body?.count ?? "10"), 10) || 10;
38818
- const seedRaw = url.searchParams.get("seed") ?? body?.seed;
38819
- const seed = seedRaw !== void 0 && seedRaw !== null && String(seedRaw) !== "" ? Number.isNaN(parseInt(String(seedRaw), 10)) ? void 0 : parseInt(String(seedRaw), 10) : void 0;
38820
- const clear = String(url.searchParams.get("clear") ?? body?.clear ?? "") === "true" || body?.clear === true;
38821
- const strict = String(url.searchParams.get("strict") ?? body?.strict ?? "") === "true" || body?.strict === true;
39467
+ const { table: table2, count, seed, clear, strict } = parseSeedRequest(url, req2.body);
38822
39468
  if (!table2) {
38823
39469
  res.json({ error: "Missing table parameter" });
38824
39470
  return;
@@ -38833,33 +39479,7 @@ var init_devAdmin = __esm({
38833
39479
  res.json({ error: `Table '${table2}' not found or has no columns` });
38834
39480
  return;
38835
39481
  }
38836
- const fieldMap = {};
38837
- for (const col of columns) {
38838
- const name = col.name.toLowerCase();
38839
- const type2 = col.type.toLowerCase();
38840
- if (name === "id" || col.primaryKey === true) continue;
38841
- if (name.includes("email")) {
38842
- fieldMap[col.name] = () => fake.email();
38843
- } else if (name.includes("name")) {
38844
- fieldMap[col.name] = () => fake.name();
38845
- } else if (name.includes("phone")) {
38846
- fieldMap[col.name] = () => fake.phone();
38847
- } else if (name.includes("address") || name.includes("city") || name.includes("country")) {
38848
- fieldMap[col.name] = () => fake.address();
38849
- } else if (name.includes("url") || name.includes("website")) {
38850
- fieldMap[col.name] = () => fake.url();
38851
- } else if (type2.includes("int")) {
38852
- fieldMap[col.name] = () => fake.integer(1, 1e3);
38853
- } else if (type2.includes("real") || type2.includes("float") || type2.includes("double") || type2.includes("numeric") || type2.includes("decimal")) {
38854
- fieldMap[col.name] = () => fake.numeric(0, 1e3, 2);
38855
- } else if (type2.includes("bool")) {
38856
- fieldMap[col.name] = () => fake.boolean();
38857
- } else if (type2.includes("date") || type2.includes("time")) {
38858
- fieldMap[col.name] = () => fake.date();
38859
- } else {
38860
- fieldMap[col.name] = () => fake.sentence(3);
38861
- }
38862
- }
39482
+ const fieldMap = buildSeedFieldMap(columns, fake);
38863
39483
  const summary = await seedTable2(db, table2, count, fieldMap, void 0, { clear, strict });
38864
39484
  res.json({ seeded: summary.seeded, failed: summary.failed, errors: summary.errors, table: table2 });
38865
39485
  } catch (e) {
@@ -39032,9 +39652,9 @@ var init_devAdmin = __esm({
39032
39652
  };
39033
39653
  handleTest = async (_req, res) => {
39034
39654
  try {
39035
- const { execFile } = await import("node:child_process");
39655
+ const { execFile: execFile2 } = await import("node:child_process");
39036
39656
  const { promisify } = await import("node:util");
39037
- const run = promisify(execFile);
39657
+ const run = promisify(execFile2);
39038
39658
  try {
39039
39659
  const { stdout, stderr } = await run("npm", ["test"], {
39040
39660
  cwd: resolve16(process.cwd()),
@@ -39152,9 +39772,9 @@ var init_devAdmin = __esm({
39152
39772
  }
39153
39773
  try {
39154
39774
  const envPath = join27(process.cwd(), ".env");
39155
- const fd = openSync4(envPath, constants3.O_RDWR | constants3.O_APPEND | constants3.O_CREAT | (constants3.O_NOFOLLOW ?? 0) | (constants3.O_NONBLOCK ?? 0), 384);
39775
+ const fd = openSync5(envPath, constants4.O_RDWR | constants4.O_APPEND | constants4.O_CREAT | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0), 384);
39156
39776
  try {
39157
- const info = fstatSync2(fd);
39777
+ const info = fstatSync3(fd);
39158
39778
  if (!info.isFile() || info.nlink !== 1) throw new Error("Refusing a non-regular or multiply-linked configuration file");
39159
39779
  fchmodSync2(fd, 384);
39160
39780
  const lines = readFileSync20(fd, "utf-8").split("\n");
@@ -39184,10 +39804,10 @@ var init_devAdmin = __esm({
39184
39804
  for (const [key, found] of Object.entries(keysFound)) {
39185
39805
  if (!found) newLines.push(`${key}=${values[key]}`);
39186
39806
  }
39187
- ftruncateSync(fd, 0);
39807
+ ftruncateSync2(fd, 0);
39188
39808
  writeFileSync15(fd, newLines.join("\n") + "\n");
39189
39809
  } finally {
39190
- closeSync4(fd);
39810
+ closeSync5(fd);
39191
39811
  }
39192
39812
  res.json({ success: true });
39193
39813
  } catch (e) {
@@ -39310,48 +39930,7 @@ var init_devAdmin = __esm({
39310
39930
  const full = join27(target, name);
39311
39931
  const entryRel = relative9(root, full).replace(/\\/g, "/");
39312
39932
  if (isSecretPath(entryRel)) continue;
39313
- let isDir = false;
39314
- let size = null;
39315
- try {
39316
- const st = statSync17(full);
39317
- isDir = st.isDirectory();
39318
- if (!isDir) size = st.size;
39319
- } catch {
39320
- }
39321
- const gitPath = cwdInGit + entryRel;
39322
- let gitLabel = "clean";
39323
- const code = gitStatus.get(gitPath);
39324
- if (code !== void 0) {
39325
- gitLabel = devGitStatusLabel(code);
39326
- } else if (isDir) {
39327
- const prefix = gitPath + "/";
39328
- for (const [gf, gc] of gitStatus) {
39329
- if (gf.startsWith(prefix)) {
39330
- gitLabel = gc === "??" ? "untracked" : "modified";
39331
- break;
39332
- }
39333
- }
39334
- }
39335
- let hasChildren = null;
39336
- if (isDir) {
39337
- hasChildren = false;
39338
- try {
39339
- for (const c of readdirSync16(full)) {
39340
- if (devFilesHidden(c)) continue;
39341
- hasChildren = true;
39342
- break;
39343
- }
39344
- } catch {
39345
- }
39346
- }
39347
- entries.push({
39348
- name,
39349
- path: entryRel,
39350
- is_dir: isDir,
39351
- has_children: hasChildren,
39352
- git_status: gitLabel,
39353
- size
39354
- });
39933
+ entries.push(buildFileEntry(name, full, entryRel, cwdInGit, gitStatus));
39355
39934
  }
39356
39935
  res.json({ path: relative9(root, target).replace(/\\/g, "/") || ".", branch, entries });
39357
39936
  };
@@ -40380,7 +40959,10 @@ function generate2(routes, models = []) {
40380
40959
  openapi: resolveOpenApiVersion(),
40381
40960
  info: buildInfo(),
40382
40961
  servers: resolveServers(),
40383
- paths: {},
40962
+ // Prototype-less: route paths are developer-defined, but a null prototype
40963
+ // makes `spec.paths[path][method] = op` structurally pollution-proof
40964
+ // regardless (js/prototype-polluting-assignment). Serialises to JSON the same.
40965
+ paths: /* @__PURE__ */ Object.create(null),
40384
40966
  components: {
40385
40967
  schemas: {},
40386
40968
  // Configurable security schemes (v3.13.42): bearerFormat via env, optional
@@ -40445,7 +41027,7 @@ function buildOperation(route, spec, ctx) {
40445
41027
  const openApiPath = patternToOpenAPI(route.pattern);
40446
41028
  const method = route.method.toLowerCase();
40447
41029
  if (!spec.paths[openApiPath]) {
40448
- spec.paths[openApiPath] = {};
41030
+ spec.paths[openApiPath] = /* @__PURE__ */ Object.create(null);
40449
41031
  }
40450
41032
  const tags = route.meta?.tags ?? inferTags(route.pattern);
40451
41033
  for (const t of tags) {
@@ -40751,7 +41333,7 @@ function inferModelFromPath(pattern) {
40751
41333
  return null;
40752
41334
  }
40753
41335
  function operationIdBase(method, openApiPath) {
40754
- const clean = openApiPath.replace(/^\/+|\/+$/g, "").replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
41336
+ const clean = trimSlashes(openApiPath).replace(/\//g, "_").replace(/\.\.\./g, "").replace(/[{}]/g, "").replace(/\*/g, "wildcard");
40755
41337
  return clean ? `${method}_${clean}` : method;
40756
41338
  }
40757
41339
  function uniqueOperationId(method, openApiPath, seen) {
@@ -40769,6 +41351,7 @@ var WRITE_METHODS, INTERNAL_PREFIXES, registeredSchemes, registeredSchemas, PARA
40769
41351
  var init_generator = __esm({
40770
41352
  "../swagger/src/generator.ts"() {
40771
41353
  "use strict";
41354
+ init_slashTrim();
40772
41355
  WRITE_METHODS = /* @__PURE__ */ new Set(["post", "put", "patch", "delete"]);
40773
41356
  INTERNAL_PREFIXES = ["/swagger", "/__dev", "/__feedback", "/ai", "/rag", "/vision", "/embed", "/image"];
40774
41357
  registeredSchemes = {};
@@ -40790,7 +41373,7 @@ var init_generator = __esm({
40790
41373
 
40791
41374
  // ../swagger/src/ui.ts
40792
41375
  function swaggerUiCdn() {
40793
- return (process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5").replace(/\/+$/, "");
41376
+ return rtrimSlashes(process.env.TINA4_SWAGGER_UI_CDN ?? "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5");
40794
41377
  }
40795
41378
  function swaggerEnabled() {
40796
41379
  const raw = (process.env.TINA4_SWAGGER_ENABLED ?? "").trim().toLowerCase();
@@ -40846,6 +41429,7 @@ var SWAGGER_UI_HTML;
40846
41429
  var init_ui = __esm({
40847
41430
  "../swagger/src/ui.ts"() {
40848
41431
  "use strict";
41432
+ init_slashTrim();
40849
41433
  SWAGGER_UI_HTML = (specUrl, nonce) => `<!DOCTYPE html>
40850
41434
  <html lang="en">
40851
41435
  <head>
@@ -40900,7 +41484,7 @@ __export(sso_exports, {
40900
41484
  SsoError: () => SsoError,
40901
41485
  liveSessionIdentity: () => liveSessionIdentity
40902
41486
  });
40903
- import { createHash as createHash10, randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
41487
+ import { createHash as createHash11, randomBytes as randomBytes8, timingSafeEqual as timingSafeEqual3 } from "node:crypto";
40904
41488
  function expiresAt(tokens) {
40905
41489
  const lifetime = Number(tokens.expires_in ?? 0);
40906
41490
  return lifetime > 0 ? Math.floor(Date.now() / 1e3) + lifetime : 0;
@@ -41031,7 +41615,7 @@ var init_sso = __esm({
41031
41615
  const state = randomBytes8(32).toString("base64url");
41032
41616
  const nonce = randomBytes8(32).toString("base64url");
41033
41617
  const verifier = randomBytes8(64).toString("base64url");
41034
- const challenge = createHash10("sha256").update(verifier).digest("base64url");
41618
+ const challenge = createHash11("sha256").update(verifier).digest("base64url");
41035
41619
  session.set(_Sso.PENDING_KEY, { state, nonce, verifier, return_to: _Sso.safeReturn(returnTo), created_at: Math.floor(Date.now() / 1e3) });
41036
41620
  const metadata = await this.discover();
41037
41621
  const query = new URLSearchParams({
@@ -41263,7 +41847,7 @@ import { resolve as resolve19, dirname as dirname15, join as join30, relative as
41263
41847
  import { existsSync as existsSync26, readdirSync as readdirSync18, readFileSync as readFileSync23, statSync as statSync18 } from "node:fs";
41264
41848
  import { isatty } from "node:tty";
41265
41849
  import { fileURLToPath as fileURLToPath8 } from "node:url";
41266
- import { execFileSync as execFileSync3, exec } from "node:child_process";
41850
+ import { execFileSync as execFileSync3, execFile } from "node:child_process";
41267
41851
  import cluster from "node:cluster";
41268
41852
  import os2 from "node:os";
41269
41853
  function isSwaggerAssetPath(pathname) {
@@ -41399,10 +41983,11 @@ function shouldOpenBrowser(isDevelopment, noBrowser = false) {
41399
41983
  });
41400
41984
  }
41401
41985
  function openBrowser(url) {
41986
+ if (!/^https?:\/\/([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\])(:\d{1,5})?\/?$/.test(url)) return;
41402
41987
  setTimeout(() => {
41403
- if (process.platform === "darwin") exec(`open ${url}`);
41404
- else if (process.platform === "win32") exec(`start "" "${url}"`);
41405
- else exec(`xdg-open ${url}`);
41988
+ if (process.platform === "darwin") execFile("open", [url]);
41989
+ else if (process.platform === "win32") execFile("rundll32", ["url.dll,FileProtocolHandler", url]);
41990
+ else execFile("xdg-open", [url]);
41406
41991
  }, 2e3);
41407
41992
  }
41408
41993
  function resolvePortAndHost(config) {
@@ -41517,7 +42102,7 @@ function resetTemplateCache() {
41517
42102
  }
41518
42103
  function resolveTemplate(pathname, templatesDir) {
41519
42104
  if (!templateAutoRoutingEnabled()) return null;
41520
- const cleanPath = pathname.replace(/^\/+/, "").replace(/\/+$/, "") || "index";
42105
+ const cleanPath = trimSlashes(pathname) || "index";
41521
42106
  const isDev2 = (process.env.TINA4_DEBUG ?? "false").toLowerCase() === "true";
41522
42107
  if (isDev2) {
41523
42108
  if (cleanPath.split("/").some((seg) => seg.startsWith("_"))) return null;
@@ -41785,7 +42370,7 @@ async function runGlobalMiddlewarePass(middleware, req2, res) {
41785
42370
  }
41786
42371
  function resolveHandlerArgs(handler, req2, res, routeParams) {
41787
42372
  const fnStr = handler.toString();
41788
- const argMatch = fnStr.match(/^(?:async\s*)?(?:function\s*\w*)?\s*\(([^)]*)\)/);
42373
+ const argMatch = fnStr.match(/^(?:async\s*)?(?:function(?:\s+\w+)?\s*)?\(([^)]*)\)/);
41789
42374
  const argNames = argMatch?.[1]?.split(",").map((a) => a.trim().replace(/[:=].*/, "")) ?? [];
41790
42375
  const filteredArgs = argNames.filter((n) => n.length > 0);
41791
42376
  if (filteredArgs.length === 0) return [];
@@ -41814,7 +42399,7 @@ async function runMatchedRoute(ctx) {
41814
42399
  const { req: req2, res, match, postMatchMiddleware } = ctx;
41815
42400
  req2.params = match.params;
41816
42401
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
41817
- if (enforceRouteAuth(req2, res, match, ctx.pathname.startsWith("/__dev"))) return;
42402
+ if (enforceRouteAuth(req2, res, match)) return;
41818
42403
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
41819
42404
  let handlerSkipped = false;
41820
42405
  if (match.middlewares && match.middlewares.length > 0) {
@@ -42021,8 +42606,9 @@ async function buildDispatchContext(router, base) {
42021
42606
  const templatesDir = resolve19(root, "src/templates");
42022
42607
  let frondEngine = null;
42023
42608
  try {
42024
- const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
42609
+ const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2, setFormTokenSessionProvider: setFormTokenSessionProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
42025
42610
  setCspNonceProvider2(currentCspNonce);
42611
+ setFormTokenSessionProvider2(currentFormTokenSessionId);
42026
42612
  frondEngine = new Frond2(templatesDir);
42027
42613
  } catch {
42028
42614
  }
@@ -42137,7 +42723,10 @@ async function runDispatch(ctx, rawReq, rawRes) {
42137
42723
  const requestNonce = generateNonce();
42138
42724
  return Log.runWithRequestId(
42139
42725
  requestId,
42140
- () => runWithCspNonce(requestNonce, () => dispatchInner(ctx, rawReq, rawRes, requestId))
42726
+ () => runWithCspNonce(
42727
+ requestNonce,
42728
+ () => runWithFormTokenSession(() => dispatchInner(ctx, rawReq, rawRes, requestId))
42729
+ )
42141
42730
  );
42142
42731
  }
42143
42732
  function loopbackBindHosts(host) {
@@ -42265,8 +42854,9 @@ async function startServer(config) {
42265
42854
  let frondEngine = null;
42266
42855
  setDefaultTemplatesDir(templatesDir);
42267
42856
  try {
42268
- const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
42857
+ const { Frond: Frond2, setCspNonceProvider: setCspNonceProvider2, setFormTokenSessionProvider: setFormTokenSessionProvider2 } = await Promise.resolve().then(() => (init_engine(), engine_exports));
42269
42858
  setCspNonceProvider2(currentCspNonce);
42859
+ setFormTokenSessionProvider2(currentFormTokenSessionId);
42270
42860
  frondEngine = new Frond2(templatesDir);
42271
42861
  router.addRoute({
42272
42862
  method: "GET",
@@ -42615,6 +43205,7 @@ var __filename, __dirname, BUILTIN_ERROR_TEMPLATES_DIR, BUILTIN_PUBLIC_DIR, swag
42615
43205
  var init_server = __esm({
42616
43206
  "src/server.ts"() {
42617
43207
  "use strict";
43208
+ init_slashTrim();
42618
43209
  init_transport();
42619
43210
  init_router();
42620
43211
  init_authGate();
@@ -42622,6 +43213,7 @@ var init_server = __esm({
42622
43213
  init_portTakeover();
42623
43214
  init_request();
42624
43215
  init_dispatchPipeline();
43216
+ init_session();
42625
43217
  init_response();
42626
43218
  init_middleware();
42627
43219
  init_static();
@@ -44237,6 +44829,7 @@ var ApiStreamError, RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON
44237
44829
  var init_api = __esm({
44238
44830
  "src/api.ts"() {
44239
44831
  "use strict";
44832
+ init_slashTrim();
44240
44833
  init_version();
44241
44834
  init_ssrf();
44242
44835
  ApiStreamError = class extends Error {
@@ -44334,7 +44927,7 @@ var init_api = __esm({
44334
44927
  * turns on a per-client, in-memory cookie jar.
44335
44928
  */
44336
44929
  constructor(baseUrl = "", authHeaderOrOptions = "", timeout = 30) {
44337
- this.baseUrl = baseUrl.replace(/\/+$/, "");
44930
+ this.baseUrl = rtrimSlashes(baseUrl);
44338
44931
  this.headers = {};
44339
44932
  this.maxRetries = 0;
44340
44933
  this.retryBackoff = 0.5;
@@ -45100,6 +45693,23 @@ function sendCommand(socket, command) {
45100
45693
  });
45101
45694
  });
45102
45695
  }
45696
+ function pushAlternativeBody(lines, altBoundary, text, body) {
45697
+ lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
45698
+ lines.push("");
45699
+ lines.push(`--${altBoundary}`);
45700
+ lines.push("Content-Type: text/plain; charset=UTF-8");
45701
+ lines.push("Content-Transfer-Encoding: 7bit");
45702
+ lines.push("");
45703
+ lines.push(text);
45704
+ lines.push("");
45705
+ lines.push(`--${altBoundary}`);
45706
+ lines.push("Content-Type: text/html; charset=UTF-8");
45707
+ lines.push("Content-Transfer-Encoding: 7bit");
45708
+ lines.push("");
45709
+ lines.push(body);
45710
+ lines.push("");
45711
+ lines.push(`--${altBoundary}--`);
45712
+ }
45103
45713
  function buildMimeMessage(options) {
45104
45714
  const boundary = `----=_Tina4_${Date.now()}_${Math.random().toString(36).substring(2)}`;
45105
45715
  const altBoundary = `----=_Tina4Alt_${Date.now()}_${Math.random().toString(36).substring(2)}`;
@@ -45129,21 +45739,7 @@ function buildMimeMessage(options) {
45129
45739
  lines.push("");
45130
45740
  lines.push(`--${boundary}`);
45131
45741
  if (hasTextAlt) {
45132
- lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
45133
- lines.push("");
45134
- lines.push(`--${altBoundary}`);
45135
- lines.push("Content-Type: text/plain; charset=UTF-8");
45136
- lines.push("Content-Transfer-Encoding: 7bit");
45137
- lines.push("");
45138
- lines.push(options.text);
45139
- lines.push("");
45140
- lines.push(`--${altBoundary}`);
45141
- lines.push("Content-Type: text/html; charset=UTF-8");
45142
- lines.push("Content-Transfer-Encoding: 7bit");
45143
- lines.push("");
45144
- lines.push(options.body);
45145
- lines.push("");
45146
- lines.push(`--${altBoundary}--`);
45742
+ pushAlternativeBody(lines, altBoundary, options.text, options.body);
45147
45743
  } else {
45148
45744
  const contentType = options.html ? "text/html" : "text/plain";
45149
45745
  lines.push(`Content-Type: ${contentType}; charset=UTF-8`);
@@ -45168,21 +45764,7 @@ function buildMimeMessage(options) {
45168
45764
  lines.push("");
45169
45765
  lines.push(`--${boundary}--`);
45170
45766
  } else if (hasTextAlt) {
45171
- lines.push(`Content-Type: multipart/alternative; boundary="${altBoundary}"`);
45172
- lines.push("");
45173
- lines.push(`--${altBoundary}`);
45174
- lines.push("Content-Type: text/plain; charset=UTF-8");
45175
- lines.push("Content-Transfer-Encoding: 7bit");
45176
- lines.push("");
45177
- lines.push(options.text);
45178
- lines.push("");
45179
- lines.push(`--${altBoundary}`);
45180
- lines.push("Content-Type: text/html; charset=UTF-8");
45181
- lines.push("Content-Transfer-Encoding: 7bit");
45182
- lines.push("");
45183
- lines.push(options.body);
45184
- lines.push("");
45185
- lines.push(`--${altBoundary}--`);
45767
+ pushAlternativeBody(lines, altBoundary, options.text, options.body);
45186
45768
  } else {
45187
45769
  const contentType = options.html ? "text/html" : "text/plain";
45188
45770
  lines.push(`Content-Type: ${contentType}; charset=UTF-8`);
@@ -45947,61 +46529,72 @@ function decodeEntities(raw) {
45947
46529
  function parseXmlDocument(xml) {
45948
46530
  const stack = [];
45949
46531
  let root = null;
45950
- let position = 0;
45951
46532
  const addText = (text) => {
45952
46533
  const current = stack[stack.length - 1];
45953
46534
  if (current.children.length === 0) current.text += text;
45954
46535
  };
45955
- while (position < xml.length) {
45956
- const nextTag = xml.indexOf("<", position);
46536
+ const skipComment = (at) => {
46537
+ const close = xml.indexOf("-->", at + 4);
46538
+ if (close === -1) malformed();
46539
+ return close + 3;
46540
+ };
46541
+ const readCData = (at) => {
46542
+ const close = xml.indexOf("]]>", at + 9);
46543
+ if (close === -1 || stack.length === 0) malformed();
46544
+ addText(xml.slice(at + 9, close));
46545
+ return close + 3;
46546
+ };
46547
+ const skipProcessingInstruction = (at) => {
46548
+ const close = xml.indexOf("?>", at + 2);
46549
+ if (close === -1) malformed();
46550
+ const target = xml.slice(at + 2, close).split(/\s/, 1)[0];
46551
+ if (target.toLowerCase() === "xml" && at !== 0) malformed();
46552
+ return close + 2;
46553
+ };
46554
+ const closeElement = (at) => {
46555
+ END_TAG.lastIndex = at;
46556
+ const match = END_TAG.exec(xml);
46557
+ const open = stack.pop();
46558
+ if (!match || !open || open.qualifiedName !== match[1]) malformed();
46559
+ return END_TAG.lastIndex;
46560
+ };
46561
+ const openElement = (at) => {
46562
+ START_TAG.lastIndex = at;
46563
+ const match = START_TAG.exec(xml);
46564
+ if (!match || stack.length === 0 && root !== null) malformed();
46565
+ for (const attribute of match[2].matchAll(ATTRIBUTE_VALUE)) decodeEntities(attribute[1] ?? attribute[2]);
46566
+ const qualifiedName = match[1];
46567
+ const element = {
46568
+ name: qualifiedName.slice(qualifiedName.indexOf(":") + 1),
46569
+ qualifiedName,
46570
+ children: [],
46571
+ text: ""
46572
+ };
46573
+ if (stack.length > 0) stack[stack.length - 1].children.push(element);
46574
+ else root = element;
46575
+ if (match[3] !== "/") stack.push(element);
46576
+ return START_TAG.lastIndex;
46577
+ };
46578
+ const readText = (at) => {
46579
+ const nextTag = xml.indexOf("<", at);
45957
46580
  const textEnd = nextTag === -1 ? xml.length : nextTag;
45958
- if (textEnd > position) {
45959
- const raw = xml.slice(position, textEnd);
46581
+ if (textEnd > at) {
46582
+ const raw = xml.slice(at, textEnd);
45960
46583
  if (stack.length > 0) addText(decodeEntities(raw));
45961
46584
  else if (raw.trim() !== "") malformed();
45962
- position = textEnd;
45963
- if (nextTag === -1) break;
45964
- }
45965
- if (xml.startsWith("<!--", position)) {
45966
- const close = xml.indexOf("-->", position + 4);
45967
- if (close === -1) malformed();
45968
- position = close + 3;
45969
- } else if (xml.startsWith("<![CDATA[", position)) {
45970
- const close = xml.indexOf("]]>", position + 9);
45971
- if (close === -1 || stack.length === 0) malformed();
45972
- addText(xml.slice(position + 9, close));
45973
- position = close + 3;
45974
- } else if (xml.startsWith("<?", position)) {
45975
- const close = xml.indexOf("?>", position + 2);
45976
- if (close === -1) malformed();
45977
- const target = xml.slice(position + 2, close).split(/\s/, 1)[0];
45978
- if (target.toLowerCase() === "xml" && position !== 0) malformed();
45979
- position = close + 2;
45980
- } else if (xml.startsWith("<!", position)) {
45981
- malformed();
45982
- } else if (xml.startsWith("</", position)) {
45983
- END_TAG.lastIndex = position;
45984
- const match = END_TAG.exec(xml);
45985
- const open = stack.pop();
45986
- if (!match || !open || open.qualifiedName !== match[1]) malformed();
45987
- position = END_TAG.lastIndex;
45988
- } else {
45989
- START_TAG.lastIndex = position;
45990
- const match = START_TAG.exec(xml);
45991
- if (!match || stack.length === 0 && root !== null) malformed();
45992
- for (const attribute of match[2].matchAll(ATTRIBUTE_VALUE)) decodeEntities(attribute[1] ?? attribute[2]);
45993
- const qualifiedName = match[1];
45994
- const element = {
45995
- name: qualifiedName.slice(qualifiedName.indexOf(":") + 1),
45996
- qualifiedName,
45997
- children: [],
45998
- text: ""
45999
- };
46000
- if (stack.length > 0) stack[stack.length - 1].children.push(element);
46001
- else root = element;
46002
- if (match[3] !== "/") stack.push(element);
46003
- position = START_TAG.lastIndex;
46004
46585
  }
46586
+ return textEnd;
46587
+ };
46588
+ let position = 0;
46589
+ while (position < xml.length) {
46590
+ position = readText(position);
46591
+ if (position >= xml.length) break;
46592
+ if (xml.startsWith("<!--", position)) position = skipComment(position);
46593
+ else if (xml.startsWith("<![CDATA[", position)) position = readCData(position);
46594
+ else if (xml.startsWith("<?", position)) position = skipProcessingInstruction(position);
46595
+ else if (xml.startsWith("<!", position)) malformed();
46596
+ else if (xml.startsWith("</", position)) position = closeElement(position);
46597
+ else position = openElement(position);
46005
46598
  }
46006
46599
  if (root === null || stack.length > 0) malformed();
46007
46600
  return root;
@@ -47485,13 +48078,13 @@ export default class User {
47485
48078
  import {
47486
48079
  createCipheriv,
47487
48080
  createECDH,
47488
- createHmac as createHmac4,
48081
+ createHmac as createHmac5,
47489
48082
  createPrivateKey,
47490
48083
  createSign as createSign2,
47491
48084
  randomBytes as randomBytes12
47492
48085
  } from "node:crypto";
47493
48086
  function encodeBase64Url(value) {
47494
- return Buffer.from(value).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
48087
+ return Buffer.from(value).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/={1,2}$/, "");
47495
48088
  }
47496
48089
  function decodeBase64Url(value, name) {
47497
48090
  if (typeof value !== "string" || value.length === 0) {
@@ -47521,15 +48114,15 @@ function vapidPrivateKey(rawPrivate, rawPublic) {
47521
48114
  format: "jwk"
47522
48115
  });
47523
48116
  }
47524
- function hmac(salt, value) {
47525
- return createHmac4("sha256", salt).update(value).digest();
48117
+ function hmac2(salt, value) {
48118
+ return createHmac5("sha256", salt).update(value).digest();
47526
48119
  }
47527
48120
  function hkdfExpand(prk, info, length) {
47528
48121
  const chunks = [];
47529
48122
  let previous = Buffer.alloc(0);
47530
48123
  for (let counter = 1; Buffer.concat(chunks).length < length; counter++) {
47531
48124
  if (counter > 255) throw new PushError("HKDF output is too large");
47532
- previous = hmac(prk, Buffer.concat([previous, info, Buffer.from([counter])]));
48125
+ previous = hmac2(prk, Buffer.concat([previous, info, Buffer.from([counter])]));
47533
48126
  chunks.push(previous);
47534
48127
  }
47535
48128
  return Buffer.concat(chunks).subarray(0, length);
@@ -47566,10 +48159,10 @@ function encryptPayload(payload, subscription) {
47566
48159
  clientPublic,
47567
48160
  serverPublic
47568
48161
  ]);
47569
- const prkKey = hmac(authSecret, sharedSecret);
48162
+ const prkKey = hmac2(authSecret, sharedSecret);
47570
48163
  const ikm = hkdfExpand(prkKey, keyInfo, 32);
47571
48164
  const salt = randomBytes12(16);
47572
- const contentPrk = hmac(salt, ikm);
48165
+ const contentPrk = hmac2(salt, ikm);
47573
48166
  const cek = hkdfExpand(contentPrk, Buffer.from("Content-Encoding: aes128gcm\0", "ascii"), 16);
47574
48167
  const nonce = hkdfExpand(contentPrk, Buffer.from("Content-Encoding: nonce\0", "ascii"), 12);
47575
48168
  const cipher = createCipheriv("aes-128-gcm", cek, nonce);
@@ -47742,6 +48335,7 @@ var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai, Aggre
47742
48335
  var init_aiClient = __esm({
47743
48336
  "src/aiClient.ts"() {
47744
48337
  "use strict";
48338
+ init_slashTrim();
47745
48339
  init_api();
47746
48340
  AiError = class extends Error {
47747
48341
  };
@@ -47946,7 +48540,7 @@ var init_aiClient = __esm({
47946
48540
  throw new AiConfigError("AI URL must be an http or https URL");
47947
48541
  }
47948
48542
  if (url.protocol !== "http:" && url.protocol !== "https:") throw new AiConfigError("AI URL must be an http or https URL");
47949
- const path10 = url.pathname.replace(/\/+$/, "");
48543
+ const path10 = rtrimSlashes(url.pathname);
47950
48544
  if (path10 === "" || path10 === "/v1" || path10 === "/api" || path10 === "/v1beta/openai") {
47951
48545
  const suffix = provider === "anthropic" ? "/messages" : capability === "embed" ? "/embeddings" : "/chat/completions";
47952
48546
  url.pathname = (path10 || "/v1") + suffix;
@@ -50316,6 +50910,7 @@ __export(index_exports, {
50316
50910
  backgroundTaskCount: () => backgroundTaskCount,
50317
50911
  buildEnvelope: () => buildEnvelope,
50318
50912
  buildFrame: () => buildFrame,
50913
+ buildSeedFieldMap: () => buildSeedFieldMap,
50319
50914
  buildSessionCookie: () => buildSessionCookie,
50320
50915
  cacheBackendStats: () => cacheBackendStats,
50321
50916
  cacheClear: () => cacheClear,
@@ -50421,6 +51016,7 @@ __export(index_exports, {
50421
51016
  parseFrame: () => parseFrame,
50422
51017
  parseLineStream: () => parseLineStream,
50423
51018
  parseMultipart: () => parseMultipart,
51019
+ parseSeedRequest: () => parseSeedRequest,
50424
51020
  parseSseStream: () => parseSseStream,
50425
51021
  parseUpgradeHeaders: () => parseUpgradeHeaders,
50426
51022
  patch: () => patch,
@@ -50705,6 +51301,7 @@ export {
50705
51301
  backgroundTaskCount,
50706
51302
  buildEnvelope,
50707
51303
  buildFrame,
51304
+ buildSeedFieldMap,
50708
51305
  buildSessionCookie,
50709
51306
  cacheBackendStats,
50710
51307
  cacheClear,
@@ -50810,6 +51407,7 @@ export {
50810
51407
  parseFrame,
50811
51408
  parseLineStream,
50812
51409
  parseMultipart,
51410
+ parseSeedRequest,
50813
51411
  parseSseStream,
50814
51412
  parseUpgradeHeaders,
50815
51413
  patch,