@rehearsal-db/core 0.1.0-beta.9 → 0.1.0-rc.2

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