@myrialabs/clopen 0.4.39 → 0.4.41

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 (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -17,13 +17,25 @@
17
17
  * account a model belongs to, so resolve against it and treat the caller's
18
18
  * `providerSlug` as a hint. Keeping this in one place means a new engine is
19
19
  * covered without touching any call site.
20
+ *
21
+ * It is also the only place that can tell a MISCONFIGURED generation apart from
22
+ * a failed one. An engine handed a blank or stale model id doesn't refuse — it
23
+ * runs with no model and returns nothing, surfacing as "OpenCode returned empty
24
+ * response" (or the equivalent on any other engine), which tells the user
25
+ * neither what went wrong nor where to fix it. So the checks below fail loudly,
26
+ * before the engine is called, naming the settings page that owns the choice.
20
27
  */
21
28
 
22
- import { getModelsByEngine, registerModels } from '$shared/constants/engines';
29
+ import { getModelsByEngine, registerModels, ENGINES } from '$shared/constants/engines';
23
30
  import { debug } from '$shared/utils/logger';
24
31
  import type { EngineModel } from '$shared/types/unified';
25
32
  import type { AIEngine } from './types';
26
33
 
34
+ /** Human name for an engine, for error messages that point at Settings. */
35
+ function engineLabel(engineType: string): string {
36
+ return ENGINES.find(e => e.type === engineType)?.name ?? engineType;
37
+ }
38
+
27
39
  /** Engine-verified coordinates for a one-shot generation call. */
28
40
  export interface GenerationTarget {
29
41
  providerSlug: string;
@@ -32,22 +44,44 @@ export interface GenerationTarget {
32
44
  accountId?: number;
33
45
  }
34
46
 
47
+ /**
48
+ * Where the user picks the model for this generation, named in error messages so
49
+ * the fix is one click away instead of a guess.
50
+ */
51
+ export const GENERATION_SETTINGS = {
52
+ artifact: 'Settings → Models → Artifacts',
53
+ commit: 'Settings → Models → Commit message',
54
+ memory: 'Settings → Models → Memory',
55
+ assistant: 'Settings → Models'
56
+ } as const;
57
+
58
+ export type GenerationSettingsPath = (typeof GENERATION_SETTINGS)[keyof typeof GENERATION_SETTINGS];
59
+
35
60
  /**
36
61
  * Resolve `providerSlug` (and the owning account) for `modelId` from the
37
62
  * engine's catalog. `providerHint` is the caller-supplied slug — used only when
38
63
  * the catalog can't answer.
39
64
  *
40
- * Throws when the model belongs to no provider this engine offers, which is a
41
- * far more actionable error than the engine-specific failure it would become.
65
+ * Throws when the model is blank, when the engine offers no models at all, or
66
+ * when the catalog says the model doesn't exist. Each of those would otherwise
67
+ * become an opaque "returned empty response" deep inside an adapter.
42
68
  */
43
69
  export async function resolveGenerationTarget(
44
70
  engine: AIEngine,
45
71
  modelId: string,
46
- providerHint?: string
72
+ providerHint?: string,
73
+ settingsPath: string = GENERATION_SETTINGS.assistant
47
74
  ): Promise<GenerationTarget> {
48
75
  const engineType = engine.name;
76
+ const label = engineLabel(engineType);
49
77
  const byId = (models: EngineModel[]) => models.find(m => m.engine.model.id === modelId);
50
78
 
79
+ // No model at all. Engines that take `model` as optional silently fall back to
80
+ // a default that may not exist, so this can never be passed through.
81
+ if (!modelId.trim()) {
82
+ throw new Error(`No model is selected for ${label}. Choose one in ${settingsPath}.`);
83
+ }
84
+
51
85
  // The registry is filled by `models:list`; only pay for a catalog fetch when
52
86
  // this process hasn't seen the engine (or the model) yet.
53
87
  let catalog = getModelsByEngine(engineType);
@@ -76,12 +110,21 @@ export async function resolveGenerationTarget(
76
110
  };
77
111
  }
78
112
 
79
- // Unknown model: only trust the hint if this engine actually serves that
80
- // provider, otherwise it is drift and would fail deep inside the adapter.
81
- if (providerHint && catalog.some(m => m.engine.provider === providerHint)) {
82
- debug.warn('engine', `Model "${modelId}" missing from ${engineType} catalog; falling back to caller provider "${providerHint}"`);
83
- return { providerSlug: providerHint, modelId };
113
+ // The catalog came back empty: the engine isn't signed in, or has no provider
114
+ // configured. Saying "pick a model again" would be useless — there is nothing
115
+ // to pick until the engine itself is set up.
116
+ if (catalog.length === 0) {
117
+ throw new Error(
118
+ `${label} has no models available — it may not be signed in or configured. ` +
119
+ `Set it up in Settings → Engines → ${label}, then choose a model in ${settingsPath}.`
120
+ );
84
121
  }
85
122
 
86
- throw new Error(`Model "${modelId}" is not available for engine "${engineType}". Pick it again in Settings → Models.`);
123
+ // The catalog answered and this model isn't in it. Engines whose model list is
124
+ // fetched live (OpenCode, Cline, Pi, Cursor) can drop a model between the day
125
+ // it was saved and the day it is used, and passing the stale id through is
126
+ // exactly what produced an empty response with no explanation.
127
+ throw new Error(
128
+ `Model "${modelId}" is no longer offered by ${label}. Choose a model again in ${settingsPath}.`
129
+ );
87
130
  }
@@ -7,6 +7,28 @@
7
7
  * Claude and Codex doesn't need these helpers.
8
8
  */
9
9
 
10
+ /**
11
+ * The error every adapter raises when a one-shot generation comes back with
12
+ * nothing.
13
+ *
14
+ * Each engine used to phrase this itself — "OpenCode returned empty response",
15
+ * "Pi returned no structured output" — which named the symptom and nothing else.
16
+ * The user is left with a dead end: no cause, no fix, and a different sentence
17
+ * per engine for the same situation. An empty completion is almost always an
18
+ * unusable model (dropped from a live catalog, not enabled for the account) or a
19
+ * disconnected engine, so say that and name both places it is fixed.
20
+ *
21
+ * `detail` carries whatever the adapter actually observed (parts received, an
22
+ * SDK error string) — useful in a bug report, never the whole message.
23
+ */
24
+ export function emptyGenerationError(engineLabel: string, detail?: string): Error {
25
+ return new Error(
26
+ `${engineLabel} returned nothing for this request${detail ? ` (${detail})` : ''}. ` +
27
+ `The selected model may be unavailable for your account — pick another in Settings → Models, ` +
28
+ `and check ${engineLabel} is connected in Settings → Engines.`
29
+ );
30
+ }
31
+
10
32
  /** Wrap a user prompt with a JSON-only instruction and the target schema. */
11
33
  export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>): string {
12
34
  return `${prompt}
@@ -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
+ }