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.
package/CLAUDE.md CHANGED
@@ -14,13 +14,13 @@ Even if the skill text is not currently loaded, these are non-negotiable:
14
14
 
15
15
  The full discipline lives in `.claude/skills/tina4-maintainer/SKILL.md`; this block is the always-on floor.
16
16
 
17
- # CLAUDE.md - AI Developer Guide for tina4-nodejs (v3.13.158)
17
+ # CLAUDE.md - AI Developer Guide for tina4-nodejs (v3.13.160)
18
18
 
19
19
  > This file helps AI assistants (Claude, Copilot, Cursor, etc.) understand and work on this codebase effectively.
20
20
 
21
21
  ## What This Project Is
22
22
 
23
- Tina4 for Node.js/TypeScript v3.13.158 - The Intelligent Native Application 4ramework. A convention-over-configuration structural paradigm. The developer writes TypeScript; Tina4 is invisible infrastructure.
23
+ Tina4 for Node.js/TypeScript v3.13.160 - The Intelligent Native Application 4ramework. A convention-over-configuration structural paradigm. The developer writes TypeScript; Tina4 is invisible infrastructure.
24
24
 
25
25
  The philosophy: zero ceremony, batteries included, file system as source of truth.
26
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tina4-nodejs",
3
- "version": "3.13.158",
3
+ "version": "3.13.160",
4
4
  "type": "module",
5
5
  "description": "Tina4 for Node.js/TypeScript - native TypeScript conventions and shared Tina4 contracts",
6
6
  "keywords": [
@@ -9326,6 +9326,13 @@ function consumeSqlDelimiter(state) {
9326
9326
  }
9327
9327
  return true;
9328
9328
  }
9329
+ function hasExecutableSql(sql) {
9330
+ const body = sql.replace(/\/\*[\s\S]*?\*\//g, "").replace(/--[^\n]*/g, "");
9331
+ return body.replace(/[;\s]/g, "") !== "";
9332
+ }
9333
+ function isUnappliedScaffold(sql) {
9334
+ return TINA4_EDIT_MARKER_RE.test(sql) && !hasExecutableSql(sql);
9335
+ }
9329
9336
  function splitStatements(sql, delimiter4 = ";") {
9330
9337
  const state = {
9331
9338
  sql: normalizeQuotes(sql),
@@ -9510,6 +9517,12 @@ async function runPendingMigrations(db, dir, delimiter4) {
9510
9517
  result.skipped.push(file);
9511
9518
  continue;
9512
9519
  }
9520
+ if (isUnappliedScaffold(sqlContent)) {
9521
+ console.warn(
9522
+ ` Migration ${file} is still an unedited scaffold (a 'tina4:edit' placeholder with no SQL yet) \u2014 skipped and kept pending. Write the migration and remove the tina4:edit line(s), then run migrate again.`
9523
+ );
9524
+ continue;
9525
+ }
9513
9526
  const statements = splitStatements(sqlContent, delimiter4);
9514
9527
  try {
9515
9528
  await adapterStartTransaction(db);
@@ -9654,7 +9667,7 @@ export class ${className} {
9654
9667
  writeFileSync2(filePath, content, "utf-8");
9655
9668
  return filePath;
9656
9669
  }
9657
- var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
9670
+ var ALTER_ADD_RE, CREATE_TABLE_RE, MIGRATION_TABLE, SMART_QUOTES, SMART_QUOTE_RE, SET_TERM_RE, TINA4_EDIT_MARKER_RE, MIGRATION_LOCK_NAME, PG_ADVISORY_KEY, delay, Migration;
9658
9671
  var init_migration = __esm({
9659
9672
  "../orm/src/migration.ts"() {
9660
9673
  "use strict";
@@ -9679,6 +9692,7 @@ var init_migration = __esm({
9679
9692
  };
9680
9693
  SMART_QUOTE_RE = new RegExp(`[${Object.keys(SMART_QUOTES).join("")}]`, "g");
9681
9694
  SET_TERM_RE = /^SET\s+TERM\s+(\S+)$/i;
9695
+ TINA4_EDIT_MARKER_RE = /(?:#|\/\/|--|\/\*|\{#)\s*tina4:edit\b/i;
9682
9696
  MIGRATION_LOCK_NAME = "tina4_migration_lock";
9683
9697
  PG_ADVISORY_KEY = BigInt.asIntN(
9684
9698
  64,
@@ -22178,6 +22192,41 @@ function negotiatedErrorBody(code, message, requestId) {
22178
22192
  body.request_id = requestId;
22179
22193
  return body;
22180
22194
  }
22195
+ async function renderNegotiatedError(req2, res, code, message) {
22196
+ const { Log: Log2 } = await Promise.resolve().then(() => (init_logger(), logger_exports));
22197
+ const requestId = Log2.getRequestId() ?? "";
22198
+ const writeJson = () => {
22199
+ const body = negotiatedErrorBody(code, message, requestId);
22200
+ res.raw.statusCode = code;
22201
+ res.raw.setHeader("Content-Type", "application/json");
22202
+ res.raw.end(JSON.stringify(body));
22203
+ };
22204
+ if (wantsJson(req2)) {
22205
+ writeJson();
22206
+ return;
22207
+ }
22208
+ const data = { path: req2?.path ?? "", error_message: "", request_id: requestId, status_code: code };
22209
+ const template = `errors/${code}.twig`;
22210
+ let html = null;
22211
+ try {
22212
+ html = (await getFrond()).render(template, data);
22213
+ } catch {
22214
+ }
22215
+ if (!html) {
22216
+ try {
22217
+ const fw = await getFrameworkFrond();
22218
+ html = fw ? fw.render(template, data) : null;
22219
+ } catch {
22220
+ html = null;
22221
+ }
22222
+ }
22223
+ if (html) {
22224
+ res.raw.writeHead(code, { "Content-Type": "text/html; charset=utf-8" });
22225
+ res.raw.end(html);
22226
+ return;
22227
+ }
22228
+ writeJson();
22229
+ }
22181
22230
  var HEADER_TOKEN, _frondCache, _defaultTemplatesDir, _globalFrond, _frameworkFrond, ERROR_CODE_NAMES;
22182
22231
  var init_response = __esm({
22183
22232
  "../core/src/response.ts"() {
@@ -22189,6 +22238,7 @@ var init_response = __esm({
22189
22238
  _globalFrond = null;
22190
22239
  _frameworkFrond = null;
22191
22240
  ERROR_CODE_NAMES = {
22241
+ 401: "UNAUTHORIZED",
22192
22242
  403: "FORBIDDEN",
22193
22243
  404: "NOT_FOUND",
22194
22244
  405: "METHOD_NOT_ALLOWED",
@@ -22257,7 +22307,7 @@ async function interpretHookResult(result, req2, res) {
22257
22307
  }
22258
22308
  return [req2, res, false];
22259
22309
  }
22260
- function middleware500(res, mwClass, methodName, error2) {
22310
+ async function middleware500(res, mwClass, methodName, error2, req2) {
22261
22311
  const clsName = mwClass?.name ?? mwClass?.constructor?.name ?? "Middleware";
22262
22312
  const err = error2;
22263
22313
  const type2 = err?.name ?? error2?.constructor?.name ?? "Error";
@@ -22266,6 +22316,10 @@ function middleware500(res, mwClass, methodName, error2) {
22266
22316
  Log.error(`Middleware ${clsName}.${methodName} raised ${type2}: ${message}`);
22267
22317
  } catch {
22268
22318
  }
22319
+ if (req2 && res?.raw && typeof res.raw.writeHead === "function" && !res.raw.writableEnded) {
22320
+ await renderNegotiatedError(req2, res, 500, "Internal Server Error");
22321
+ return res;
22322
+ }
22269
22323
  if (typeof res.json === "function") {
22270
22324
  res.json({ error: "Internal Server Error", status: 500 }, 500);
22271
22325
  } else if (typeof res === "function") {
@@ -22566,7 +22620,7 @@ var init_middleware = __esm({
22566
22620
  res = nextRes;
22567
22621
  if (stop2) return [req2, res, false];
22568
22622
  } catch (error2) {
22569
- res = middleware500(res, cls, method, error2);
22623
+ res = await middleware500(res, cls, method, error2, req2);
22570
22624
  return [req2, res, false];
22571
22625
  }
22572
22626
  if (res.raw.statusCode >= 400 || res.raw.writableEnded) {
@@ -22610,7 +22664,7 @@ var init_middleware = __esm({
22610
22664
  res = nextRes;
22611
22665
  if (stop2) return [req2, res];
22612
22666
  } catch (error2) {
22613
- res = middleware500(res, cls, method, error2);
22667
+ res = await middleware500(res, cls, method, error2, req2);
22614
22668
  continue;
22615
22669
  }
22616
22670
  }
@@ -23614,7 +23668,7 @@ var init_ssoIdentity = __esm({
23614
23668
  // ../core/src/authGate.ts
23615
23669
  function enforceRouteAuth(req2, res, match) {
23616
23670
  if (!(match.secure === true && match.noAuth !== true)) {
23617
- return false;
23671
+ return null;
23618
23672
  }
23619
23673
  const authHeader = req2.headers.authorization ?? "";
23620
23674
  const headerToken = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : "";
@@ -23644,7 +23698,7 @@ function enforceRouteAuth(req2, res, match) {
23644
23698
  const identity = liveSessionIdentity(req2.session?.get?.("_tina4_sso"));
23645
23699
  if (identity) {
23646
23700
  req2.user = identity;
23647
- return rbacForbidden(match, identity, res);
23701
+ return rbacForbidden(match, identity);
23648
23702
  }
23649
23703
  const sessionToken = req2.session?.get?.("token");
23650
23704
  if (sessionToken) {
@@ -23657,9 +23711,7 @@ function enforceRouteAuth(req2, res, match) {
23657
23711
  }
23658
23712
  }
23659
23713
  if (!payload) {
23660
- res.raw.writeHead(401, { "Content-Type": "application/json" });
23661
- res.raw.end(JSON.stringify({ error: "Unauthorized" }));
23662
- return true;
23714
+ return { status: 401, message: "Unauthorized" };
23663
23715
  }
23664
23716
  req2.user = payload;
23665
23717
  if (tokenSource === "body") {
@@ -23668,7 +23720,7 @@ function enforceRouteAuth(req2, res, match) {
23668
23720
  res.header("FreshToken", fresh);
23669
23721
  }
23670
23722
  }
23671
- return rbacForbidden(match, req2.user, res);
23723
+ return rbacForbidden(match, req2.user);
23672
23724
  }
23673
23725
  function rbacClaimList(subject, key, legacy) {
23674
23726
  const coerce = (v) => {
@@ -23685,27 +23737,23 @@ function rbacPermGranted(granted, required) {
23685
23737
  (g) => g === "*" || g === required || g.endsWith(".*") && required.startsWith(g.slice(0, -1))
23686
23738
  );
23687
23739
  }
23688
- function rbacForbidden(match, payload, res) {
23740
+ function rbacForbidden(match, payload) {
23689
23741
  const requiredRoles = match.requiredRoles ?? [];
23690
23742
  const requiredPerms = match.requiredPerms ?? [];
23691
23743
  if (requiredRoles.length === 0 && requiredPerms.length === 0) {
23692
- return false;
23744
+ return null;
23693
23745
  }
23694
23746
  const subject = payload && typeof payload === "object" ? payload : {};
23747
+ const forbidden = { status: 403, message: "Forbidden" };
23695
23748
  const roles = rbacClaimList(subject, "roles", "role");
23696
23749
  for (const group of requiredRoles) {
23697
- if (!group.some((r) => roles.includes(r))) return writeForbidden(res);
23750
+ if (!group.some((r) => roles.includes(r))) return forbidden;
23698
23751
  }
23699
23752
  const perms = rbacClaimList(subject, "permissions");
23700
23753
  for (const group of requiredPerms) {
23701
- if (!group.some((p) => rbacPermGranted(perms, p))) return writeForbidden(res);
23754
+ if (!group.some((p) => rbacPermGranted(perms, p))) return forbidden;
23702
23755
  }
23703
- return false;
23704
- }
23705
- function writeForbidden(res) {
23706
- res.raw.writeHead(403, { "Content-Type": "application/json" });
23707
- res.raw.end(JSON.stringify({ error: "Forbidden" }));
23708
- return true;
23756
+ return null;
23709
23757
  }
23710
23758
  var init_authGate = __esm({
23711
23759
  "../core/src/authGate.ts"() {
@@ -28222,6 +28270,7 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
28222
28270
  }
28223
28271
  const fields = fieldsOverride || parseFields(flags.fields || "");
28224
28272
  const isCreate = name.startsWith("create_") || fieldsOverride !== void 0;
28273
+ const isView = isCreate && fieldsOverride === void 0 && table2.endsWith("_view");
28225
28274
  const fileName = `${ts}_${name}.sql`;
28226
28275
  const path10 = join22(dir, fileName);
28227
28276
  setResolutionField("migration_path", `migrations/${fileName}`);
@@ -28231,7 +28280,13 @@ function generateMigration(name, flags, fieldsOverride, tableOverride, emitTest
28231
28280
  }
28232
28281
  let upSql;
28233
28282
  let downSql;
28234
- if (isCreate) {
28283
+ if (isView) {
28284
+ upSql = `-- tina4:edit write the CREATE VIEW statement, then remove the
28285
+ -- tina4:edit lines. For example:
28286
+ -- CREATE VIEW ${table2} AS
28287
+ -- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
28288
+ downSql = `DROP VIEW IF EXISTS ${table2};`;
28289
+ } else if (isCreate) {
28235
28290
  const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
28236
28291
  for (const [fname, ftype] of fields) {
28237
28292
  const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
@@ -28257,9 +28312,6 @@ DROP TABLE IF EXISTS ${table2};`;
28257
28312
 
28258
28313
  -- UP
28259
28314
  ${upSql}
28260
-
28261
- -- DOWN
28262
- ${downSql}
28263
28315
  `;
28264
28316
  writeFileSafe(path10, content);
28265
28317
  const downPath = join22(dir, `${ts}_${name}.down.sql`);
@@ -28269,7 +28321,7 @@ ${downSql}
28269
28321
  ${downSql}
28270
28322
  `;
28271
28323
  writeFileSafe(downPath, downContent);
28272
- if (emitTest && isCreate) emitMigrationTest(name, table2);
28324
+ if (emitTest && isCreate && !isView) emitMigrationTest(name, table2);
28273
28325
  }
28274
28326
  function generateMiddleware(name, _flags) {
28275
28327
  const snake = toSnake(name);
@@ -29080,9 +29132,11 @@ function emitRouteStubTest(route) {
29080
29132
  * Routing test for ${route} \u2014 no mocks, real Router + route discovery.
29081
29133
  *
29082
29134
  * Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
29083
- * ${route}\` (no --model). The handlers are AI-FILL stubs that throw until you
29084
- * implement them, so this tests what IS live on generation: all five routes
29085
- * register on the REAL Router, and the list handler fails loud until filled.
29135
+ * ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
29136
+ * you implement them. This tests what is live on generation: all five routes
29137
+ * register on the REAL Router, and the list handler is wired and callable. It
29138
+ * stays GREEN whether the stub still throws OR you have filled it in \u2014
29139
+ * implementing the handler never turns this test red.
29086
29140
  * Run with: npx tsx tests/${route}.test.ts
29087
29141
  */
29088
29142
  import { dirname, resolve } from "node:path";
@@ -29099,9 +29153,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
29099
29153
  assert(\`route registered: \${sig}\`, sigs.includes(sig));
29100
29154
  }
29101
29155
 
29102
- // The scaffolded list handler is a loud AI-FILL stub \u2014 it throws until filled.
29103
- await assertThrows("list handler is a live stub (throws until filled)",
29104
- () => listHandler({} as never, {} as never));`;
29156
+ // The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
29157
+ // stays green whether it still throws OR you have filled it in, so doing the
29158
+ // work never turns the suite red.
29159
+ assert("list handler is callable", typeof listHandler === "function");
29160
+ try {
29161
+ await listHandler({} as never, {} as never);
29162
+ } catch {
29163
+ // still the scaffold stub (throws until filled) \u2014 expected
29164
+ }`;
29105
29165
  writeTest(route, standaloneTest(doc, body));
29106
29166
  }
29107
29167
  function emitMiddlewareTest(name, snake) {
@@ -29185,8 +29245,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
29185
29245
  assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
29186
29246
  ServiceRunner.remove("${snake}");
29187
29247
 
29188
- // The scaffolded task body is an AI-FILL stub \u2014 it throws until filled.
29189
- await assertThrows("task is a live stub (throws until filled)", () => ${camel}Task({} as never));`;
29248
+ // The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
29249
+ // green whether it still throws OR you have filled it in.
29250
+ assert("task is callable", typeof ${camel}Task === "function");
29251
+ try {
29252
+ await ${camel}Task({} as never);
29253
+ } catch {
29254
+ // still the scaffold stub (throws until filled) \u2014 expected
29255
+ }`;
29190
29256
  writeTest(snake, standaloneTest(doc, body));
29191
29257
  }
29192
29258
  function emitQueueTest(topic, slug, pascal) {
@@ -29208,8 +29274,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
29208
29274
  assert("consumer default export is a daemon", worker.daemon === true);
29209
29275
  assert("consumer handler is wired", typeof worker.handler === "function");
29210
29276
 
29211
- // The per-job handler is an AI-FILL stub \u2014 it throws until filled.
29212
- await assertThrows("handle is a live stub (throws until filled)", () => handle${pascal}({}));`;
29277
+ // The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
29278
+ // This stays green whether it still throws OR you have filled it in.
29279
+ assert("handle is callable", typeof handle${pascal} === "function");
29280
+ try {
29281
+ await handle${pascal}({});
29282
+ } catch {
29283
+ // still the scaffold stub (throws until filled) \u2014 expected
29284
+ }`;
29213
29285
  writeTest(slug, standaloneTest(doc, body));
29214
29286
  }
29215
29287
  function emitValidatorTest(name, snake, pascal) {
@@ -29271,9 +29343,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
29271
29343
  const closed = await ${handler}(null as never, "close", "");
29272
29344
  assert("close event handled cleanly", closed === undefined);
29273
29345
 
29274
- // The "message" branch is an AI-FILL stub \u2014 it throws until filled.
29275
- await assertThrows("message branch is a live stub (throws until filled)",
29276
- () => ${handler}(null as never, "message", "hi"));`;
29346
+ // The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
29347
+ // This stays green whether it still throws OR you have filled it in.
29348
+ try {
29349
+ await ${handler}(null as never, "message", "hi");
29350
+ assert("message branch is callable", true);
29351
+ } catch {
29352
+ assert("message branch is callable", true); // still the scaffold stub
29353
+ }`;
29277
29354
  writeTest(`ws_${base}`, standaloneTest(doc, body));
29278
29355
  }
29279
29356
  function emitListenerTest(event, slug) {
@@ -29290,9 +29367,15 @@ import { Events } from "tina4-nodejs";
29290
29367
  import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
29291
29368
  const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
29292
29369
 
29293
- // strict emit re-raises the stub error, proving the listener actually ran.
29294
- await assertThrows("emitting the event reaches the (stub) listener",
29295
- () => Events.emit("${event}", { strict: true }, { id: 1 }));`;
29370
+ // Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
29371
+ // re-raises); once you implement it this test STILL passes, so doing the work
29372
+ // never turns the suite red.
29373
+ try {
29374
+ await Events.emit("${event}", { strict: true }, { id: 1 });
29375
+ assert("emitting reaches the listener", true);
29376
+ } catch {
29377
+ assert("emitting reaches the listener", true); // still the scaffold stub
29378
+ }`;
29296
29379
  writeTest(slug, standaloneTest(doc, body));
29297
29380
  }
29298
29381
  function emitAuthTest() {
@@ -43723,6 +43806,12 @@ async function invokeRouteHandler(match, req2, res) {
43723
43806
  if (args.length === 0) return await match.handler();
43724
43807
  return await match.handler(...args);
43725
43808
  }
43809
+ function coerceHandlerResult(res, result) {
43810
+ if (res.raw.writableEnded || res.raw.headersSent) return;
43811
+ if (result === void 0 || result === null) return;
43812
+ if (result === res) return;
43813
+ res(result);
43814
+ }
43726
43815
  async function renderIfTemplateRoute(match, res, result) {
43727
43816
  if (res.raw.writableEnded) return;
43728
43817
  if (!match.template) return;
@@ -43734,7 +43823,11 @@ async function runMatchedRoute(ctx) {
43734
43823
  const { req: req2, res, match, postMatchMiddleware } = ctx;
43735
43824
  req2.params = match.params;
43736
43825
  if (await runGlobalMiddlewarePass(postMatchMiddleware, req2, res)) return;
43737
- if (enforceRouteAuth(req2, res, match)) return;
43826
+ const authReject = enforceRouteAuth(req2, res, match);
43827
+ if (authReject) {
43828
+ await renderNegotiatedError(req2, res, authReject.status, authReject.message);
43829
+ return;
43830
+ }
43738
43831
  const routeMiddlewareClasses = (match.middlewares ?? []).filter(isMiddlewareClass);
43739
43832
  let handlerSkipped = false;
43740
43833
  if (match.middlewares && match.middlewares.length > 0) {
@@ -43742,7 +43835,9 @@ async function runMatchedRoute(ctx) {
43742
43835
  handlerSkipped = !proceed || res.raw.writableEnded;
43743
43836
  }
43744
43837
  if (!handlerSkipped) {
43745
- await renderIfTemplateRoute(match, res, await invokeRouteHandler(match, req2, res));
43838
+ const result = await invokeRouteHandler(match, req2, res);
43839
+ await renderIfTemplateRoute(match, res, result);
43840
+ coerceHandlerResult(res, result);
43746
43841
  }
43747
43842
  const afterMiddleware = [...ctx.allGlobalMiddleware, ...routeMiddlewareClasses];
43748
43843
  if (afterMiddleware.length > 0) {
@@ -1482,6 +1482,12 @@ export function generateMigration(
1482
1482
  // Build SQL columns from fields
1483
1483
  const fields = fieldsOverride || parseFields((flags.fields as string) || "");
1484
1484
  const isCreate = name.startsWith("create_") || fieldsOverride !== undefined;
1485
+ // A `create_*_view` name is a VIEW, not a table. Emitting a runnable
1486
+ // `CREATE TABLE <name>_view` made migrate build a table and never the view,
1487
+ // silently (#297). A view needs a SELECT, so scaffold commented guidance with
1488
+ // tina4:edit markers and no executable SQL, so the runner keeps it pending
1489
+ // until it is written (#288).
1490
+ const isView = isCreate && fieldsOverride === undefined && table.endsWith("_view");
1485
1491
 
1486
1492
  const fileName = `${ts}_${name}.sql`;
1487
1493
  const path = join(dir, fileName);
@@ -1507,7 +1513,14 @@ export function generateMigration(
1507
1513
  // parsed label (the migration runner's splitStatements strips `--` line
1508
1514
  // comments, so a comma-less marker line inside a DDL body is still
1509
1515
  // syntactically inert on every engine).
1510
- if (isCreate) {
1516
+ if (isView) {
1517
+ upSql =
1518
+ `-- tina4:edit write the CREATE VIEW statement, then remove the\n` +
1519
+ `-- tina4:edit lines. For example:\n` +
1520
+ `-- CREATE VIEW ${table} AS\n` +
1521
+ `-- SELECT id, /* columns */ FROM source_table WHERE /* ... */;`;
1522
+ downSql = `DROP VIEW IF EXISTS ${table};`;
1523
+ } else if (isCreate) {
1511
1524
  const colLines = [" id INTEGER PRIMARY KEY AUTOINCREMENT"];
1512
1525
  for (const [fname, ftype] of fields) {
1513
1526
  const info = FIELD_TYPE_MAP[ftype] || FIELD_TYPE_MAP.string;
@@ -1533,11 +1546,15 @@ export function generateMigration(
1533
1546
  }
1534
1547
 
1535
1548
  const now = isoNow();
1549
+ // The main .sql holds ONLY the UP migration. The runner executes the WHOLE
1550
+ // file (comments stripped), so embedding the DOWN here made it CREATE then
1551
+ // immediately DROP the table — a generated migration silently undid itself.
1552
+ // Rollback reads the sibling .down.sql, never this file's DOWN. Keep DOWN out
1553
+ // of the main file (parity with the Python/PHP/Ruby masters).
1536
1554
  const content =
1537
1555
  `-- Migration: ${name}\n` +
1538
1556
  `-- Created: ${now}\n\n` +
1539
- `-- UP\n${upSql}\n\n` +
1540
- `-- DOWN\n${downSql}\n`;
1557
+ `-- UP\n${upSql}\n`;
1541
1558
 
1542
1559
  writeFileSafe(path, content);
1543
1560
 
@@ -1550,10 +1567,11 @@ export function generateMigration(
1550
1567
 
1551
1568
  writeFileSafe(downPath, downContent);
1552
1569
 
1553
- // Co-emit a real up/down migration test — only for CREATE migrations (a
1554
- // placeholder ALTER migration has no asserted schema yet). Suppressed when a
1555
- // model generates its matching migration (the model's own test covers schema).
1556
- if (emitTest && isCreate) emitMigrationTest(name, table);
1570
+ // Co-emit a real up/down migration test — only for CREATE TABLE migrations (a
1571
+ // placeholder ALTER, or a VIEW stub that still needs its SELECT, has no
1572
+ // asserted schema yet). Suppressed when a model generates its matching
1573
+ // migration (the model's own test covers schema).
1574
+ if (emitTest && isCreate && !isView) emitMigrationTest(name, table);
1557
1575
  }
1558
1576
 
1559
1577
  // ── Middleware ───────────────────────────────────────────────────────
@@ -2541,9 +2559,11 @@ function emitRouteStubTest(route: string): void {
2541
2559
  * Routing test for ${route} — no mocks, real Router + route discovery.
2542
2560
  *
2543
2561
  * Generated with src/routes/api/${route}/ by \`tina4nodejs generate route
2544
- * ${route}\` (no --model). The handlers are AI-FILL stubs that throw until you
2545
- * implement them, so this tests what IS live on generation: all five routes
2546
- * register on the REAL Router, and the list handler fails loud until filled.
2562
+ * ${route}\` (no --model). The handlers start as AI-FILL stubs that throw until
2563
+ * you implement them. This tests what is live on generation: all five routes
2564
+ * register on the REAL Router, and the list handler is wired and callable. It
2565
+ * stays GREEN whether the stub still throws OR you have filled it in —
2566
+ * implementing the handler never turns this test red.
2547
2567
  * Run with: npx tsx tests/${route}.test.ts
2548
2568
  */
2549
2569
  import { dirname, resolve } from "node:path";
@@ -2560,9 +2580,15 @@ for (const sig of ["GET /api/${route}", "POST /api/${route}", "GET /api/${route}
2560
2580
  assert(\`route registered: \${sig}\`, sigs.includes(sig));
2561
2581
  }
2562
2582
 
2563
- // The scaffolded list handler is a loud AI-FILL stub — it throws until filled.
2564
- await assertThrows("list handler is a live stub (throws until filled)",
2565
- () => listHandler({} as never, {} as never));`;
2583
+ // The list handler is WIRED: a loud AI-FILL stub (throws) on generation. This
2584
+ // stays green whether it still throws OR you have filled it in, so doing the
2585
+ // work never turns the suite red.
2586
+ assert("list handler is callable", typeof listHandler === "function");
2587
+ try {
2588
+ await listHandler({} as never, {} as never);
2589
+ } catch {
2590
+ // still the scaffold stub (throws until filled) — expected
2591
+ }`;
2566
2592
  writeTest(route, standaloneTest(doc, body));
2567
2593
  }
2568
2594
 
@@ -2651,8 +2677,14 @@ ServiceRunner.register(service.name, service.handler, { interval: (service as {
2651
2677
  assert("registers on a real ServiceRunner", ServiceRunner.list().some((s) => s.name === "${snake}"));
2652
2678
  ServiceRunner.remove("${snake}");
2653
2679
 
2654
- // The scaffolded task body is an AI-FILL stub — it throws until filled.
2655
- await assertThrows("task is a live stub (throws until filled)", () => ${camel}Task({} as never));`;
2680
+ // The task is WIRED: a loud AI-FILL stub (throws) on generation. This stays
2681
+ // green whether it still throws OR you have filled it in.
2682
+ assert("task is callable", typeof ${camel}Task === "function");
2683
+ try {
2684
+ await ${camel}Task({} as never);
2685
+ } catch {
2686
+ // still the scaffold stub (throws until filled) — expected
2687
+ }`;
2656
2688
  writeTest(snake, standaloneTest(doc, body));
2657
2689
  }
2658
2690
 
@@ -2676,8 +2708,14 @@ assert("the job is really on the queue", new Queue({ topic: "${topic}" }).size()
2676
2708
  assert("consumer default export is a daemon", worker.daemon === true);
2677
2709
  assert("consumer handler is wired", typeof worker.handler === "function");
2678
2710
 
2679
- // The per-job handler is an AI-FILL stub — it throws until filled.
2680
- await assertThrows("handle is a live stub (throws until filled)", () => handle${pascal}({}));`;
2711
+ // The per-job handler is WIRED: a loud AI-FILL stub (throws) on generation.
2712
+ // This stays green whether it still throws OR you have filled it in.
2713
+ assert("handle is callable", typeof handle${pascal} === "function");
2714
+ try {
2715
+ await handle${pascal}({});
2716
+ } catch {
2717
+ // still the scaffold stub (throws until filled) — expected
2718
+ }`;
2681
2719
  writeTest(slug, standaloneTest(doc, body));
2682
2720
  }
2683
2721
 
@@ -2748,9 +2786,14 @@ import { ${handler} } from "../src/routes/ws_${base}.js"; // importing register
2748
2786
  const closed = await ${handler}(null as never, "close", "");
2749
2787
  assert("close event handled cleanly", closed === undefined);
2750
2788
 
2751
- // The "message" branch is an AI-FILL stub — it throws until filled.
2752
- await assertThrows("message branch is a live stub (throws until filled)",
2753
- () => ${handler}(null as never, "message", "hi"));`;
2789
+ // The "message" branch is WIRED: a loud AI-FILL stub (throws) on generation.
2790
+ // This stays green whether it still throws OR you have filled it in.
2791
+ try {
2792
+ await ${handler}(null as never, "message", "hi");
2793
+ assert("message branch is callable", true);
2794
+ } catch {
2795
+ assert("message branch is callable", true); // still the scaffold stub
2796
+ }`;
2754
2797
  writeTest(`ws_${base}`, standaloneTest(doc, body));
2755
2798
  }
2756
2799
 
@@ -2769,9 +2812,15 @@ import { Events } from "tina4-nodejs";
2769
2812
  import "../src/listeners/${slug}.js"; // importing registers the listener via Events.on()`;
2770
2813
  const body = `assert("listener registered on the real event bus", Events.listeners("${event}").length >= 1);
2771
2814
 
2772
- // strict emit re-raises the stub error, proving the listener actually ran.
2773
- await assertThrows("emitting the event reaches the (stub) listener",
2774
- () => Events.emit("${event}", { strict: true }, { id: 1 }));`;
2815
+ // Emitting reaches the listener. It starts as a loud AI-FILL stub (a strict emit
2816
+ // re-raises); once you implement it this test STILL passes, so doing the work
2817
+ // never turns the suite red.
2818
+ try {
2819
+ await Events.emit("${event}", { strict: true }, { id: 1 });
2820
+ assert("emitting reaches the listener", true);
2821
+ } catch {
2822
+ assert("emitting reaches the listener", true); // still the scaffold stub
2823
+ }`;
2775
2824
  writeTest(slug, standaloneTest(doc, body));
2776
2825
  }
2777
2826