@rehearsal-db/core 0.1.0-beta.14 → 0.1.0-beta.16

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