gencow 0.1.268 → 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,15 @@
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";
8
+ import {
9
+ buildHintsRequiredCommand,
10
+ HINTS_DATA_LOSS_NOTICE,
11
+ SAFE_COLUMN_REFERENCE,
12
+ } from "./migration-hints.mjs";
3
13
 
4
14
  const SAFE_CORRELATION_ID = /^[A-Za-z0-9_-]{8,128}$/u;
5
15
  const SAFE_APP_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
@@ -38,12 +48,17 @@ const SAFE_LOCAL_ERROR_CODES = new Map([
38
48
  message: (caught) =>
39
49
  caught.migrationFolderFormat
40
50
  ? describeMigrationFolderFormatFailure(caught.migrationFolderFormat).cliMessage
41
- : "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.",
42
54
  stage: "migration",
55
+ detail: (caught) => (caught.migrationSchemaFailure ? SCHEMA_LOAD_FAILURE_CAUSE_HINT : null),
43
56
  action: (caught) =>
44
57
  caught.migrationFolderFormat
45
58
  ? describeMigrationFolderFormatFailure(caught.migrationFolderFormat).cliAction
46
- : "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.",
47
62
  },
48
63
  ],
49
64
  [
@@ -166,8 +181,61 @@ const SAFE_LOCAL_ERROR_CODES = new Map([
166
181
  },
167
182
  },
168
183
  ],
184
+ [
185
+ "MIGRATION_HINTS_REQUIRED",
186
+ {
187
+ message: (caught) => {
188
+ const count = safeHintCount(caught);
189
+ const columns = safeHintColumns(caught);
190
+ if (columns.length === 0) {
191
+ return `Migration generation stopped: ${count} schema change(s) need your decision.`;
192
+ }
193
+ return `Migration generation stopped: ${count} column change(s) need your decision (${columns.join(", ")}).`;
194
+ },
195
+ stage: "migration",
196
+ action: (caught) => {
197
+ const example = `\`${buildHintsRequiredCommand(safeHintColumns(caught))}\``;
198
+ const createExample = `{"type":"create",...} to add a new column instead`;
199
+ const tail = `${HINTS_DATA_LOSS_NOTICE} Do not edit applied migration files.`;
200
+ if (caught.migrationHints?.hintsProvided) {
201
+ return `Retryable: yes, after your --hints array decides every listed column change — rerun with one rename or create decision per column, for example ${example}, or use ${createExample}. ${tail}`;
202
+ }
203
+ return `Retryable: yes, after you declare the decision — rerun ${example} (or use ${createExample}). ${tail}`;
204
+ },
205
+ },
206
+ ],
207
+ [
208
+ "MIGRATION_HINTS_INVALID",
209
+ {
210
+ message: (caught) => {
211
+ const source = caught.hintsSource === "file" ? "--hints-file" : "--hints";
212
+ const reasons = {
213
+ conflicting_options: "use only one of --hints or --hints-file.",
214
+ value_missing: `${source} needs a value.`,
215
+ json_invalid: `${source} value is not valid JSON.`,
216
+ not_array: `${source} must be a JSON array of decisions.`,
217
+ too_large: `${source} value is too large.`,
218
+ file_unreadable: "the --hints-file could not be read.",
219
+ };
220
+ return `Migration generation not started: ${reasons[caught.hintsReason] ?? "the hints value is not accepted."}`;
221
+ },
222
+ stage: "input",
223
+ action:
224
+ "Retryable: yes, after the hints value is fixed — pass a JSON array with `--hints '<json-array>'` or a JSON file with `--hints-file <path>`, then rerun `npx gencow@latest db:generate`.",
225
+ },
226
+ ],
169
227
  ]);
170
228
 
229
+ function safeHintCount(caught) {
230
+ const count = caught.migrationHints?.count;
231
+ return Number.isInteger(count) && count > 0 && count <= 9999 ? count : 1;
232
+ }
233
+
234
+ function safeHintColumns(caught) {
235
+ const columns = caught.migrationHints?.columns;
236
+ return Array.isArray(columns) ? columns.filter((value) => typeof value === "string" && SAFE_COLUMN_REFERENCE.test(value)) : [];
237
+ }
238
+
171
239
  function safeDisplayDir(caught) {
172
240
  const { displayDir } = caught;
173
241
  return typeof displayDir === "string" && SAFE_DISPLAY_DIR.test(displayDir) ? displayDir : null;
@@ -219,6 +287,9 @@ function commandErrorMessage(caught) {
219
287
  `Code: ${caught.code}`,
220
288
  `Stage: ${localDiagnostic.stage}`,
221
289
  ];
290
+ const detail =
291
+ typeof localDiagnostic.detail === "function" ? localDiagnostic.detail(caught) : localDiagnostic.detail;
292
+ if (detail) lines.push(detail);
222
293
  const location = safeSourceLocation(caught);
223
294
  if (location) lines.push(`${localDiagnostic.locationLabel ?? "Source location"}: ${location}`);
224
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
  }
@@ -14,8 +14,10 @@ import {
14
14
  import { dirname, resolve } from "path";
15
15
  import { tmpdir } from "os";
16
16
  import { createDbCheckCommand, createDbPushCommand } from "./db-push-command.mjs";
17
+ import { renderMaintenanceFailure } from "./db-seed-failure-render.mjs";
17
18
  import { logEnvFileOperationWithType } from "./backend-env-resolver.mjs";
18
- import { runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
19
+ import { markMigrationSchemaLoadFailure, runDrizzleGenerateWithFallback } from "./drizzle-generate.mjs";
20
+ import { HINTS_DATA_LOSS_NOTICE, parseMigrationHintsArgs } from "./migration-hints.mjs";
19
21
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, error, info, log, success, warn } from "./output.mjs";
20
22
  import {
21
23
  describeProdTargetFailure,
@@ -150,8 +152,17 @@ function renderDbCheckHelp(logImpl = log) {
150
152
 
151
153
  function renderDbGenerateHelp(logImpl = log) {
152
154
  logImpl(`\n${BOLD}${CYAN}gencow db:generate${RESET} — Generate SQL migration files\n`);
153
- logImpl(` ${BOLD}Usage:${RESET} gencow db:generate\n`);
155
+ logImpl(` ${BOLD}Usage:${RESET} gencow db:generate [--hints '<json-array>' | --hints-file <path>]\n`);
154
156
  logImpl(` Generates migration files from schema.ts using drizzle-kit.\n`);
157
+ logImpl(` ${BOLD}Options:${RESET}`);
158
+ logImpl(` --hints '<json-array>' Decide each changed column: rename or create.`);
159
+ logImpl(` --hints-file <path> Same decisions, read from a JSON array file.\n`);
160
+ logImpl(` Example (rename column label to tag in table files):`);
161
+ logImpl(
162
+ ` gencow db:generate --hints '[{"type":"rename","kind":"column","from":["public","files","label"],"to":["public","files","tag"]}]'\n`,
163
+ );
164
+ logImpl(` Use only one of --hints or --hints-file. Hints are never inferred automatically.`);
165
+ logImpl(` ${HINTS_DATA_LOSS_NOTICE}\n`);
155
166
  }
156
167
 
157
168
  function renderLocalSeedMissingFile({ infoImpl = info, logImpl = log, warnImpl = warn } = {}) {
@@ -200,6 +211,7 @@ export function createDbCommands({
200
211
  resolvePathImpl = resolve,
201
212
  rmSyncImpl = rmSync,
202
213
  runInServer,
214
+ spawnSyncImpl,
203
215
  statSyncImpl = statSync,
204
216
  successImpl = success,
205
217
  tarCreateImpl,
@@ -296,12 +308,23 @@ export function createDbCommands({
296
308
  headers: { "Content-Type": "application/json" },
297
309
  body: JSON.stringify({ confirm: "delete all data" }),
298
310
  });
299
- const data = await res.json();
311
+ const data = await res.json().catch(() => null);
312
+ if (data === null) {
313
+ errorImpl("Server connection failed: the server response could not be read.");
314
+ logImpl("");
315
+ return 1;
316
+ }
300
317
 
301
318
  if (!res.ok) {
302
- errorImpl(`Reset failed: ${data.error || "Unknown error"}`);
319
+ renderMaintenanceFailure(data, res.status, {
320
+ errorImpl,
321
+ infoImpl,
322
+ label: "Reset failed",
323
+ retryCommand: "gencow db:reset",
324
+ impactNote: "verify which tables still contain data before rerunning",
325
+ });
303
326
  logImpl("");
304
- return;
327
+ return 1;
305
328
  }
306
329
 
307
330
  successImpl(`TRUNCATE done: ${data.truncated?.length || 0} tables`);
@@ -315,6 +338,8 @@ export function createDbCommands({
315
338
  }
316
339
  } catch (e) {
317
340
  errorImpl(`Server connection failed: ${e.message}`);
341
+ logImpl("");
342
+ return 1;
318
343
  }
319
344
  } else {
320
345
  const dbPath = resolvePathImpl(cwd, config.db.url);
@@ -442,13 +467,18 @@ export function createDbCommands({
442
467
  headers: { "Content-Type": "application/json" },
443
468
  signal: AbortSignal.timeout(30000),
444
469
  });
445
- const data = await res.json();
470
+ const data = await res.json().catch(() => null);
471
+ if (data === null) {
472
+ errorImpl("Cloud app connection failed: the platform response could not be read.");
473
+ infoImpl(`${DIM}Check if the platform is reachable: ${targetCreds.platformUrl}${RESET}`);
474
+ return 1;
475
+ }
446
476
 
447
477
  if (res.status === 404 && String(data.error || "").includes("seed.ts")) {
448
478
  renderCloudSeedMissingFile({ infoImpl, logImpl, warnImpl });
449
479
  return 1;
450
480
  } else if (!res.ok) {
451
- errorImpl(`Cloud seed failed: ${data.error || "Unknown error"}`);
481
+ renderMaintenanceFailure(data, res.status, { errorImpl, infoImpl });
452
482
  return 1;
453
483
  } else {
454
484
  successImpl("Cloud seed completed ✓");
@@ -531,18 +561,30 @@ export function createDbCommands({
531
561
  return;
532
562
  }
533
563
 
564
+ // Hints are validated before the config is read or the generator starts.
565
+ const hints = parseMigrationHintsArgs(args, {
566
+ cwd: cwdImpl(),
567
+ readFileSyncImpl,
568
+ resolvePathImpl,
569
+ });
534
570
  const config = await loadConfig();
535
571
  logImpl(`\n${BOLD}${CYAN}Gencow DB Generate${RESET}\n`);
536
572
  infoImpl("Generating migration files from schema.ts...");
537
573
 
538
- runDrizzleGenerateWithFallback({
539
- cwd: cwdImpl(),
540
- drizzleKitCmdImpl,
541
- env: buildEnv(config),
542
- execSyncImpl,
543
- stdio: "inherit",
544
- warnImpl,
545
- });
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
+ }
546
588
  successImpl("Migration files generated in gencow/migrations/");
547
589
  },
548
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) {
@@ -28,7 +28,9 @@ import {
28
28
  buildClientPreflightFailureDiagnostic,
29
29
  buildClientUserFixableDiagnostic,
30
30
  buildMigrationFolderFormatDiagnostic,
31
+ buildMigrationHintsRequiredDiagnostic,
31
32
  } from "./migration-client-diagnostic.mjs";
33
+ import { MIGRATION_HINTS_REQUIRED } from "./migration-hints.mjs";
32
34
  import { detectConflictingAuthSchemaFiles, formatAuthSchemaConflictMessage } from "./codegen-command.mjs";
33
35
  import { BOLD, CYAN, DIM, RESET } from "./output.mjs";
34
36
  import { stageMigrationBundleArchive } from "./migration-bundle-staging.mjs";
@@ -43,6 +45,7 @@ import {
43
45
  handleLocalMigrationCommand,
44
46
  handleMigrationStatus,
45
47
  isNoChangeGenerationError,
48
+ isNoChangeOutput,
46
49
  promptDbPushConfirm,
47
50
  } from "./db-migration-command-steps.mjs";
48
51
  import { resolveConfiguredSchemaPaths, resolveDrizzleSchemaPaths } from "./cli-schema-paths.mjs";
@@ -449,15 +452,27 @@ function createDbMigrationCommand(deps, command) {
449
452
  if (!jsonMode) deps.infoImpl("Generating schema migrations...");
450
453
  try {
451
454
  const generationEnv = deps.buildEnv(config, { cwd: deps.cwdImpl() });
455
+ let generatorOutput = "";
452
456
  generatorVersion = runDrizzleGenerateWithFallback({
453
457
  cwd: deps.cwdImpl(),
454
458
  drizzleKitCmdImpl: deps.drizzleKitCmdImpl,
455
459
  env: generationEnv,
456
460
  execSyncImpl: deps.execSyncImpl,
461
+ onOutput: (text) => {
462
+ generatorOutput += text;
463
+ },
457
464
  stdio: jsonMode ? "pipe" : "inherit",
458
465
  warnImpl: jsonMode ? () => {} : deps.warnImpl,
459
466
  });
460
- 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
+ }
461
476
  } catch (error) {
462
477
  generatorVersion = error?.gencowGeneratorVersion || generatorVersion;
463
478
  if (isNoChangeGenerationError(error)) {
@@ -468,7 +483,9 @@ function createDbMigrationCommand(deps, command) {
468
483
  emitFailure(
469
484
  folderFormat
470
485
  ? buildMigrationFolderFormatDiagnostic(folderFormat, clientCorrelationId())
471
- : buildClientUserFixableDiagnostic("MIGRATION_GENERATION_FAILED", clientCorrelationId()),
486
+ : error?.code === MIGRATION_HINTS_REQUIRED
487
+ ? buildMigrationHintsRequiredDiagnostic(error.migrationHints, clientCorrelationId())
488
+ : buildClientUserFixableDiagnostic("MIGRATION_GENERATION_FAILED", clientCorrelationId()),
472
489
  );
473
490
  return;
474
491
  }
@@ -0,0 +1,84 @@
1
+ import { DIM, RESET } from "./output.mjs";
2
+
3
+ const TYPED_CODE_PATTERN = /^(SEED|RESET)_[A-Z_]+$/;
4
+ const UNAUTHORIZED_TEXT = "Seed request was not authorized for this app.";
5
+ const UNEXPECTED_TEXT = "the platform returned an unexpected response.";
6
+ const GENERIC_NEXT_ACTION = "Verify the app state, then rerun";
7
+ const PLAIN_TEXT_LIMIT = 400;
8
+
9
+ // Exact platform messages from packages/platform/gencow/apps-seed-handler.ts and apps-account-hold.ts.
10
+ // Any other untyped text is never printed, even when it looks harmless.
11
+ const KNOWN_PLATFORM_MESSAGES = new Set([
12
+ "App not found or not owned by you",
13
+ "Static-only app has no backend to seed",
14
+ "App is frozen — thaw before seed",
15
+ "App is locked because the owner account is suspended.",
16
+ "App is locked because the owner account is pending deletion.",
17
+ "App is locked because the owner account is deleted.",
18
+ ]);
19
+ const KNOWN_NOT_RUNNING_PATTERN = /^Cloud app "[^"\n]{1,128}" is not running$/;
20
+
21
+ // Typed text is rebuilt from the server catalog by the platform. This screen only blocks SQL-shaped text
22
+ // that a tampered or future body could carry, because the CLI does not import the catalog.
23
+ const SQL_SHAPED_PATTERN =
24
+ /Failed query|params:|\b(select|insert|update|delete|truncate|from|into|values|where)\b|\$\d/i;
25
+
26
+ export function isTypedMaintenanceFailure(data) {
27
+ return (
28
+ data !== null &&
29
+ typeof data === "object" &&
30
+ typeof data.code === "string" &&
31
+ TYPED_CODE_PATTERN.test(data.code)
32
+ );
33
+ }
34
+
35
+ function typedText(value, fallback) {
36
+ if (typeof value !== "string" || value.trim() === "" || value.length > PLAIN_TEXT_LIMIT) return fallback;
37
+ return SQL_SHAPED_PATTERN.test(value) ? fallback : value;
38
+ }
39
+
40
+ function isKnownPlatformMessage(text) {
41
+ return KNOWN_PLATFORM_MESSAGES.has(text) || KNOWN_NOT_RUNNING_PATTERN.test(text);
42
+ }
43
+
44
+ /**
45
+ * Renders a failed db:seed or db:reset response. The label and retry command name the operation.
46
+ * - Typed platform failures show the code, stage, data impact, retry condition, next action and correlation ID.
47
+ * - Untyped responses print only a fixed sentence per status, or an exact known platform message.
48
+ * Everything else, including raw database text, is replaced by the generic sentence.
49
+ */
50
+ export function renderMaintenanceFailure(
51
+ data,
52
+ status,
53
+ { errorImpl, infoImpl, label = "Cloud seed failed", retryCommand = "gencow db:seed --prod", impactNote },
54
+ ) {
55
+ if (!isTypedMaintenanceFailure(data)) {
56
+ const text = typeof data?.error === "string" ? data.error : "";
57
+ if (status === 401 || status === 403) {
58
+ errorImpl(`${label}: ${UNAUTHORIZED_TEXT}`);
59
+ return;
60
+ }
61
+ if (isKnownPlatformMessage(text)) {
62
+ errorImpl(`${label}: ${text}`);
63
+ return;
64
+ }
65
+ errorImpl(`${label}: ${UNEXPECTED_TEXT}`);
66
+ infoImpl(`${DIM}Next action: ${GENERIC_NEXT_ACTION} \`${retryCommand}\`.${RESET}`);
67
+ return;
68
+ }
69
+
70
+ errorImpl(`${label}: ${typedText(data.error, "the platform reported a failure.")}`);
71
+ infoImpl(`${DIM}Code: ${data.code}${RESET}`);
72
+ infoImpl(`${DIM}Stage: ${typedText(data.stage, "unknown")}${RESET}`);
73
+ infoImpl(
74
+ `${DIM}Data impact: unknown — ${impactNote ?? "verify what was inserted before rerunning"}${RESET}`,
75
+ );
76
+ infoImpl(`${DIM}Retryable: ${data.retryable === true ? "yes" : "no"}${RESET}`);
77
+ infoImpl(
78
+ `${DIM}Retry condition: ${typedText(data.retryPrecondition, "Verify the current data before retrying.")}${RESET}`,
79
+ );
80
+ infoImpl(
81
+ `${DIM}Next action: ${typedText(data.nextAction, `${GENERIC_NEXT_ACTION} \`${retryCommand}\`.`)}${RESET}`,
82
+ );
83
+ infoImpl(`${DIM}Correlation: ${typedText(data.correlationId, "unavailable")}${RESET}`);
84
+ }
@@ -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;