@myrialabs/clopen 0.4.39 → 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 (88) hide show
  1. package/backend/auth/permissions.ts +23 -0
  2. package/backend/database/crypto/secret-columns.ts +5 -1
  3. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  4. package/backend/database/migrations/index.ts +7 -0
  5. package/backend/database/queries/index.ts +6 -0
  6. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  7. package/backend/db-client/cloning.test.ts +161 -0
  8. package/backend/db-client/cloning.ts +672 -0
  9. package/backend/db-client/connection-url.test.ts +117 -0
  10. package/backend/db-client/connection-url.ts +126 -0
  11. package/backend/db-client/drivers/mongodb.ts +2 -14
  12. package/backend/db-client/drivers/mysql.ts +2 -8
  13. package/backend/db-client/drivers/postgres.ts +10 -13
  14. package/backend/db-client/drivers/redis.ts +2 -6
  15. package/backend/db-client/env/detect.ts +438 -0
  16. package/backend/db-client/env/diff.ts +94 -0
  17. package/backend/db-client/env/env.test.ts +574 -0
  18. package/backend/db-client/env/index.ts +15 -0
  19. package/backend/db-client/env/naming.ts +202 -0
  20. package/backend/db-client/env/service.ts +487 -0
  21. package/backend/db-client/integrations/index.ts +7 -0
  22. package/backend/db-client/integrations/links.ts +41 -10
  23. package/backend/db-client/providers/neon/adapter.ts +522 -0
  24. package/backend/db-client/providers/neon/api-types.ts +182 -0
  25. package/backend/db-client/providers/neon/client.ts +298 -0
  26. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  27. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  28. package/backend/db-client/providers/neon/list.test.ts +181 -0
  29. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  30. package/backend/db-client/providers/types.ts +57 -0
  31. package/backend/env-files/discovery.ts +48 -0
  32. package/backend/env-files/edit.ts +213 -0
  33. package/backend/env-files/env-files.test.ts +515 -0
  34. package/backend/env-files/git.ts +27 -0
  35. package/backend/env-files/index.ts +44 -0
  36. package/backend/env-files/keys.ts +69 -0
  37. package/backend/env-files/parse.ts +157 -0
  38. package/backend/env-files/write.ts +229 -0
  39. package/backend/integrations/health.ts +18 -4
  40. package/backend/integrations/projections/types.ts +9 -2
  41. package/backend/integrations/registry/index.ts +3 -0
  42. package/backend/integrations/registry/providers/context7.ts +1 -0
  43. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  44. package/backend/integrations/registry/providers/github.ts +1 -0
  45. package/backend/integrations/registry/providers/neon.ts +55 -0
  46. package/backend/integrations/registry/providers/supabase.ts +1 -0
  47. package/backend/integrations/registry/providers/vercel.ts +1 -0
  48. package/backend/integrations/registry/types.ts +2 -0
  49. package/backend/work/start-work.ts +4 -0
  50. package/backend/worktrees/branching/engine.ts +557 -0
  51. package/backend/worktrees/branching/index.ts +56 -0
  52. package/backend/worktrees/branching/naming.test.ts +118 -0
  53. package/backend/worktrees/branching/naming.ts +97 -0
  54. package/backend/worktrees/branching/projector.test.ts +229 -0
  55. package/backend/worktrees/branching/projector.ts +139 -0
  56. package/backend/worktrees/branching/providers/neon.ts +220 -0
  57. package/backend/worktrees/branching/registry.ts +27 -0
  58. package/backend/worktrees/branching/service.ts +620 -0
  59. package/backend/worktrees/branching/suggest.test.ts +154 -0
  60. package/backend/worktrees/branching/suggest.ts +202 -0
  61. package/backend/worktrees/branching/types.ts +88 -0
  62. package/backend/worktrees/index.ts +7 -0
  63. package/backend/worktrees/service.ts +48 -1
  64. package/backend/ws/db-client/env.ts +142 -0
  65. package/backend/ws/db-client/index.ts +2 -0
  66. package/backend/ws/projects/index.ts +6 -1
  67. package/backend/ws/projects/info.ts +70 -6
  68. package/backend/ws/projects/overview.test.ts +108 -0
  69. package/backend/ws/projects/overview.ts +300 -0
  70. package/backend/ws/system/device-info.ts +307 -76
  71. package/backend/ws/worktrees/branching.ts +212 -0
  72. package/backend/ws/worktrees/crud.ts +33 -7
  73. package/backend/ws/worktrees/index.ts +14 -0
  74. package/dist/assets/{index-C8Gi-b6U.js → index-D4igjF6e.js} +1 -1
  75. package/dist/assets/{index-BrF6nqld.js → index-DONNwiXm.js} +1 -1
  76. package/dist/assets/main-BrfXH1bL.js +1205 -0
  77. package/dist/assets/main-CT1PygsW.css +1 -0
  78. package/dist/index.html +2 -2
  79. package/package.json +1 -1
  80. package/shared/constants/tool-icons.ts +6 -2
  81. package/shared/types/db-client/env.ts +192 -0
  82. package/shared/types/db-client/index.ts +1 -0
  83. package/shared/types/db-client/integrations.ts +30 -0
  84. package/shared/types/integrations.ts +9 -0
  85. package/shared/types/worktree-branching.ts +315 -0
  86. package/shared/utils/logger.ts +1 -0
  87. package/dist/assets/main-Bd3gb79F.css +0 -1
  88. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -0,0 +1,438 @@
1
+ /**
2
+ * Reading a project's own naming convention instead of guessing one.
3
+ *
4
+ * This is the part that answers the actual complaint: some projects fold a
5
+ * database into `DATABASE_URL`, some split it across `DB_HOST`/`DB_PASSWORD`,
6
+ * some call it `POSTGRES_URL` because Vercel does, and a tool that picks one
7
+ * writes a variable nothing reads. So the files the project already has are
8
+ * read first, and what they already use is what gets offered — the preset list
9
+ * is for a project with nothing in it.
10
+ *
11
+ * THREE SOURCES, in descending authority:
12
+ *
13
+ * 1. The dotenv files a project LOADS. What is there is what is true.
14
+ * 2. `.env.example` and friends. Usually the only record of the names a
15
+ * project expects, and the reason `parseDotenv` keeps commented
16
+ * assignments: half those files document optional settings as `# REDIS_URL=`.
17
+ * Read, never written — writing a live password into a committed file is
18
+ * the opposite of the point.
19
+ * 3. `prisma/schema.prisma` and `drizzle.config.*`, which name the variable
20
+ * they read even when no dotenv file exists yet. A fresh clone with a
21
+ * schema and no `.env` is the common case, and it is the one where guessing
22
+ * would be worst.
23
+ *
24
+ * Nothing here is authoritative about the DATABASE — only about what the
25
+ * project calls one. A group whose keys all sit in a template is marked as
26
+ * such, because updating documentation is not the same as configuring an app.
27
+ */
28
+
29
+ import fs from 'fs/promises';
30
+ import path from 'path';
31
+ import {
32
+ envFilePrecedence,
33
+ isTrackedInGit,
34
+ listEnvFileEntries,
35
+ parseDotenv
36
+ } from '$backend/env-files';
37
+ import type {
38
+ DbDriver,
39
+ DbEnvDetection,
40
+ DbEnvExistingGroup,
41
+ DbEnvFileInfo,
42
+ DbEnvRole,
43
+ DbEnvShape
44
+ } from '$shared/types/db-client';
45
+ import { debug } from '$shared/utils/logger';
46
+
47
+ /** A value that is unmistakably a database connection string. */
48
+ const URL_VALUE = /^(postgres(ql)?|mysql2?|mongodb(\+srv)?|rediss?|mssql|sqlserver|libsql|sqlite|file):/i;
49
+
50
+ /** libpq reads these six on its own, with no prefix to speak of. */
51
+ const LIBPQ_KEY = /^PG(HOST|PORT|USER|PASSWORD|DATABASE|SSLMODE)$/;
52
+
53
+ /** The field names a split convention uses. */
54
+ const SPLIT_ROLE =
55
+ /^(.+?)_(HOST|PORT|USER|USERNAME|PASSWORD|PASS|NAME|DATABASE|DB|SSLMODE|SSL_MODE|SCHEMA|CONNECTION)$/;
56
+
57
+ /** Names for a second endpoint of the SAME database, not a second database. */
58
+ const ALTERNATE_SUFFIXES = ['_URL_UNPOOLED', '_URL_NON_POOLING', '_PRISMA_URL', '_URL_NO_SSL'];
59
+
60
+ /**
61
+ * A database Clopen must never offer to overwrite.
62
+ *
63
+ * Prisma's shadow database is a SEPARATE, disposable database it creates
64
+ * migrations against. Pointing it at the real one would let a migration diff
65
+ * run against production data.
66
+ */
67
+ const DENY_KEYS = new Set(['SHADOW_DATABASE_URL']);
68
+
69
+ /** Prefix words that mean "this is about a database". */
70
+ const DB_WORDS = new Set([
71
+ 'DB',
72
+ 'DATABASE',
73
+ 'POSTGRES',
74
+ 'POSTGRESQL',
75
+ 'PG',
76
+ 'MYSQL',
77
+ 'MARIADB',
78
+ 'MONGO',
79
+ 'MONGODB',
80
+ 'REDIS',
81
+ 'MSSQL',
82
+ 'SQLSERVER',
83
+ 'SQL',
84
+ 'SQLITE',
85
+ 'TURSO',
86
+ 'NEON',
87
+ 'SUPABASE',
88
+ 'PLANETSCALE'
89
+ ]);
90
+
91
+ /** Config files that name the variable they read. */
92
+ const CODE_SOURCES = [
93
+ 'prisma/schema.prisma',
94
+ 'drizzle.config.ts',
95
+ 'drizzle.config.mts',
96
+ 'drizzle.config.js',
97
+ 'drizzle.config.mjs',
98
+ 'drizzle.config.cjs'
99
+ ];
100
+
101
+ function looksLikeDatabase(prefix: string): boolean {
102
+ if (DB_WORDS.has(prefix)) return true;
103
+ const last = prefix.split('_').pop() ?? '';
104
+ return DB_WORDS.has(last);
105
+ }
106
+
107
+ /**
108
+ * Which field a split convention's word names.
109
+ *
110
+ * `CONNECTION` and `SCHEMA` map to nothing on purpose. Laravel's
111
+ * `DB_CONNECTION=pgsql` names the DRIVER, and a project that has it already has
112
+ * it right — rewriting it would be changing something the user did not ask
113
+ * about to a value that cannot differ.
114
+ */
115
+ const ROLE_OF_WORD: Record<string, DbEnvRole | null> = {
116
+ HOST: 'host',
117
+ PORT: 'port',
118
+ USER: 'user',
119
+ USERNAME: 'user',
120
+ PASSWORD: 'password',
121
+ PASS: 'password',
122
+ NAME: 'database',
123
+ DATABASE: 'database',
124
+ DB: 'database',
125
+ SSLMODE: 'sslMode',
126
+ SSL_MODE: 'sslMode',
127
+ CONNECTION: null,
128
+ SCHEMA: null
129
+ };
130
+
131
+ interface Classification {
132
+ prefix: string;
133
+ shape: DbEnvShape;
134
+ /** True when the NAME alone says this is a database. */
135
+ strong: boolean;
136
+ /** The field this key holds. */
137
+ role: DbEnvRole | null;
138
+ /** The word the split key ended in, for deciding whether a group is real. */
139
+ word: string | null;
140
+ }
141
+
142
+ function classify(key: string, value: string): Classification | null {
143
+ const upper = key.toUpperCase();
144
+ if (DENY_KEYS.has(upper)) return null;
145
+
146
+ if (LIBPQ_KEY.test(upper)) {
147
+ const word = upper.slice(2);
148
+ return {
149
+ prefix: 'PG',
150
+ shape: 'split',
151
+ strong: true,
152
+ role: ROLE_OF_WORD[word] ?? null,
153
+ word
154
+ };
155
+ }
156
+
157
+ // Prisma's direct endpoint belongs to the DATABASE_URL beside it; on its own
158
+ // it would show up as a group called "DIRECT", which is not a thing.
159
+ if (upper === 'DIRECT_URL') {
160
+ return { prefix: 'DATABASE', shape: 'url', strong: true, role: 'altUrl', word: null };
161
+ }
162
+
163
+ for (const suffix of ALTERNATE_SUFFIXES) {
164
+ if (upper.endsWith(suffix) && upper.length > suffix.length) {
165
+ return {
166
+ prefix: upper.slice(0, -suffix.length),
167
+ shape: 'url',
168
+ strong: true,
169
+ role: 'altUrl',
170
+ word: null
171
+ };
172
+ }
173
+ }
174
+
175
+ const urlMatch = /^(.*?)(_URL|_URI|_DSN)$/.exec(upper);
176
+ if (urlMatch) {
177
+ const prefix = urlMatch[1] || upper;
178
+ const strong = looksLikeDatabase(prefix);
179
+ // A name that says nothing is accepted only when the VALUE does. That is
180
+ // what catches `MY_STORE_URL=postgres://…` without also catching
181
+ // `NEXT_PUBLIC_API_URL`.
182
+ if (!strong && !URL_VALUE.test(value)) return null;
183
+ return { prefix, shape: 'url', strong, role: 'url', word: null };
184
+ }
185
+
186
+ const splitMatch = SPLIT_ROLE.exec(upper);
187
+ if (splitMatch) {
188
+ const word = splitMatch[2];
189
+ return {
190
+ prefix: splitMatch[1],
191
+ shape: 'split',
192
+ strong: looksLikeDatabase(splitMatch[1]),
193
+ role: ROLE_OF_WORD[word] ?? null,
194
+ word
195
+ };
196
+ }
197
+
198
+ return null;
199
+ }
200
+
201
+ interface Draft {
202
+ prefix: string;
203
+ shape: DbEnvShape;
204
+ keys: Map<string, { commented: boolean }>;
205
+ /** role → the key this project actually uses for it. */
206
+ keyMap: Partial<Record<DbEnvRole, string>>;
207
+ roles: Set<string>;
208
+ files: string[];
209
+ /** Files where at least one of these keys is live rather than commented. */
210
+ liveFiles: string[];
211
+ sources: Set<string>;
212
+ strong: boolean;
213
+ }
214
+
215
+ /**
216
+ * A split group is only real when its name says so, or when it has enough
217
+ * fields that nothing else explains it.
218
+ *
219
+ * Without the second half, `NEXT_PUBLIC_SITE_NAME` and `SMTP_HOST` would each
220
+ * become a one-key "database". With it, a project using `STORE_HOST`,
221
+ * `STORE_USER` and `STORE_PASSWORD` is still recognised.
222
+ */
223
+ function isRealSplitGroup(draft: Draft): boolean {
224
+ if (draft.strong) return true;
225
+ const hasEndpoint = draft.roles.has('HOST') || draft.roles.has('DATABASE') || draft.roles.has('NAME');
226
+ return hasEndpoint && draft.roles.size >= 3;
227
+ }
228
+
229
+ async function readIfPresent(root: string, relative: string): Promise<string | null> {
230
+ try {
231
+ return await fs.readFile(path.join(root, relative), 'utf-8');
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+
237
+ /** Variable names a config file reads, with no value to go on. */
238
+ function keysReferencedIn(relative: string, content: string): string[] {
239
+ const found = new Set<string>();
240
+
241
+ if (relative.endsWith('.prisma')) {
242
+ for (const match of content.matchAll(/env\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\)/g)) {
243
+ found.add(match[1]);
244
+ }
245
+ return [...found];
246
+ }
247
+
248
+ const patterns = [
249
+ /(?:process\.env|Bun\.env|import\.meta\.env)\.([A-Za-z_][A-Za-z0-9_]*)/g,
250
+ /(?:process\.env|Bun\.env|import\.meta\.env)\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]/g
251
+ ];
252
+ for (const pattern of patterns) {
253
+ for (const match of content.matchAll(pattern)) found.add(match[1]);
254
+ }
255
+ return [...found];
256
+ }
257
+
258
+ /** Prefix words that name a specific engine rather than "a database". */
259
+ const DRIVER_WORDS: Record<DbDriver, string[]> = {
260
+ postgres: ['POSTGRES', 'POSTGRESQL', 'PG', 'SUPABASE', 'NEON'],
261
+ mysql: ['MYSQL', 'MARIADB'],
262
+ mongodb: ['MONGO', 'MONGODB'],
263
+ redis: ['REDIS'],
264
+ mssql: ['MSSQL', 'SQLSERVER'],
265
+ sqlite: ['SQLITE', 'TURSO']
266
+ };
267
+
268
+ /**
269
+ * Score a group so the panel opens on the right one.
270
+ *
271
+ * A live value outranks everything: a group documented only in `.env.example`
272
+ * describes what the project wants, while a live one describes what it is
273
+ * doing.
274
+ *
275
+ * Then the ENGINE, read off the prefix. A project with both `REDIS_URL` and
276
+ * `POSTGRES_URL` has two groups and only one of them belongs to the connection
277
+ * being written, so naming another engine is a penalty rather than merely not a
278
+ * bonus — without that, a Redis connection opens on the Postgres group and the
279
+ * first thing the user sees is an offer to overwrite it. `DB` and `DATABASE`
280
+ * name no engine and stay neutral, which is correct: they could be either.
281
+ */
282
+ function scoreOf(group: DbEnvExistingGroup, driver: DbDriver, bestPrecedence: number): number {
283
+ let score = 0;
284
+ if (!group.isTemplateOnly) score += 100;
285
+
286
+ const words = group.prefix.split('_');
287
+ if (words.some((word) => DRIVER_WORDS[driver].includes(word))) score += 30;
288
+ else if (
289
+ Object.entries(DRIVER_WORDS).some(
290
+ ([id, list]) => id !== driver && words.some((word) => list.includes(word))
291
+ )
292
+ ) {
293
+ score -= 60;
294
+ }
295
+
296
+ score += (3 - Math.min(bestPrecedence, 3)) * 5;
297
+ score += Math.min(group.keys.length, 6);
298
+ return score;
299
+ }
300
+
301
+ export async function detectEnvUsage(input: {
302
+ root: string;
303
+ projectId: string | null;
304
+ projectName: string | null;
305
+ driver: DbDriver;
306
+ }): Promise<DbEnvDetection> {
307
+ const entries = await listEnvFileEntries(input.root);
308
+
309
+ const files: DbEnvFileInfo[] = await Promise.all(
310
+ entries.map(async (entry) => ({
311
+ name: entry.name,
312
+ isTemplate: entry.isTemplate,
313
+ isTracked: await isTrackedInGit(input.root, entry.name),
314
+ precedence: envFilePrecedence(entry.name)
315
+ }))
316
+ );
317
+
318
+ const drafts = new Map<string, Draft>();
319
+ const sources = new Set<string>();
320
+ const precedenceOf = new Map<string, number>();
321
+
322
+ const remember = (
323
+ key: string,
324
+ value: string,
325
+ options: { file: string | null; commented: boolean; source: string }
326
+ ): void => {
327
+ const classification = classify(key, value);
328
+ if (!classification) return;
329
+
330
+ const id = `${classification.shape}:${classification.prefix}`;
331
+ const draft: Draft = drafts.get(id) ?? {
332
+ prefix: classification.prefix,
333
+ shape: classification.shape,
334
+ keys: new Map(),
335
+ keyMap: {},
336
+ roles: new Set(),
337
+ files: [],
338
+ liveFiles: [],
339
+ sources: new Set(),
340
+ strong: false
341
+ };
342
+
343
+ const upper = key.toUpperCase();
344
+ const seen = draft.keys.get(upper);
345
+ // A key live anywhere is live: `.env` holding a real value outranks the
346
+ // commented copy in `.env.example`.
347
+ draft.keys.set(upper, { commented: (seen?.commented ?? true) && options.commented });
348
+ if (classification.word) draft.roles.add(classification.word);
349
+ // FIRST writer wins, and the files arrive most-precedent first — so a key
350
+ // live in `.env.local` is the name offered even when `.env.example`
351
+ // documents a different spelling for the same role.
352
+ if (classification.role && !draft.keyMap[classification.role]) {
353
+ draft.keyMap[classification.role] = upper;
354
+ }
355
+ draft.strong = draft.strong || classification.strong;
356
+ draft.sources.add(options.source);
357
+ if (options.file) {
358
+ if (!draft.files.includes(options.file)) draft.files.push(options.file);
359
+ if (!options.commented && !draft.liveFiles.includes(options.file)) {
360
+ draft.liveFiles.push(options.file);
361
+ }
362
+ }
363
+
364
+ drafts.set(id, draft);
365
+ sources.add(options.source);
366
+ };
367
+
368
+ for (const file of files) {
369
+ const content = await readIfPresent(input.root, file.name);
370
+ if (content === null) continue;
371
+ for (const assignment of parseDotenv(content)) {
372
+ remember(assignment.key, assignment.value, {
373
+ file: file.name,
374
+ // A template's live-looking line is still documentation: the value in
375
+ // `.env.example` is a placeholder, not a configuration.
376
+ commented: assignment.commented || file.isTemplate,
377
+ source: file.name
378
+ });
379
+ }
380
+ }
381
+
382
+ for (const relative of CODE_SOURCES) {
383
+ const content = await readIfPresent(input.root, relative);
384
+ if (content === null) continue;
385
+ for (const key of keysReferencedIn(relative, content)) {
386
+ // No value and no file: this says what the project READS, which is
387
+ // exactly the name to offer, but it configures nothing by itself.
388
+ remember(key, '', { file: null, commented: true, source: relative });
389
+ }
390
+ }
391
+
392
+ const existing: DbEnvExistingGroup[] = [];
393
+ for (const draft of drafts.values()) {
394
+ if (draft.shape === 'split' && !isRealSplitGroup(draft)) continue;
395
+ if (draft.shape === 'url' && !draft.strong && draft.files.length === 0) continue;
396
+
397
+ const keys = [...draft.keys.keys()].sort();
398
+ const orderedFiles = [...draft.files].sort(
399
+ (a, b) => envFilePrecedence(a) - envFilePrecedence(b) || a.localeCompare(b)
400
+ );
401
+ const isTemplateOnly = draft.liveFiles.length === 0;
402
+ const where = orderedFiles[0] ?? [...draft.sources][0] ?? 'this project';
403
+
404
+ const group: DbEnvExistingGroup = {
405
+ prefix: draft.prefix,
406
+ shape: draft.shape,
407
+ keys,
408
+ keyMap: draft.keyMap,
409
+ files: orderedFiles,
410
+ isTemplateOnly,
411
+ label: `${keys.slice(0, 3).join(', ')}${keys.length > 3 ? ` +${keys.length - 3}` : ''} · ${where}`
412
+ };
413
+ existing.push(group);
414
+ precedenceOf.set(
415
+ `${group.shape}:${group.prefix}`,
416
+ orderedFiles.length > 0 ? envFilePrecedence(orderedFiles[0]) : 3
417
+ );
418
+ }
419
+
420
+ existing.sort(
421
+ (a, b) =>
422
+ scoreOf(b, input.driver, precedenceOf.get(`${b.shape}:${b.prefix}`) ?? 3) -
423
+ scoreOf(a, input.driver, precedenceOf.get(`${a.shape}:${a.prefix}`) ?? 3)
424
+ );
425
+
426
+ debug.log(
427
+ 'db-client',
428
+ `env detection found ${existing.length} group(s) across ${sources.size} source(s) in ${input.root}`
429
+ );
430
+
431
+ return {
432
+ projectId: input.projectId,
433
+ projectName: input.projectName,
434
+ files,
435
+ existing,
436
+ sources: [...sources]
437
+ };
438
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * A line diff small enough to read inside a panel.
3
+ *
4
+ * Exists because applying this feature EDITS SOMEONE'S CONFIGURATION FILE, and
5
+ * the only version of that which is defensible is one where they see the change
6
+ * first. `shared/utils/diff-calculator` counts lines for checkpoint stats and
7
+ * never produces the lines themselves, so there was nothing to reuse.
8
+ *
9
+ * Unchanged runs are collapsed to an ellipsis rather than dropped silently: a
10
+ * dotenv file can hold thirty unrelated variables, and a preview that showed
11
+ * all of them would bury the two lines that matter — but one that quietly
12
+ * omitted them would read as "this is the whole file".
13
+ */
14
+
15
+ import type { DbEnvDiffLine } from '$shared/types/db-client';
16
+
17
+ /** How many unchanged lines to keep on each side of a change. */
18
+ const CONTEXT = 2;
19
+
20
+ export function diffLines(before: string, after: string, context = CONTEXT): DbEnvDiffLine[] {
21
+ const a = before === '' ? [] : before.split('\n');
22
+ const b = after === '' ? [] : after.split('\n');
23
+
24
+ // Longest common subsequence. Both sides are one dotenv file, so the table
25
+ // is at worst a few hundred squared — small enough that the simple algorithm
26
+ // is the right one.
27
+ const table: number[][] = Array.from({ length: a.length + 1 }, () =>
28
+ new Array<number>(b.length + 1).fill(0)
29
+ );
30
+ for (let i = a.length - 1; i >= 0; i -= 1) {
31
+ for (let j = b.length - 1; j >= 0; j -= 1) {
32
+ table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
33
+ }
34
+ }
35
+
36
+ const full: DbEnvDiffLine[] = [];
37
+ let i = 0;
38
+ let j = 0;
39
+ while (i < a.length && j < b.length) {
40
+ if (a[i] === b[j]) {
41
+ full.push({ kind: 'context', text: a[i] });
42
+ i += 1;
43
+ j += 1;
44
+ } else if (table[i + 1][j] >= table[i][j + 1]) {
45
+ full.push({ kind: 'removed', text: a[i] });
46
+ i += 1;
47
+ } else {
48
+ full.push({ kind: 'added', text: b[j] });
49
+ j += 1;
50
+ }
51
+ }
52
+ for (; i < a.length; i += 1) full.push({ kind: 'removed', text: a[i] });
53
+ for (; j < b.length; j += 1) full.push({ kind: 'added', text: b[j] });
54
+
55
+ // A file's final newline shows up as a blank line gained or lost, which is
56
+ // not a change anyone means. Left in, it rendered as a lone `+` under every
57
+ // preview.
58
+ while (full.length > 0 && full.at(-1)!.text === '' && full.at(-1)!.kind !== 'context') {
59
+ full.pop();
60
+ }
61
+ // No change at all is an EMPTY diff, not one ellipsis standing in for the
62
+ // whole file — an empty region reads as "nothing to show", an ellipsis reads
63
+ // as "something is hidden here".
64
+ if (!full.some((line) => line.kind !== 'context')) return [];
65
+
66
+ return collapse(full, context);
67
+ }
68
+
69
+ function collapse(lines: DbEnvDiffLine[], context: number): DbEnvDiffLine[] {
70
+ const keep = new Array<boolean>(lines.length).fill(false);
71
+ lines.forEach((line, index) => {
72
+ if (line.kind === 'context') return;
73
+ for (let offset = -context; offset <= context; offset += 1) {
74
+ const target = index + offset;
75
+ if (target >= 0 && target < lines.length) keep[target] = true;
76
+ }
77
+ });
78
+
79
+ const result: DbEnvDiffLine[] = [];
80
+ let skipping = false;
81
+ lines.forEach((line, index) => {
82
+ if (keep[index]) {
83
+ result.push(line);
84
+ skipping = false;
85
+ return;
86
+ }
87
+ if (!skipping) {
88
+ result.push({ kind: 'context', text: '…' });
89
+ skipping = true;
90
+ }
91
+ });
92
+
93
+ return result;
94
+ }