@rehearsal-db/core 0.1.0-beta.13 → 0.1.0-beta.15

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 (169) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +4 -1
  3. package/dist/package.json +100 -0
  4. package/dist/scripts/install/create_root_config.d.mts +3 -0
  5. package/dist/scripts/install/create_root_config.mjs +13 -0
  6. package/dist/scripts/runtime/manage_database.d.mts +6 -0
  7. package/{scripts → dist/scripts}/runtime/manage_database.mjs +6 -8
  8. package/dist/src/application/session.d.mts +96 -0
  9. package/dist/src/application/session.mjs +380 -0
  10. package/dist/src/baseline/artifact.d.mts +119 -0
  11. package/dist/src/baseline/artifact.mjs +522 -0
  12. package/dist/src/baseline/builder.d.mts +19 -0
  13. package/dist/src/baseline/builder.mjs +142 -0
  14. package/dist/src/baseline/input_discovery.d.mts +13 -0
  15. package/dist/src/baseline/input_discovery.mjs +149 -0
  16. package/dist/src/baseline/policy_review.d.mts +56 -0
  17. package/dist/src/baseline/policy_review.mjs +73 -0
  18. package/dist/src/baseline/preparation.d.mts +63 -0
  19. package/dist/src/baseline/preparation.mjs +295 -0
  20. package/dist/src/baseline/privacy_engine.d.mts +162 -0
  21. package/dist/src/baseline/privacy_engine.mjs +1162 -0
  22. package/dist/src/baseline/privacy_structured_json.d.mts +66 -0
  23. package/dist/src/baseline/privacy_structured_json.mjs +464 -0
  24. package/dist/src/baseline/sanitization_policy.d.mts +69 -0
  25. package/dist/src/baseline/sanitization_policy.mjs +227 -0
  26. package/dist/src/baseline/schema_snapshot.d.mts +19 -0
  27. package/dist/src/baseline/schema_snapshot.mjs +79 -0
  28. package/dist/src/cli/arguments.d.mts +43 -0
  29. package/dist/src/cli/arguments.mjs +135 -0
  30. package/dist/src/cli/guided.d.mts +51 -0
  31. package/dist/src/cli/guided.mjs +713 -0
  32. package/dist/src/cli/init_command.d.mts +21 -0
  33. package/dist/src/cli/init_command.mjs +90 -0
  34. package/dist/src/cli/project_commands.d.mts +157 -0
  35. package/dist/src/cli/project_commands.mjs +183 -0
  36. package/dist/src/cli/rehearsal.d.mts +7 -0
  37. package/dist/src/cli/rehearsal.mjs +706 -0
  38. package/dist/src/cli/renderers.d.mts +299 -0
  39. package/dist/src/cli/renderers.mjs +554 -0
  40. package/dist/src/cli/runtime_commands.d.mts +265 -0
  41. package/dist/src/cli/runtime_commands.mjs +599 -0
  42. package/dist/src/cli/source_commands.d.mts +432 -0
  43. package/dist/src/cli/source_commands.mjs +299 -0
  44. package/dist/src/cli/terminal.d.mts +59 -0
  45. package/dist/src/cli/terminal.mjs +230 -0
  46. package/dist/src/identity/claim.d.mts +144 -0
  47. package/dist/src/identity/claim.mjs +947 -0
  48. package/dist/src/identity/provider_configuration.d.mts +37 -0
  49. package/dist/src/identity/provider_configuration.mjs +132 -0
  50. package/dist/src/identity/storage.d.mts +21 -0
  51. package/dist/src/identity/storage.mjs +122 -0
  52. package/dist/src/index.d.mts +4 -0
  53. package/dist/src/index.mjs +3 -0
  54. package/dist/src/project/configuration.d.mts +181 -0
  55. package/dist/src/project/configuration.mjs +958 -0
  56. package/dist/src/project/install_scaffold.d.mts +42 -0
  57. package/dist/src/project/install_scaffold.mjs +263 -0
  58. package/dist/src/project/setup.d.mts +87 -0
  59. package/dist/src/project/setup.mjs +414 -0
  60. package/dist/src/project/support_report.d.mts +88 -0
  61. package/dist/src/project/support_report.mjs +83 -0
  62. package/dist/src/runtime/cleanup.d.mts +85 -0
  63. package/dist/src/runtime/cleanup.mjs +311 -0
  64. package/dist/src/runtime/migration_history.d.mts +51 -0
  65. package/dist/src/runtime/migration_history.mjs +170 -0
  66. package/dist/src/runtime/plan.d.mts +134 -0
  67. package/dist/src/runtime/plan.mjs +636 -0
  68. package/dist/src/runtime/policy.d.mts +66 -0
  69. package/dist/src/runtime/policy.mjs +369 -0
  70. package/dist/src/runtime/restore.d.mts +22 -0
  71. package/dist/src/runtime/restore.mjs +276 -0
  72. package/dist/src/runtime/service_environment.d.mts +11 -0
  73. package/dist/src/runtime/service_environment.mjs +58 -0
  74. package/dist/src/runtime/topology.d.mts +51 -0
  75. package/dist/src/runtime/topology.mjs +128 -0
  76. package/dist/src/shared/diagnostics.d.mts +97 -0
  77. package/dist/src/shared/diagnostics.mjs +170 -0
  78. package/dist/src/shared/human_output.d.mts +2 -0
  79. package/{src → dist/src}/shared/human_output.mjs +1 -3
  80. package/dist/src/shared/node_runtime.d.mts +14 -0
  81. package/dist/src/shared/node_runtime.mjs +25 -0
  82. package/dist/src/shared/operation_guard.d.mts +22 -0
  83. package/dist/src/shared/operation_guard.mjs +150 -0
  84. package/dist/src/shared/process_environment.d.mts +15 -0
  85. package/dist/src/shared/process_environment.mjs +50 -0
  86. package/dist/src/source/access.d.mts +165 -0
  87. package/dist/src/source/access.mjs +602 -0
  88. package/dist/src/source/asset_transfer.d.mts +27 -0
  89. package/dist/src/source/asset_transfer.mjs +202 -0
  90. package/dist/src/source/baseline.d.mts +66 -0
  91. package/dist/src/source/baseline.mjs +372 -0
  92. package/dist/src/source/external_reader.d.mts +42 -0
  93. package/dist/src/source/external_reader.mjs +278 -0
  94. package/dist/src/source/postgresql_access.d.mts +86 -0
  95. package/dist/src/source/postgresql_access.mjs +454 -0
  96. package/dist/src/source/privacy_paths.d.mts +10 -0
  97. package/dist/src/source/privacy_paths.mjs +27 -0
  98. package/dist/src/targets/driver.d.mts +2 -0
  99. package/dist/src/targets/driver.mjs +13 -0
  100. package/dist/src/targets/postgresql.d.mts +5 -0
  101. package/dist/src/targets/postgresql.mjs +641 -0
  102. package/dist/src/targets/supabase.d.mts +8 -0
  103. package/dist/src/targets/supabase.mjs +659 -0
  104. package/dist/src/targets/supabase_environment.d.mts +49 -0
  105. package/dist/src/targets/supabase_environment.mjs +162 -0
  106. package/dist/src/targets/target.d.mts +33 -0
  107. package/dist/src/targets/target.mjs +39 -0
  108. package/docs/README.md +1 -0
  109. package/docs/architecture.md +17 -9
  110. package/docs/configuration.md +49 -8
  111. package/docs/getting-started.md +28 -0
  112. package/docs/index.md +1 -0
  113. package/docs/production-source.md +43 -7
  114. package/docs/releasing.md +5 -3
  115. package/docs/roadmap.md +3 -2
  116. package/docs/sanitization.md +415 -14
  117. package/docs/standalone-workflow.md +12 -6
  118. package/docs/troubleshooting.md +5 -1
  119. package/docs/tutorial.md +5 -0
  120. package/docs/typescript.md +87 -0
  121. package/package.json +35 -29
  122. package/scripts/install/create_root_config.mjs +0 -36
  123. package/src/README.md +0 -17
  124. package/src/application/session.mjs +0 -435
  125. package/src/baseline/artifact.mjs +0 -684
  126. package/src/baseline/builder.mjs +0 -164
  127. package/src/baseline/input_discovery.mjs +0 -155
  128. package/src/baseline/policy_review.mjs +0 -92
  129. package/src/baseline/preparation.mjs +0 -323
  130. package/src/baseline/privacy_engine.mjs +0 -952
  131. package/src/baseline/sanitization_policy.mjs +0 -299
  132. package/src/baseline/schema_snapshot.mjs +0 -113
  133. package/src/cli/arguments.mjs +0 -126
  134. package/src/cli/guided.mjs +0 -814
  135. package/src/cli/init_command.mjs +0 -94
  136. package/src/cli/rehearsal.mjs +0 -970
  137. package/src/cli/renderers.mjs +0 -626
  138. package/src/cli/runtime_commands.mjs +0 -707
  139. package/src/cli/source_commands.mjs +0 -347
  140. package/src/cli/terminal.mjs +0 -275
  141. package/src/identity/claim.mjs +0 -1163
  142. package/src/identity/provider_configuration.mjs +0 -177
  143. package/src/identity/storage.mjs +0 -165
  144. package/src/project/configuration.mjs +0 -1337
  145. package/src/project/install_scaffold.mjs +0 -291
  146. package/src/project/setup.mjs +0 -466
  147. package/src/project/support_report.mjs +0 -105
  148. package/src/runtime/cleanup.mjs +0 -381
  149. package/src/runtime/migration_history.mjs +0 -220
  150. package/src/runtime/plan.mjs +0 -722
  151. package/src/runtime/policy.mjs +0 -438
  152. package/src/runtime/restore.mjs +0 -337
  153. package/src/runtime/service_environment.mjs +0 -82
  154. package/src/runtime/topology.mjs +0 -177
  155. package/src/shared/diagnostics.mjs +0 -207
  156. package/src/shared/node_runtime.mjs +0 -31
  157. package/src/shared/operation_guard.mjs +0 -162
  158. package/src/shared/process_environment.mjs +0 -68
  159. package/src/source/access.mjs +0 -753
  160. package/src/source/asset_transfer.mjs +0 -207
  161. package/src/source/baseline.mjs +0 -482
  162. package/src/source/external_reader.mjs +0 -255
  163. package/src/source/postgresql_access.mjs +0 -581
  164. package/src/source/privacy_paths.mjs +0 -38
  165. package/src/targets/postgresql.mjs +0 -808
  166. package/src/targets/supabase.mjs +0 -840
  167. package/src/targets/supabase_environment.mjs +0 -229
  168. package/src/targets/target.mjs +0 -66
  169. /package/{src/project → types}/configuration.d.mts +0 -0
@@ -0,0 +1,659 @@
1
+ /**
2
+ * Purpose: Restore and manage the disposable local Rehearsal Supabase runtime from
3
+ * the active verified sanitized baseline.
4
+ * Run: `npm run db:rehearsal:reset`, `npm run db:rehearsal:start`,
5
+ * `npm run db:rehearsal:status`, or `npm run db:rehearsal:stop`.
6
+ * Reset deletes only the dedicated local Rehearsal runtime and its Docker volumes.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { cp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
10
+ import { createReadStream } from "node:fs";
11
+ import { once } from "node:events";
12
+ import { join, resolve } from "node:path";
13
+ import { createInterface } from "node:readline";
14
+ import { pathToFileURL } from "node:url";
15
+ import { resolveActiveBaselinePaths, verifyActiveBaseline, } from "../baseline/artifact.mjs";
16
+ import { createCleanProcessEnvironment, assertLoopbackUrl, } from "../shared/process_environment.mjs";
17
+ import { localCommandSucceeds, readLocalSupabaseEnvironment, removeLocalSupabaseProjectResources, runLocalCommand, startLocalSupabase, stopLocalSupabase, } from "./supabase_environment.mjs";
18
+ import { buildRestoreSqlPrefix, buildRestoreSqlSuffix, createCandidateMigrationReceipt, encodeBaselineRecordForCopy, summarizeRestoreError, } from "../runtime/restore.mjs";
19
+ import { buildMigrationLedgerInventory, compareSourceToReplay, createMigrationReplayReceipt, readMigrationFileInventory, } from "../runtime/migration_history.mjs";
20
+ import { loadRehearsalConfig } from "../project/configuration.mjs";
21
+ import { readRehearsalServiceEnvironment } from "../runtime/service_environment.mjs";
22
+ import { applySupabaseAuthenticationProviders } from "../identity/provider_configuration.mjs";
23
+ import { readBoundRuntimeSanitizationPolicy } from "../baseline/sanitization_policy.mjs";
24
+ import { captureLocalPublicSchema, compareProductionSchemaDumps, } from "../baseline/schema_snapshot.mjs";
25
+ import { formatCount } from "../shared/human_output.mjs";
26
+ import { parseRuntimeInvocation } from "./target.mjs";
27
+ import { buildRuntimeFinalizationSql, buildRuntimePostSchemaSql, buildRuntimePrerequisiteSql, buildRuntimeVerificationSql, validateRuntimePolicy, } from "../runtime/policy.mjs";
28
+ const repositoryRoot = process.cwd();
29
+ const invocation = parseRuntimeInvocation();
30
+ const loadedConfiguration = await loadRehearsalConfig({
31
+ projectRoot: repositoryRoot,
32
+ ...(invocation.configPath === undefined
33
+ ? {}
34
+ : { configPath: invocation.configPath }),
35
+ });
36
+ const { config, paths: configuredPaths } = loadedConfiguration;
37
+ if (!config.supabase) {
38
+ throw new Error("The Supabase runtime requires config.supabase.");
39
+ }
40
+ if (!configuredPaths.rehearsalConfig) {
41
+ throw new Error("The Supabase runtime requires a Rehearsal config template.");
42
+ }
43
+ const supabaseConfig = config.supabase;
44
+ const artifactRoot = configuredPaths.artifactDirectory;
45
+ const runtimeWorkdir = configuredPaths.runtimeWorkdir;
46
+ const runtimeSupabaseDirectory = join(runtimeWorkdir, "supabase");
47
+ const runtimeMarkerPath = join(runtimeWorkdir, "baseline.json");
48
+ const runtimeCandidateReceiptPath = join(runtimeWorkdir, "candidate-receipt.json");
49
+ const environmentPath = configuredPaths.applicationEnvironment;
50
+ const configTemplatePath = configuredPaths.rehearsalConfig;
51
+ const manifestPath = configuredPaths.sanitizationPolicy;
52
+ const applicationMigrations = new URL("./", pathToFileURL(`${configuredPaths.migrationDirectory}/`));
53
+ const projectId = config.runtime.projectId;
54
+ const runtimeAdapter = configuredPaths.runtimeAdapter
55
+ ? (await import(pathToFileURL(configuredPaths.runtimeAdapter).href))
56
+ : null;
57
+ const runtimePolicy = configuredPaths.runtimePolicy
58
+ ? validateRuntimePolicy(JSON.parse(await readFile(configuredPaths.runtimePolicy, "utf8")))
59
+ : null;
60
+ const environmentKeyPattern = /^[A-Z][A-Z0-9_]*$/u;
61
+ const action = invocation.action;
62
+ const readBaselineDataSha256 = (baseline) => {
63
+ const receipt = baseline.files["sanitized-data.ndjson"];
64
+ if (!receipt) {
65
+ throw new Error("The active baseline is missing its sanitized data receipt.");
66
+ }
67
+ return receipt.sha256;
68
+ };
69
+ const readServiceEnvironment = () => readRehearsalServiceEnvironment({
70
+ path: configuredPaths.serviceEnvironment,
71
+ keys: supabaseConfig.serviceEnvironmentVariables,
72
+ blockedKeys: config.safety.blockedEnvironmentVariables,
73
+ });
74
+ const assertRuntimePath = () => {
75
+ const resolvedRoot = resolve(artifactRoot);
76
+ const resolvedRuntime = resolve(runtimeWorkdir);
77
+ if (resolvedRuntime !== join(resolvedRoot, "runtime")) {
78
+ throw new Error("Refusing an unsafe Rehearsal runtime path.");
79
+ }
80
+ };
81
+ const pathExists = async (path) => stat(path)
82
+ .then(() => true)
83
+ .catch((error) => {
84
+ if (typeof error === "object" &&
85
+ error !== null &&
86
+ "code" in error &&
87
+ error.code === "ENOENT")
88
+ return false;
89
+ throw error;
90
+ });
91
+ const hasProjectRuntimeResources = () => {
92
+ const containers = runLocalCommand("docker", [
93
+ "ps",
94
+ "--all",
95
+ "--filter",
96
+ `label=com.supabase.cli.project=${projectId}`,
97
+ "--format",
98
+ "{{.ID}}",
99
+ ], { capture: true, cwd: repositoryRoot }).trim();
100
+ const volumes = runLocalCommand("docker", ["volume", "ls", "--format", "{{.Name}}"], { capture: true, cwd: repositoryRoot })
101
+ .split("\n")
102
+ .some((name) => name.trim().endsWith(`_${projectId}`));
103
+ return Boolean(containers) || volumes;
104
+ };
105
+ const removeRuntime = async () => {
106
+ assertRuntimePath();
107
+ const hasRuntimeConfig = await pathExists(join(runtimeSupabaseDirectory, "config.toml"));
108
+ if (hasRuntimeConfig || hasProjectRuntimeResources()) {
109
+ try {
110
+ const serviceEnvironment = await readServiceEnvironment().catch(() => ({}));
111
+ runLocalCommand("supabase", hasRuntimeConfig
112
+ ? ["stop", "--no-backup", "--workdir", runtimeWorkdir]
113
+ : ["stop", "--no-backup", "--project-id", projectId], { cwd: repositoryRoot, environment: serviceEnvironment });
114
+ }
115
+ catch {
116
+ removeLocalSupabaseProjectResources({
117
+ cwd: repositoryRoot,
118
+ projectId,
119
+ });
120
+ }
121
+ }
122
+ await rm(runtimeWorkdir, { recursive: true, force: true });
123
+ await rm(environmentPath, { force: true });
124
+ };
125
+ const findDatabaseContainer = () => {
126
+ const output = runLocalCommand("docker", [
127
+ "ps",
128
+ "--filter",
129
+ `label=com.supabase.cli.project=${projectId}`,
130
+ "--format",
131
+ "{{.Names}}",
132
+ ], { capture: true, cwd: repositoryRoot });
133
+ const names = output
134
+ .split("\n")
135
+ .map((value) => value.trim())
136
+ .filter((value) => value.startsWith("supabase_db_"));
137
+ if (names.length !== 1) {
138
+ throw new Error(`Expected one local Rehearsal database container; found ${names.length}.`);
139
+ }
140
+ return names[0];
141
+ };
142
+ const writeChunk = async (stream, chunk, completion) => {
143
+ if (stream.destroyed || stream.writableEnded) {
144
+ throw new Error("The Rehearsal restore connection closed early.");
145
+ }
146
+ if (!stream.write(chunk)) {
147
+ await Promise.race([once(stream, "drain"), completion]);
148
+ if (stream.destroyed || stream.writableEnded) {
149
+ throw new Error("The Rehearsal restore connection closed early.");
150
+ }
151
+ }
152
+ };
153
+ const restoreBaselineRows = async ({ baseline, paths, manifest, }) => {
154
+ const child = spawn("docker", [
155
+ "exec",
156
+ "--interactive",
157
+ findDatabaseContainer(),
158
+ "psql",
159
+ "--quiet",
160
+ "--set",
161
+ "ON_ERROR_STOP=1",
162
+ "--username",
163
+ "postgres",
164
+ "--dbname",
165
+ "postgres",
166
+ ], {
167
+ cwd: repositoryRoot,
168
+ env: createCleanProcessEnvironment(),
169
+ stdio: ["pipe", "ignore", "pipe"],
170
+ });
171
+ let stderr = "";
172
+ child.stderr.setEncoding("utf8");
173
+ child.stderr.on("data", (chunk) => {
174
+ stderr = `${stderr}${chunk}`.slice(-16_384);
175
+ });
176
+ const completion = new Promise((complete, reject) => {
177
+ child.once("error", reject);
178
+ child.once("close", complete);
179
+ });
180
+ child.stdin.on("error", () => undefined);
181
+ try {
182
+ await writeChunk(child.stdin, buildRestoreSqlPrefix(), completion);
183
+ const lines = createInterface({
184
+ input: createReadStream(paths.dataPath, { encoding: "utf8" }),
185
+ crlfDelay: Infinity,
186
+ });
187
+ for await (const line of lines) {
188
+ if (line) {
189
+ await writeChunk(child.stdin, `${encodeBaselineRecordForCopy(line)}\n`, completion);
190
+ }
191
+ }
192
+ await writeChunk(child.stdin, buildRestoreSqlSuffix({
193
+ manifest,
194
+ tableCounts: baseline.tableCounts,
195
+ }), completion);
196
+ child.stdin.end();
197
+ const exitCode = await completion;
198
+ if (exitCode !== 0) {
199
+ throw new Error(`The local Rehearsal restore failed. ${summarizeRestoreError(stderr)}`);
200
+ }
201
+ }
202
+ catch (error) {
203
+ if (child.exitCode === null)
204
+ child.kill("SIGTERM");
205
+ await completion.catch(() => undefined);
206
+ throw new Error(`The local Rehearsal restore failed. ${summarizeRestoreError(stderr)}`, { cause: error });
207
+ }
208
+ };
209
+ const restoreBaselineAssets = async ({ baseline, paths, environment, }) => {
210
+ const assets = Object.entries(baseline.storageAssets ?? {});
211
+ if (assets.length === 0)
212
+ return;
213
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
214
+ for (const [relativePath, receipt] of assets) {
215
+ const content = await readFile(join(paths.generationDirectory, relativePath));
216
+ const objectUrl = new URL(`/storage/v1/object/${encodeURIComponent(receipt.bucket)}/${receipt.objectPath
217
+ .split("/")
218
+ .map(encodeURIComponent)
219
+ .join("/")}`, environment.apiUrl);
220
+ const response = await fetch(objectUrl, {
221
+ method: "POST",
222
+ headers: {
223
+ apikey: environment.serviceRoleKey,
224
+ authorization: `Bearer ${environment.serviceRoleKey}`,
225
+ "content-type": receipt.contentType,
226
+ "x-upsert": "true",
227
+ },
228
+ body: content,
229
+ signal: AbortSignal.timeout(30_000),
230
+ });
231
+ if (!response.ok) {
232
+ throw new Error(`The local Rehearsal Storage restore failed for ${receipt.bucket} with status ${response.status}.`);
233
+ }
234
+ }
235
+ };
236
+ const prepareRuntimeWorkdir = async ({ baseline, paths, }) => {
237
+ assertRuntimePath();
238
+ await mkdir(join(runtimeSupabaseDirectory, "migrations"), {
239
+ recursive: true,
240
+ mode: 0o700,
241
+ });
242
+ const configTemplate = await readFile(configTemplatePath, "utf8");
243
+ await writeFile(join(runtimeSupabaseDirectory, "config.toml"), applySupabaseAuthenticationProviders({
244
+ source: configTemplate,
245
+ authentication: supabaseConfig.authentication,
246
+ apiPort: config.runtime.ports.api ??
247
+ (() => {
248
+ throw new Error("The Supabase runtime requires runtime.ports.api.");
249
+ })(),
250
+ }), { mode: 0o600 });
251
+ for (const filename of Object.keys(baseline.migrations).sort()) {
252
+ await cp(join(paths.migrationsDirectory, filename), join(runtimeSupabaseDirectory, "migrations", filename));
253
+ }
254
+ await writeFile(runtimeMarkerPath, `${JSON.stringify({
255
+ formatVersion: 1,
256
+ generationId: baseline.generationId,
257
+ dataSha256: readBaselineDataSha256(baseline),
258
+ }, null, "\t")}\n`, { mode: 0o600 });
259
+ };
260
+ const writeRuntimeEnvironment = async ({ environment, baseline, projectRuntime, }) => {
261
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
262
+ const variables = {
263
+ REHEARSAL_RUNTIME_ENVIRONMENT: "rehearsal",
264
+ REHEARSAL_BASELINE_ID: baseline.generationId,
265
+ DATABASE_URL: environment.databaseUrl,
266
+ PGHOST: environment.databaseHost,
267
+ PGPORT: environment.databasePort,
268
+ PGDATABASE: environment.databaseName,
269
+ PGUSER: environment.databaseUser,
270
+ PGPASSWORD: environment.databasePassword,
271
+ SUPABASE_URL: environment.apiUrl,
272
+ SUPABASE_PUBLISHABLE_KEY: environment.publishableKey,
273
+ SUPABASE_SERVICE_ROLE_KEY: environment.serviceRoleKey,
274
+ ...projectRuntime.environmentVariables,
275
+ };
276
+ await writeFile(environmentPath, [
277
+ "# Generated local Rehearsal runtime credentials. Do not commit.",
278
+ ...Object.entries(variables).map(([key, value]) => `${key}=${value}`),
279
+ "",
280
+ ].join("\n"), { mode: 0o600 });
281
+ };
282
+ function runDatabaseSql(sql) {
283
+ const databaseArguments = [
284
+ "exec",
285
+ "--interactive",
286
+ findDatabaseContainer(),
287
+ "psql",
288
+ "--quiet",
289
+ "--no-align",
290
+ "--tuples-only",
291
+ "--set",
292
+ "ON_ERROR_STOP=1",
293
+ "--username",
294
+ "postgres",
295
+ "--dbname",
296
+ "postgres",
297
+ ];
298
+ return runLocalCommand("docker", databaseArguments, {
299
+ capture: true,
300
+ cwd: repositoryRoot,
301
+ input: sql,
302
+ });
303
+ }
304
+ const restoreProductionSchema = async ({ baseline, paths, }) => {
305
+ const receipt = baseline.files?.["production-schema.sql"];
306
+ if (baseline.formatVersion === 1 && receipt === undefined) {
307
+ if (runtimePolicy) {
308
+ runDatabaseSql(buildRuntimePrerequisiteSql(runtimePolicy));
309
+ runDatabaseSql(buildRuntimePostSchemaSql(runtimePolicy));
310
+ }
311
+ return null;
312
+ }
313
+ if (baseline.formatVersion !== 2 ||
314
+ !/^[a-f0-9]{64}$/u.test(receipt?.sha256 ?? "") ||
315
+ typeof receipt?.bytes !== "number" ||
316
+ !Number.isSafeInteger(receipt.bytes)) {
317
+ throw new Error("The active baseline predates exact production-schema restoration; refresh it first.");
318
+ }
319
+ const schemaSql = await readFile(paths.schemaPath, "utf8");
320
+ runDatabaseSql(`drop schema if exists public cascade;
321
+ create schema public authorization pg_database_owner;
322
+ grant usage on schema public to public;`);
323
+ if (runtimePolicy) {
324
+ runDatabaseSql(buildRuntimePrerequisiteSql(runtimePolicy));
325
+ }
326
+ if (runtimeAdapter?.prepareSchema) {
327
+ const preparation = runtimeAdapter.prepareSchema({
328
+ runSql: runDatabaseSql,
329
+ });
330
+ if (!preparation || typeof preparation.message !== "string") {
331
+ throw new Error("The project runtime adapter returned an invalid schema preparation result.");
332
+ }
333
+ }
334
+ runDatabaseSql(schemaSql);
335
+ if (runtimePolicy) {
336
+ runDatabaseSql(buildRuntimePostSchemaSql(runtimePolicy));
337
+ }
338
+ const restoredSchema = await captureLocalPublicSchema({
339
+ repositoryRoot,
340
+ artifactRoot,
341
+ workdir: runtimeWorkdir,
342
+ });
343
+ return compareProductionSchemaDumps({
344
+ expected: schemaSql,
345
+ actual: restoredSchema,
346
+ });
347
+ };
348
+ const configureProjectRuntime = ({ environment, baseline, }) => {
349
+ assertLoopbackUrl("Rehearsal Supabase API", environment.apiUrl);
350
+ if (!runtimeAdapter?.configureRuntime) {
351
+ return {
352
+ message: "Project-neutral local runtime is configured.",
353
+ environmentVariables: {},
354
+ };
355
+ }
356
+ const projectRuntime = runtimeAdapter.configureRuntime({
357
+ baseline,
358
+ environment,
359
+ runSql: runDatabaseSql,
360
+ });
361
+ if (!projectRuntime ||
362
+ typeof projectRuntime.message !== "string" ||
363
+ !projectRuntime.environmentVariables ||
364
+ typeof projectRuntime.environmentVariables !== "object" ||
365
+ Array.isArray(projectRuntime.environmentVariables)) {
366
+ throw new Error("The project runtime adapter returned an invalid result.");
367
+ }
368
+ for (const [key, value] of Object.entries(projectRuntime.environmentVariables)) {
369
+ if (!environmentKeyPattern.test(key) ||
370
+ typeof value !== "string" ||
371
+ /[\n\r\0]/u.test(value)) {
372
+ throw new Error("The project runtime adapter returned an unsafe environment variable.");
373
+ }
374
+ }
375
+ return projectRuntime;
376
+ };
377
+ const readActive = async () => {
378
+ const [baseline, paths, policyBytes] = await Promise.all([
379
+ verifyActiveBaseline({ artifactRoot }),
380
+ resolveActiveBaselinePaths({ artifactRoot }),
381
+ readFile(manifestPath),
382
+ ]);
383
+ const manifest = readBoundRuntimeSanitizationPolicy({
384
+ bytes: policyBytes,
385
+ expectedSha256: baseline.sanitizationPolicySha256,
386
+ });
387
+ return { baseline, paths, manifest };
388
+ };
389
+ const resetRuntime = async () => {
390
+ const active = await readActive();
391
+ const serviceEnvironment = await readServiceEnvironment();
392
+ await removeRuntime();
393
+ try {
394
+ await prepareRuntimeWorkdir(active);
395
+ const environment = startLocalSupabase({
396
+ cwd: repositoryRoot,
397
+ workdir: runtimeWorkdir,
398
+ exclude: ["edge-runtime", "logflare", "vector", "realtime"],
399
+ environment: serviceEnvironment,
400
+ autoStartColima: config.containerRuntime.autoStartColima,
401
+ });
402
+ const structuralSchemaSha256 = await restoreProductionSchema(active);
403
+ await restoreBaselineRows(active);
404
+ await restoreBaselineAssets({
405
+ baseline: active.baseline,
406
+ paths: active.paths,
407
+ environment,
408
+ });
409
+ if (runtimePolicy && runtimePolicy.localRows.length > 0) {
410
+ runDatabaseSql(buildRuntimeFinalizationSql(runtimePolicy));
411
+ console.log("Applied reviewed local-only recipes.");
412
+ }
413
+ const projectRuntime = configureProjectRuntime({
414
+ environment,
415
+ baseline: active.baseline,
416
+ });
417
+ await writeRuntimeEnvironment({
418
+ environment,
419
+ baseline: active.baseline,
420
+ projectRuntime,
421
+ });
422
+ await writeFile(runtimeMarkerPath, `${JSON.stringify({
423
+ formatVersion: active.baseline.formatVersion,
424
+ generationId: active.baseline.generationId,
425
+ dataSha256: readBaselineDataSha256(active.baseline),
426
+ schemaSha256: active.baseline.files?.["production-schema.sql"]?.sha256 ?? null,
427
+ structuralSchemaSha256,
428
+ }, null, "\t")}\n`, { mode: 0o600 });
429
+ console.log(`Restored Rehearsal baseline ${active.baseline.generationId}: ${formatCount(active.baseline.rowCount, "row")} across ${formatCount(Object.keys(active.baseline.tableCounts).length, "table")}.`);
430
+ console.log(projectRuntime.message);
431
+ return environment;
432
+ }
433
+ catch (error) {
434
+ await removeRuntime().catch(() => undefined);
435
+ throw error;
436
+ }
437
+ };
438
+ const startRuntime = async () => {
439
+ const { baseline } = await readActive();
440
+ if (!(await pathExists(runtimeMarkerPath)))
441
+ return resetRuntime();
442
+ const serviceEnvironment = await readServiceEnvironment();
443
+ const marker = JSON.parse(await readFile(runtimeMarkerPath, "utf8"));
444
+ if (marker.generationId !== baseline.generationId ||
445
+ marker.dataSha256 !== readBaselineDataSha256(baseline) ||
446
+ marker.schemaSha256 !==
447
+ (baseline.files?.["production-schema.sql"]?.sha256 ?? null)) {
448
+ throw new Error("The local Rehearsal runtime does not match the active baseline; run db:rehearsal:reset.");
449
+ }
450
+ const environment = startLocalSupabase({
451
+ cwd: repositoryRoot,
452
+ workdir: runtimeWorkdir,
453
+ exclude: ["edge-runtime", "logflare", "vector", "realtime"],
454
+ environment: serviceEnvironment,
455
+ autoStartColima: config.containerRuntime.autoStartColima,
456
+ });
457
+ const projectRuntime = configureProjectRuntime({ environment, baseline });
458
+ await writeRuntimeEnvironment({
459
+ environment,
460
+ baseline,
461
+ projectRuntime,
462
+ });
463
+ return environment;
464
+ };
465
+ const readCandidateReceipt = async (baseline) => {
466
+ const currentFiles = await readMigrationFileInventory(applicationMigrations);
467
+ return {
468
+ currentFiles,
469
+ ...createCandidateMigrationReceipt({
470
+ baselineManifest: baseline,
471
+ currentFiles,
472
+ }),
473
+ };
474
+ };
475
+ const readRuntimeMigrationLedger = () => {
476
+ const output = runLocalCommand("docker", [
477
+ "exec",
478
+ "--interactive",
479
+ findDatabaseContainer(),
480
+ "psql",
481
+ "--quiet",
482
+ "--no-align",
483
+ "--tuples-only",
484
+ "--set",
485
+ "ON_ERROR_STOP=1",
486
+ "--username",
487
+ "postgres",
488
+ "--dbname",
489
+ "postgres",
490
+ ], {
491
+ capture: true,
492
+ cwd: repositoryRoot,
493
+ input: `select coalesce(json_agg(json_build_object(
494
+ 'version', version,
495
+ 'name', name,
496
+ 'statements', statements
497
+ ) order by version), '[]'::json)::text
498
+ from supabase_migrations.schema_migrations;`,
499
+ });
500
+ return buildMigrationLedgerInventory(JSON.parse(output.trim()), "Rehearsal runtime migration ledger");
501
+ };
502
+ const verifyRuntimeMigrationHistory = async ({ baseline, currentFiles, }) => {
503
+ const ledger = readRuntimeMigrationLedger();
504
+ const appliedFiles = currentFiles.slice(0, ledger.length);
505
+ const replayReceipt = createMigrationReplayReceipt({
506
+ files: appliedFiles,
507
+ ledger,
508
+ });
509
+ if (!baseline.sourceMigrationHistory) {
510
+ throw new Error("The active baseline is missing source migration history.");
511
+ }
512
+ return compareSourceToReplay({
513
+ sourceLedger: baseline.sourceMigrationHistory,
514
+ replayReceipt,
515
+ ...(baseline.files["production-schema.sql"]?.sha256 === undefined
516
+ ? {}
517
+ : {
518
+ snapshotSchemaSha256: baseline.files["production-schema.sql"].sha256,
519
+ }),
520
+ });
521
+ };
522
+ const verifyRuntime = async () => {
523
+ const { baseline } = await readActive();
524
+ const environment = await startRuntime();
525
+ const candidateReceipt = await readCandidateReceipt(baseline);
526
+ const migrationComparison = await verifyRuntimeMigrationHistory({
527
+ baseline,
528
+ currentFiles: candidateReceipt.currentFiles,
529
+ });
530
+ let projectVerification;
531
+ if (runtimePolicy)
532
+ runDatabaseSql(buildRuntimeVerificationSql(runtimePolicy));
533
+ if (runtimeAdapter?.verifyRuntime) {
534
+ projectVerification = runtimeAdapter.verifyRuntime({
535
+ baseline,
536
+ environment,
537
+ runSql: runDatabaseSql,
538
+ });
539
+ if (!projectVerification ||
540
+ typeof projectVerification.message !== "string") {
541
+ throw new Error("The project runtime adapter returned an invalid verification result.");
542
+ }
543
+ }
544
+ console.log(`Verified Rehearsal runtime ${baseline.generationId}: immutable baseline and migration history are valid with ${formatCount(migrationComparison.candidates.length, "applied candidate migration")}. Runtime rows may differ from the baseline until the next reset.`);
545
+ if (projectVerification)
546
+ console.log(projectVerification.message);
547
+ return { baseline, candidateReceipt, migrationComparison };
548
+ };
549
+ const migrateRuntime = async () => {
550
+ const { baseline } = await readActive();
551
+ await startRuntime();
552
+ const receipt = await readCandidateReceipt(baseline);
553
+ if (receipt.candidates.length === 0) {
554
+ await writeFile(runtimeCandidateReceiptPath, `${JSON.stringify({
555
+ formatVersion: 1,
556
+ baselineGenerationId: baseline.generationId,
557
+ candidateSha256: receipt.candidateSha256,
558
+ candidates: [],
559
+ }, null, "\t")}\n`, { mode: 0o600 });
560
+ console.log(`No candidate migrations follow baseline ${baseline.migrationCutoff}.`);
561
+ return receipt;
562
+ }
563
+ console.log(`${receipt.candidates.length === 1 ? "Candidate migration" : "Candidate migrations"} (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ")}`);
564
+ const confirmation = invocation.confirmation;
565
+ if (confirmation !== receipt.candidateSha256) {
566
+ throw new Error("Candidate migration confirmation is missing or does not match the exact SHA-256.");
567
+ }
568
+ try {
569
+ const serviceEnvironment = await readServiceEnvironment();
570
+ for (const candidate of receipt.candidates) {
571
+ await cp(join(configuredPaths.migrationDirectory, candidate.filename), join(runtimeSupabaseDirectory, "migrations", candidate.filename));
572
+ }
573
+ runLocalCommand("supabase", ["migration", "up", "--local", "--workdir", runtimeWorkdir], { cwd: repositoryRoot, environment: serviceEnvironment });
574
+ const comparison = await verifyRuntimeMigrationHistory({
575
+ baseline,
576
+ currentFiles: receipt.currentFiles,
577
+ });
578
+ if (comparison.candidates
579
+ .map((candidate) => candidate.filename)
580
+ .join("\0") !==
581
+ receipt.candidates.map((candidate) => candidate.filename).join("\0")) {
582
+ throw new Error("Applied Rehearsal migration history does not match the confirmed candidate suffix.");
583
+ }
584
+ await writeFile(runtimeCandidateReceiptPath, `${JSON.stringify({
585
+ formatVersion: 1,
586
+ baselineGenerationId: baseline.generationId,
587
+ candidateSha256: receipt.candidateSha256,
588
+ candidates: receipt.candidates.map((candidate) => ({
589
+ filename: candidate.filename,
590
+ sha256: candidate.fileSha256,
591
+ })),
592
+ }, null, "\t")}\n`, { mode: 0o600 });
593
+ console.log(`Applied ${formatCount(receipt.candidates.length, "confirmed candidate migration")} to the disposable Rehearsal runtime.`);
594
+ return receipt;
595
+ }
596
+ catch (error) {
597
+ await removeRuntime().catch(() => undefined);
598
+ throw error;
599
+ }
600
+ };
601
+ switch (action) {
602
+ case "reset":
603
+ await resetRuntime();
604
+ break;
605
+ case "start": {
606
+ const environment = await startRuntime();
607
+ console.log(`Local Rehearsal Supabase: ${environment.apiUrl}`);
608
+ break;
609
+ }
610
+ case "status": {
611
+ const baseline = await verifyActiveBaseline({ artifactRoot });
612
+ const receipt = await readCandidateReceipt(baseline);
613
+ const serviceEnvironment = await readServiceEnvironment();
614
+ const runtimeIsRunning = localCommandSucceeds("supabase", ["status", "--workdir", runtimeWorkdir], { cwd: repositoryRoot, environment: serviceEnvironment });
615
+ if (runtimeIsRunning) {
616
+ const environment = readLocalSupabaseEnvironment({
617
+ cwd: repositoryRoot,
618
+ workdir: runtimeWorkdir,
619
+ environment: serviceEnvironment,
620
+ });
621
+ console.log(`Local Rehearsal Supabase: running at ${environment.apiUrl}`);
622
+ }
623
+ else {
624
+ console.log("Local Rehearsal Supabase: stopped");
625
+ }
626
+ console.log(`Active sanitized baseline: ${baseline.generationId}`);
627
+ console.log(`Candidate migrations (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ") || "none"}`);
628
+ break;
629
+ }
630
+ case "candidates": {
631
+ const baseline = await verifyActiveBaseline({ artifactRoot });
632
+ const receipt = await readCandidateReceipt(baseline);
633
+ console.log(`Candidate migrations (${receipt.candidateSha256}): ${receipt.candidates.map((candidate) => candidate.filename).join(", ") || "none"}`);
634
+ break;
635
+ }
636
+ case "migrate":
637
+ await migrateRuntime();
638
+ break;
639
+ case "verify":
640
+ await verifyRuntime();
641
+ break;
642
+ case "run":
643
+ await resetRuntime();
644
+ await migrateRuntime();
645
+ await verifyRuntime();
646
+ break;
647
+ case "stop":
648
+ stopLocalSupabase({
649
+ cwd: repositoryRoot,
650
+ workdir: runtimeWorkdir,
651
+ environment: await readServiceEnvironment(),
652
+ });
653
+ break;
654
+ case "discard":
655
+ await removeRuntime();
656
+ break;
657
+ default:
658
+ throw new Error(`Unknown Rehearsal database action: ${action}`);
659
+ }