@myrialabs/clopen 0.4.38 → 0.4.40

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 (177) hide show
  1. package/backend/auth/permissions.ts +48 -0
  2. package/backend/chat/stream-manager.ts +1 -1
  3. package/backend/database/crypto/secret-columns.ts +9 -1
  4. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  5. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  6. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  7. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  8. package/backend/database/migrations/index.ts +28 -0
  9. package/backend/database/queries/db-client-connection-queries.ts +19 -0
  10. package/backend/database/queries/deploy-queries.ts +124 -0
  11. package/backend/database/queries/graph-queries.ts +291 -247
  12. package/backend/database/queries/index.ts +10 -0
  13. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  14. package/backend/database/queries/integration-queries.ts +34 -6
  15. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  16. package/backend/db-client/cloning.test.ts +161 -0
  17. package/backend/db-client/cloning.ts +672 -0
  18. package/backend/db-client/connection-url.test.ts +117 -0
  19. package/backend/db-client/connection-url.ts +126 -0
  20. package/backend/db-client/drivers/mongodb.ts +2 -14
  21. package/backend/db-client/drivers/mysql.ts +2 -8
  22. package/backend/db-client/drivers/postgres.ts +10 -13
  23. package/backend/db-client/drivers/redis.ts +2 -6
  24. package/backend/db-client/env/detect.ts +438 -0
  25. package/backend/db-client/env/diff.ts +94 -0
  26. package/backend/db-client/env/env.test.ts +574 -0
  27. package/backend/db-client/env/index.ts +15 -0
  28. package/backend/db-client/env/naming.ts +202 -0
  29. package/backend/db-client/env/service.ts +487 -0
  30. package/backend/db-client/integrations/index.ts +44 -0
  31. package/backend/db-client/integrations/links.ts +564 -0
  32. package/backend/db-client/integrations/projector.test.ts +280 -0
  33. package/backend/db-client/integrations/projector.ts +256 -0
  34. package/backend/db-client/integrations/supabase-service.ts +266 -0
  35. package/backend/db-client/providers/neon/adapter.ts +522 -0
  36. package/backend/db-client/providers/neon/api-types.ts +182 -0
  37. package/backend/db-client/providers/neon/client.ts +298 -0
  38. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  39. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  40. package/backend/db-client/providers/neon/list.test.ts +181 -0
  41. package/backend/db-client/providers/registry.ts +27 -0
  42. package/backend/db-client/providers/supabase/adapter.ts +523 -0
  43. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  44. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  45. package/backend/db-client/providers/supabase/client.ts +259 -0
  46. package/backend/db-client/providers/supabase/features.ts +502 -0
  47. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  48. package/backend/db-client/providers/supabase/local.ts +137 -0
  49. package/backend/db-client/providers/types.ts +194 -0
  50. package/backend/deployments/bindings.test.ts +43 -0
  51. package/backend/deployments/bindings.ts +216 -0
  52. package/backend/deployments/index.ts +53 -0
  53. package/backend/deployments/log-streams.ts +214 -0
  54. package/backend/deployments/prompts.ts +70 -0
  55. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  56. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  57. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  58. package/backend/deployments/providers/vercel/client.ts +203 -0
  59. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  60. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  61. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  62. package/backend/deployments/providers/vercel/types.ts +104 -0
  63. package/backend/deployments/registry.ts +27 -0
  64. package/backend/deployments/service.ts +458 -0
  65. package/backend/deployments/types.ts +278 -0
  66. package/backend/env-files/discovery.ts +48 -0
  67. package/backend/env-files/edit.ts +213 -0
  68. package/backend/env-files/env-files.test.ts +515 -0
  69. package/backend/env-files/git.ts +27 -0
  70. package/backend/env-files/index.ts +44 -0
  71. package/backend/env-files/keys.ts +69 -0
  72. package/backend/env-files/parse.ts +157 -0
  73. package/backend/env-files/write.ts +229 -0
  74. package/backend/index.ts +4 -0
  75. package/backend/integrations/health.ts +18 -4
  76. package/backend/integrations/projections/index.ts +0 -0
  77. package/backend/integrations/projections/mcp-projector.ts +7 -3
  78. package/backend/integrations/projections/types.ts +28 -9
  79. package/backend/integrations/registry/index.ts +8 -1
  80. package/backend/integrations/registry/providers/context7.ts +1 -0
  81. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  82. package/backend/integrations/registry/providers/github.ts +1 -0
  83. package/backend/integrations/registry/providers/neon.ts +55 -0
  84. package/backend/integrations/registry/providers/supabase.ts +62 -0
  85. package/backend/integrations/registry/providers/vercel.ts +47 -0
  86. package/backend/integrations/registry/types.ts +2 -0
  87. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  88. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  89. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  90. package/backend/memory/README.md +57 -34
  91. package/backend/memory/compose.test.ts +3 -3
  92. package/backend/memory/compose.ts +6 -9
  93. package/backend/memory/config.ts +0 -5
  94. package/backend/memory/consolidate.ts +1 -2
  95. package/backend/memory/context.test.ts +8 -54
  96. package/backend/memory/context.ts +19 -25
  97. package/backend/memory/extract/episodic.ts +10 -12
  98. package/backend/memory/extract/index.ts +23 -52
  99. package/backend/memory/extract/scheduler.ts +3 -6
  100. package/backend/memory/index.ts +6 -5
  101. package/backend/memory/invalidate.ts +36 -48
  102. package/backend/memory/layout.ts +319 -130
  103. package/backend/memory/retention.ts +12 -42
  104. package/backend/memory/retrieval.eval.test.ts +2 -2
  105. package/backend/memory/retrieval.test.ts +228 -183
  106. package/backend/memory/retrieval.ts +22 -21
  107. package/backend/memory/revise.test.ts +62 -116
  108. package/backend/memory/revise.ts +0 -1
  109. package/backend/memory/view.ts +8 -5
  110. package/backend/snapshot/helpers.ts +35 -41
  111. package/backend/snapshot/snapshot-service.ts +90 -0
  112. package/backend/snapshot/turn-changes.test.ts +163 -0
  113. package/backend/snapshot/turn-changes.ts +131 -0
  114. package/backend/work/start-work.ts +4 -0
  115. package/backend/worktrees/branching/engine.ts +557 -0
  116. package/backend/worktrees/branching/index.ts +56 -0
  117. package/backend/worktrees/branching/naming.test.ts +118 -0
  118. package/backend/worktrees/branching/naming.ts +97 -0
  119. package/backend/worktrees/branching/projector.test.ts +229 -0
  120. package/backend/worktrees/branching/projector.ts +139 -0
  121. package/backend/worktrees/branching/providers/neon.ts +220 -0
  122. package/backend/worktrees/branching/registry.ts +27 -0
  123. package/backend/worktrees/branching/service.ts +620 -0
  124. package/backend/worktrees/branching/suggest.test.ts +154 -0
  125. package/backend/worktrees/branching/suggest.ts +202 -0
  126. package/backend/worktrees/branching/types.ts +88 -0
  127. package/backend/worktrees/index.ts +7 -0
  128. package/backend/worktrees/service.ts +48 -1
  129. package/backend/ws/db-client/accounts.ts +225 -0
  130. package/backend/ws/db-client/connections.ts +34 -3
  131. package/backend/ws/db-client/context.ts +37 -0
  132. package/backend/ws/db-client/env.ts +142 -0
  133. package/backend/ws/db-client/index.ts +22 -1
  134. package/backend/ws/db-client/supabase.ts +188 -0
  135. package/backend/ws/deployments/actions.ts +360 -0
  136. package/backend/ws/deployments/context.ts +43 -0
  137. package/backend/ws/deployments/crud.ts +152 -0
  138. package/backend/ws/deployments/index.ts +15 -0
  139. package/backend/ws/deployments/schemas.ts +183 -0
  140. package/backend/ws/index.ts +6 -2
  141. package/backend/ws/memory/crud.ts +4 -16
  142. package/backend/ws/projects/index.ts +6 -1
  143. package/backend/ws/projects/info.ts +70 -6
  144. package/backend/ws/projects/overview.test.ts +108 -0
  145. package/backend/ws/projects/overview.ts +300 -0
  146. package/backend/ws/snapshot/changes.ts +279 -0
  147. package/backend/ws/snapshot/index.ts +4 -3
  148. package/backend/ws/system/device-info.ts +307 -76
  149. package/backend/ws/worktrees/branching.ts +212 -0
  150. package/backend/ws/worktrees/crud.ts +33 -7
  151. package/backend/ws/worktrees/index.ts +14 -0
  152. package/dist/assets/{index-DSHIANSy.js → index-D4igjF6e.js} +1 -1
  153. package/dist/assets/{index-CyH7fSbR.js → index-DONNwiXm.js} +1 -1
  154. package/dist/assets/main-BrfXH1bL.js +1205 -0
  155. package/dist/assets/main-CT1PygsW.css +1 -0
  156. package/dist/index.html +2 -2
  157. package/package.json +1 -1
  158. package/shared/constants/tool-icons.ts +13 -0
  159. package/shared/types/db-client/connection.ts +6 -0
  160. package/shared/types/db-client/env.ts +192 -0
  161. package/shared/types/db-client/index.ts +3 -0
  162. package/shared/types/db-client/integrations.ts +204 -0
  163. package/shared/types/db-client/supabase.ts +131 -0
  164. package/shared/types/deployments.ts +382 -0
  165. package/shared/types/integrations.ts +9 -0
  166. package/shared/types/memory.ts +34 -51
  167. package/shared/types/ui/components.ts +1 -1
  168. package/shared/types/worktree-branching.ts +315 -0
  169. package/shared/utils/diff-calculator.test.ts +89 -0
  170. package/shared/utils/diff-calculator.ts +30 -65
  171. package/shared/utils/logger.ts +2 -0
  172. package/backend/memory/extract/languages.ts +0 -176
  173. package/backend/memory/extract/structural.test.ts +0 -215
  174. package/backend/memory/extract/structural.ts +0 -364
  175. package/backend/ws/snapshot/content.ts +0 -85
  176. package/dist/assets/main-D2IOjftb.css +0 -1
  177. package/dist/assets/main-DM-tHKbW.js +0 -1152
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Deploy-provider adapter contract.
3
+ *
4
+ * This is the interface `Task 3` exists to build. Vercel is the first provider
5
+ * behind it; Netlify, Railway, Fly.io, Render, Coolify/Dokploy and Cloudflare
6
+ * Pages are meant to land as another directory in `providers/` and one line in
7
+ * the registry. If any of them needs a change to the PANEL, this interface is
8
+ * what was wrong.
9
+ *
10
+ * Note what this is NOT: a projector. A projection derives a row on a surface
11
+ * that already has its own table — `mcp_servers` for agent tools,
12
+ * `db_client_connections` for a database. Deployments are never copied locally
13
+ * (see migration 075), so there is no derived row to keep in step. A deploy
14
+ * provider registers CODE here, and the account row itself is what makes it
15
+ * appear in the panel. That is the same conclusion the Issues surface reached.
16
+ *
17
+ * Every optional method is paired with a flag in `capabilities`. A caller must
18
+ * read the flag rather than probe for the method, because the panel renders its
19
+ * controls before any call is made.
20
+ */
21
+
22
+ import type {
23
+ BuildLogBundle,
24
+ Deployment,
25
+ DeploymentDetail,
26
+ DeploymentDraft,
27
+ DeploymentPage,
28
+ DeployBindingConfig,
29
+ DeployInfo,
30
+ DeployProjectStatus,
31
+ DeployProviderCapabilities,
32
+ DeployTarget,
33
+ NewProjectDraft
34
+ } from '$shared/types/deployments';
35
+ import type { IntegrationAccountRow } from '$backend/database/queries';
36
+
37
+ /**
38
+ * What an adapter can say about deployability.
39
+ *
40
+ * The client-facing `DeployInfo` also carries facts read from the LOCAL working
41
+ * tree — the suggested repository, the checked-out branch — which an adapter
42
+ * has no business knowing about, and the readiness verdict, which the route
43
+ * composes. This is deliberately the shared shape minus those rather than a
44
+ * second declaration that could drift.
45
+ */
46
+ export type AdapterDeployInfo = Omit<
47
+ DeployInfo,
48
+ 'suggestedRepo' | 'connectState' | 'connectHint' | 'connectUrl' | 'currentBranch'
49
+ >;
50
+
51
+ /**
52
+ * Whether a specific repository could be attached, and what to do if not.
53
+ *
54
+ * `unknown` is a first-class answer rather than an optimistic `true`: a check
55
+ * we could not read must not present itself as a green light, because the cost
56
+ * of being wrong is the exact failure the check exists to prevent.
57
+ */
58
+ export interface RepositoryAccess {
59
+ state: 'ready' | 'blocked' | 'unknown';
60
+ reason: string | null;
61
+ /** Provider settings page that fixes it, when there is one. */
62
+ actionUrl: string | null;
63
+ }
64
+
65
+ /** The remote project one account is pointed at, for one Clopen project. */
66
+ export interface ResolvedDeployBinding {
67
+ locator: string;
68
+ displayName: string;
69
+ detected: boolean;
70
+ teamId: string | null;
71
+ config: DeployBindingConfig;
72
+ }
73
+
74
+ /**
75
+ * Everything an adapter call needs.
76
+ *
77
+ * `credentials` is already decoded. It is assembled by the service from the
78
+ * account row and never leaves the backend — no route serialises it, and the
79
+ * adapter must not put it anywhere a `Deployment` can carry it back out.
80
+ */
81
+ export interface DeployContext {
82
+ projectId: string;
83
+ account: IntegrationAccountRow;
84
+ credentials: Record<string, string>;
85
+ binding: ResolvedDeployBinding;
86
+ }
87
+
88
+ /** Same, before a binding exists — the only calls that can run unbound. */
89
+ export interface UnboundDeployContext {
90
+ projectId: string;
91
+ account: IntegrationAccountRow;
92
+ credentials: Record<string, string>;
93
+ }
94
+
95
+ /** How the list is narrowed. Everything optional is "not set", never a default. */
96
+ export interface DeploymentQuery {
97
+ environment: 'production' | 'preview' | 'custom' | 'all';
98
+ branch?: string;
99
+ /** Opaque cursor from the previous page. */
100
+ cursor?: string;
101
+ limit?: number;
102
+ }
103
+
104
+ /** A live log follow, as the stream manager drives it. */
105
+ export interface LogStreamHandle {
106
+ /** Stop the follow and release whatever socket is behind it. */
107
+ stop: () => void;
108
+ }
109
+
110
+ export interface LogStreamCallbacks {
111
+ onChunk: (text: string) => void;
112
+ /**
113
+ * The build moved to a new stage.
114
+ *
115
+ * Separate from the log text because it answers a different question. A log
116
+ * says what a command printed; this says what the provider is DOING — and
117
+ * during the long quiet stretches of a build (uploading, provisioning,
118
+ * assigning domains) the log prints nothing at all, which is exactly when a
119
+ * watcher most needs to know it has not stalled.
120
+ */
121
+ onPhase?: (phase: string) => void;
122
+ /** Called exactly once, with a message when the follow ended badly. */
123
+ onEnd: (error: string | null) => void;
124
+ }
125
+
126
+ export interface DeployProviderAdapter {
127
+ /** Must match the `IntegrationProvider.id` this adapter serves. */
128
+ provider: string;
129
+ capabilities: DeployProviderCapabilities;
130
+
131
+ /**
132
+ * Read the provider's own CLI config out of the project, if it left one.
133
+ *
134
+ * This is what makes binding automatic for a project someone has already
135
+ * linked: `.vercel/project.json` names the project and the team, and asking
136
+ * the user to pick it from a dropdown would be asking them to retype a file
137
+ * that is sitting in their repository.
138
+ *
139
+ * Returns null when there is no such file, which is the ordinary case and
140
+ * not an error.
141
+ */
142
+ detectFromProject?(projectRoot: string): Promise<{ locator: string; teamId: string | null } | null>;
143
+
144
+ /**
145
+ * Remote projects this credential can reach.
146
+ *
147
+ * Used for the binding picker, and for the second detection pass: each
148
+ * target carries the git repository it is connected to, so a project whose
149
+ * `origin` matches one of them can be bound without the user choosing.
150
+ */
151
+ listTargets(context: UnboundDeployContext): Promise<DeployTarget[]>;
152
+
153
+ /** Resolve one target, so a stored locator can be given a display name. */
154
+ describeTarget(context: UnboundDeployContext, locator: string, teamId: string | null): Promise<DeployTarget | null>;
155
+
156
+ /**
157
+ * Is this credential good, and does it reach the bound project?
158
+ *
159
+ * Runs at connect time and from the hub's health button. A token that is
160
+ * valid but cannot see the bound project must fail HERE, naming which of the
161
+ * two it is — not later as an empty list that looks like "no deployments".
162
+ */
163
+ probe(context: UnboundDeployContext, binding: ResolvedDeployBinding | null): Promise<{
164
+ status: 'ok' | 'needs_auth' | 'needs_config' | 'error';
165
+ detail: string | null;
166
+ }>;
167
+
168
+ list(context: DeployContext, query: DeploymentQuery): Promise<DeploymentPage>;
169
+ get(context: DeployContext, id: string): Promise<DeploymentDetail>;
170
+
171
+ /** Build logs as one budgeted bundle — what the chat prompt is built from. */
172
+ fetchLogs?(context: DeployContext, id: string): Promise<BuildLogBundle>;
173
+
174
+ /**
175
+ * Follow a running build's logs.
176
+ *
177
+ * Only called when `capabilities.streamLogs` is set. The handle must stop
178
+ * the underlying request: the stream manager closes it when the last viewer
179
+ * leaves, and a follow nobody aborts is an open socket for the life of the
180
+ * process.
181
+ */
182
+ streamLogs?(context: DeployContext, id: string, callbacks: LogStreamCallbacks): Promise<LogStreamHandle>;
183
+
184
+ /**
185
+ * Outward-facing actions. Each is gated by its capability flag, and the
186
+ * caller has already confirmed with the user before any of these run.
187
+ *
188
+ * `rollback` and `promote` return `pending` rather than `done` when the
189
+ * provider moves traffic asynchronously, which Vercel does — reporting them
190
+ * as complete would tell someone their incident was over before it was.
191
+ */
192
+ redeploy?(context: DeployContext, id: string): Promise<{ deploymentId: string | null; message: string }>;
193
+ cancel?(context: DeployContext, id: string): Promise<{ message: string }>;
194
+ rollback?(context: DeployContext, id: string): Promise<{ status: 'done' | 'pending'; message: string }>;
195
+ promote?(context: DeployContext, id: string): Promise<{ status: 'done' | 'pending'; message: string }>;
196
+
197
+ /**
198
+ * What starting a build from here would need, and whether it is possible.
199
+ *
200
+ * Answered before the deploy dialog opens so the dialog can prefill the
201
+ * branch and refuse honestly, rather than offering a button whose failure is
202
+ * only discovered after someone presses it.
203
+ */
204
+ deployInfo?(context: DeployContext): Promise<AdapterDeployInfo>;
205
+
206
+ /**
207
+ * Start a NEW build from a branch.
208
+ *
209
+ * Distinct from `redeploy`, which copies an existing deployment: this is the
210
+ * only path available to a project that has never been deployed. Outward
211
+ * facing — the caller has confirmed first.
212
+ */
213
+ createDeployment?(
214
+ context: DeployContext,
215
+ draft: DeploymentDraft
216
+ ): Promise<{ deploymentId: string | null; message: string }>;
217
+
218
+ /**
219
+ * Create a remote project.
220
+ *
221
+ * Unbound on purpose: this is what a Clopen project with nothing to point at
222
+ * does, so there is no binding yet. The caller binds to the result.
223
+ */
224
+ createProject?(context: UnboundDeployContext, draft: NewProjectDraft): Promise<DeployTarget>;
225
+
226
+ /**
227
+ * Can this repository be attached, and if not, what would fix it.
228
+ *
229
+ * Asked before `connectRepository` is offered, and also before the new-project
230
+ * form offers to connect a repository to something that does not exist yet —
231
+ * which is why it takes an UNBOUND context. It reads a property of the
232
+ * account, not of any particular project.
233
+ *
234
+ * Attaching a repository needs the ACCOUNT to have git access of its own,
235
+ * established on the provider's site and impossible with an API token — the
236
+ * one prerequisite Clopen can detect but not satisfy. Naming it beats a
237
+ * button that fails.
238
+ */
239
+ repositoryAccess?(context: UnboundDeployContext, gitRepo: string): Promise<RepositoryAccess>;
240
+
241
+ /**
242
+ * Attach a git repository to the bound remote project.
243
+ *
244
+ * The escape hatch from "this project is not connected to a git repository,
245
+ * so it cannot be deployed from here" — which is otherwise a dead end that
246
+ * sends the user to the provider's dashboard.
247
+ */
248
+ connectRepository?(
249
+ context: DeployContext,
250
+ repo: { gitRepo: string; gitProvider: string }
251
+ ): Promise<void>;
252
+
253
+ /**
254
+ * Delete a deployment outright.
255
+ *
256
+ * Outward-facing and irreversible — the build, its logs and its URLs all go.
257
+ * The caller confirms, and must not offer it for whatever is currently
258
+ * serving production.
259
+ */
260
+ deleteDeployment?(context: DeployContext, id: string): Promise<{ message: string }>;
261
+
262
+ /**
263
+ * State that belongs to the target, not to any one build.
264
+ *
265
+ * Also carries the outcome of a rollback or promotion still in flight, which
266
+ * is the only way to turn the `pending` those actions return into an answer.
267
+ */
268
+ projectStatus?(context: DeployContext): Promise<DeployProjectStatus>;
269
+
270
+ /** Who the stored credential belongs to. Shown beside the account label. */
271
+ viewer?(context: UnboundDeployContext): Promise<string | null>;
272
+
273
+ /**
274
+ * The deployment currently serving production traffic, if the provider can
275
+ * answer it directly rather than by inference from the list.
276
+ */
277
+ currentProduction?(context: DeployContext): Promise<Deployment | null>;
278
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Finding the dotenv files a project actually has.
3
+ *
4
+ * Ordered rather than alphabetical, and the order is the reason this is shown
5
+ * at all: Next.js and Vite read `.env.local` IN PREFERENCE to `.env`, so a
6
+ * project with both has exactly one right answer and picking the other produces
7
+ * the worst outcome available — the variable is written and nothing reads it.
8
+ */
9
+
10
+ import fs from 'fs/promises';
11
+ import { envFilePrecedence, isDotenvFileName, isTemplateEnvFile } from './keys';
12
+
13
+ export interface DotenvFileEntry {
14
+ name: string;
15
+ /** True for `.env.example` and friends: read for their shape, never written. */
16
+ isTemplate: boolean;
17
+ }
18
+
19
+ /** Every dotenv-shaped file in the root, templates included, most-precedent first. */
20
+ export async function listEnvFileEntries(projectRoot: string): Promise<DotenvFileEntry[]> {
21
+ let entries: string[];
22
+ try {
23
+ entries = await fs.readdir(projectRoot);
24
+ } catch {
25
+ return [];
26
+ }
27
+
28
+ return entries
29
+ .filter((name) => isDotenvFileName(name))
30
+ .map((name) => ({ name, isTemplate: isTemplateEnvFile(name) }))
31
+ .sort(
32
+ (a, b) =>
33
+ Number(a.isTemplate) - Number(b.isTemplate) ||
34
+ envFilePrecedence(a.name) - envFilePrecedence(b.name) ||
35
+ a.name.localeCompare(b.name)
36
+ );
37
+ }
38
+
39
+ /**
40
+ * The files a project would LOAD, most-precedent first.
41
+ *
42
+ * Templates are excluded. `.env.example` is documentation, and writing a live
43
+ * password into the file a project commits is the opposite of the rule above.
44
+ */
45
+ export async function listDotenvFiles(projectRoot: string): Promise<string[]> {
46
+ const entries = await listEnvFileEntries(projectRoot);
47
+ return entries.filter((entry) => !entry.isTemplate).map((entry) => entry.name);
48
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Editing a dotenv file without rewriting it.
3
+ *
4
+ * **In place**, when the project already assigns the variable. The value is
5
+ * replaced exactly where it was, so the file keeps the shape its author gave
6
+ * it, and the previous value is left behind as a comment — the whole point of
7
+ * touching someone's configuration is that they can get it back. This is the
8
+ * mode that answers "my project calls it `POSTGRES_URL`, not `DATABASE_URL`":
9
+ * nothing is guessed, the existing key is what gets written.
10
+ *
11
+ * **Appended**, plainly, for a variable the file does not have yet.
12
+ *
13
+ * NO MARKED BLOCK, and there used to be one. It existed to tell Clopen's lines
14
+ * from the user's so that undoing could not delete a variable they wrote — but
15
+ * it cost three lines of scaffolding around one value, and worse, a block that
16
+ * has to come LAST leaves the project's own `DATABASE_URL` sitting untouched
17
+ * above it. A reader takes the last assignment, so the file WORKS and looks
18
+ * like it does not, which is the least defensible thing a config editor can do.
19
+ *
20
+ * Removal keeps the guarantee more cheaply. A replaced value is restored from
21
+ * the comment left beside it, and an appended key is removed only while it
22
+ * still holds exactly what was written — anything else is the user's and stays.
23
+ *
24
+ * Backups do not stack. A second apply removes the comment the first one left
25
+ * for the same key before writing a new one, or a file rewritten weekly would
26
+ * grow a dead line per week.
27
+ */
28
+
29
+ import { formatEnvLine } from './keys';
30
+ import { effectiveAssignment, parseDotenv } from './parse';
31
+
32
+ /** Marks the line holding a value Clopen replaced, so it can be put back. */
33
+ export const PREVIOUS_VALUE_PREFIX = '# clopen:previous ';
34
+
35
+ export interface EnvUpsertOptions {
36
+ /** A comment written above the appended lines, naming where they came from. */
37
+ note?: string;
38
+ }
39
+
40
+ export interface EnvUpsertResult {
41
+ text: string;
42
+ /** Keys whose existing assignment was rewritten where it stood. */
43
+ updated: string[];
44
+ /** Keys the file did not have, now in the managed block. */
45
+ appended: string[];
46
+ /** Keys already holding exactly this value. */
47
+ unchanged: string[];
48
+ }
49
+
50
+ /** The key a `# clopen:previous …` line is a backup of, or null. */
51
+ function keyOfBackup(line: string): string | null {
52
+ const trimmed = line.trim();
53
+ if (!trimmed.startsWith(PREVIOUS_VALUE_PREFIX)) return null;
54
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=/.exec(
55
+ trimmed.slice(PREVIOUS_VALUE_PREFIX.length)
56
+ );
57
+ return match ? match[1] : null;
58
+ }
59
+
60
+ /**
61
+ * Whether this file uses Windows line endings.
62
+ *
63
+ * Everything below works in LF and converts back at the end, so a file written
64
+ * on Windows keeps its own convention instead of gaining one mixed line per
65
+ * variable Clopen touches.
66
+ */
67
+ function usesCrlf(content: string): boolean {
68
+ return /\r\n/.test(content);
69
+ }
70
+
71
+ export function upsertEnvKeys(
72
+ content: string,
73
+ vars: Record<string, string>,
74
+ options: EnvUpsertOptions = {}
75
+ ): EnvUpsertResult {
76
+ const keys = Object.keys(vars);
77
+ const crlf = usesCrlf(content);
78
+ if (crlf) content = content.replace(/\r\n/g, '\n');
79
+
80
+ // Our own backup comments for the keys being written come out first, so this
81
+ // apply replaces them rather than adding a second one. Backups for keys NOT
82
+ // in this write are left alone — they still document a value we replaced.
83
+ const base = content
84
+ .split('\n')
85
+ .filter((line) => {
86
+ const key = keyOfBackup(line);
87
+ return !(key !== null && keys.includes(key));
88
+ })
89
+ .join('\n');
90
+
91
+ const assignments = parseDotenv(base);
92
+ const lines = base.split('\n');
93
+
94
+ const updated: string[] = [];
95
+ const appended: string[] = [];
96
+ const unchanged: string[] = [];
97
+ /** Keys bound for the block, whether or not their value changed. */
98
+ const placed: string[] = [];
99
+ const edits: { line: number; lineCount: number; replacement: string[] }[] = [];
100
+
101
+ for (const key of keys) {
102
+ const value = vars[key];
103
+ const existing = effectiveAssignment(assignments, key);
104
+
105
+ if (!existing) {
106
+ placed.push(key);
107
+ appended.push(key);
108
+ continue;
109
+ }
110
+ if (existing.value === value) {
111
+ unchanged.push(key);
112
+ continue;
113
+ }
114
+
115
+ edits.push({
116
+ line: existing.line,
117
+ lineCount: existing.lineCount,
118
+ replacement: [
119
+ // Folded to one line. A multi-line quoted value would otherwise
120
+ // become several comment lines, only the first of which is a comment.
121
+ `${PREVIOUS_VALUE_PREFIX}${existing.raw.split('\n').join(' ')}`,
122
+ formatEnvLine(key, value)
123
+ ]
124
+ });
125
+ updated.push(key);
126
+ }
127
+
128
+ // Back to front, so every line index recorded above stays valid.
129
+ for (const edit of edits.sort((a, b) => b.line - a.line)) {
130
+ lines.splice(edit.line, edit.lineCount, ...edit.replacement);
131
+ }
132
+
133
+ const added =
134
+ placed.length > 0
135
+ ? [
136
+ ...(options.note ? [`# ${options.note}`] : []),
137
+ ...placed.map((key) => formatEnvLine(key, vars[key]))
138
+ ]
139
+ : [];
140
+
141
+ const text = appendPlainLines(lines.join('\n'), added);
142
+
143
+ return {
144
+ text: crlf ? text.replace(/\n/g, '\r\n') : text,
145
+ updated,
146
+ appended,
147
+ unchanged
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Add lines to the end of a file, with no markers around them.
153
+ *
154
+ * One blank line between the user's content and ours, and none when the file
155
+ * was empty — which is what someone appending by hand would do.
156
+ */
157
+ function appendPlainLines(existing: string, lines: string[]): string {
158
+ if (lines.length === 0) return existing;
159
+ const block = `${lines.join('\n')}\n`;
160
+ if (!existing.trim()) return block;
161
+ return `${existing.replace(/\n*$/, '')}\n\n${block}`;
162
+ }
163
+
164
+ /**
165
+ * Take the write back out.
166
+ *
167
+ * The managed block goes entirely, and every value replaced in place is
168
+ * restored from the comment left beside it. A key with no backup is LEFT
169
+ * ALONE rather than deleted: it was the project's own variable before Clopen
170
+ * touched it, and removing a variable the app needs is worse than leaving one
171
+ * pointing at a database the user can still reach.
172
+ */
173
+ export function removeEnvKeys(
174
+ content: string,
175
+ keys: string[],
176
+ options: { values?: Record<string, string> } = {}
177
+ ): string {
178
+ const crlf = usesCrlf(content);
179
+ const lines = (crlf ? content.replace(/\r\n/g, '\n') : content).split('\n');
180
+
181
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
182
+ const key = keyOfBackup(lines[index]);
183
+ if (key === null || !keys.includes(key)) continue;
184
+
185
+ const original = lines[index].trim().slice(PREVIOUS_VALUE_PREFIX.length);
186
+ // The line we wrote sits directly below its backup. When it does not, the
187
+ // user has edited it since, and their line is the one that stays.
188
+ const next = lines[index + 1] ?? '';
189
+ const ours = new RegExp(`^\\s*(?:export\\s+)?${key}[ \\t]*=`).test(next);
190
+ lines.splice(index, ours ? 2 : 1, original);
191
+ }
192
+
193
+ // Keys that were APPENDED have no backup to restore, so they are removed —
194
+ // but only while they still hold exactly what was written. A value the user
195
+ // has since edited is theirs now, and deleting it would be this feature
196
+ // taking away a variable it did not put there.
197
+ if (options.values) {
198
+ const ours = parseDotenv(lines.join('\n')).filter(
199
+ (entry) =>
200
+ !entry.commented &&
201
+ keys.includes(entry.key) &&
202
+ options.values?.[entry.key] === entry.value
203
+ );
204
+ // Back to front, so every recorded position stays valid.
205
+ for (const entry of ours.reverse()) lines.splice(entry.line, entry.lineCount);
206
+ // The blank line that separated the appended lines from the user's own
207
+ // content has nothing left to separate.
208
+ while (lines.length > 1 && lines.at(-1) === '' && lines.at(-2) === '') lines.pop();
209
+ }
210
+
211
+ const text = lines.join('\n');
212
+ return crlf ? text.replace(/\n/g, '\r\n') : text;
213
+ }