@gadicc/loom 1.34.0 → 1.35.0

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 (104) hide show
  1. package/README.md +108 -41
  2. package/esm/src/apiKeys/authorize.d.ts.map +1 -1
  3. package/esm/src/apiKeys/authorize.js +71 -0
  4. package/esm/src/apiKeys/betterAuth.d.ts +123 -0
  5. package/esm/src/apiKeys/betterAuth.d.ts.map +1 -0
  6. package/esm/src/apiKeys/betterAuth.js +164 -0
  7. package/esm/src/apiKeys/credentials.d.ts +37 -2
  8. package/esm/src/apiKeys/credentials.d.ts.map +1 -1
  9. package/esm/src/apiKeys/credentials.js +69 -8
  10. package/esm/src/apiKeys/lifecycle.d.ts +41 -0
  11. package/esm/src/apiKeys/lifecycle.d.ts.map +1 -0
  12. package/esm/src/apiKeys/lifecycle.js +6 -0
  13. package/esm/src/apiKeys/limits.d.ts +132 -0
  14. package/esm/src/apiKeys/limits.d.ts.map +1 -0
  15. package/esm/src/apiKeys/limits.js +246 -0
  16. package/esm/src/apiKeys/mod.d.ts +4 -0
  17. package/esm/src/apiKeys/mod.d.ts.map +1 -1
  18. package/esm/src/apiKeys/mod.js +4 -0
  19. package/esm/src/apiKeys/permissions.d.ts +56 -0
  20. package/esm/src/apiKeys/permissions.d.ts.map +1 -0
  21. package/esm/src/apiKeys/permissions.js +128 -0
  22. package/esm/src/apiKeys/policy.d.ts +3 -1
  23. package/esm/src/apiKeys/policy.d.ts.map +1 -1
  24. package/esm/src/apiKeys/policy.js +3 -1
  25. package/esm/src/apiKeys/types.d.ts +68 -1
  26. package/esm/src/apiKeys/types.d.ts.map +1 -1
  27. package/esm/src/cli/localDevLock.d.ts +97 -0
  28. package/esm/src/cli/localDevLock.d.ts.map +1 -0
  29. package/esm/src/cli/localDevLock.js +312 -0
  30. package/esm/src/cli/localDevPackage.d.ts +172 -0
  31. package/esm/src/cli/localDevPackage.d.ts.map +1 -0
  32. package/esm/src/cli/localDevPackage.js +617 -0
  33. package/esm/src/cli/migrationEnv.d.ts +19 -0
  34. package/esm/src/cli/migrationEnv.d.ts.map +1 -1
  35. package/esm/src/cli/migrationEnv.js +44 -1
  36. package/esm/src/cli/mod.d.ts +69 -4
  37. package/esm/src/cli/mod.d.ts.map +1 -1
  38. package/esm/src/cli/mod.js +2806 -437
  39. package/esm/src/cli/projectTooling.d.ts +19 -1
  40. package/esm/src/cli/projectTooling.d.ts.map +1 -1
  41. package/esm/src/cli/projectTooling.js +142 -12
  42. package/esm/src/mui/apiKeys.d.ts +123 -17
  43. package/esm/src/mui/apiKeys.d.ts.map +1 -1
  44. package/esm/src/mui/apiKeys.js +219 -78
  45. package/esm/src/mui/apiKeysView.d.ts +145 -0
  46. package/esm/src/mui/apiKeysView.d.ts.map +1 -1
  47. package/esm/src/mui/apiKeysView.js +278 -0
  48. package/esm/src/next/apiKeys/mod.d.ts +8 -1
  49. package/esm/src/next/apiKeys/mod.d.ts.map +1 -1
  50. package/esm/src/next/apiKeys/mod.js +5 -2
  51. package/package.json +2 -6
  52. package/script/src/apiKeys/authorize.d.ts.map +1 -1
  53. package/script/src/apiKeys/authorize.js +71 -0
  54. package/script/src/apiKeys/betterAuth.d.ts +123 -0
  55. package/script/src/apiKeys/betterAuth.d.ts.map +1 -0
  56. package/script/src/apiKeys/betterAuth.js +169 -0
  57. package/script/src/apiKeys/credentials.d.ts +37 -2
  58. package/script/src/apiKeys/credentials.d.ts.map +1 -1
  59. package/script/src/apiKeys/credentials.js +71 -8
  60. package/script/src/apiKeys/lifecycle.d.ts +41 -0
  61. package/script/src/apiKeys/lifecycle.d.ts.map +1 -0
  62. package/script/src/apiKeys/lifecycle.js +7 -0
  63. package/script/src/apiKeys/limits.d.ts +132 -0
  64. package/script/src/apiKeys/limits.d.ts.map +1 -0
  65. package/script/src/apiKeys/limits.js +254 -0
  66. package/script/src/apiKeys/mod.d.ts +4 -0
  67. package/script/src/apiKeys/mod.d.ts.map +1 -1
  68. package/script/src/apiKeys/mod.js +4 -0
  69. package/script/src/apiKeys/permissions.d.ts +56 -0
  70. package/script/src/apiKeys/permissions.d.ts.map +1 -0
  71. package/script/src/apiKeys/permissions.js +136 -0
  72. package/script/src/apiKeys/policy.d.ts +3 -1
  73. package/script/src/apiKeys/policy.d.ts.map +1 -1
  74. package/script/src/apiKeys/policy.js +3 -1
  75. package/script/src/apiKeys/types.d.ts +68 -1
  76. package/script/src/apiKeys/types.d.ts.map +1 -1
  77. package/script/src/cli/localDevLock.d.ts +97 -0
  78. package/script/src/cli/localDevLock.d.ts.map +1 -0
  79. package/script/src/cli/localDevLock.js +320 -0
  80. package/script/src/cli/localDevPackage.d.ts +172 -0
  81. package/script/src/cli/localDevPackage.d.ts.map +1 -0
  82. package/script/src/cli/localDevPackage.js +635 -0
  83. package/script/src/cli/migrationEnv.d.ts +19 -0
  84. package/script/src/cli/migrationEnv.d.ts.map +1 -1
  85. package/script/src/cli/migrationEnv.js +48 -1
  86. package/script/src/cli/mod.d.ts +69 -4
  87. package/script/src/cli/mod.d.ts.map +1 -1
  88. package/script/src/cli/mod.js +2807 -437
  89. package/script/src/cli/projectTooling.d.ts +19 -1
  90. package/script/src/cli/projectTooling.d.ts.map +1 -1
  91. package/script/src/cli/projectTooling.js +176 -12
  92. package/script/src/mui/apiKeys.d.ts +123 -17
  93. package/script/src/mui/apiKeys.d.ts.map +1 -1
  94. package/script/src/mui/apiKeys.js +220 -77
  95. package/script/src/mui/apiKeysView.d.ts +145 -0
  96. package/script/src/mui/apiKeysView.d.ts.map +1 -1
  97. package/script/src/mui/apiKeysView.js +291 -0
  98. package/script/src/next/apiKeys/mod.d.ts +8 -1
  99. package/script/src/next/apiKeys/mod.d.ts.map +1 -1
  100. package/script/src/next/apiKeys/mod.js +5 -2
  101. package/skills/loom/SKILL.md +111 -18
  102. package/skills/loom-api-keys/SKILL.md +101 -7
  103. package/skills/loom-auth/SKILL.md +9 -0
  104. package/skills/loom-db/SKILL.md +3 -1
@@ -0,0 +1,617 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile, realpath, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ /**
5
+ * Loom repository paths whose content can change the generated npm package.
6
+ * Release equivalence (`git diff`) and local build fingerprints share this list.
7
+ * It includes every script `scripts/build_npm.ts` imports.
8
+ */
9
+ export const LOOM_PACKAGE_RELEVANT_PATHS = [
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "README.md",
13
+ "THIRD_PARTY_NOTICES.md",
14
+ "bin",
15
+ "deno.json",
16
+ "deno.lock",
17
+ "mod.ts",
18
+ "runtime",
19
+ "scripts/browser_entrypoints.ts",
20
+ "scripts/build_npm.ts",
21
+ "scripts/git_visible_copy.ts",
22
+ "scripts/node_check_dependencies.ts",
23
+ "scripts/npm_package.ts",
24
+ "skills",
25
+ "src",
26
+ ];
27
+ /**
28
+ * Build stamp written into Loom's `npm/` output by `scripts/build_npm.ts`.
29
+ * The build excludes it from the packed package, so it never reaches npm or a
30
+ * consumer's `node_modules`.
31
+ */
32
+ export const LOOM_BUILD_STAMP_FILE = ".loom-build.json";
33
+ /**
34
+ * Asks git for a checkout's HEAD commit and whether its working tree differs
35
+ * from it: tracked changes, untracked files that are not ignored (listed
36
+ * individually, whatever `status.showUntrackedFiles` says), or files marked
37
+ * skip-worktree or assume-unchanged, whose changes `git status` hides.
38
+ * `git` runs one git command in the checkout and returns its stdout, or null
39
+ * when it failed (git missing, not a repository). Whatever git cannot answer
40
+ * is null.
41
+ */
42
+ export function readLoomSourceProvenance(git) {
43
+ const head = git(["rev-parse", "HEAD"])?.trim() ?? "";
44
+ if (!/^[0-9a-f]{40,64}$/.test(head)) {
45
+ return { sourceCommit: null, sourceDirty: null };
46
+ }
47
+ const status = git(["status", "--porcelain", "--untracked-files=all"]);
48
+ // `ls-files -v` tags skip-worktree files S and assume-unchanged files with
49
+ // a lowercase letter.
50
+ const tags = status === null ? null : git(["ls-files", "-v"]);
51
+ return {
52
+ sourceCommit: head,
53
+ sourceDirty: status === null || tags === null
54
+ ? null
55
+ : status.trim() !== "" ||
56
+ tags.split("\n").some((line) => /^(?:S|[a-z]) /.test(line)),
57
+ };
58
+ }
59
+ /**
60
+ * Settles a build's provenance from what git reported when the build started
61
+ * and when it finished. Any change in between (a commit, a checkout, an
62
+ * edit, which `sourcesChanged` reports from the source fingerprints, or git
63
+ * becoming unable to tell) means the output may mix two states, so the build
64
+ * is stamped dirty, which `loom dev published` refuses; the starting commit
65
+ * is kept. A start git could not read stays unknown.
66
+ */
67
+ export function settleLoomBuildProvenance(start, end, sourcesChanged) {
68
+ const changedDuringBuild = sourcesChanged ||
69
+ end.sourceCommit !== start.sourceCommit ||
70
+ end.sourceDirty !== start.sourceDirty;
71
+ const provenance = changedDuringBuild && start.sourceCommit !== null
72
+ ? { sourceCommit: start.sourceCommit, sourceDirty: true }
73
+ : start;
74
+ return { changedDuringBuild, provenance };
75
+ }
76
+ /**
77
+ * Whether a stamp records the build's provenance and output digest. Stamps
78
+ * from older build scripts lack them.
79
+ */
80
+ export function hasLoomBuildProvenance(stamp) {
81
+ return stamp.sourceCommit !== undefined && stamp.sourceDirty !== undefined &&
82
+ typeof stamp.packageDigest === "string";
83
+ }
84
+ const SOURCE_FINGERPRINT_SKIPPED_DIRS = new Set([
85
+ ".git",
86
+ "coverage",
87
+ "node_modules",
88
+ "npm",
89
+ ]);
90
+ // dnt builds with `test: false`, so test-only edits cannot change the output.
91
+ const SOURCE_FINGERPRINT_SKIPPED_FILE = /\.test\.[cm]?[jt]sx?$/;
92
+ function compareNames(left, right) {
93
+ return left < right ? -1 : left > right ? 1 : 0;
94
+ }
95
+ function isMissingPathError(error) {
96
+ const code = error?.code;
97
+ return code === "ENOENT" || code === "ENOTDIR";
98
+ }
99
+ async function statIfExists(path) {
100
+ try {
101
+ return await stat(path);
102
+ }
103
+ catch (error) {
104
+ if (isMissingPathError(error))
105
+ return null;
106
+ throw error;
107
+ }
108
+ }
109
+ /**
110
+ * Lists the package-relevant source files of a Loom checkout in fingerprint
111
+ * order, with their stats. Test files and build outputs are skipped.
112
+ */
113
+ async function listLoomSourceFiles(sourceRoot) {
114
+ const files = [];
115
+ const visit = async (relativePath) => {
116
+ const pathStat = await statIfExists(join(sourceRoot, relativePath));
117
+ if (!pathStat)
118
+ return;
119
+ if (pathStat.isDirectory()) {
120
+ const entries = (await readdir(join(sourceRoot, relativePath)))
121
+ .sort(compareNames);
122
+ for (const name of entries) {
123
+ if (SOURCE_FINGERPRINT_SKIPPED_DIRS.has(name))
124
+ continue;
125
+ await visit(`${relativePath}/${name}`);
126
+ }
127
+ return;
128
+ }
129
+ if (pathStat.isFile() && !SOURCE_FINGERPRINT_SKIPPED_FILE.test(relativePath)) {
130
+ files.push({ path: relativePath, stat: pathStat });
131
+ }
132
+ };
133
+ for (const path of [...LOOM_PACKAGE_RELEVANT_PATHS].sort(compareNames)) {
134
+ await visit(path);
135
+ }
136
+ return files;
137
+ }
138
+ /**
139
+ * Hashes the content of every package-relevant file in a Loom checkout.
140
+ * Unlike modification times, the result changes exactly when a rebuild could
141
+ * produce a different package, including after checkouts that restore older
142
+ * timestamps and edits made while a build is running.
143
+ */
144
+ export async function computeLoomSourceFingerprint(sourceRoot) {
145
+ const hash = createHash("sha256");
146
+ hash.update("loom-source-fingerprint:1\n");
147
+ for (const { path } of await listLoomSourceFiles(sourceRoot)) {
148
+ const content = await readFile(join(sourceRoot, path));
149
+ hash.update(`${path}\0${content.length}\0`);
150
+ hash.update(content);
151
+ hash.update("\0");
152
+ }
153
+ return `sha256:${hash.digest("hex")}`;
154
+ }
155
+ /** Records {@link LoomSourceSnapshot} for a Loom checkout. */
156
+ export async function snapshotLoomSources(sourceRoot) {
157
+ return new Map((await listLoomSourceFiles(sourceRoot)).map(({ path, stat }) => [
158
+ path,
159
+ { mtimeMs: stat.mtimeMs, size: stat.size },
160
+ ]));
161
+ }
162
+ /**
163
+ * How far before a build's start a whole-second modification time still
164
+ * counts as possibly written during it: FAT stores even seconds, and
165
+ * timestamps are rounded down to the filesystem's granularity.
166
+ */
167
+ const COARSE_MTIME_MARGIN_MS = 2_500;
168
+ /**
169
+ * Whether any package-relevant source file was written while a build ran,
170
+ * from snapshots taken when it started (at `startedAtMs`) and when it
171
+ * finished. Content alone misses an edit that was reverted before the build
172
+ * finished, but the revert rewrites the file:
173
+ * - a file added, removed, resized or with a new modification time counts;
174
+ * - so does one modified at or after the start;
175
+ * - on filesystems with coarse timestamps (a whole-second modification time)
176
+ * an edit can keep the old value, so a file modified shortly before the
177
+ * start counts as well.
178
+ */
179
+ export function loomSourcesWrittenDuringBuild(start, end, startedAtMs) {
180
+ if (start.size !== end.size)
181
+ return true;
182
+ for (const [path, after] of end) {
183
+ const before = start.get(path);
184
+ if (!before || before.size !== after.size ||
185
+ before.mtimeMs !== after.mtimeMs || after.mtimeMs >= startedAtMs) {
186
+ return true;
187
+ }
188
+ if (after.mtimeMs % 1000 === 0 &&
189
+ after.mtimeMs >= startedAtMs - COARSE_MTIME_MARGIN_MS) {
190
+ return true;
191
+ }
192
+ }
193
+ return false;
194
+ }
195
+ /** Serializes the build stamp that `scripts/build_npm.ts` writes. */
196
+ export function formatLoomBuildStamp(stamp) {
197
+ const value = { version: 1, ...stamp };
198
+ return `${JSON.stringify(value, null, 2)}\n`;
199
+ }
200
+ /** Reads a build stamp, returning null when it is absent or unrecognized. */
201
+ export async function readLoomBuildStamp(packagePath) {
202
+ let text;
203
+ try {
204
+ text = await readFile(join(packagePath, LOOM_BUILD_STAMP_FILE), "utf8");
205
+ }
206
+ catch (error) {
207
+ if (isMissingPathError(error))
208
+ return null;
209
+ throw error;
210
+ }
211
+ try {
212
+ const stamp = JSON.parse(text);
213
+ const commitOk = stamp.sourceCommit === undefined ||
214
+ stamp.sourceCommit === null || typeof stamp.sourceCommit === "string";
215
+ const dirtyOk = stamp.sourceDirty === undefined ||
216
+ stamp.sourceDirty === null || typeof stamp.sourceDirty === "boolean";
217
+ const digestOk = stamp.packageDigest === undefined ||
218
+ typeof stamp.packageDigest === "string";
219
+ const legacyOk = stamp.legacyBuildFingerprint === undefined ||
220
+ typeof stamp.legacyBuildFingerprint === "string";
221
+ return stamp.version === 1 &&
222
+ typeof stamp.sourceFingerprint === "string" && commitOk && dirtyOk &&
223
+ digestOk && legacyOk
224
+ ? stamp
225
+ : null;
226
+ }
227
+ catch {
228
+ return null;
229
+ }
230
+ }
231
+ /** Names npm packing, and so pnpm's directory import, always leaves out. */
232
+ const ALWAYS_UNPACKED_NAMES = new Set([
233
+ "CVS",
234
+ "config.gypi",
235
+ "node_modules",
236
+ "npm-debug.log",
237
+ "package-lock.json",
238
+ ]);
239
+ async function readTextOrNull(path) {
240
+ try {
241
+ return await readFile(path, "utf8");
242
+ }
243
+ catch (error) {
244
+ if (isMissingPathError(error))
245
+ return null;
246
+ throw error;
247
+ }
248
+ }
249
+ /**
250
+ * Reads the root ignore rules npm packing applies to a package directory
251
+ * (`.npmignore`, else `.gitignore`). Only literal names are understood, which
252
+ * covers the `.npmignore` dnt writes; globs, nested paths, negations, and a
253
+ * `files` allowlist return null so callers fall back to a weaker comparison.
254
+ */
255
+ async function readPackExclusions(root) {
256
+ try {
257
+ const packageJson = JSON.parse(await readTextOrNull(join(root, "package.json")) ?? "{}");
258
+ if (packageJson.files !== undefined)
259
+ return null;
260
+ }
261
+ catch {
262
+ return null;
263
+ }
264
+ const ignoreText = await readTextOrNull(join(root, ".npmignore")) ??
265
+ await readTextOrNull(join(root, ".gitignore")) ?? "";
266
+ const exclusions = {
267
+ anyDepth: new Set(),
268
+ topLevel: new Set(),
269
+ };
270
+ for (const rawLine of ignoreText.split(/\r?\n/)) {
271
+ const line = rawLine.trim();
272
+ if (line === "" || line.startsWith("#"))
273
+ continue;
274
+ if (line.startsWith("!"))
275
+ return null;
276
+ const anchored = line.startsWith("/");
277
+ const name = line.replace(/^\/+/, "").replace(/\/+$/, "");
278
+ if (name === "")
279
+ continue;
280
+ if (/[*?[\]\\/]/.test(name))
281
+ return null;
282
+ (anchored ? exclusions.topLevel : exclusions.anyDepth).add(name);
283
+ }
284
+ return exclusions;
285
+ }
286
+ function isPackedEntry(name, anyDepthExclusions) {
287
+ // Dot entries cover npm's other always-ignored names (.git, .npmrc, ...)
288
+ // and the ignore files themselves.
289
+ return !name.startsWith(".") && !ALWAYS_UNPACKED_NAMES.has(name) &&
290
+ !name.endsWith(".orig") && !anyDepthExclusions.has(name);
291
+ }
292
+ async function collectPackageFiles(root, includeTopLevel, anyDepthExclusions) {
293
+ const files = new Map();
294
+ let nestedIgnoreFile = false;
295
+ const visit = async (relativePath) => {
296
+ const directory = relativePath ? join(root, relativePath) : root;
297
+ const entries = (await readdir(directory, { withFileTypes: true }))
298
+ .sort((left, right) => compareNames(left.name, right.name));
299
+ for (const entry of entries) {
300
+ if (relativePath &&
301
+ (entry.name === ".npmignore" || entry.name === ".gitignore")) {
302
+ nestedIgnoreFile = true;
303
+ }
304
+ if (!isPackedEntry(entry.name, anyDepthExclusions))
305
+ continue;
306
+ if (!relativePath && !includeTopLevel(entry.name))
307
+ continue;
308
+ const childPath = relativePath
309
+ ? `${relativePath}/${entry.name}`
310
+ : entry.name;
311
+ let isDirectory = entry.isDirectory();
312
+ let isFile = entry.isFile();
313
+ let fileStat = { ino: 0, mtimeMs: 0, size: 0 };
314
+ if (entry.isSymbolicLink() || isFile) {
315
+ const childStat = await statIfExists(join(root, childPath));
316
+ if (!childStat)
317
+ continue;
318
+ isDirectory = childStat.isDirectory();
319
+ isFile = childStat.isFile();
320
+ fileStat = {
321
+ ino: childStat.ino,
322
+ mtimeMs: childStat.mtimeMs,
323
+ size: childStat.size,
324
+ };
325
+ }
326
+ if (isDirectory) {
327
+ await visit(childPath);
328
+ }
329
+ else if (isFile) {
330
+ files.set(childPath, fileStat);
331
+ }
332
+ }
333
+ };
334
+ await visit("");
335
+ return { files, nestedIgnoreFile };
336
+ }
337
+ /**
338
+ * Digest of a built package's files by path and content, filtered as
339
+ * {@link findPackageTreeDifference} filters them: its root ignore rules,
340
+ * npm's always-ignored names, and every dot entry, which Loom's packing
341
+ * approximation treats as unpacked although npm would pack some. The build
342
+ * stamp records it, so any later edit to those files shows.
343
+ */
344
+ export async function computePackageContentDigest(root) {
345
+ let exclusions = await readPackExclusions(root);
346
+ const collect = () => collectPackageFiles(root, (name) => !exclusions?.topLevel.has(name), exclusions?.anyDepth ?? new Set());
347
+ let collected = await collect();
348
+ if (exclusions && collected.nestedIgnoreFile) {
349
+ // As in findPackageTreeDifference: nested rules are not applied.
350
+ exclusions = null;
351
+ collected = await collect();
352
+ }
353
+ const hash = createHash("sha256");
354
+ hash.update("loom-package-digest:1\n");
355
+ for (const path of [...collected.files.keys()].sort(compareNames)) {
356
+ const content = await readFile(join(root, path));
357
+ hash.update(`${path}\0${content.length}\0`);
358
+ hash.update(content);
359
+ hash.update("\0");
360
+ }
361
+ return `sha256:${hash.digest("hex")}`;
362
+ }
363
+ /**
364
+ * Compares a built package directory with the copy a package manager
365
+ * installed from it, by file list and byte content. Returns a short
366
+ * description of the first difference, or null when the installed copy
367
+ * matches.
368
+ *
369
+ * Both trees are filtered by the build's packing rules (its root
370
+ * `.npmignore` plus npm's always-ignored names), so a build that only adds a
371
+ * new top-level entry is still detected. When those rules cannot be read
372
+ * literally, top-level build entries absent from the installed copy are
373
+ * skipped instead.
374
+ */
375
+ export async function findPackageTreeDifference(builtRoot, installedRoot) {
376
+ const installedTopLevel = await readdir(installedRoot).catch((error) => {
377
+ if (isMissingPathError(error))
378
+ return null;
379
+ throw error;
380
+ });
381
+ if (!installedTopLevel?.includes("package.json")) {
382
+ return "the package is not installed";
383
+ }
384
+ const installedNames = new Set(installedTopLevel);
385
+ const collect = (exclusions) => {
386
+ const includeTopLevel = exclusions
387
+ ? (name) => !exclusions.topLevel.has(name)
388
+ : (name) => installedNames.has(name);
389
+ const anyDepth = exclusions?.anyDepth ?? new Set();
390
+ return Promise.all([
391
+ collectPackageFiles(builtRoot, includeTopLevel, anyDepth),
392
+ collectPackageFiles(installedRoot, includeTopLevel, anyDepth),
393
+ ]);
394
+ };
395
+ let exclusions = await readPackExclusions(builtRoot);
396
+ let [built, installed] = await collect(exclusions);
397
+ if (exclusions && built.nestedIgnoreFile) {
398
+ // Nested ignore files add rules this reader does not apply.
399
+ exclusions = null;
400
+ [built, installed] = await collect(exclusions);
401
+ }
402
+ const builtFiles = built.files;
403
+ const installedFiles = installed.files;
404
+ for (const path of builtFiles.keys()) {
405
+ if (!installedFiles.has(path))
406
+ return `${path} is not installed`;
407
+ }
408
+ for (const path of installedFiles.keys()) {
409
+ if (!builtFiles.has(path))
410
+ return `${path} is no longer built`;
411
+ }
412
+ for (const [path, { size }] of builtFiles) {
413
+ if (installedFiles.get(path)?.size !== size)
414
+ return `${path} differs`;
415
+ }
416
+ for (const path of builtFiles.keys()) {
417
+ const [builtContent, installedContent] = await Promise.all([
418
+ readFile(join(builtRoot, path)),
419
+ readFile(join(installedRoot, path)),
420
+ ]);
421
+ if (!builtContent.equals(installedContent))
422
+ return `${path} differs`;
423
+ }
424
+ return null;
425
+ }
426
+ /**
427
+ * Cheap signature of an installed package tree: its real path plus each
428
+ * file's path, size, inode, and modification time (no file contents), or
429
+ * null when it is not installed. pnpm links unchanged files from its
430
+ * content-addressed store, so the signature changes when the package is
431
+ * replaced with different content. Lets a process tell whether the package
432
+ * it loaded was replaced later.
433
+ */
434
+ export async function computePackageTreeSignature(root) {
435
+ const topLevel = await readdir(root).catch((error) => {
436
+ if (isMissingPathError(error))
437
+ return null;
438
+ throw error;
439
+ });
440
+ if (!topLevel?.includes("package.json"))
441
+ return null;
442
+ const { files } = await collectPackageFiles(root, () => true, new Set());
443
+ const hash = createHash("sha256");
444
+ hash.update(`${await realpath(root)}\n`);
445
+ for (const [path, { ino, mtimeMs, size }] of files) {
446
+ hash.update(`${path}\0${size}\0${ino}\0${mtimeMs}\n`);
447
+ }
448
+ return `stat:${hash.digest("hex")}`;
449
+ }
450
+ function unquoteYamlScalar(value) {
451
+ const trimmed = value.trim();
452
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length > 1) {
453
+ return trimmed.slice(1, -1).replaceAll("''", "'");
454
+ }
455
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length > 1) {
456
+ try {
457
+ return JSON.parse(trimmed);
458
+ }
459
+ catch {
460
+ return trimmed.slice(1, -1);
461
+ }
462
+ }
463
+ return trimmed;
464
+ }
465
+ /** Splits `key: value` YAML mapping lines at the given indentation. */
466
+ function parseYamlMappingLine(line, indent) {
467
+ const prefix = " ".repeat(indent);
468
+ if (!line.startsWith(prefix) || line[indent] === " ")
469
+ return null;
470
+ const body = line.slice(indent);
471
+ if (body.startsWith("#"))
472
+ return null;
473
+ const match = body.match(/^(?:'((?:[^']|'')*)'|"((?:[^"\\]|\\.)*)"|([^\s'"#][^\s]*?)):(?:\s+(.*))?$/);
474
+ if (!match)
475
+ return null;
476
+ const key = match[1] !== undefined
477
+ ? match[1].replaceAll("''", "'")
478
+ : match[2] !== undefined
479
+ ? unquoteYamlScalar(`"${match[2]}"`)
480
+ : match[3];
481
+ return { key, value: match[4] === undefined ? "" : match[4] };
482
+ }
483
+ /**
484
+ * Returns the project document of a lockfile. With `configDependencies`,
485
+ * pnpm 11 writes a multi-document lockfile whose first document locks the
486
+ * config-dependency environment and has its own importers and snapshots;
487
+ * the project document, which carries `settings:`, comes last.
488
+ */
489
+ function getMainLockfileDocument(lockfileText) {
490
+ const documents = lockfileText.replace(/\r\n/g, "\n")
491
+ .split(/^---[ \t]*$/m)
492
+ .filter((document) => document.trim() !== "");
493
+ if (documents.length <= 1)
494
+ return documents[0] ?? "";
495
+ for (let index = documents.length - 1; index >= 0; index -= 1) {
496
+ if (/^settings:/m.test(documents[index]))
497
+ return documents[index];
498
+ }
499
+ return documents[documents.length - 1];
500
+ }
501
+ /** Returns the lines of a top-level section of a pnpm lockfile. */
502
+ function getLockfileSection(lockfileText, section) {
503
+ const lines = getMainLockfileDocument(lockfileText).split("\n");
504
+ const start = lines.indexOf(`${section}:`);
505
+ if (start === -1)
506
+ return [];
507
+ const body = [];
508
+ for (const line of lines.slice(start + 1)) {
509
+ if (line !== "" && !line.startsWith(" ") && !line.startsWith("#"))
510
+ break;
511
+ body.push(line);
512
+ }
513
+ return body;
514
+ }
515
+ /**
516
+ * Reads the override pnpm recorded for a package in the lockfile's top-level
517
+ * `overrides:` map. pnpm records the override map it actually applied, so
518
+ * this proves whether an override took effect.
519
+ */
520
+ export function getLockfileOverride(lockfileText, name) {
521
+ for (const line of getLockfileSection(lockfileText, "overrides")) {
522
+ const entry = parseYamlMappingLine(line, 2);
523
+ if (entry?.key === name)
524
+ return unquoteYamlScalar(entry.value);
525
+ }
526
+ return null;
527
+ }
528
+ /** Reads a direct dependency of the root importer (`.`) from a lockfile. */
529
+ export function getLockfileRootImporterDependency(lockfileText, name) {
530
+ let inRootImporter = false;
531
+ let inDependency = false;
532
+ const result = {};
533
+ for (const line of getLockfileSection(lockfileText, "importers")) {
534
+ const importer = parseYamlMappingLine(line, 2);
535
+ if (importer) {
536
+ if (inDependency)
537
+ break;
538
+ inRootImporter = importer.key === ".";
539
+ continue;
540
+ }
541
+ if (!inRootImporter)
542
+ continue;
543
+ if (parseYamlMappingLine(line, 4)) {
544
+ if (inDependency)
545
+ break;
546
+ continue;
547
+ }
548
+ const dependency = parseYamlMappingLine(line, 6);
549
+ if (dependency) {
550
+ if (inDependency)
551
+ break;
552
+ inDependency = dependency.key === name;
553
+ continue;
554
+ }
555
+ const field = inDependency ? parseYamlMappingLine(line, 8) : null;
556
+ if (field?.key === "specifier") {
557
+ result.specifier = unquoteYamlScalar(field.value);
558
+ }
559
+ else if (field?.key === "version") {
560
+ result.version = unquoteYamlScalar(field.value);
561
+ }
562
+ }
563
+ return result.specifier !== undefined || result.version !== undefined
564
+ ? result
565
+ : null;
566
+ }
567
+ /**
568
+ * Groups lockfile snapshot keys by `name@version`, collecting the peer (and
569
+ * patch) suffix of each variant, for example `(react@19.2.0)`.
570
+ */
571
+ export function getLockfileSnapshotVariants(lockfileText) {
572
+ const variants = new Map();
573
+ const section = getLockfileSection(lockfileText, "snapshots");
574
+ // Lockfile v6 and older kept peer variants in `packages:` with a `/` prefix.
575
+ const lines = section.length
576
+ ? section
577
+ : getLockfileSection(lockfileText, "packages");
578
+ for (const line of lines) {
579
+ const entry = parseYamlMappingLine(line, 2);
580
+ if (!entry)
581
+ continue;
582
+ const key = entry.key.replace(/^\//, "");
583
+ const versionSeparator = key.indexOf("@", key.startsWith("@") ? 1 : 0);
584
+ if (versionSeparator <= 0)
585
+ continue;
586
+ const suffixStart = key.indexOf("(", versionSeparator);
587
+ const base = suffixStart === -1 ? key : key.slice(0, suffixStart);
588
+ const suffix = suffixStart === -1 ? "" : key.slice(suffixStart);
589
+ const set = variants.get(base) ?? new Set();
590
+ set.add(suffix);
591
+ variants.set(base, set);
592
+ }
593
+ return variants;
594
+ }
595
+ /**
596
+ * Lists `name@version` entries that have more than one peer variant after a
597
+ * lockfile change and more variants than before it. Pre-existing duplicates
598
+ * are ignored so warnings point only at what the change introduced.
599
+ */
600
+ export function findNewPeerVariantDuplicates(beforeLockfileText, afterLockfileText) {
601
+ const before = beforeLockfileText
602
+ ? getLockfileSnapshotVariants(beforeLockfileText)
603
+ : new Map();
604
+ const after = getLockfileSnapshotVariants(afterLockfileText);
605
+ const duplicates = [];
606
+ for (const [packageVersion, variants] of after) {
607
+ const beforeCount = before.get(packageVersion)?.size ?? 0;
608
+ if (variants.size > 1 && variants.size > beforeCount) {
609
+ duplicates.push({
610
+ after: variants.size,
611
+ before: beforeCount,
612
+ packageVersion,
613
+ });
614
+ }
615
+ }
616
+ return duplicates.sort((left, right) => compareNames(left.packageVersion, right.packageVersion));
617
+ }
@@ -29,6 +29,25 @@ export declare function resolveMigrationEnvironment(env: Record<string, string |
29
29
  * process values, including a dedicated migration secret, to take precedence.
30
30
  */
31
31
  export declare function resolveMigrationEnvironmentFromEnvFile(envFile: string, env: Record<string, string | undefined>): MigrationEnvironmentResolution;
32
+ /**
33
+ * Thrown when the app does not have the optional `postgres` peer installed,
34
+ * so the connection preflight cannot run at all.
35
+ */
36
+ export declare class MigrationDriverMissingError extends Error {
37
+ constructor();
38
+ }
39
+ /**
40
+ * Whether `error` reports that `packageName` itself could not be resolved, as
41
+ * thrown by Node's ESM loader (`ERR_MODULE_NOT_FOUND`), Node's CommonJS
42
+ * `require` used by the npm CLI build (`MODULE_NOT_FOUND`), Deno
43
+ * (`Import "x" not a dependency`), or Yarn Plug'n'Play when the app does not
44
+ * provide the peer (`MISSING_PEER_DEPENDENCY`). A missing file inside an
45
+ * installed package, which Node reports by its path, does not count.
46
+ */
47
+ export declare function isPackageNotFoundError(error: unknown, packageName: string): boolean;
48
+ declare const importPostgres: () => Promise<any>;
49
+ /** Loads the app's `postgres` driver, which is an optional Loom peer. */
50
+ export declare function loadPostgresDriver(importModule?: typeof importPostgres): Promise<any>;
32
51
  /**
33
52
  * Authenticates with the selected migration URL and verifies that the
34
53
  * connection reaches the declared role/database with usable schema access.
@@ -1 +1 @@
1
- {"version":3,"file":"migrationEnv.d.ts","sourceRoot":"","sources":["../../../src/src/cli/migrationEnv.ts"],"names":[],"mappings":"AAGA,QAAA,MAAM,wCAAwC,iHAKpC,CAAC;AAEX,MAAM,MAAM,2BAA2B,GACrC,OAAO,wCAAwC,CAAC,MAAM,CAAC,CAAC;AAE1D,MAAM,MAAM,8BAA8B,GAAG;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,2BAA2B,CAAC;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,6EAA6E;AAC7E,MAAM,MAAM,+BAA+B,GACvC,8BAA8B,GAC9B;IACA,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEJ,KAAK,4BAA4B,GAAG;IAClC,iBAAiB,EAAE,OAAO,CAAC;IAC3B,YAAY,EAAE,OAAO,CAAC;IACtB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