tina4-nodejs 3.13.158 → 3.13.160

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.
@@ -39,7 +39,7 @@ import {
39
39
  sessionAutoStart,
40
40
  } from "./dispatchPipeline.js";
41
41
  import { runWithFormTokenSession, currentFormTokenSessionId } from "./session.js";
42
- import { createResponse, setDefaultTemplatesDir, wantsJson, negotiatedErrorBody } from "./response.js";
42
+ import { createResponse, setDefaultTemplatesDir, wantsJson, negotiatedErrorBody, renderNegotiatedError } from "./response.js";
43
43
  import { MiddlewareChain, MiddlewareRunner, cors, requestLogger, isMiddlewareClass, attachCsrfFromEnv, SecurityHeadersMiddleware } from "./middleware.js";
44
44
  import { tryServeStatic } from "./static.js";
45
45
  import { loadEnv, isTruthy } from "./dotenv.js";
@@ -1130,6 +1130,25 @@ async function invokeRouteHandler(
1130
1130
  * other shape - a handler that already wrote, no template, null/undefined, a
1131
1131
  * string, a Buffer - is left exactly as it was.
1132
1132
  */
1133
+ /**
1134
+ * Coerce a handler's RETURN value into a response (#289).
1135
+ *
1136
+ * Node's idiom is `res.json()` / `res.send()`, but a handler that `return`s a
1137
+ * dict / array / string without writing used to answer an empty 200 with no
1138
+ * error and no log line — the value was dropped. This mirrors the Python, PHP
1139
+ * and Ruby masters, which coerce a bare return: a non-null, non-undefined
1140
+ * return is run through the auto-detecting `response()` callable (`res` itself),
1141
+ * so `return { open: 3 }` serialises to JSON. It is skipped when the handler
1142
+ * already sent (a template render, `res.json()`, a stream) or returned nothing,
1143
+ * so an explicit `res.json(...)` is never double-sent.
1144
+ */
1145
+ function coerceHandlerResult(res: Tina4Response, result: unknown): void {
1146
+ if (res.raw.writableEnded || res.raw.headersSent) return;
1147
+ if (result === undefined || result === null) return;
1148
+ if (result === (res as unknown)) return; // handler returned the response itself
1149
+ (res as unknown as (data: unknown) => void)(result);
1150
+ }
1151
+
1133
1152
  async function renderIfTemplateRoute(
1134
1153
  match: { template?: string },
1135
1154
  res: Tina4Response,
@@ -1186,7 +1205,13 @@ async function runMatchedRoute(ctx: MatchedRouteContext): Promise<void> {
1186
1205
  // The dev dashboard's own routes are public because DevAdmin registers them
1187
1206
  // noAuth, not because of their path: a "/__dev" prefix test also opened any
1188
1207
  // write route of the application's own named /__developer or /__dev/anything.
1189
- if (enforceRouteAuth(req, res, match as never)) return;
1208
+ // The gate decides; server.ts renders the rejection so the auth path stays
1209
+ // free of the template engine (ERR-DEC-02, #342).
1210
+ const authReject = enforceRouteAuth(req, res, match as never);
1211
+ if (authReject) {
1212
+ await renderNegotiatedError(req, res, authReject.status, authReject.message);
1213
+ return;
1214
+ }
1190
1215
 
1191
1216
  // The route's OWN class middleware: its beforeX hooks run inside
1192
1217
  // runRouteMiddlewares, its afterX hooks join the after pass below - one
@@ -1201,7 +1226,9 @@ async function runMatchedRoute(ctx: MatchedRouteContext): Promise<void> {
1201
1226
  }
1202
1227
 
1203
1228
  if (!handlerSkipped) {
1204
- await renderIfTemplateRoute(match, res, await invokeRouteHandler(match, req, res));
1229
+ const result = await invokeRouteHandler(match, req, res);
1230
+ await renderIfTemplateRoute(match, res, result);
1231
+ coerceHandlerResult(res, result);
1205
1232
  }
1206
1233
 
1207
1234
  // Global afterX hooks (logging / post-processing), over EVERY global
@@ -9074,6 +9074,41 @@ function negotiatedErrorBody(code, message, requestId) {
9074
9074
  body.request_id = requestId;
9075
9075
  return body;
9076
9076
  }
9077
+ async function renderNegotiatedError(req2, res, code, message) {
9078
+ const { Log: Log2 } = await Promise.resolve().then(() => (init_logger(), logger_exports));
9079
+ const requestId = Log2.getRequestId() ?? "";
9080
+ const writeJson = () => {
9081
+ const body = negotiatedErrorBody(code, message, requestId);
9082
+ res.raw.statusCode = code;
9083
+ res.raw.setHeader("Content-Type", "application/json");
9084
+ res.raw.end(JSON.stringify(body));
9085
+ };
9086
+ if (wantsJson(req2)) {
9087
+ writeJson();
9088
+ return;
9089
+ }
9090
+ const data = { path: req2?.path ?? "", error_message: "", request_id: requestId, status_code: code };
9091
+ const template = `errors/${code}.twig`;
9092
+ let html = null;
9093
+ try {
9094
+ html = (await getFrond()).render(template, data);
9095
+ } catch {
9096
+ }
9097
+ if (!html) {
9098
+ try {
9099
+ const fw = await getFrameworkFrond();
9100
+ html = fw ? fw.render(template, data) : null;
9101
+ } catch {
9102
+ html = null;
9103
+ }
9104
+ }
9105
+ if (html) {
9106
+ res.raw.writeHead(code, { "Content-Type": "text/html; charset=utf-8" });
9107
+ res.raw.end(html);
9108
+ return;
9109
+ }
9110
+ writeJson();
9111
+ }
9077
9112
  var HEADER_TOKEN, _frondCache, _defaultTemplatesDir, _globalFrond, _frameworkFrond, ERROR_CODE_NAMES;
9078
9113
  var init_response = __esm({
9079
9114
  "../core/src/response.ts"() {
@@ -9085,6 +9120,7 @@ var init_response = __esm({
9085
9120
  _globalFrond = null;
9086
9121
  _frameworkFrond = null;
9087
9122
  ERROR_CODE_NAMES = {
9123
+ 401: "UNAUTHORIZED",
9088
9124
  403: "FORBIDDEN",
9089
9125
  404: "NOT_FOUND",
9090
9126
  405: "METHOD_NOT_ALLOWED",
@@ -9153,7 +9189,7 @@ async function interpretHookResult(result, req2, res) {
9153
9189
  }
9154
9190
  return [req2, res, false];
9155
9191
  }
9156
- function middleware500(res, mwClass, methodName, error2) {
9192
+ async function middleware500(res, mwClass, methodName, error2, req2) {
9157
9193
  const clsName = mwClass?.name ?? mwClass?.constructor?.name ?? "Middleware";
9158
9194
  const err = error2;
9159
9195
  const type2 = err?.name ?? error2?.constructor?.name ?? "Error";
@@ -9162,6 +9198,10 @@ function middleware500(res, mwClass, methodName, error2) {
9162
9198
  Log.error(`Middleware ${clsName}.${methodName} raised ${type2}: ${message}`);
9163
9199
  } catch {
9164
9200
  }
9201
+ if (req2 && res?.raw && typeof res.raw.writeHead === "function" && !res.raw.writableEnded) {
9202
+ await renderNegotiatedError(req2, res, 500, "Internal Server Error");
9203
+ return res;
9204
+ }
9165
9205
  if (typeof res.json === "function") {
9166
9206
  res.json({ error: "Internal Server Error", status: 500 }, 500);
9167
9207
  } else if (typeof res === "function") {
@@ -9462,7 +9502,7 @@ var init_middleware = __esm({
9462
9502
  res = nextRes;
9463
9503
  if (stop2) return [req2, res, false];
9464
9504
  } catch (error2) {
9465
- res = middleware500(res, cls, method, error2);
9505
+ res = await middleware500(res, cls, method, error2, req2);
9466
9506
  return [req2, res, false];
9467
9507
  }
9468
9508
  if (res.raw.statusCode >= 400 || res.raw.writableEnded) {
@@ -9506,7 +9546,7 @@ var init_middleware = __esm({
9506
9546
  res = nextRes;
9507
9547
  if (stop2) return [req2, res];
9508
9548
  } catch (error2) {
9509
- res = middleware500(res, cls, method, error2);
9549
+ res = await middleware500(res, cls, method, error2, req2);
9510
9550
  continue;
9511
9551
  }
9512
9552
  }
@@ -10510,7 +10550,7 @@ var init_ssoIdentity = __esm({
10510
10550
  // ../core/src/authGate.ts
10511
10551
  function enforceRouteAuth(req2, res, match) {
10512
10552
  if (!(match.secure === true && match.noAuth !== true)) {
10513
- return false;
10553
+ return null;
10514
10554
  }
10515
10555
  const authHeader = req2.headers.authorization ?? "";
10516
10556
  const headerToken = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : "";
@@ -10540,7 +10580,7 @@ function enforceRouteAuth(req2, res, match) {
10540
10580
  const identity = liveSessionIdentity(req2.session?.get?.("_tina4_sso"));
10541
10581
  if (identity) {
10542
10582
  req2.user = identity;
10543
- return rbacForbidden(match, identity, res);
10583
+ return rbacForbidden(match, identity);
10544
10584
  }
10545
10585
  const sessionToken = req2.session?.get?.("token");
10546
10586
  if (sessionToken) {
@@ -10553,9 +10593,7 @@ function enforceRouteAuth(req2, res, match) {
10553
10593
  }
10554
10594
  }
10555
10595
  if (!payload) {
10556
- res.raw.writeHead(401, { "Content-Type": "application/json" });
10557
- res.raw.end(JSON.stringify({ error: "Unauthorized" }));
10558
- return true;
10596
+ return { status: 401, message: "Unauthorized" };
10559
10597
  }
10560
10598
  req2.user = payload;
10561
10599
  if (tokenSource === "body") {
@@ -10564,7 +10602,7 @@ function enforceRouteAuth(req2, res, match) {
10564
10602
  res.header("FreshToken", fresh);
10565
10603
  }
10566
10604
  }
10567
- return rbacForbidden(match, req2.user, res);
10605
+ return rbacForbidden(match, req2.user);
10568
10606
  }
10569
10607
  function rbacClaimList(subject, key, legacy) {
10570
10608
  const coerce = (v) => {
@@ -10581,27 +10619,23 @@ function rbacPermGranted(granted, required) {
10581
10619
  (g) => g === "*" || g === required || g.endsWith(".*") && required.startsWith(g.slice(0, -1))
10582
10620
  );
10583
10621
  }
10584
- function rbacForbidden(match, payload, res) {
10622
+ function rbacForbidden(match, payload) {
10585
10623
  const requiredRoles = match.requiredRoles ?? [];
10586
10624
  const requiredPerms = match.requiredPerms ?? [];
10587
10625
  if (requiredRoles.length === 0 && requiredPerms.length === 0) {
10588
- return false;
10626
+ return null;
10589
10627
  }
10590
10628
  const subject = payload && typeof payload === "object" ? payload : {};
10629
+ const forbidden = { status: 403, message: "Forbidden" };
10591
10630
  const roles = rbacClaimList(subject, "roles", "role");
10592
10631
  for (const group of requiredRoles) {
10593
- if (!group.some((r) => roles.includes(r))) return writeForbidden(res);
10632
+ if (!group.some((r) => roles.includes(r))) return forbidden;
10594
10633
  }
10595
10634
  const perms = rbacClaimList(subject, "permissions");
10596
10635
  for (const group of requiredPerms) {
10597
- if (!group.some((p) => rbacPermGranted(perms, p))) return writeForbidden(res);
10636
+ if (!group.some((p) => rbacPermGranted(perms, p))) return forbidden;
10598
10637
  }
10599
- return false;
10600
- }
10601
- function writeForbidden(res) {
10602
- res.raw.writeHead(403, { "Content-Type": "application/json" });
10603
- res.raw.end(JSON.stringify({ error: "Forbidden" }));
10604
- return true;
10638
+ return null;
10605
10639
  }
10606
10640
  var init_authGate = __esm({
10607
10641
  "../core/src/authGate.ts"() {
@@ -15075,6 +15109,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
15075
15109
  }
15076
15110
  const fields = fieldsOverride || parseFields(flags.fields || "");
15077
15111
  const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
15112
+ const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
15078
15113
  const fileName = `${ts}_${name}.sql`;
15079
15114
  const path10 = join15(dir, fileName);
15080
15115
  setResolutionField("migration_path", `migrations/${fileName}`);
@@ -15084,7 +15119,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
15084
15119
  }
15085
15120
  let upSql;
15086
15121
  let downSql;
15087
- if (isCreate) {
15122
+ if (isView) {
15123
+ upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
15124
+ -- tina4:edit lines. For example:
15125
+ -- CREATE VIEW ${table2} AS
15126
+ -- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
15127
+ downSql = `DROP VIEW IF EXISTS ${table2};`;
15128
+ } else if (isCreate) {
15088
15129
  const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
15089
15130
  for (const [fname, ftype] of fields) {
15090
15131
  const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
@@ -15110,9 +15151,6 @@ DROP TABLE IF EXISTS ${table2};`;
15110
15151
 
15111
15152
  -- UP
15112
15153
  ${upSql}
15113
-
15114
- -- DOWN
15115
- ${downSql}
15116
15154
  `;
15117
15155
  writeFileSafe(path10, content);
15118
15156
  const downPath = join15(dir, `${ts}_${name}.down.sql`);
@@ -15122,7 +15160,7 @@ ${downSql}
15122
15160
  ${downSql}
15123
15161
  `;
15124
15162
  writeFileSafe(downPath, downContent);
15125
- if (emitTest && isCreate) emitMigrationTest(name, table2);
15163
+ if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
15126
15164
  }
15127
15165
  function generateMiddleware(name, _flags) {
15128
15166
  const snake = toSnake(name);
@@ -15933,9 +15971,11 @@ function emitRouteStubTest(route) {
15933
15971
  * Routing test for ${route} \u2014 no mocks, real Router + route discovery.
15934
15972
  *
15935
15973
  * Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
15936
- * ${route}\` (no --model). The handlers are AI-FILL stubs that throw until you
15937
- * implement them, so this tests what IS live on generation: all five routes
15938
- * register on the REAL Router, and the list handler fails loud until filled.
15974
+ * ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
15975
+ * you implement them. This tests what is live on generation: all five routes
15976
+ * register on the REAL Router, and the list handler is wired and callable. It
15977
+ * stays GREEN whether the stub still throws OR you have filled it in \u2014
15978
+ * implementing the handler never turns this test red.
15939
15979
  * Run with: npx tsx tests/${route}.test.ts
15940
15980
  */
15941
15981
  import { dirname, resolve } from "node:path";
@@ -15952,9 +15992,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
15952
15992
  assert(\`route registered: \${sig}\`, sigs.includes(sig));
15953
15993
  }
15954
15994
 
15955
- // The scaffolded list handler is a loud AI-FILL stub \u2014 it throws until filled.
15956
- await assertThrows("list handler is a live stub (throws until filled)",
15957
- () => listHandler({} as never, {} as never));`;
15995
+ // The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
15996
+ // stays green whether it still throws OR you have filled it in, so doing the
15997
+ // work never turns the suite red.
15998
+ assert("list handler is callable", typeof listHandler === "function");
15999
+ try {
16000
+ await listHandler({} as never, {} as never);
16001
+ } catch {
16002
+ // still the scaffold stub (throws until filled) \u2014 expected
16003
+ }`;
15958
16004
  writeTest(route, standaloneTest(doc, body));
15959
16005
  }
15960
16006
  function emitMiddlewareTest(name, snake) {
@@ -16038,8 +16084,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
16038
16084
  assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
16039
16085
  ServiceRunner.remove("${snake}");
16040
16086
 
16041
- // The scaffolded task body is an AI-FILL stub \u2014 it throws until filled.
16042
- await assertThrows("task is a live stub (throws until filled)", () => ${camel}Task({} as never));`;
16087
+ // The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
16088
+ // green whether it still throws OR you have filled it in.
16089
+ assert("task is callable", typeof ${camel}Task === "function");
16090
+ try {
16091
+ await ${camel}Task({} as never);
16092
+ } catch {
16093
+ // still the scaffold stub (throws until filled) \u2014 expected
16094
+ }`;
16043
16095
  writeTest(snake, standaloneTest(doc, body));
16044
16096
  }
16045
16097
  function emitQueueTest(topic, slug, pascal) {
@@ -16061,8 +16113,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
16061
16113
  assert("consumer default export is a daemon", worker.daemon === true);
16062
16114
  assert("consumer handler is wired", typeof worker.handler === "function");
16063
16115
 
16064
- // The per-job handler is an AI-FILL stub \u2014 it throws until filled.
16065
- await assertThrows("handle is a live stub (throws until filled)", () => handle${pascal}({}));`;
16116
+ // The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
16117
+ // This stays green whether it still throws OR you have filled it in.
16118
+ assert("handle is callable", typeof handle${pascal} === "function");
16119
+ try {
16120
+ await handle${pascal}({});
16121
+ } catch {
16122
+ // still the scaffold stub (throws until filled) \u2014 expected
16123
+ }`;
16066
16124
  writeTest(slug, standaloneTest(doc, body));
16067
16125
  }
16068
16126
  function emitValidatorTest(name, snake, pascal) {
@@ -16124,9 +16182,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
16124
16182
  const closed = await ${handler}(null as never, "close", "");
16125
16183
  assert("close event handled cleanly", closed === undefined);
16126
16184
 
16127
- // The "message" branch is an AI-FILL stub \u2014 it throws until filled.
16128
- await assertThrows("message branch is a live stub (throws until filled)",
16129
- () => ${handler}(null as never, "message", "hi"));`;
16185
+ // The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
16186
+ // This stays green whether it still throws OR you have filled it in.
16187
+ try {
16188
+ await ${handler}(null as never, "message", "hi");
16189
+ assert("message branch is callable", true);
16190
+ } catch {
16191
+ assert("message branch is callable", true); // still the scaffold stub
16192
+ }`;
16130
16193
  writeTest(`ws_${base}`, standaloneTest(doc, body));
16131
16194
  }
16132
16195
  function emitListenerTest(event, slug) {
@@ -16143,9 +16206,15 @@ import { Events } from "tina4-nodejs";
16143
16206
  import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
16144
16207
  const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
16145
16208
 
16146
- // strict emit re-raises the stub error, proving the listener actually ran.
16147
- await assertThrows("emitting the event reaches the (stub) listener",
16148
- () => Events.emit("${event}", { strict: true }, { id: 1 }));`;
16209
+ // Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
16210
+ // re-raises); once you implement it this test STILL passes, so doing the work
16211
+ // never turns the suite red.
16212
+ try {
16213
+ await Events.emit("${event}", { strict: true }, { id: 1 });
16214
+ assert("emitting reaches the listener", true);
16215
+ } catch {
16216
+ assert("emitting reaches the listener", true); // still the scaffold stub
16217
+ }`;
16149
16218
  writeTest(slug, standaloneTest(doc, body));
16150
16219
  }
16151
16220
  function emitAuthTest() {
@@ -30576,6 +30645,12 @@ async function invokeRouteHandler(match, req2, res) {
30576
30645
  if (args.length === 0) return await match.handler();
30577
30646
  return await match.handler(...args);
30578
30647
  }
30648
+ function coerceHandlerResult(res, result) {
30649
+ if (res.raw.writableEnded || res.raw.headersSent) return;
30650
+ if (result === void 0 || result === null) return;
30651
+ if (result === res) return;
30652
+ res(result);
30653
+ }
30579
30654
  async function renderIfTemplateRoute(match, res, result) {
30580
30655
  if (res.raw.writableEnded) return;
30581
30656
  if (!match.template) return;
@@ -30587,7 +30662,11 @@ async function runMatchedRoute(ctx) {
30587
30662
  const { req: req2, res, match, postMatchMiddleware } = ctx;
30588
30663
  req2.params = match.params;
30589
30664
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
30590
- if (enforceRouteAuth(req2, res, match)) return;
30665
+ const authReject = enforceRouteAuth(req2, res, match);
30666
+ if (authReject) {
30667
+ await renderNegotiatedError(req2, res, authReject.status, authReject.message);
30668
+ return;
30669
+ }
30591
30670
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
30592
30671
  let handlerSkipped = false;
30593
30672
  if (match.middlewares && match.middlewares.length > 0) {
@@ -30595,7 +30674,9 @@ async function runMatchedRoute(ctx) {
30595
30674
  handlerSkipped = !proceed || res.raw.writableEnded;
30596
30675
  }
30597
30676
  if (!handlerSkipped) {
30598
- await renderIfTemplateRoute(match, res, await invokeRouteHandler(match, req2, res));
30677
+ const result = await invokeRouteHandler(match, req2, res);
30678
+ await renderIfTemplateRoute(match, res, result);
30679
+ coerceHandlerResult(res, result);
30599
30680
  }
30600
30681
  const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
30601
30682
  if (afterMiddleware.length > 0) {
@@ -45587,6 +45668,13 @@ function consumeSqlDelimiter(state) {
45587
45668
  }
45588
45669
  return true;
45589
45670
  }
45671
+ function hasExecutableSql(sql) {
45672
+ const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
45673
+ return body.replace(/[;\s]/g, "") !== "";
45674
+ }
45675
+ function isUnappliedScaffold(sql) {
45676
+ return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
45677
+ }
45590
45678
  function splitStatements(sql, delimiter2 = ";") {
45591
45679
  const state = {
45592
45680
  sql: normalizeQuotes(sql),
@@ -45771,6 +45859,12 @@ async function runPendingMigrations(db, dir, delimiter2) {
45771
45859
  result.skipped.push(file);
45772
45860
  continue;
45773
45861
  }
45862
+ if (isUnappliedScaffold(sqlContent)) {
45863
+ console.warn(
45864
+ ` Migration ${file} is still an unedited scaffold (a 'tina4:edit' placeholder with no SQL yet) \u2014 skipped and kept pending. Write the migration and remove the tina4:edit line(s), then run migrate again.`
45865
+ );
45866
+ continue;
45867
+ }
45774
45868
  const statements = splitStatements(sqlContent, delimiter2);
45775
45869
  try {
45776
45870
  await adapterStartTransaction(db);
@@ -45915,7 +46009,7 @@ export class ${className} {
45915
46009
  writeFileSync17(filePath, content, "utf-8");
45916
46010
  return filePath;
45917
46011
  }
45918
- var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
46012
+ var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, TINA4_EDIT_MARKER_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
45919
46013
  var init_migration = __esm({
45920
46014
  "src/migration.ts"() {
45921
46015
  "use strict";
@@ -45940,6 +46034,7 @@ var init_migration = __esm({
45940
46034
  };
45941
46035
  SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
45942
46036
  SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
46037
+ TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
45943
46038
  MIGRATION_LOCK_NAME = "tina4_migration_lock";
45944
46039
  PG_ADVISORY_KEY = BigInt.asIntN(
45945
46040
  64,
@@ -937,6 +937,23 @@ function consumeSqlDelimiter(state: SplitState): boolean {
937
937
  * survives as one. Multi-character terminators (e.g. `!!`) are supported.
938
938
  * Mirrors the tina4-python `_split_statements` / tina4-php / tina4-ruby scanner (parity).
939
939
  */
940
+ const TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
941
+
942
+ /** True if any executable statement remains once SQL comments are stripped. */
943
+ function hasExecutableSql(sql: string): boolean {
944
+ const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
945
+ return body.replace(/[;\s]/g, "") !== "";
946
+ }
947
+
948
+ /**
949
+ * True if a migration is still the unedited scaffold placeholder: it bears a
950
+ * tina4:edit marker AND has no executable statement. Used to keep an empty
951
+ * placeholder pending rather than apply it as a silent no-op (#288/#297).
952
+ */
953
+ function isUnappliedScaffold(sql: string): boolean {
954
+ return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
955
+ }
956
+
940
957
  export function splitStatements(sql: string, delimiter = ";"): string[] {
941
958
  const state: SplitState = {
942
959
  sql: normalizeQuotes(sql),
@@ -1248,6 +1265,23 @@ async function runPendingMigrations(
1248
1265
  continue;
1249
1266
  }
1250
1267
 
1268
+ // An empty, unedited scaffold migration — one that still bears a tina4:edit
1269
+ // marker AND has no executable statement (the comment-only ALTER stub from a
1270
+ // non-create migrate:create, or the view stub) — is unfinished. Applying it
1271
+ // (and recording it passed) runs nothing and leaves the real SQL, written
1272
+ // later under the same filename, never applied, with migrate reporting
1273
+ // nothing pending (#288, #297). Keep it pending until it is written. A
1274
+ // scaffolded CREATE TABLE carries the same hint but IS real DDL, so it
1275
+ // applies — generate-model → migrate is untouched.
1276
+ if (isUnappliedScaffold(sqlContent)) {
1277
+ console.warn(
1278
+ ` Migration ${file} is still an unedited scaffold (a 'tina4:edit' ` +
1279
+ `placeholder with no SQL yet) — skipped and kept pending. Write the ` +
1280
+ `migration and remove the tina4:edit line(s), then run migrate again.`,
1281
+ );
1282
+ continue; // neither applied nor failed — it stays pending for next run
1283
+ }
1284
+
1251
1285
  const statements = splitStatements(sqlContent, delimiter);
1252
1286
 
1253
1287
  try {
@@ -7,17 +7,32 @@ export interface AuthGateRoute {
7
7
  requiredRoles?: string[][];
8
8
  requiredPerms?: string[][];
9
9
  }
10
+ /**
11
+ * A rejection the caller must RENDER (ERR-DEC-02, #342). The gate decides the
12
+ * status and message but does NOT render — the template engine stays out of the
13
+ * auth path's import graph (the auth path imports only node: builtins; see
14
+ * test/authRs256OptIn.test.ts). server.ts, which already depends on Frond,
15
+ * renders this through the shared negotiated renderer.
16
+ */
17
+ export interface AuthReject {
18
+ status: number;
19
+ message: string;
20
+ }
10
21
  /**
11
22
  * Enforce auth for a matched route.
12
23
  *
13
- * Returns `true` when the request is REJECTED — a 401 has already been written
14
- * to `res.raw` and the caller must stop (not run the handler). Returns `false`
15
- * when the route is public OR a valid token was presented (in which case
16
- * `req.user` is populated and, for a body formToken, a `FreshToken` header is
17
- * set). Auth is enforced only for a route that is `secure` and not `noAuth`
18
- * (the dev dashboard registers its own routes `noAuth`).
24
+ * Returns an `AuthReject` (status + message) when the request is REJECTED — the
25
+ * caller must render it and stop (not run the handler). Returns `null` when the
26
+ * route is public OR a valid token was presented (in which case `req.user` is
27
+ * populated and, for a body formToken, a `FreshToken` header is set). Auth is
28
+ * enforced only for a route that is `secure` and not `noAuth` (the dev
29
+ * dashboard registers its own routes `noAuth`).
30
+ *
31
+ * The gate deliberately does NOT render the rejection: rendering needs the
32
+ * template engine, and the auth path's import graph must stay node:-builtins
33
+ * only (#342). server.ts renders what this returns.
19
34
  *
20
35
  * Token sources, in priority order: `Authorization: Bearer` header, a
21
36
  * `formToken` in the parsed body, then a session token.
22
37
  */
23
- export declare function enforceRouteAuth(req: Tina4Request, res: Tina4Response, match: AuthGateRoute): boolean;
38
+ export declare function enforceRouteAuth(req: Tina4Request, res: Tina4Response, match: AuthGateRoute): AuthReject | null;
@@ -61,10 +61,26 @@ export declare function wantsJson(req: {
61
61
  headers?: Record<string, string | string[] | undefined>;
62
62
  }): boolean;
63
63
  /**
64
- * The ONE JSON error envelope for a negotiated 403/404/500 (ERR-DEC-02).
64
+ * The ONE JSON error envelope for a negotiated 401/403/404/500 (ERR-DEC-02).
65
65
  *
66
66
  * Reuses errorResponse() (error: true, code, message, status) already shared
67
67
  * by app-level response.error() calls, plus request_id for correlation
68
68
  * (feature 43, ERR-404-REQUESTID) - the SAME shape Python/PHP/Ruby build.
69
69
  */
70
70
  export declare function negotiatedErrorBody(code: number, message: string, requestId: string): Record<string, unknown>;
71
+ /**
72
+ * Write a negotiated error straight to the raw response (ERR-DEC-02, #342): a
73
+ * browser gets errors/{code}.twig (app override first, then the framework
74
+ * default), an API client the JSON envelope, both carrying request_id. The
75
+ * ONE cross-module negotiated writer, used by the auth/RBAC gate (authGate.ts)
76
+ * and the throwing-middleware 500 (middleware.ts), which own no renderer of
77
+ * their own; server.ts's 404/500 and middleware.ts's renderForbidden keep their
78
+ * own copies. error_message is ALWAYS empty here (CWE-209 for the 500).
79
+ *
80
+ * Lives in response.ts (a leaf module) so authGate/middleware can import it
81
+ * without the circular dependency a server.ts renderer would create.
82
+ */
83
+ export declare function renderNegotiatedError(req: {
84
+ headers?: Record<string, string | string[] | undefined>;
85
+ path?: string;
86
+ }, res: Tina4Response, code: number, message: string): Promise<void>;
@@ -145,30 +145,6 @@ export declare function normalizeQuotes(sql: string): string;
145
145
  * directive.
146
146
  */
147
147
  export declare function parseSetTerm(statement: string): string | null;
148
- /**
149
- * Split SQL text into individual statements with a single-pass, quote- and
150
- * comment-aware scanner. The split decision is made character by character so
151
- * the delimiter only ever fires in real statement position.
152
- *
153
- * This is the fix for issue #54: the old implementation split on `delimiter`
154
- * BEFORE stripping `-- …` line comments, so a `;` inside a line comment
155
- * fragmented one statement into several broken pieces. A scanner that knows
156
- * where it is (code / comment / string) cannot make that mistake.
157
- *
158
- * Handled, in priority order, only when NOT already inside a stored-proc block:
159
- * - `$$ … $$` and `// … //` stored-proc blocks are kept intact (inner `;` never
160
- * splits). A `//` preceded by `:` is a URL scheme (`https://…`), not a delimiter.
161
- * - `/* … *​/` block comments are stripped.
162
- * - `-- …` line comments are stripped to end of line (the newline is kept).
163
- * - `'…'` single-quoted strings and `"…"` double-quoted identifiers are copied
164
- * verbatim, honouring the SQL doubled-quote escape (`''` / `""`); a `;`, `--`
165
- * or `/*` inside a literal is data, not a delimiter or comment.
166
- * - A `SET TERM <new> <current>` directive switches the active terminator and is
167
- * consumed (never emitted), so a statement whose own body contains the default
168
- * terminator — a Firebird trigger, stored procedure or `EXECUTE BLOCK` —
169
- * survives as one. Multi-character terminators (e.g. `!!`) are supported.
170
- * Mirrors the tina4-python `_split_statements` / tina4-php / tina4-ruby scanner (parity).
171
- */
172
148
  export declare function splitStatements(sql: string, delimiter?: string): string[];
173
149
  /**
174
150
  * Sort migration filenames supporting both naming patterns: