@supatype/cli 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +174 -164
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +36 -0
  5. package/dist/adopt-walkthrough.d.ts +40 -0
  6. package/dist/adopt-walkthrough.d.ts.map +1 -0
  7. package/dist/adopt-walkthrough.js +113 -0
  8. package/dist/adopt-walkthrough.js.map +1 -0
  9. package/dist/cli-version-embedded.js +1 -1
  10. package/dist/commands/admin.d.ts.map +1 -1
  11. package/dist/commands/admin.js +7 -16
  12. package/dist/commands/admin.js.map +1 -1
  13. package/dist/commands/adopt.d.ts.map +1 -1
  14. package/dist/commands/adopt.js +5 -6
  15. package/dist/commands/adopt.js.map +1 -1
  16. package/dist/commands/db.js +3 -3
  17. package/dist/commands/db.js.map +1 -1
  18. package/dist/commands/deploy.d.ts.map +1 -1
  19. package/dist/commands/deploy.js +7 -4
  20. package/dist/commands/deploy.js.map +1 -1
  21. package/dist/commands/dev.d.ts.map +1 -1
  22. package/dist/commands/dev.js +20 -5
  23. package/dist/commands/dev.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +5 -7
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/init.js +1 -1
  28. package/dist/commands/init.js.map +1 -1
  29. package/dist/commands/migrate.d.ts.map +1 -1
  30. package/dist/commands/migrate.js +6 -3
  31. package/dist/commands/migrate.js.map +1 -1
  32. package/dist/commands/push.d.ts.map +1 -1
  33. package/dist/commands/push.js +10 -6
  34. package/dist/commands/push.js.map +1 -1
  35. package/dist/commands/seed.js +2 -2
  36. package/dist/commands/seed.js.map +1 -1
  37. package/dist/dev-compose.d.ts +42 -0
  38. package/dist/dev-compose.d.ts.map +1 -1
  39. package/dist/dev-compose.js +128 -81
  40. package/dist/dev-compose.js.map +1 -1
  41. package/dist/dev-db-reset.d.ts +19 -0
  42. package/dist/dev-db-reset.d.ts.map +1 -0
  43. package/dist/dev-db-reset.js +75 -0
  44. package/dist/dev-db-reset.js.map +1 -0
  45. package/dist/dev-initial-push.d.ts +37 -0
  46. package/dist/dev-initial-push.d.ts.map +1 -0
  47. package/dist/dev-initial-push.js +91 -0
  48. package/dist/dev-initial-push.js.map +1 -0
  49. package/dist/dev-ports.d.ts.map +1 -1
  50. package/dist/dev-ports.js +1 -1
  51. package/dist/dev-ports.js.map +1 -1
  52. package/dist/diff-output.d.ts +2 -2
  53. package/dist/diff-output.d.ts.map +1 -1
  54. package/dist/diff-output.js +1 -1
  55. package/dist/diff-output.js.map +1 -1
  56. package/dist/engine-client.d.ts +5 -1
  57. package/dist/engine-client.d.ts.map +1 -1
  58. package/dist/engine-client.js +8 -6
  59. package/dist/engine-client.js.map +1 -1
  60. package/dist/engine-push-output.d.ts +10 -0
  61. package/dist/engine-push-output.d.ts.map +1 -1
  62. package/dist/engine-push-output.js +12 -0
  63. package/dist/engine-push-output.js.map +1 -1
  64. package/dist/{seed-connection.d.ts → host-database.d.ts} +20 -10
  65. package/dist/host-database.d.ts.map +1 -0
  66. package/dist/{seed-connection.js → host-database.js} +40 -14
  67. package/dist/host-database.js.map +1 -0
  68. package/dist/resolve-target.d.ts +2 -2
  69. package/dist/resolve-target.d.ts.map +1 -1
  70. package/dist/resolve-target.js +15 -11
  71. package/dist/resolve-target.js.map +1 -1
  72. package/dist/retired-no-cache.d.ts +18 -0
  73. package/dist/retired-no-cache.d.ts.map +1 -0
  74. package/dist/retired-no-cache.js +21 -0
  75. package/dist/retired-no-cache.js.map +1 -0
  76. package/dist/self-host-compose.d.ts +21 -0
  77. package/dist/self-host-compose.d.ts.map +1 -1
  78. package/dist/self-host-compose.js +27 -4
  79. package/dist/self-host-compose.js.map +1 -1
  80. package/dist/type-extractor.d.ts.map +1 -1
  81. package/dist/type-extractor.js +12 -6
  82. package/dist/type-extractor.js.map +1 -1
  83. package/package.json +2 -2
  84. package/src/adopt-walkthrough.ts +142 -0
  85. package/src/cli-version-embedded.ts +1 -1
  86. package/src/commands/admin.ts +7 -20
  87. package/src/commands/adopt.ts +5 -6
  88. package/src/commands/db.ts +3 -3
  89. package/src/commands/deploy.ts +7 -4
  90. package/src/commands/dev.ts +22 -6
  91. package/src/commands/doctor.ts +5 -7
  92. package/src/commands/init.ts +1 -1
  93. package/src/commands/migrate.ts +7 -4
  94. package/src/commands/push.ts +28 -10
  95. package/src/commands/seed.ts +2 -2
  96. package/src/dev-compose.ts +178 -88
  97. package/src/dev-db-reset.ts +95 -0
  98. package/src/dev-initial-push.ts +134 -0
  99. package/src/dev-ports.ts +1 -1
  100. package/src/diff-output.ts +2 -2
  101. package/src/engine-client.ts +5 -4
  102. package/src/engine-push-output.ts +19 -0
  103. package/src/{seed-connection.ts → host-database.ts} +42 -12
  104. package/src/resolve-target.ts +20 -14
  105. package/src/retired-no-cache.ts +27 -0
  106. package/src/self-host-compose.ts +29 -4
  107. package/src/type-extractor.ts +15 -5
  108. package/tests/adopt-result.test.ts +27 -0
  109. package/tests/adopt-walkthrough.test.ts +129 -0
  110. package/tests/db-published-and-addressable.test.ts +69 -0
  111. package/tests/dev-db-reset.test.ts +162 -0
  112. package/tests/dev-initial-push.test.ts +142 -0
  113. package/tests/engine-push-output.test.ts +30 -1
  114. package/tests/host-connection-targets.test.ts +84 -0
  115. package/tests/{seed-connection.test.ts → host-database.test.ts} +33 -15
  116. package/tests/retired-no-cache.test.ts +46 -0
  117. package/tests/type-extractor.test.ts +44 -0
  118. package/tsconfig.tsbuildinfo +1 -1
  119. package/dist/seed-connection.d.ts.map +0 -1
  120. package/dist/seed-connection.js.map +0 -1
@@ -68,6 +68,8 @@ export class EngineError extends Error {
68
68
  message: string,
69
69
  public readonly endpoint: string,
70
70
  public readonly exitCode: number | null,
71
+ /** What the engine printed on stdout. A refused push puts its machine-readable reason there. */
72
+ public readonly stdout = "",
71
73
  ) {
72
74
  super(message)
73
75
  this.name = "EngineError"
@@ -221,6 +223,7 @@ export async function engineRequest<T = unknown>(
221
223
  `Engine ${endpoint} failed (exit ${result.status}): ${stderr}`,
222
224
  endpoint,
223
225
  result.status,
226
+ result.stdout ?? "",
224
227
  )
225
228
  }
226
229
 
@@ -316,14 +319,12 @@ function endpointToArgs(
316
319
 
317
320
  case "/doctor": {
318
321
  const strict = body["strict"] ? ["--strict"] : []
319
- const noCache = body["no_cache"] ? ["--no-cache"] : []
320
- return ["doctor", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...strict, ...noCache]
322
+ return ["doctor", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...strict]
321
323
  }
322
324
 
323
325
  case "/adopt": {
324
326
  const yes = body["yes"] ? ["--yes"] : []
325
- const noCache = body["no_cache"] ? ["--no-cache"] : []
326
- return ["adopt", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...yes, ...noCache]
327
+ return ["adopt", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...yes]
327
328
  }
328
329
 
329
330
  case "/validate":
@@ -2,11 +2,30 @@
2
2
  * Parse and format schema-engine push output (compose subprocess or HTTP).
3
3
  */
4
4
 
5
+ import { printDiffWarnings } from "./diff-output.js"
6
+
7
+ /**
8
+ * Print what a push warned about, less anything the diff before it already showed.
9
+ *
10
+ * Every caller of `/push` reports through here. The warnings used to reach only `supatype diff`, so
11
+ * a push said nothing about a bucket operation it had just made unreachable, and the ones found
12
+ * after applying were not shown anywhere.
13
+ */
14
+ export function printPushWarnings(
15
+ result: Pick<EnginePushResult, "warnings">,
16
+ alreadyShown: readonly string[] = [],
17
+ ): void {
18
+ const shown = new Set(alreadyShown)
19
+ printDiffWarnings({ warnings: (result.warnings ?? []).filter((w) => !shown.has(w)) })
20
+ }
21
+
5
22
  export interface EnginePushResult {
6
23
  status?: string
7
24
  operations?: number
8
25
  admin_refreshed?: boolean
9
26
  message?: string
27
+ /** The schema's warnings (a bucket rule left out, say), then any found once applied. */
28
+ warnings?: string[]
10
29
  }
11
30
 
12
31
  /** Extract the engine JSON object from mixed docker compose stdout/stderr. */
@@ -1,26 +1,56 @@
1
1
  /**
2
- * Which database a seed run targets, and how that was decided.
2
+ * Which database a command run on the host connects to, and how that was decided.
3
3
  *
4
- * Its own file so the failure is testable without spawning anything. The failure is the
5
- * point: the old seed template carried a hardcoded fallback DSN, so a project with no
6
- * `.env` did not fail, it silently tried `localhost:5432` with a guessed password and
7
- * reported a connection error that named none of the things it had looked at. Someone
8
- * reading that has no way to tell "I have not set DATABASE_URL" from "the stack is not
9
- * running".
4
+ * One resolver for every host-side command: seed, adopt, introspect, migrate, doctor, pull, and
5
+ * any target resolved in direct mode. They used to find the database three different ways, and
6
+ * the one most of them used took `.supatype/environment.json`'s URL, which describes the docker
7
+ * `db` *container*, so `supatype adopt` on a docker project failed looking up the host `db`
8
+ * (supatype#85). Another read `process.env` and never the project's `.env`, where `supatype dev`
9
+ * writes the host-published URL. Seed's order was the one that worked, so it is this one.
10
10
  *
11
- * So every source is recorded whether it was found or not, and the error prints the lot.
11
+ * Its own file so the failure is testable without spawning anything. The failure is the point: a
12
+ * hardcoded fallback DSN meant a project with no `.env` silently tried `localhost:5432` with a
13
+ * guessed password and reported a connection error that named none of the things it had looked
14
+ * at. So every source is recorded whether it was found or not, and the error prints the lot.
12
15
  */
13
16
 
14
17
  import { existsSync } from "node:fs"
15
18
  import { join } from "node:path"
16
- import { readEnvFile } from "./env-file.js"
19
+ import { readEnvFile, readEnvValue } from "./env-file.js"
20
+ import { devPostgresPassword } from "./local-secrets.js"
17
21
  import {
18
22
  externalDatabaseUrl,
19
23
  localDSN,
20
24
  projectRootFromConfig,
25
+ resolveRuntimeProvider,
21
26
  type SupatypeProjectConfig,
22
27
  } from "./project-config.js"
23
28
 
29
+ /** Where `supatype dev` publishes a docker project's Postgres when `.env` does not say. */
30
+ export const COMPOSE_DEV_DB_PORT = 54329
31
+
32
+ /**
33
+ * A docker project's own Postgres, as reached from the host: the port `supatype dev` publishes it
34
+ * on, with the credentials and database the stack was created with, all read from `.env`.
35
+ */
36
+ export function hostComposeDbUrl(cwd: string): string {
37
+ const port = readEnvValue(cwd, "SUPATYPE_DEV_DB_PORT", String(COMPOSE_DEV_DB_PORT))
38
+ const user = readEnvValue(cwd, "POSTGRES_USER", "supatype_admin")
39
+ const db = readEnvValue(cwd, "POSTGRES_DB", "supatype")
40
+ return `postgresql://${user}:${devPostgresPassword(cwd)}@127.0.0.1:${port}/${db}?sslmode=disable`
41
+ }
42
+
43
+ /**
44
+ * The database Supatype runs for this project, when nothing names one.
45
+ *
46
+ * For docker, the published compose database. It used to be `localDSN` for every provider,
47
+ * `postgres:postgres@127.0.0.1:5432/<project name>`, which is the native layout: a docker
48
+ * project with no `.env` got a user, database and port that do not exist.
49
+ */
50
+ function derivedDsn(root: string, config: SupatypeProjectConfig): string {
51
+ return resolveRuntimeProvider(config) === "docker" ? hostComposeDbUrl(root) : localDSN(config)
52
+ }
53
+
24
54
  /** One place a connection string could have come from. */
25
55
  export interface DsnSource {
26
56
  /** How it would be described to the person running the command. */
@@ -42,7 +72,7 @@ export interface ResolvedDsn {
42
72
  export class DsnNotFound extends Error {
43
73
  constructor(readonly tried: readonly DsnSource[]) {
44
74
  super(
45
- `No database connection string for this seed run.\n${tried
75
+ `No database connection string to connect with.\n${tried
46
76
  .map((source) => ` ${source.found ? "found" : "not set"} ${source.name}: ${source.detail}`)
47
77
  .join("\n")}`,
48
78
  )
@@ -69,7 +99,7 @@ export interface ResolveOptions {
69
99
  * `.env` is loaded first but ranks below a real environment variable, which is how every
70
100
  * other dotenv reader behaves and how Compose resolves the same names.
71
101
  */
72
- export function resolveSeedDsn(
102
+ export function resolveHostDatabaseUrl(
73
103
  cwd: string,
74
104
  config: SupatypeProjectConfig,
75
105
  options: ResolveOptions = {},
@@ -122,7 +152,7 @@ export function resolveSeedDsn(
122
152
  if (fileValue !== undefined) return { dsn: fileValue, source: fileLabel, tried }
123
153
 
124
154
  if (options.allowDerived === true) {
125
- const derived = localDSN(config)
155
+ const derived = derivedDsn(root, config)
126
156
  tried.push({ name: "the project's own local database", detail: redact(derived), found: true })
127
157
  return { dsn: derived, source: "the project's own local database", tried }
128
158
  }
@@ -4,12 +4,13 @@ import { loadConfig } from "./config.js"
4
4
  import type { DiffResult } from "./engine-client.js"
5
5
  import { ensureEngine, engineRequest } from "./engine-client.js"
6
6
  import type { SchemaSourcesPayload } from "./schema-sources.js"
7
+ import { resolveHostDatabaseUrl } from "./host-database.js"
7
8
  import {
8
- connectionString,
9
9
  pgSchema,
10
10
  resolveRuntimeProvider,
11
11
  schemaPathFromProject,
12
12
  serverBaseUrl,
13
+ type SupatypeProjectConfig,
13
14
  } from "./project-config.js"
14
15
  import {
15
16
  getEnvironmentTarget,
@@ -86,6 +87,17 @@ function resolveBranchDefaults(cwd: string, configEnvDefault?: string): string |
86
87
  }
87
88
  }
88
89
 
90
+ /**
91
+ * The project's database as a host process reaches it, for a target that runs the engine here.
92
+ *
93
+ * Never `.supatype/environment.json`'s URL: that one describes the docker `db` container, right
94
+ * for a container and unresolvable from the host, which is how `supatype adopt` on a docker
95
+ * project failed (supatype#85).
96
+ */
97
+ function hostDatabaseUrl(cwd: string, config: SupatypeProjectConfig, connection: string | undefined): string {
98
+ return resolveHostDatabaseUrl(cwd, config, { connection, allowDerived: true }).dsn
99
+ }
100
+
89
101
  export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): DeployTarget {
90
102
  const config = loadConfig(cwd)
91
103
  const projectRef = config.project?.name ?? config.project?.ref ?? "project"
@@ -104,7 +116,6 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
104
116
  }
105
117
 
106
118
  if (flags.direct || flags.local) {
107
- const localEnv = loadLocalEnvironment(cwd)
108
119
  return {
109
120
  mode: "direct",
110
121
  environment: "local",
@@ -112,10 +123,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
112
123
  apiBaseUrl: (serverBaseUrl(config) ?? "").replace(/\/$/, ""),
113
124
  apiPrefix: "/platform/v1",
114
125
  link: null,
115
- databaseUrl:
116
- flags.connection ??
117
- localEnv?.databaseUrl ??
118
- connectionString(config),
126
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
119
127
  }
120
128
  }
121
129
 
@@ -132,7 +140,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
132
140
  apiPrefix: "/platform/v1",
133
141
  token: resolveLocalToken(cwd),
134
142
  link: null,
135
- databaseUrl: localEnv.databaseUrl,
143
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
136
144
  }
137
145
  }
138
146
  return {
@@ -142,7 +150,7 @@ export function resolveTarget(cwd: string, flags: ResolveTargetFlags = {}): Depl
142
150
  apiBaseUrl: (serverBaseUrl(config) ?? "").replace(/\/$/, ""),
143
151
  apiPrefix: "/platform/v1",
144
152
  link: null,
145
- databaseUrl: flags.connection ?? connectionString(config),
153
+ databaseUrl: hostDatabaseUrl(cwd, config, flags.connection),
146
154
  }
147
155
  }
148
156
 
@@ -269,6 +277,8 @@ export async function targetSchemaPush(
269
277
  message?: string
270
278
  status?: string
271
279
  name?: string
280
+ /** The schema's warnings, then any found once applied. See `printPushWarnings`. */
281
+ warnings?: string[]
272
282
  /**
273
283
  * What the control plane made of this schema's cache declaration. Absent from an engine push and
274
284
  * from a control plane too old to send it, which is why every reader of it has to treat absence
@@ -381,7 +391,7 @@ export async function targetListMigrations(
381
391
  export async function targetSchemaDoctor(
382
392
  target: DeployTarget,
383
393
  ast: unknown,
384
- opts?: { noCache?: boolean | undefined; schema?: string },
394
+ opts?: { schema?: string },
385
395
  ): Promise<unknown> {
386
396
  if (target.mode === "direct" || (target.mode === "local" && !target.token)) {
387
397
  await ensureEngine()
@@ -389,7 +399,6 @@ export async function targetSchemaDoctor(
389
399
  ast,
390
400
  database_url: target.databaseUrl!,
391
401
  schema: opts?.schema ?? "public",
392
- no_cache: opts?.noCache ?? false,
393
402
  })
394
403
  }
395
404
 
@@ -398,7 +407,6 @@ export async function targetSchemaDoctor(
398
407
  target.apiPrefix,
399
408
  apiFetchOpts(target, "POST", projectPath(target, "/schema/doctor"), {
400
409
  ast,
401
- no_cache: opts?.noCache ?? false,
402
410
  schema: opts?.schema ?? "public",
403
411
  }),
404
412
  )
@@ -428,7 +436,7 @@ export async function targetSchemaIntrospect(
428
436
  export async function targetSchemaAdopt(
429
437
  target: DeployTarget,
430
438
  ast: unknown,
431
- opts?: { names?: string[]; schema?: string; yes?: boolean; noCache?: boolean },
439
+ opts?: { names?: string[]; schema?: string; yes?: boolean },
432
440
  ): Promise<unknown> {
433
441
  if (target.mode === "direct" || (target.mode === "local" && !target.token)) {
434
442
  await ensureEngine()
@@ -438,7 +446,6 @@ export async function targetSchemaAdopt(
438
446
  schema: opts?.schema ?? "public",
439
447
  names: opts?.names,
440
448
  yes: opts?.yes ?? false,
441
- no_cache: opts?.noCache ?? false,
442
449
  })
443
450
  }
444
451
 
@@ -449,7 +456,6 @@ export async function targetSchemaAdopt(
449
456
  ast,
450
457
  schema: opts?.schema ?? "public",
451
458
  yes: opts?.yes ?? false,
452
- no_cache: opts?.noCache ?? false,
453
459
  ...(opts?.names !== undefined ? { names: opts.names } : {}),
454
460
  }),
455
461
  )
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `--no-cache` on `adopt` and `doctor`, which no longer read a cache at all.
3
+ *
4
+ * The engine diffed `adopt` against the snapshot the last push wrote, so a table changed outside
5
+ * Supatype since was invisible to it (supatype#86). Both commands read the database live now, so
6
+ * the flag has nothing left to bypass. It never worked from the CLI either: Commander stores
7
+ * `--no-cache` as `cache: false`, the commands read `noCache`, and the flag was always ignored.
8
+ *
9
+ * Kept, hidden, for one release so a script that passes it keeps working, and says so.
10
+ */
11
+ import { Option, type Command } from "commander"
12
+ import { warn } from "./ui/messages.js"
13
+
14
+ export function addRetiredNoCacheOption(command: Command): Command {
15
+ return command.addOption(new Option("--no-cache", "No longer needed; does nothing").hideHelp())
16
+ }
17
+
18
+ /** Commander's spelling of a passed `--no-cache`. */
19
+ export interface RetiredNoCacheOpts {
20
+ cache?: boolean
21
+ }
22
+
23
+ export function warnIfRetiredNoCache(opts: RetiredNoCacheOpts): void {
24
+ if (opts.cache === false) {
25
+ warn("--no-cache is no longer needed: the database is always read live. It will be removed.")
26
+ }
27
+ }
@@ -51,7 +51,7 @@ const SEAWEEDFS_IMAGE =
51
51
  * Not a guess and not configurable: the plugin prefixes every key it writes
52
52
  * with this and enforces it in its own `reserved_words.lua`, so it is the one
53
53
  * durable thing in a keyspace that is otherwise a cache. Verified on a live
54
- * instance — both ACME keys survived `kill -9` with only this prefix named
54
+ * instance: both ACME keys survived `kill -9` with only this prefix named
55
55
  * durable, and a response-cache key beside them did not.
56
56
  */
57
57
  const ACME_KEY_PREFIX = "kong_acme:"
@@ -62,6 +62,13 @@ const OBJECT_STORE_SECRET_KEY = "supatype-secret"
62
62
  /** Where the rendered SeaweedFS identity file sits, resolved from the project root like kong.yml. */
63
63
  const SEAWEED_CONFIG_MOUNT = ".supatype/self-host/s3.json"
64
64
 
65
+ /**
66
+ * The compose volume key Postgres keeps its data in. Docker names the volume
67
+ * `<compose project>_<key>`, and `supatype dev --reset-db` removes it by that name, so the key is
68
+ * declared once rather than spelled out in the file and again in the code that deletes it.
69
+ */
70
+ export const DB_VOLUME_KEY = "db-data"
71
+
65
72
  type DockerPinComponent = "engine" | "server" | "postgres"
66
73
 
67
74
  /** Map a config version pin to a Docker Hub image reference. */
@@ -158,6 +165,24 @@ export function composePullNeedsIgnoreFailures(
158
165
  * Uses config pin when set; otherwise CDN engine semver (Docker Hub `:latest` can lag).
159
166
  * Does not touch `.env`, server/postgres still use compose `:latest` defaults.
160
167
  */
168
+ /**
169
+ * Whether this project's database is published to the host, and so needs a `DATABASE_URL` that
170
+ * points at it.
171
+ *
172
+ * One function because the two halves came apart once. Publishing was made unconditional for a
173
+ * local stack, because seeding is a host process and a database nothing on the host can reach is
174
+ * a database no seed can use. The code that writes `DATABASE_URL` to match kept an older
175
+ * condition, `overrides.engine`, so a project without a local engine build got a database
176
+ * published on 54329 and a `DATABASE_URL` still pointing at 5432. `supatype seed` then timed out
177
+ * and advised checking that the stack was running, which it was.
178
+ *
179
+ * The exception is an external database. There is no `db` container to publish, and that URL
180
+ * belongs to the operator: writing it once clobbered a real external Postgres.
181
+ */
182
+ export function publishesDbToHost(config: SupatypeProjectConfig): boolean {
183
+ return !usesExternalDatabase(config)
184
+ }
185
+
161
186
  export async function schemaEngineImageForPush(
162
187
  config: SupatypeProjectConfig,
163
188
  ): Promise<string | undefined> {
@@ -415,7 +440,7 @@ ${studioService}
415
440
  //
416
441
  // This exposes nothing new: the dev port below is bound to `127.0.0.1`, so it is reachable from
417
442
  // this machine and from nowhere else.
418
- const publishDbToHost = true
443
+ const publishDbToHost = publishesDbToHost(config)
419
444
  const dbPorts = publishDbToHost
420
445
  ? devLocal
421
446
  ? ` ports:
@@ -506,7 +531,7 @@ ${seaweedPorts}`
506
531
  `
507
532
  // An external database is not ours to declare a volume for.
508
533
  const volumesBlock = `volumes:
509
- ${external ? "" : " db-data:\n"} storage-data:
534
+ ${external ? "" : ` ${DB_VOLUME_KEY}:\n`} storage-data:
510
535
  ${keyspaceInPg ? "" : " valkey-data:\n"}`
511
536
 
512
537
  // `depends_on` for the services that talk to Postgres. With an external database there is no
@@ -664,7 +689,7 @@ ${dbDependency}`
664
689
  # Read by the image's init to password the \`authenticator\` role PostgREST connects as.
665
690
  AUTHENTICATOR_PASSWORD: \${AUTHENTICATOR_PASSWORD:?AUTHENTICATOR_PASSWORD is missing from .env}
666
691
  ${keyspaceDbEnv}${dbPorts}${keyspaceExpose} volumes:
667
- - db-data:/var/lib/postgresql/data
692
+ - ${DB_VOLUME_KEY}:/var/lib/postgresql/data
668
693
  healthcheck:
669
694
  # -h 127.0.0.1 forces TCP. Without it \`pg_isready\` uses the Unix socket, which the
670
695
  # entrypoint's temporary init server is already listening on while TCP is still refused,
@@ -1344,6 +1344,9 @@ function parseMimeAcceptList(typeNode: ts.TypeNode, sourceFile: ts.SourceFile):
1344
1344
  return undefined
1345
1345
  }
1346
1346
 
1347
+ /** The operations a bucket's `access` may name, the same four a model's may. */
1348
+ const BUCKET_RULE_KEYS: ReadonlySet<string> = new Set(["read", "create", "update", "delete"])
1349
+
1347
1350
  function parsePartialBucketAccess(
1348
1351
  typeNode: ts.TypeNode,
1349
1352
  sourceFile: ts.SourceFile,
@@ -1367,7 +1370,14 @@ function parsePartialBucketAccess(
1367
1370
  for (const member of literal.members) {
1368
1371
  if (!ts.isPropertySignature(member) || !member.type) continue
1369
1372
  const key = getPropertyName(member.name)
1370
- if (key !== "read" && key !== "create" && key !== "delete") continue
1373
+ // Refused rather than skipped. Skipping is how `update` went unenforced: the author wrote an
1374
+ // overwrite rule, the bucket got none, and nothing said so.
1375
+ if (key === null || !BUCKET_RULE_KEYS.has(key)) {
1376
+ const written = key ?? member.name.getText(sourceFile)
1377
+ throw new Error(
1378
+ `Bucket "${bucketId}": \`${written}\` is not a bucket rule. Use read, create, update or delete.`,
1379
+ )
1380
+ }
1371
1381
  const bucketRule = parseAccessRule(member.type, sourceFile, resolveCtx)
1372
1382
  assertAccessRuleIsRenderable(bucketRule, bucketId, key)
1373
1383
  access[key] = bucketRule
@@ -1826,7 +1836,7 @@ function assertCacheIsServable(
1826
1836
  `Model "${model}": \`cache.public\` cannot be used with an \`access.read\` rule that ` +
1827
1837
  `varies by caller. A public cache entry is shared by everyone, so one caller's rows ` +
1828
1838
  `would be served to another. Use \`cache: { enabled: true }\` for per-user entries, or ` +
1829
- `make the read rule row-independent — a rule like \`Lte<"published_at", Now>\` varies by ` +
1839
+ `make the read rule row-independent: a rule like \`Lte<"published_at", Now>\` varies by ` +
1830
1840
  `row without varying by caller and is safe to share.`,
1831
1841
  )
1832
1842
  }
@@ -1837,7 +1847,7 @@ function assertCacheIsServable(
1837
1847
  if (keyed.length === 0) {
1838
1848
  throw new Error(
1839
1849
  `Model "${model}": \`cache.rows\` needs a primary key, because the row cache's key IS the ` +
1840
- `primary key — there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1850
+ `primary key, so there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1841
1851
  `response cache, which has no such requirement.`,
1842
1852
  )
1843
1853
  }
@@ -1887,7 +1897,7 @@ function resolveSearchFields(
1887
1897
  *
1888
1898
  * `cache_max_ttl` is refused outside 0–86400 by `PATCH /admin/v1/config/rest`, and a declared cap
1889
1899
  * is the same quantity. Left to the server, an out-of-range `maxTtl` reaches it as part of a
1890
- * manifest rather than a request — nothing refuses a manifest — and the ceiling it produces is
1900
+ * manifest rather than a request (nothing refuses a manifest), and the ceiling it produces is
1891
1901
  * whatever the arithmetic makes of it: a negative cap reads as "no cap declared" and permits more
1892
1902
  * than the author asked for, which is the one direction a ceiling must never move in.
1893
1903
  */
@@ -3323,7 +3333,7 @@ export interface ParsedModelCache {
3323
3333
  * Shaped like `parseModelHooks`, and travelling the same way: onto the route manifest beside
3324
3334
  * `hooks`, not into `annotations.platform`. The schema engine re-serialises its own parsed AST
3325
3335
  * (`serde_json::to_value(&ast)`), and `PlatformModelAnnotations` carries only `access` and
3326
- * `search_fields` with no catch-all — so a key placed there is silently dropped on the way to the
3336
+ * `search_fields` with no catch-all, so a key placed there is silently dropped on the way to the
3327
3337
  * server rather than riding through. Verified rather than assumed; see plan §13.1.
3328
3338
  */
3329
3339
  function parseModelCache(
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import { adoptResultFrom } from "../src/dev-compose.js"
3
+
4
+ /**
5
+ * The engine prints the adopt preview as multi-line JSON. Read with stderr joined on, any warning a
6
+ * compose run prints made it unparseable, and a preview that worked was reported as a failed adopt.
7
+ */
8
+ const PREVIEW = JSON.stringify(
9
+ { status: "preview", stampStatements: ['COMMENT ON TABLE "public"."orders" IS \'...\''] },
10
+ null,
11
+ 2,
12
+ )
13
+
14
+ describe("adoptResultFrom()", () => {
15
+ it("reads the preview from stdout even when stderr printed something", () => {
16
+ const run = {
17
+ status: 0,
18
+ stdout: PREVIEW,
19
+ output: `${PREVIEW}\nWARN[0000] The "FOO" variable is not set. Defaulting to a blank string.`,
20
+ }
21
+ expect(adoptResultFrom(run)?.stampStatements).toHaveLength(1)
22
+ })
23
+
24
+ it("is null for a run that failed, whatever it printed", () => {
25
+ expect(adoptResultFrom({ status: 1, stdout: PREVIEW, output: PREVIEW })).toBeNull()
26
+ })
27
+ })
@@ -0,0 +1,129 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
2
+
3
+ /**
4
+ * What a push does when the engine refuses tables Supatype does not manage.
5
+ *
6
+ * It used to stop with a message naming `supatype adopt`, a command that could not reach a docker
7
+ * database and found nothing to stamp when it did. Now a terminal is offered adoption there and
8
+ * then, shown the SQL, and asked twice; anywhere else nothing is adopted and the command is
9
+ * printed. These pin that agreeing to a push is never agreeing to adopt.
10
+ */
11
+
12
+ const printed: string[] = []
13
+ vi.mock("../src/ui/messages.js", () => ({
14
+ warn: (line: string) => printed.push(`warn: ${line}`),
15
+ plain: (line?: string) => printed.push(line ?? ""),
16
+ }))
17
+
18
+ let interactive = true
19
+ vi.mock("../src/ui/interactive.js", () => ({ isInteractive: () => interactive }))
20
+
21
+ const answers: boolean[] = []
22
+ vi.mock("../src/ui/confirm.js", () => ({ confirm: vi.fn(async () => answers.shift() ?? false) }))
23
+
24
+ const { EngineError } = await import("../src/engine-client.js")
25
+ const { engineOutputOf, offerAdoption, pushOfferingAdoption, unmanagedTables } = await import(
26
+ "../src/adopt-walkthrough.js"
27
+ )
28
+
29
+ const REFUSAL = '{"status":"refused","reason":"unmanaged_model_tables","tables":["orders","items"]}'
30
+ const POLICY = { yes: false, retry: "supatype push" }
31
+
32
+ function adoptSteps(statements = ['COMMENT ON TABLE "public"."orders" IS ...']) {
33
+ return { preview: vi.fn(async () => statements), apply: vi.fn(async () => statements.length) }
34
+ }
35
+
36
+ beforeEach(() => {
37
+ printed.length = 0
38
+ answers.length = 0
39
+ interactive = true
40
+ })
41
+ afterEach(() => vi.clearAllMocks())
42
+
43
+ describe("unmanagedTables()", () => {
44
+ it("reads the tables from the engine's JSON refusal", () => {
45
+ expect(unmanagedTables(`some compose noise\n${REFUSAL}\nError: ...`)).toEqual(["orders", "items"])
46
+ })
47
+
48
+ it("falls back to the wording of an engine that predates the JSON", () => {
49
+ const legacy = "Your schema declares model(s) for table(s) Supatype does not manage: public.orders, public.items.\n\nNothing was applied."
50
+ expect(unmanagedTables(legacy)).toEqual(["public.orders", "public.items"])
51
+ })
52
+
53
+ it("is null for any other failure, including another JSON refusal", () => {
54
+ expect(unmanagedTables("2 destructive operation(s) detected")).toBeNull()
55
+ expect(unmanagedTables('{"status":"refused","reason":"something_else","tables":["x"]}')).toBeNull()
56
+ })
57
+
58
+ it("reads an engine error's stdout, where the refusal is printed", () => {
59
+ const err = new EngineError("Engine /push failed (exit 1): Error: ...", "/push", 1, REFUSAL)
60
+ expect(unmanagedTables(engineOutputOf(err))).toEqual(["orders", "items"])
61
+ })
62
+ })
63
+
64
+ describe("offerAdoption()", () => {
65
+ it("never adopts without a terminal, and prints the command instead", async () => {
66
+ interactive = false
67
+ // Would be yes to both, so only the missing terminal can be what stops it.
68
+ answers.push(true, true)
69
+ const steps = adoptSteps()
70
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("declined")
71
+ expect(steps.preview).not.toHaveBeenCalled()
72
+ expect(steps.apply).not.toHaveBeenCalled()
73
+ expect(printed.join("\n")).toContain("Run `supatype adopt`")
74
+ })
75
+
76
+ it("never adopts on --yes, because agreeing to a push is not agreeing to adopt", async () => {
77
+ answers.push(true, true)
78
+ const steps = adoptSteps()
79
+ expect(await offerAdoption(["orders"], steps, { ...POLICY, yes: true })).toBe("declined")
80
+ expect(steps.apply).not.toHaveBeenCalled()
81
+ })
82
+
83
+ it("says which tables, and that their access rules are not in force", async () => {
84
+ interactive = false
85
+ await offerAdoption(["orders", "items"], adoptSteps(), POLICY)
86
+ expect(printed.join("\n")).toContain("access rules your schema declares for them are not in force: orders, items")
87
+ })
88
+
89
+ it("shows the SQL before applying, and applies only on the second yes", async () => {
90
+ answers.push(true, true)
91
+ const steps = adoptSteps()
92
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("adopted")
93
+ expect(printed.join("\n")).toContain('COMMENT ON TABLE "public"."orders"')
94
+ expect(steps.apply).toHaveBeenCalledTimes(1)
95
+ })
96
+
97
+ it("applies nothing when the SQL is declined", async () => {
98
+ answers.push(true, false)
99
+ const steps = adoptSteps()
100
+ expect(await offerAdoption(["orders"], steps, POLICY)).toBe("declined")
101
+ expect(steps.apply).not.toHaveBeenCalled()
102
+ })
103
+ })
104
+
105
+ describe("pushOfferingAdoption()", () => {
106
+ it("adopts and pushes once more after an unmanaged-tables refusal", async () => {
107
+ answers.push(true, true)
108
+ const push = vi
109
+ .fn<() => Promise<string>>()
110
+ .mockRejectedValueOnce(new EngineError("refused", "/push", 1, REFUSAL))
111
+ .mockResolvedValueOnce("applied")
112
+ expect(await pushOfferingAdoption(push, adoptSteps(), POLICY)).toBe("applied")
113
+ expect(push).toHaveBeenCalledTimes(2)
114
+ })
115
+
116
+ it("throws the refusal as it came when adoption is declined, so the push still fails", async () => {
117
+ const refusal = new EngineError("refused", "/push", 1, REFUSAL)
118
+ const push = vi.fn<() => Promise<string>>().mockRejectedValue(refusal)
119
+ await expect(pushOfferingAdoption(push, adoptSteps(), POLICY)).rejects.toBe(refusal)
120
+ expect(push).toHaveBeenCalledTimes(1)
121
+ })
122
+
123
+ it("does not offer anything for any other failure", async () => {
124
+ const other = new Error("2 destructive operation(s) detected")
125
+ const steps = adoptSteps()
126
+ await expect(pushOfferingAdoption(vi.fn().mockRejectedValue(other), steps, POLICY)).rejects.toBe(other)
127
+ expect(steps.preview).not.toHaveBeenCalled()
128
+ })
129
+ })