gencow 0.1.269 → 0.1.270

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.
@@ -1,5 +1,10 @@
1
1
  import { formatProcedureRpcDiagnostic } from "./procedure-rpc-diagnostic.mjs";
2
2
  import { describeMigrationFolderFormatFailure } from "./migration-folder-format.mjs";
3
+ import {
4
+ SCHEMA_LOAD_FAILURE_CAUSE_HINT,
5
+ SCHEMA_LOAD_FAILURE_CLI_ACTION,
6
+ SCHEMA_LOAD_FAILURE_CLI_MESSAGE,
7
+ } from "./migration-schema-load-failure.mjs";
3
8
  import {
4
9
  buildHintsRequiredCommand,
5
10
  HINTS_DATA_LOSS_NOTICE,
@@ -43,12 +48,17 @@ const SAFE_LOCAL_ERROR_CODES = new Map([
43
48
  message: (caught) =>
44
49
  caught.migrationFolderFormat
45
50
  ? describeMigrationFolderFormatFailure(caught.migrationFolderFormat).cliMessage
46
- : "Migration generation failed: Drizzle could not generate migrations from schema.ts.",
51
+ : caught.migrationSchemaFailure
52
+ ? SCHEMA_LOAD_FAILURE_CLI_MESSAGE
53
+ : "Migration generation failed: Drizzle could not generate migrations from schema.ts.",
47
54
  stage: "migration",
55
+ detail: (caught) => (caught.migrationSchemaFailure ? SCHEMA_LOAD_FAILURE_CAUSE_HINT : null),
48
56
  action: (caught) =>
49
57
  caught.migrationFolderFormat
50
58
  ? describeMigrationFolderFormatFailure(caught.migrationFolderFormat).cliAction
51
- : "Retryable: no — fix the schema source, then rerun the command.",
59
+ : caught.migrationSchemaFailure
60
+ ? SCHEMA_LOAD_FAILURE_CLI_ACTION
61
+ : "Retryable: no — fix the schema source, then rerun the command.",
52
62
  },
53
63
  ],
54
64
  [
@@ -277,6 +287,9 @@ function commandErrorMessage(caught) {
277
287
  `Code: ${caught.code}`,
278
288
  `Stage: ${localDiagnostic.stage}`,
279
289
  ];
290
+ const detail =
291
+ typeof localDiagnostic.detail === "function" ? localDiagnostic.detail(caught) : localDiagnostic.detail;
292
+ if (detail) lines.push(detail);
280
293
  const location = safeSourceLocation(caught);
281
294
  if (location) lines.push(`${localDiagnostic.locationLabel ?? "Source location"}: ${location}`);
282
295
  const action =
@@ -0,0 +1,124 @@
1
+ import { readProjectAppTargets, resolveCloudAppTarget } from "./cloud-targets.mjs";
2
+ import { readJsonValueResponse } from "./http-response-json.mjs";
3
+
4
+ const SAFE_CORRELATION_ID = /^[A-Za-z0-9_-]{8,128}$/u;
5
+ const LOOKUP_FAILED_CODE = "APP_DEPLOY_TARGET_LOOKUP_FAILED";
6
+
7
+ // Reads the environment fact the server stores for an app (apps.get: environment "production" |
8
+ // "development", prodApp = the dev app's prod sibling). Used only when the project cannot tell us the
9
+ // environment, i.e. an explicit --app that this project does not bind.
10
+ export async function lookupAppEnvironment({ creds, appId, rpcQueryImpl }) {
11
+ let response;
12
+ try {
13
+ response = await rpcQueryImpl(creds, "apps.get", { name: appId });
14
+ } catch {
15
+ return { kind: "error", code: LOOKUP_FAILED_CODE, retryable: true };
16
+ }
17
+ const decoded = await readJsonValueResponse(response);
18
+ const body = decoded.parsed ? decoded.value : undefined;
19
+ if (!response.ok) {
20
+ const code = response.status === 401 ? "APP_RELEASE_AUTH_REQUIRED" : LOOKUP_FAILED_CODE;
21
+ const retryable = typeof body?.retryable === "boolean" ? body.retryable : response.status >= 500;
22
+ return {
23
+ kind: "error",
24
+ code,
25
+ status: response.status,
26
+ retryable,
27
+ ...(typeof body?.correlationId === "string" && SAFE_CORRELATION_ID.test(body.correlationId)
28
+ ? { correlationId: body.correlationId }
29
+ : {}),
30
+ };
31
+ }
32
+ // The RPC answers null for an app this account does not own or that does not exist.
33
+ if (body === null) return { kind: "missing" };
34
+ if (!body || typeof body !== "object" || Array.isArray(body) || body.name !== appId) {
35
+ return { kind: "error", code: LOOKUP_FAILED_CODE, status: response.status, retryable: false };
36
+ }
37
+ if (body.environment !== "production" && body.environment !== "development") {
38
+ return { kind: "error", code: LOOKUP_FAILED_CODE, status: response.status, retryable: false };
39
+ }
40
+ return {
41
+ kind: "found",
42
+ environment: body.environment,
43
+ prodAppName: typeof body.prodApp?.name === "string" ? body.prodApp.name : null,
44
+ };
45
+ }
46
+
47
+ // Same flag reading as resolveCloudAppTarget: the last --app value wins and any --prod selects prod.
48
+ function readExplicitTargetArgs(restArgs) {
49
+ let explicitAppId = null;
50
+ let prod = false;
51
+ for (let index = 0; index < restArgs.length; index += 1) {
52
+ if (restArgs[index] === "--app" || restArgs[index] === "-a") {
53
+ explicitAppId = restArgs[index + 1];
54
+ index += 1;
55
+ continue;
56
+ }
57
+ if (restArgs[index] === "--prod") prod = true;
58
+ }
59
+ return { explicitAppId: typeof explicitAppId === "string" ? explicitAppId : null, prod };
60
+ }
61
+
62
+ function renderLookupFailure(failure, { stage, appId }) {
63
+ const lines = [
64
+ `Code: ${failure.code}`,
65
+ `Stage: ${stage}`,
66
+ `App ID: ${appId}`,
67
+ "Changed: nothing. No app, env value, or serving state was changed.",
68
+ `Retryable: ${failure.retryable ? "yes" : "no"}`,
69
+ ];
70
+ if (failure.status) lines.push(`HTTP status: ${failure.status}`);
71
+ if (failure.correlationId) lines.push(`Correlation ID: ${failure.correlationId}`);
72
+ if (failure.code === "APP_RELEASE_AUTH_REQUIRED") {
73
+ lines.push("Next: gencow login, then retry the same command.");
74
+ } else if (failure.retryable) {
75
+ lines.push("Next: retry the same command after a short wait.");
76
+ } else {
77
+ lines.push("Next: gencow app list (confirm the app ID you own, then retry)");
78
+ }
79
+ return lines.join("\n");
80
+ }
81
+
82
+ // Target resolution for a cloud command that may receive an explicit --app without a project app binding
83
+ // (no gencow.json, or one with no appId/prodApp). Any project that binds an app gets exactly
84
+ // resolveCloudAppTarget's result. Without a binding, the server's environment fact decides:
85
+ // - prod app: targets prod even without --prod, like a bound prod app inside the project;
86
+ // - dev app with --prod: the typed EXPLICIT_APP_NOT_PROD_APP rejection, nothing is requested;
87
+ // - lookup failure: a typed error with a next action, never a silent dev fallback.
88
+ // A missing app (null answer) keeps resolveCloudAppTarget's result so the command reports not-found.
89
+ export async function resolveCloudAppTargetWithServerEnvironment(restArgs, options = {}) {
90
+ const {
91
+ cwd = process.cwd(),
92
+ creds,
93
+ rpcQueryImpl,
94
+ stage = "target resolution",
95
+ command = "deploy",
96
+ } = options;
97
+ const base = resolveCloudAppTarget(restArgs, options);
98
+ if (base.error) return base;
99
+
100
+ const { explicitAppId, prod } = readExplicitTargetArgs(restArgs);
101
+ if (!explicitAppId) return base;
102
+ // A project that binds any app keeps the project's own rules unchanged, including for unrelated --app values.
103
+ const projectTargets = readProjectAppTargets(cwd);
104
+ if (projectTargets.appId || projectTargets.prodApp) return base;
105
+
106
+ const lookup = await lookupAppEnvironment({ creds, appId: explicitAppId, rpcQueryImpl });
107
+ if (lookup.kind === "error") {
108
+ return { error: renderLookupFailure(lookup, { stage, appId: explicitAppId }) };
109
+ }
110
+ if (lookup.kind === "missing") return base;
111
+
112
+ if (lookup.environment === "production") return { appId: explicitAppId, envTarget: "prod" };
113
+ if (!prod) return { appId: explicitAppId, envTarget: "dev" };
114
+ const next = lookup.prodAppName
115
+ ? `gencow ${command} --app ${lookup.prodAppName} (this app's production app)`
116
+ : `gencow ${command} --app ${explicitAppId} (development app: drop --prod)`;
117
+ return {
118
+ error: `--app with --prod must name a production app, and ${explicitAppId} is a development app.`,
119
+ reason: "explicit_app_not_prod_app",
120
+ prodApp: null,
121
+ explicitAppId,
122
+ next,
123
+ };
124
+ }
@@ -57,6 +57,10 @@ export function resolveImplicitProdEnvironment({ explicitApp = false, envTarget
57
57
 
58
58
  // Shared human message for a failed prod target; falls back to the call site's own text.
59
59
  export function describeProdTargetFailure(result, fallbackMessage) {
60
+ if (result?.reason === "explicit_app_not_prod_app" && !result.prodApp) {
61
+ // Outside a project there is no prod binding to name; the server reported the app as development.
62
+ return "`--app` with `--prod` must name a production app, and this app is a development app.";
63
+ }
60
64
  if (result?.reason === "explicit_app_not_prod_app") {
61
65
  return `\`--app\` with \`--prod\` must name this project's prod app: ${result.prodApp}. Run again with --app ${result.prodApp} or without --app.`;
62
66
  }
@@ -16,7 +16,7 @@ import { tmpdir } from "os";
16
16
  import { createDbCheckCommand, createDbPushCommand } from "./db-push-command.mjs";
17
17
  import { renderMaintenanceFailure } from "./db-seed-failure-render.mjs";
18
18
  import { logEnvFileOperationWithType } from "./backend-env-resolver.mjs";
19
- import { runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
19
+ import { markMigrationSchemaLoadFailure, runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
20
20
  import { HINTS_DATA_LOSS_NOTICE, parseMigrationHintsArgs } from "./migration-hints.mjs";
21
21
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, error, info, log, success, warn } from "./output.mjs";
22
22
  import {
@@ -571,16 +571,20 @@ export function createDbCommands({
571
571
  logImpl(`\n${BOLD}${CYAN}Gencow DB Generate${RESET}\n`);
572
572
  infoImpl("Generating migration files from schema.ts...");
573
573
 
574
- runDrizzleGenerateWithFallback({
575
- cwd: cwdImpl(),
576
- drizzleKitCmdImpl,
577
- env: buildEnv(config),
578
- execSyncImpl,
579
- generatorArgs: hints.args,
580
- spawnSyncImpl,
581
- stdio: "inherit",
582
- warnImpl,
583
- });
574
+ try {
575
+ runDrizzleGenerateWithFallback({
576
+ cwd: cwdImpl(),
577
+ drizzleKitCmdImpl,
578
+ env: buildEnv(config),
579
+ execSyncImpl,
580
+ generatorArgs: hints.args,
581
+ spawnSyncImpl,
582
+ stdio: "inherit",
583
+ warnImpl,
584
+ });
585
+ } catch (error) {
586
+ throw markMigrationSchemaLoadFailure(error);
587
+ }
584
588
  successImpl("Migration files generated in gencow/migrations/");
585
589
  },
586
590
 
@@ -15,11 +15,14 @@ import { emitMigrationAdvisories, extractMigrationAdvisories } from "./migration
15
15
 
16
16
  const NO_CHANGE_MARKERS = ["No schema changes", "nothing to migrate", "No changes detected"];
17
17
 
18
- export function isNoChangeGenerationError(error) {
19
- const message = error?.stderr?.toString() || error?.message || "";
18
+ export function isNoChangeOutput(message) {
20
19
  return NO_CHANGE_MARKERS.some((marker) => message.includes(marker));
21
20
  }
22
21
 
22
+ export function isNoChangeGenerationError(error) {
23
+ return isNoChangeOutput(error?.stderr?.toString() || error?.message || "");
24
+ }
25
+
23
26
  // Resolves to true (typed "yes"), false (any other answer), or null when input
24
27
  // ended before an answer. Callers must treat null as a non-cancel failure.
25
28
  export async function promptDbPushConfirm(appId, createInterfaceImpl, plain = false) {
@@ -45,6 +45,7 @@ import {
45
45
  handleLocalMigrationCommand,
46
46
  handleMigrationStatus,
47
47
  isNoChangeGenerationError,
48
+ isNoChangeOutput,
48
49
  promptDbPushConfirm,
49
50
  } from "./db-migration-command-steps.mjs";
50
51
  import { resolveConfiguredSchemaPaths, resolveDrizzleSchemaPaths } from "./cli-schema-paths.mjs";
@@ -451,15 +452,27 @@ function createDbMigrationCommand(deps, command) {
451
452
  if (!jsonMode) deps.infoImpl("Generating schema migrations...");
452
453
  try {
453
454
  const generationEnv = deps.buildEnv(config, { cwd: deps.cwdImpl() });
455
+ let generatorOutput = "";
454
456
  generatorVersion = runDrizzleGenerateWithFallback({
455
457
  cwd: deps.cwdImpl(),
456
458
  drizzleKitCmdImpl: deps.drizzleKitCmdImpl,
457
459
  env: generationEnv,
458
460
  execSyncImpl: deps.execSyncImpl,
461
+ onOutput: (text) => {
462
+ generatorOutput += text;
463
+ },
459
464
  stdio: jsonMode ? "pipe" : "inherit",
460
465
  warnImpl: jsonMode ? () => {} : deps.warnImpl,
461
466
  });
462
- if (!jsonMode) deps.successImpl("Migrations generated");
467
+ if (!jsonMode) {
468
+ // drizzle-kit exits 0 with "No schema changes" when nothing new was generated;
469
+ // the committed pending migrations are still applied by this push.
470
+ if (isNoChangeOutput(generatorOutput)) {
471
+ deps.infoImpl("No new migration generated — applying committed pending migrations");
472
+ } else {
473
+ deps.successImpl("Migrations generated");
474
+ }
475
+ }
463
476
  } catch (error) {
464
477
  generatorVersion = error?.gencowGeneratorVersion || generatorVersion;
465
478
  if (isNoChangeGenerationError(error)) {
@@ -136,6 +136,8 @@ export function cloudTargetRejectionMessage(rejection, { fallbackMessage, ...opt
136
136
  explicitAppId: rejection.explicitAppId,
137
137
  rejection,
138
138
  ...options,
139
+ // A resolver that knows the exact next command (for example outside a project) overrides the caller's text.
140
+ ...(rejection.next ? { next: rejection.next } : {}),
139
141
  }).join("\n");
140
142
  }
141
143
 
@@ -6,7 +6,7 @@ import {
6
6
  selectAppDiagnosticLogLines,
7
7
  } from "./app-diagnostics.mjs";
8
8
  import { appNotFoundDiagnostic, parseAppLookupResponse } from "./app-response-contract.mjs";
9
- import { resolveCloudAppTarget } from "./cloud-targets.mjs";
9
+ import { resolveCloudAppTargetWithServerEnvironment } from "./cloud-target-environment.mjs";
10
10
  import { cloudTargetRejectionMessage, prodRetryCommandLine } from "./deploy-app-target.mjs";
11
11
  import { readJsonValueResponse } from "./http-response-json.mjs";
12
12
  import { renderDeployFailureDiagnosticLines } from "./deploy-failure-diagnostic.mjs";
@@ -151,8 +151,12 @@ export async function handleDeployReadonlySubcommand(params) {
151
151
  const targetArgs = deployArgs
152
152
  .slice(1)
153
153
  .filter((arg, index, list) => arg !== "--release-attempt" && list[index - 1] !== "--release-attempt");
154
- const target = resolveCloudAppTarget(targetArgs, {
154
+ const target = await resolveCloudAppTargetWithServerEnvironment(targetArgs, {
155
155
  cwd,
156
+ creds,
157
+ rpcQueryImpl,
158
+ stage: "deploy target resolution",
159
+ command: "deploy status",
156
160
  missingAppMessage: "App not found. Run from the project root with gencow.json.",
157
161
  missingProdMessage: "No prod app yet. Run gencow deploy --prod first.",
158
162
  });
@@ -235,8 +239,12 @@ export async function handleDeployReadonlySubcommand(params) {
235
239
  logDeploymentOperationStatus(logImpl, infoImpl, body);
236
240
  return true;
237
241
  }
238
- const target = resolveCloudAppTarget(deployArgs.slice(1), {
242
+ const target = await resolveCloudAppTargetWithServerEnvironment(deployArgs.slice(1), {
239
243
  cwd,
244
+ creds,
245
+ rpcQueryImpl,
246
+ stage: "deploy target resolution",
247
+ command: `deploy ${subcmd}`,
240
248
  missingAppMessage: "App not found. Run from the project root with gencow.json.",
241
249
  missingProdMessage: "No prod app yet. Run gencow deploy --prod first.",
242
250
  });
@@ -109,7 +109,7 @@ export async function ensureProductionDeployTarget({
109
109
  logImpl(` ${GREEN}gencow upgrade${RESET} ${DIM}← Upgrade to Startup${RESET}`);
110
110
  logImpl("");
111
111
  } else {
112
- errorImpl(prodCreateFailureMessage(errData, createProdRes));
112
+ errorImpl(prodCreateFailureMessage(errData, createProdRes, { requestedRegion: region }));
113
113
  }
114
114
  exitImpl(1);
115
115
  return null;
@@ -9,6 +9,7 @@ import {
9
9
  createMigrationHintsRequiredError,
10
10
  MIGRATION_HINTS_REQUIRED,
11
11
  } from "./migration-hints.mjs";
12
+ import { classifySchemaLoadFailure } from "./migration-schema-load-failure.mjs";
12
13
 
13
14
  export const SUPPORTED_DRIZZLE_KIT_GENERATOR_VERSION = SUPPORTED_MIGRATION_GENERATOR_VERSION;
14
15
  export const UNKNOWN_DRIZZLE_KIT_GENERATOR_VERSION = "unknown";
@@ -136,6 +137,21 @@ function getMissingHintsFailure(error) {
136
137
  return classifyMissingHintsOutput(rawGeneratorOutput(error));
137
138
  }
138
139
 
140
+ // db:generate only. Runs after the hints and folder-format judgments, so an error that already
141
+ // carries a code keeps it. Other callers keep the generic path they had before.
142
+ export function markMigrationSchemaLoadFailure(error) {
143
+ if (!error || typeof error !== "object" || error.code) return error;
144
+ const schemaFailure = classifySchemaLoadFailure(rawGeneratorOutput(error));
145
+ if (!schemaFailure) return error;
146
+ try {
147
+ error.code = "MIGRATION_GENERATION_FAILED";
148
+ error.migrationSchemaFailure = schemaFailure;
149
+ } catch {
150
+ /* keep the raw generator error; the schema-load code is then unavailable */
151
+ }
152
+ return error;
153
+ }
154
+
139
155
  export function buildMigrationGenerationError(error) {
140
156
  if (error?.code === MIGRATION_HINTS_REQUIRED && error.migrationHints) {
141
157
  return createMigrationHintsRequiredError(error.migrationHints);
@@ -166,6 +182,7 @@ export function runDrizzleGenerateWithFallback({
166
182
  env = {},
167
183
  execSyncImpl,
168
184
  generatorArgs = [],
185
+ onOutput,
169
186
  spawnSyncImpl = spawnSync,
170
187
  stderrWriteImpl = (value) => process.stderr.write(value),
171
188
  stdio = "inherit",
@@ -199,6 +216,8 @@ export function runDrizzleGenerateWithFallback({
199
216
  });
200
217
  throw failure;
201
218
  }
219
+ // Successful runs can still report "No schema changes"; expose that output to callers.
220
+ onOutput?.(`${rawStdout}\n${rawStderr}`);
202
221
  if (stdio === "inherit") {
203
222
  const stdout = sanitizeDrizzleGeneratorOutput(rawStdout, { cwd });
204
223
  const stderr = sanitizeDrizzleGeneratorOutput(rawStderr, { cwd });
@@ -6,10 +6,10 @@ import {
6
6
  resolveBackendEnvFile,
7
7
  resolveExplicitEnvFile,
8
8
  } from "./backend-env-resolver.mjs";
9
- import { resolveCloudAppTarget } from "./cloud-targets.mjs";
9
+ import { resolveCloudAppTargetWithServerEnvironment } from "./cloud-target-environment.mjs";
10
10
  import { cloudTargetRejectionMessage, prodRetryCommandLine, redactConfigSetValue, redactEnvPairs } from "./deploy-app-target.mjs";
11
11
  import { BOLD, CYAN, DIM, GREEN, RESET, error, info, log, success, warn } from "./output.mjs";
12
- import { platformFetch, requireCreds } from "./platform-client.mjs";
12
+ import { platformFetch, requireCreds, rpcQuery } from "./platform-client.mjs";
13
13
 
14
14
  const ENV_RESPONSE_UNREADABLE_CODE = "ENV_RESPONSE_UNREADABLE";
15
15
 
@@ -141,7 +141,8 @@ export function createEnvCommand(deps = {}) {
141
141
  const cwdImpl = deps.cwdImpl ?? (() => process.cwd());
142
142
  const loadConfigImpl = deps.loadConfig ?? (async () => ({ rootDir: "./gencow", envFile: "./gencow/.env" }));
143
143
  const readFileSyncImpl = deps.readFileSync ?? readFileSync;
144
- const resolveAppTargetImpl = deps.resolveCloudAppTarget ?? resolveCloudAppTarget;
144
+ const resolveAppTargetImpl = deps.resolveCloudAppTarget ?? resolveCloudAppTargetWithServerEnvironment;
145
+ const rpcQueryImpl = deps.rpcQuery ?? rpcQuery;
145
146
  const resolvePathImpl = deps.resolvePathImpl ?? resolve;
146
147
  const sleepImpl = deps.sleep ?? ((ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)));
147
148
  const projectionPollAttempts = deps.projectionPollAttempts ?? 40;
@@ -255,7 +256,11 @@ export function createEnvCommand(deps = {}) {
255
256
  return;
256
257
  }
257
258
  const creds = requireCredsImpl();
258
- const target = resolveAppTargetImpl(restArgs, {
259
+ const target = await resolveAppTargetImpl(restArgs, {
260
+ creds,
261
+ rpcQueryImpl,
262
+ stage: "env target resolution",
263
+ command: `env ${subcmd}`,
259
264
  missingAppMessage: "App ID not found. Run gencow deploy first.",
260
265
  missingProdMessage: "No prod app yet. Run gencow deploy --prod first.",
261
266
  });
@@ -1,5 +1,7 @@
1
1
  const ADVISORY_SUMMARIES = Object.freeze({
2
2
  MIGRATION_POTENTIAL_DATA_LOSS: "The pending migration may remove tenant data.",
3
+ MIGRATION_NOT_NULL_NO_DEFAULT_RISK:
4
+ "ADD COLUMN … NOT NULL without a DEFAULT fails if the table already has rows. Make the column nullable, add a DEFAULT, or use expand → backfill → contract.",
3
5
  MIGRATION_LOCK_RISK: "The pending migration may take a blocking PostgreSQL lock.",
4
6
  MIGRATION_COMPATIBILITY_RISK: "Coordinate this schema change with application rollout compatibility.",
5
7
  MIGRATION_BACKUP_NOT_CREATED:
@@ -3,6 +3,15 @@ import { readFileSync, realpathSync } from "node:fs";
3
3
  import { relative, resolve, sep } from "node:path";
4
4
  import { escapeTerminalControls, safeDiagnosticText } from "./migration-diagnostic-contract.mjs";
5
5
  import { formatLatestCliInvocation } from "./cli-update-guidance.mjs";
6
+ import {
7
+ UNLOCATED_ROLLBACK_DETAIL,
8
+ UNLOCATED_ROLLBACK_RETRY_CONDITION,
9
+ UNLOCATED_ROLLBACK_SUMMARY,
10
+ isUserFixableRolledBackDiagnostic,
11
+ renderRollbackCauseLine,
12
+ renderUnlocatedRollbackFix,
13
+ renderUnlocatedRollbackLocation,
14
+ } from "./migration-rollback-cause.mjs";
6
15
 
7
16
  export {
8
17
  extractActionableMigrationDiagnostic,
@@ -320,6 +329,12 @@ export function renderMigrationDiagnosticLines(diagnostic) {
320
329
  lines.push(`Correlation: ${diagnostic.correlationId}`);
321
330
  return lines.map((line) => escapeTerminalControls(line));
322
331
  }
332
+ // Without a verified local span, the server's "exact statement" wording would overclaim.
333
+ const unlocatedRollback =
334
+ isUserFixableRolledBackDiagnostic(diagnostic) && !diagnostic.localSource?.projectRelativePath;
335
+ const retryCondition = unlocatedRollback
336
+ ? UNLOCATED_ROLLBACK_RETRY_CONDITION
337
+ : diagnostic.retryCondition;
323
338
  const lines = [
324
339
  migrationDiagnosticTitle(diagnostic),
325
340
  "",
@@ -327,7 +342,7 @@ export function renderMigrationDiagnosticLines(diagnostic) {
327
342
  `Phase: ${diagnostic.phase}`,
328
343
  `Database state: ${diagnostic.databaseState}`,
329
344
  `Safe to retry now: ${diagnostic.safeToRetryNow ? "YES" : "NO"}`,
330
- `Retry policy: ${diagnostic.retryPolicy}${diagnostic.retryCondition ? ` — ${diagnostic.retryCondition}` : ""}`,
345
+ `Retry policy: ${diagnostic.retryPolicy}${retryCondition ? ` — ${retryCondition}` : ""}`,
331
346
  ];
332
347
  const source = diagnostic.localSource;
333
348
  if (source?.projectRelativePath) {
@@ -342,6 +357,10 @@ export function renderMigrationDiagnosticLines(diagnostic) {
342
357
  } else if (diagnostic.migration?.name) {
343
358
  lines.push("", `Migration: ${diagnostic.migration.name}`);
344
359
  }
360
+ if (unlocatedRollback) {
361
+ if (diagnostic.migration?.name) lines.push(renderUnlocatedRollbackLocation(diagnostic));
362
+ else lines.push("", renderUnlocatedRollbackLocation(diagnostic));
363
+ }
345
364
  if (diagnostic.operation?.kind) {
346
365
  lines.push(
347
366
  `Operation: ${diagnostic.operation.kind}${diagnostic.operation.objectName ? ` ${diagnostic.operation.objectName}` : ""}`,
@@ -349,12 +368,20 @@ export function renderMigrationDiagnosticLines(diagnostic) {
349
368
  }
350
369
  if (diagnostic.receiptId) lines.push(`Receipt: ${diagnostic.receiptId}`);
351
370
  if (diagnostic.statusLookup?.code) lines.push(`Status lookup: ${diagnostic.statusLookup.code}`);
352
- lines.push("", "Why this failed:", ` ${diagnostic.reason.summary}`, ` ${diagnostic.reason.detail}`);
353
- if (diagnostic.suggestedFixes?.length > 0) {
371
+ const causeLine = renderRollbackCauseLine(diagnostic);
372
+ if (causeLine) lines.push("", causeLine);
373
+ lines.push(
374
+ "",
375
+ "Why this failed:",
376
+ ` ${unlocatedRollback ? UNLOCATED_ROLLBACK_SUMMARY : diagnostic.reason.summary}`,
377
+ ` ${unlocatedRollback ? UNLOCATED_ROLLBACK_DETAIL : diagnostic.reason.detail}`,
378
+ );
379
+ const fixes = unlocatedRollback
380
+ ? [renderUnlocatedRollbackFix(diagnostic)]
381
+ : (diagnostic.suggestedFixes ?? []);
382
+ if (fixes.length > 0) {
354
383
  lines.push("", "Possible fixes:");
355
- diagnostic.suggestedFixes.forEach((fix, index) =>
356
- lines.push(` ${index + 1}. ${fix.title}`, ` ${fix.detail}`),
357
- );
384
+ fixes.forEach((fix, index) => lines.push(` ${index + 1}. ${fix.title}`, ` ${fix.detail}`));
358
385
  }
359
386
  if (shouldRenderForbiddenActions(diagnostic) && diagnostic.forbiddenActions?.length > 0) {
360
387
  lines.push("", "Do not:");
@@ -0,0 +1,75 @@
1
+ // Plain-language one-liners for the PostgreSQL reason codes the Platform already
2
+ // classifies as user-fixable (migration-execution-outcome.ts). Only static text is
3
+ // printed here; the server never sends SQL, row values, or parameters for these codes.
4
+ const USER_FIXABLE_CAUSES = new Map([
5
+ ["string_data_right_truncation", "a value is longer than its column type allows"],
6
+ ["invalid_text_representation", "a value does not match the column's data type"],
7
+ ["active_sql_transaction", "the statement cannot run inside a transaction block"],
8
+ [
9
+ "not_null_violation",
10
+ "a NOT NULL constraint rejected the statement (a populated table needs a DEFAULT or a nullable column)",
11
+ ],
12
+ ["foreign_key_violation", "a foreign key constraint rejected existing or new rows"],
13
+ ["unique_violation", "a UNIQUE constraint rejected rows with duplicate values"],
14
+ ["syntax_error", "PostgreSQL could not parse the statement"],
15
+ ["duplicate_column", "the column already exists"],
16
+ ["undefined_column", "the statement references a column that does not exist"],
17
+ ["undefined_table", "the statement references a table that does not exist"],
18
+ ["duplicate_table", "the table already exists"],
19
+ ]);
20
+
21
+ // Extra guidance for causes whose generic repair advice needs a specific hint.
22
+ const NOT_NULL_REPAIR_HINT =
23
+ "For a NOT NULL failure, give the new column a DEFAULT or make it nullable, or split the change into forward migrations (expand → backfill → contract).";
24
+
25
+ const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
26
+
27
+ export function isUserFixableRolledBackDiagnostic(diagnostic) {
28
+ return (
29
+ diagnostic?.code === "MIGRATION_TRANSACTION_ROLLED_BACK" &&
30
+ diagnostic.databaseState === "ROLLED_BACK" &&
31
+ diagnostic.failureClass === "USER_FIXABLE"
32
+ );
33
+ }
34
+
35
+ export function safeRollbackReasonCode(diagnostic) {
36
+ const code = diagnostic?.reason?.code;
37
+ return typeof code === "string" && SAFE_REASON_CODE.test(code) ? code : null;
38
+ }
39
+
40
+ // Returns the "Cause:" line for a user-fixable rollback, or null when no safe code exists.
41
+ export function renderRollbackCauseLine(diagnostic) {
42
+ if (!isUserFixableRolledBackDiagnostic(diagnostic)) return null;
43
+ const code = safeRollbackReasonCode(diagnostic);
44
+ if (!code) return null;
45
+ const cause = USER_FIXABLE_CAUSES.get(code);
46
+ return cause ? `Cause: ${code} — ${cause}` : `Cause: ${code}`;
47
+ }
48
+
49
+ // Honest replacement for the server's "exact statement" wording when the CLI could not
50
+ // verify a local source span. Only the already-safe migration name is shown.
51
+ export function renderUnlocatedRollbackFix(diagnostic) {
52
+ const name = diagnostic?.migration?.name;
53
+ const code = safeRollbackReasonCode(diagnostic);
54
+ const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : "";
55
+ return {
56
+ title: name
57
+ ? `Inspect the unapplied migration file ${name}`
58
+ : "Inspect the pending migrations listed by db:check",
59
+ detail: `Repair only the unapplied migration source for the cause above, review the generated diff, and create a fresh plan. Applied migrations and the journal are not edited.${hint}`,
60
+ };
61
+ }
62
+
63
+ export function renderUnlocatedRollbackLocation(diagnostic) {
64
+ const name = diagnostic?.migration?.name;
65
+ return name
66
+ ? `Statement location: unavailable — inspect the unapplied migration file ${name}`
67
+ : "Statement location: unavailable — inspect the pending migrations listed by db:check";
68
+ }
69
+
70
+ export const UNLOCATED_ROLLBACK_SUMMARY =
71
+ "PostgreSQL rejected a pending migration statement and rolled back the transaction.";
72
+ export const UNLOCATED_ROLLBACK_RETRY_CONDITION =
73
+ "Fix only the unapplied migration source for the cause above, then create and check a fresh plan.";
74
+ export const UNLOCATED_ROLLBACK_DETAIL =
75
+ "The failed transaction did not commit any migration or journal change.";
@@ -0,0 +1,31 @@
1
+ // Single judgment for a db:generate failure where drizzle-kit throws a JavaScript runtime
2
+ // error AND its output names schema.ts. A runtime error alone is not enough: tooling and
3
+ // environment errors (for example `require is not defined` or `fetch failed`) also surface
4
+ // as TypeError/ReferenceError. Without the schema context those stay on the raw fallback.
5
+ // The construct inside schema.ts is still unknown, so the copy never confirms a cause.
6
+ const RUNTIME_ERROR_PATTERNS = Object.freeze([
7
+ /^\s*(?:TypeError|ReferenceError):\s/mu,
8
+ /\bCannot read properties of (?:undefined|null) \(reading '/u,
9
+ ]);
10
+ // Matched against the raw output, because the sanitized text replaces paths and loses the file name.
11
+ const SCHEMA_CONTEXT_PATTERN = /\bschema(?:-auth)?(?:\.gen)?\.[cm]?[jt]sx?\b/u;
12
+
13
+ export const SCHEMA_LOAD_FAILED_REASON_CODE = "schema_load_failed";
14
+
15
+ // Returns { reasonCode } when the output is a runtime error that names the schema, otherwise null.
16
+ export function classifySchemaLoadFailure(rawMessage) {
17
+ const message = String(rawMessage ?? "");
18
+ if (!RUNTIME_ERROR_PATTERNS.some((pattern) => pattern.test(message))) return null;
19
+ if (!SCHEMA_CONTEXT_PATTERN.test(message)) return null;
20
+ return Object.freeze({ reasonCode: SCHEMA_LOAD_FAILED_REASON_CODE });
21
+ }
22
+
23
+ // The raw generator text is never printed; only these fixed sentences reach the user.
24
+ export const SCHEMA_LOAD_FAILURE_CLI_MESSAGE =
25
+ "Migration generation stopped: drizzle-kit failed while generating migrations (possibly while loading your schema), so no migration file was generated.";
26
+
27
+ export const SCHEMA_LOAD_FAILURE_CAUSE_HINT =
28
+ "Possible cause (not confirmed): a table callback (the third argument of pgTable) returns an entry that is not an index, policy, or constraint. If a policy helper returns an array, spread it into the returned array with `...`. The tooling or environment may also be the cause.";
29
+
30
+ export const SCHEMA_LOAD_FAILURE_CLI_ACTION =
31
+ "Retryable: no — check the schema source (schema.ts) and the local tooling or environment, then rerun `gencow db:generate`.";
@@ -1,11 +1,19 @@
1
1
  import { appResponseError } from "./app-response-error.mjs";
2
+ import {
3
+ formatRegionUnavailableMessage,
4
+ readRegionUnavailableDiagnostic,
5
+ } from "./prod-create-region-diagnostic.mjs";
2
6
 
3
7
  /** One rendering of a failed `create-prod` response for every CLI deploy path. */
4
- export function prodCreateFailureMessage(errData, response) {
8
+ export function prodCreateFailureMessage(errData, response, options = {}) {
5
9
  const fallback =
6
10
  response.status === 503
7
11
  ? "Prod app creation is temporarily unavailable."
8
12
  : errData?.error || response.statusText || `HTTP ${response.status}`;
13
+ const regionDiagnostic = readRegionUnavailableDiagnostic(errData, response);
14
+ if (regionDiagnostic) {
15
+ return formatRegionUnavailableMessage(regionDiagnostic, fallback, options.requestedRegion ?? null);
16
+ }
9
17
  return [
10
18
  `Prod app creation failed: ${appResponseError(errData, fallback, response)}`,
11
19
  "Retry: run the same command again; if another gencow command is creating this app, wait for it to finish first.",