knarr 0.3.0 → 0.3.1

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 (138) hide show
  1. package/README.md +1 -1
  2. package/dist/add-CyrFHzUe.mjs +1 -0
  3. package/dist/add-flow-BjjRSNWm.mjs +3 -0
  4. package/dist/batch-push-Cee2SPW3.mjs +1 -0
  5. package/dist/build-detect-Bo1fe8OV.mjs +1 -0
  6. package/dist/bundler-detect-BaShXORS.mjs +1 -0
  7. package/dist/check-ChNlHxR5.mjs +1 -0
  8. package/dist/chokidar-DoHpObCq.mjs +1 -0
  9. package/dist/clean-oNr4nUNk.mjs +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.mjs +2 -3
  12. package/dist/config-D0TqqAAJ.mjs +2 -0
  13. package/dist/console-C8XtlRyM.mjs +1 -0
  14. package/dist/dev-vA8K5egW.mjs +1 -0
  15. package/dist/dist-jMqCJR3W.mjs +5 -0
  16. package/dist/doctor-ITFcIVoj.mjs +4 -0
  17. package/dist/dry-run-DPoN8bZo.mjs +1 -0
  18. package/dist/errors-DRugrv36.mjs +1 -0
  19. package/dist/explain-xtY13-Ex.mjs +1 -0
  20. package/dist/format-IsfSiyGV.mjs +1 -0
  21. package/dist/fs-Ce7wcxvx.mjs +1 -0
  22. package/dist/fs-DusqxRQR.mjs +1 -0
  23. package/dist/hints-BKo_2axg.mjs +1 -0
  24. package/dist/history-540r0BHF.mjs +1 -0
  25. package/dist/history-B3E1DMFO.mjs +1 -0
  26. package/dist/index.mjs +1 -3637
  27. package/dist/init-KBwXbX7j.mjs +2 -0
  28. package/dist/init-helpers-DGSTVbNx.mjs +13 -0
  29. package/dist/injector-BMOi1uN3.mjs +1 -0
  30. package/dist/json-1jsvqdBb.mjs +1 -0
  31. package/dist/list-BkniWIlD.mjs +1 -0
  32. package/dist/logger-Oo2Slehd.mjs +1 -0
  33. package/dist/migrate-DM80YXOF.mjs +3 -0
  34. package/dist/nextjs-config-BlbmHmCb.mjs +1 -0
  35. package/dist/nextjs-config-m83qz9Qp.mjs +2 -0
  36. package/dist/output-B7NC4xgj.mjs +1 -0
  37. package/dist/package-manager-Cs9kCsjJ.mjs +11 -0
  38. package/dist/paths-B5sEvS_7.mjs +1 -0
  39. package/dist/picomatch-DEttMFSR.mjs +1 -0
  40. package/dist/preflight-C_Zr3uyO.mjs +1 -0
  41. package/dist/preflight-fF8g1t6F.mjs +1 -0
  42. package/dist/publish-PaTRQ5Ga.mjs +1 -0
  43. package/dist/publisher-oHVy3LA2.mjs +2 -0
  44. package/dist/push-DX9dRKDw.mjs +1 -0
  45. package/dist/push-engine-ByiNZr52.mjs +1 -0
  46. package/dist/remove-BEBkMPak.mjs +1 -0
  47. package/dist/remove-DxezmGfU.mjs +1 -0
  48. package/dist/reset-B9Xcepo1.mjs +1 -0
  49. package/dist/restore-B8aEJn3N.mjs +1 -0
  50. package/dist/rollback-pqomySb-.mjs +1 -0
  51. package/dist/shell-DQfdqK0J.mjs +1 -0
  52. package/dist/status-2-lE-2hH.mjs +1 -0
  53. package/dist/store-CAzxNmpU.mjs +1 -0
  54. package/dist/tailwind-source-Ho_nKVtd.mjs +3 -0
  55. package/dist/timer-BZNWRS3O.mjs +1 -0
  56. package/dist/topo-sort-CNCKE3Ap.mjs +1 -0
  57. package/dist/topo-sort-I086ZoiN.mjs +1 -0
  58. package/dist/tracker-OhIA445x.mjs +1 -0
  59. package/dist/tracker-nsfA6PWa.mjs +1 -0
  60. package/dist/update-CjAl0ZO9.mjs +1 -0
  61. package/dist/use-BCXyvJf2.mjs +1 -0
  62. package/dist/vite-config-B6bZDoGe.mjs +1 -0
  63. package/dist/vite-config-D_iXaoHh.mjs +10 -0
  64. package/dist/vite-plugin.mjs +1 -210
  65. package/dist/watch-orchestrator-DGe9gBjj.mjs +1 -0
  66. package/dist/watch-orchestrator-DkuwJOEb.mjs +1 -0
  67. package/dist/watcher-DN6vT6nw.mjs +1 -0
  68. package/dist/watcher-LcNLwOgA.mjs +1 -0
  69. package/dist/webpack-plugin.mjs +1 -145
  70. package/dist/workspace-7rWwh6jI.mjs +1 -0
  71. package/dist/workspace-CSQVbAw4.mjs +1 -0
  72. package/package.json +4 -7
  73. package/dist/add-B_xzUp5y.mjs +0 -3
  74. package/dist/add-flow-cvrMO_aV.mjs +0 -5
  75. package/dist/batch-push-DXtZxRx0.mjs +0 -3
  76. package/dist/build-detect-BTHh2OBm.mjs +0 -3
  77. package/dist/bundler-detect-Dq-QAbQj.mjs +0 -3
  78. package/dist/check-CbVdpTsw.mjs +0 -3
  79. package/dist/chokidar-BkIWf7Ix.mjs +0 -3
  80. package/dist/clean-CyDDqbBD.mjs +0 -3
  81. package/dist/config-BJsL6NqN.mjs +0 -4
  82. package/dist/console-CIiXr7ge.mjs +0 -3
  83. package/dist/console-CyaBcUd-.mjs +0 -98
  84. package/dist/dev-kqgY9NjI.mjs +0 -3
  85. package/dist/dist-CFkjiIqD.mjs +0 -7
  86. package/dist/doctor-D-S1P0UG.mjs +0 -6
  87. package/dist/dry-run-BkdMYSIx.mjs +0 -3
  88. package/dist/errors-BlOfexcH.mjs +0 -3
  89. package/dist/explain-9Y4SZHjC.mjs +0 -3
  90. package/dist/format-DRqD29u-.mjs +0 -3
  91. package/dist/fs-C4juVCTd.mjs +0 -3
  92. package/dist/fs-CPnWm9CR.mjs +0 -3
  93. package/dist/fs-DzsciYAL.mjs +0 -757
  94. package/dist/hints-Hz3V4h3A.mjs +0 -3
  95. package/dist/history-DRhLwzhq.mjs +0 -3
  96. package/dist/history-vS3w4EGu.mjs +0 -3
  97. package/dist/init-TN84d5jM.mjs +0 -4
  98. package/dist/init-helpers-CYYWQm-P.mjs +0 -15
  99. package/dist/injector-nt40JxVt.mjs +0 -3
  100. package/dist/json-DbSkpxtr.mjs +0 -3
  101. package/dist/list-9hWJjw19.mjs +0 -3
  102. package/dist/logger-9C6B9Na8.mjs +0 -3
  103. package/dist/migrate-Co4qcFt6.mjs +0 -5
  104. package/dist/nextjs-config-BQgTWZ96.mjs +0 -3
  105. package/dist/nextjs-config-dUw2J6B9.mjs +0 -4
  106. package/dist/output-BxR2v-jn.mjs +0 -3
  107. package/dist/package-manager-DJ8CE0zL.mjs +0 -13
  108. package/dist/picomatch-B0_Pxgms.mjs +0 -3
  109. package/dist/preflight-BDsxR2Ct.mjs +0 -3
  110. package/dist/preflight-MzNjLXiy.mjs +0 -3
  111. package/dist/publish-C7ZUvHkE.mjs +0 -3
  112. package/dist/publisher-CvXTbkLP.mjs +0 -4
  113. package/dist/push-B5KrkILW.mjs +0 -3
  114. package/dist/push-engine-BpNr8qXR.mjs +0 -3
  115. package/dist/remove-DkOgVQMZ.mjs +0 -3
  116. package/dist/remove-J5tY_BFk.mjs +0 -3
  117. package/dist/reset-ClGouUb5.mjs +0 -3
  118. package/dist/restore-Bx2V59SL.mjs +0 -3
  119. package/dist/rollback-RPjHZWtG.mjs +0 -3
  120. package/dist/rolldown-runtime-BZbIAPMk.mjs +0 -3
  121. package/dist/shell-RQ7Hf1kp.mjs +0 -3
  122. package/dist/status-Rnvw6dG2.mjs +0 -3
  123. package/dist/store-DjPdOKqg.mjs +0 -3
  124. package/dist/tailwind-source-D1cUiG-t.mjs +0 -5
  125. package/dist/timer-DqgB175x.mjs +0 -3
  126. package/dist/topo-sort-DOCpHjT7.mjs +0 -3
  127. package/dist/topo-sort-yd4jxr_E.mjs +0 -3
  128. package/dist/tracker-89eW0ArT.mjs +0 -3
  129. package/dist/tracker-B3Fqx94J.mjs +0 -3
  130. package/dist/update-CAKFICZu.mjs +0 -3
  131. package/dist/use-CCx6J0mc.mjs +0 -3
  132. package/dist/vite-config-BHmawlD2.mjs +0 -12
  133. package/dist/vite-config-BRlYc4ni.mjs +0 -3
  134. package/dist/watch-orchestrator-BfuCaZLA.mjs +0 -3
  135. package/dist/watcher-T123sBDg.mjs +0 -3
  136. package/dist/workspace-CdLSxPFS.mjs +0 -3
  137. package/dist/workspace-DBxNrowu.mjs +0 -3
  138. package/dist/xxhash-wasm-D_QjdUuv.mjs +0 -3
@@ -1,757 +0,0 @@
1
- import { t as consola } from "./console-CyaBcUd-.mjs";
2
- import { constants, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
3
- import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
4
- import { availableParallelism, homedir } from "node:os";
5
- import { createHash, randomUUID } from "node:crypto";
6
- import { setTimeout } from "node:timers/promises";
7
- // \0rolldown/runtime.js
8
- var __defProp = Object.defineProperty;
9
- var __exportAll = (all, flags) => {
10
- let target = Object.setPrototypeOf({}, null);
11
- for (var name in all) __defProp(target, name, {
12
- get: all[name],
13
- enumerable: true
14
- });
15
- if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
16
- return flags & 2 ? target : Object.preventExtensions(target);
17
- };
18
- // src/utils/concurrency.ts
19
- /**
20
- * Minimal p-limit replacement using a promise queue.
21
- * Drop-in compatible: `const limit = pLimit(N); await limit(fn)`
22
- *
23
- * Uses a head pointer for O(1) dequeue instead of Array.shift() which is O(n).
24
- * Compacts the queue array when it drains to prevent unbounded memory growth.
25
- */
26
- function pLimit(concurrency) {
27
- let active = 0;
28
- const queue = [];
29
- let head = 0;
30
- const next = () => {
31
- const task = active < concurrency ? queue[head] : void 0;
32
- if (task) {
33
- head++;
34
- active++;
35
- task();
36
- }
37
- if (head > 0 && head === queue.length) {
38
- queue.length = 0;
39
- head = 0;
40
- }
41
- };
42
- return (fn) => new Promise((resolve, reject) => {
43
- const run = () => {
44
- fn().then((val) => {
45
- active--;
46
- resolve(val);
47
- next();
48
- }, (err) => {
49
- active--;
50
- reject(err);
51
- next();
52
- });
53
- };
54
- if (active < concurrency) {
55
- active++;
56
- run();
57
- } else queue.push(run);
58
- });
59
- }
60
- // src/utils/json.ts
61
- function ownRecord(source) {
62
- const record = Object.create(null);
63
- if (source) for (const [key, value] of Object.entries(source)) record[key] = value;
64
- return record;
65
- }
66
- function isJsonObject(value) {
67
- return typeof value === "object" && value !== null && !Array.isArray(value);
68
- }
69
- /** Parse JSON to `unknown`; callers must validate before use. */
70
- function parseJson(text) {
71
- return JSON.parse(text);
72
- }
73
- /** Parse JSON that must be an object (package.json, state files). Throws otherwise. */
74
- function parseJsonObject(text, label = "JSON") {
75
- const value = parseJson(text);
76
- if (!isJsonObject(value)) throw new Error(`${label} must contain a JSON object`);
77
- return value;
78
- }
79
- async function readJsonObject(path, label = path) {
80
- return parseJsonObject(await readFile(path, "utf-8"), label);
81
- }
82
- /** `obj[key]` when it is a string. */
83
- function stringField(obj, key) {
84
- const value = obj[key];
85
- return typeof value === "string" ? value : void 0;
86
- }
87
- /** `obj[key]` when it is a JSON object. */
88
- function objectField(obj, key) {
89
- const value = obj[key];
90
- return isJsonObject(value) ? value : void 0;
91
- }
92
- /** The string-valued entries of `obj[key]` (e.g. package.json "scripts"). */
93
- function stringRecordField(obj, key) {
94
- const value = objectField(obj, key);
95
- const result = ownRecord();
96
- if (!value) return result;
97
- for (const [k, v] of Object.entries(value)) if (typeof v === "string") result[k] = v;
98
- return result;
99
- }
100
- /**
101
- * Narrow a parsed package.json to `PackageJson`. `name` and `version` (the
102
- * identity used for store paths) must be strings. Other fields stay as parsed
103
- * and must be checked where they are used.
104
- */
105
- function asPackageJson(obj) {
106
- if (typeof obj["name"] !== "string" || typeof obj["version"] !== "string") return null;
107
- return obj;
108
- }
109
- // src/utils/validators.ts
110
- const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
111
- const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
112
- const CONTROL_CHARS_RE = /[\x00-\x1F\x7F]/;
113
- /**
114
- * Validate an npm package name before using it in store/node_modules paths.
115
- * This intentionally mirrors npm's modern lowercase package-name shape and
116
- * rejects path separators/traversal segments before any filesystem mutation.
117
- */
118
- function validatePackageName(name) {
119
- if (!name || name.length > 214 || CONTROL_CHARS_RE.test(name) || name.includes("\\") || name.includes("//") || name.split("/").some((part) => part === "." || part === "..") || !PACKAGE_NAME_RE.test(name)) throw new Error(`Invalid package name "${name}"`);
120
- }
121
- /** Validate a package.json version string before it becomes part of a path. */
122
- function validatePackageVersion(version) {
123
- if (!version || CONTROL_CHARS_RE.test(version) || version.includes("/") || version.includes("\\") || version.includes("..") || !SEMVER_RE.test(version)) throw new Error(`Invalid package version "${version}"`);
124
- }
125
- function validatePackageIdentity(name, version) {
126
- validatePackageName(name);
127
- validatePackageVersion(version);
128
- }
129
- /** Check if a value is valid Knarr metadata. */
130
- function isKnarrMeta(value) {
131
- if (typeof value !== "object" || value === null) return false;
132
- const v = value;
133
- return typeof v.contentHash === "string" && typeof v.publishedAt === "string" && typeof v.sourcePath === "string" && (v.buildId === void 0 || typeof v.buildId === "string") && (v.schemaVersion === void 0 || typeof v.schemaVersion === "number");
134
- }
135
- /** Check if a value is a valid LinkEntry */
136
- function isLinkEntry(value) {
137
- if (typeof value !== "object" || value === null) return false;
138
- const v = value;
139
- return typeof v.version === "string" && typeof v.contentHash === "string" && typeof v.linkedAt === "string" && typeof v.sourcePath === "string" && typeof v.backupExists === "boolean" && typeof v.packageManager === "string" && [
140
- "npm",
141
- "pnpm",
142
- "yarn",
143
- "bun"
144
- ].includes(v.packageManager) && (v.buildId === void 0 || typeof v.buildId === "string");
145
- }
146
- function parseConsumerState(value) {
147
- if (typeof value !== "object" || value === null) return null;
148
- const v = value;
149
- if (v.version !== "1") return null;
150
- if (typeof v.links !== "object" || v.links === null) return null;
151
- const links = ownRecord();
152
- for (const [name, entry] of Object.entries(v.links)) {
153
- if (!isLinkEntry(entry)) return null;
154
- links[name] = entry;
155
- }
156
- return {
157
- ...v,
158
- links
159
- };
160
- }
161
- function parseConsumersRegistry(value) {
162
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
163
- const registry = ownRecord();
164
- for (const [name, consumers] of Object.entries(value)) {
165
- if (!Array.isArray(consumers) || !consumers.every((item) => typeof item === "string")) return null;
166
- registry[name] = consumers;
167
- }
168
- return registry;
169
- }
170
- // src/utils/paths.ts
171
- function assertInside(root, target, label) {
172
- const resolvedRoot = resolve(root);
173
- const resolvedTarget = resolve(target);
174
- const rel = relative(resolvedRoot, resolvedTarget);
175
- if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return;
176
- throw new Error(`${label} escapes expected directory: ${target}`);
177
- }
178
- /** Root knarr directory: ~/.knarr/ (override with KNARR_HOME env var). */
179
- function getKnarrHome() {
180
- return process.env.KNARR_HOME || join(homedir(), ".knarr");
181
- }
182
- /** Store root: ~/.knarr/store/ */
183
- function getStorePath() {
184
- return join(getKnarrHome(), "store");
185
- }
186
- /** Consumers registry: ~/.knarr/consumers.json */
187
- function getConsumersPath() {
188
- return join(getKnarrHome(), "consumers.json");
189
- }
190
- /**
191
- * Encode a package name for use as a directory name.
192
- * Scoped packages: `@scope/name` -> `@scope+name`
193
- */
194
- function encodePackageName(name) {
195
- validatePackageName(name);
196
- return name.replace(/\//g, "+");
197
- }
198
- /**
199
- * Decode a directory name back to a package name.
200
- * `@scope+name` -> `@scope/name`
201
- */
202
- function decodePackageName(encoded) {
203
- if (encoded.startsWith("@")) {
204
- const plusIdx = encoded.indexOf("+");
205
- if (plusIdx !== -1) return encoded.slice(0, plusIdx) + "/" + encoded.slice(plusIdx + 1);
206
- }
207
- return encoded;
208
- }
209
- /** Get the store directory for a specific package@version */
210
- function getStoreEntryPath(name, version) {
211
- validatePackageIdentity(name, version);
212
- const root = getStorePath();
213
- const target = join(root, `${encodePackageName(name)}@${version}`);
214
- assertInside(root, target, "Store entry path");
215
- return target;
216
- }
217
- /** Get the package directory within a store entry */
218
- function getStorePackagePath(name, version) {
219
- return join(getStoreEntryPath(name, version), "package");
220
- }
221
- /** Get the .knarr-meta.json path for a store entry */
222
- function getStoreMetaPath(name, version) {
223
- return join(getStoreEntryPath(name, version), ".knarr-meta.json");
224
- }
225
- /** Get the history directory for a store entry */
226
- function getStoreHistoryPath(name, version) {
227
- return join(getStoreEntryPath(name, version), "history");
228
- }
229
- /** Get a specific history entry directory */
230
- function getHistoryEntryPath(name, version, buildId) {
231
- if (!/^[a-f0-9]{8,64}$/i.test(buildId)) throw new Error(`Invalid build id "${buildId}"`);
232
- return join(getStoreHistoryPath(name, version), buildId);
233
- }
234
- /** Get the .knarr/ directory in a consumer project */
235
- function getConsumerKnarrDir(consumerPath) {
236
- return join(consumerPath, ".knarr");
237
- }
238
- /** Get the state file in a consumer project */
239
- function getConsumerStatePath(consumerPath) {
240
- return join(consumerPath, ".knarr", "state.json");
241
- }
242
- /** Get the backups directory in a consumer project */
243
- function getConsumerBackupPath(consumerPath, packageName) {
244
- validatePackageName(packageName);
245
- const root = join(consumerPath, ".knarr", "backups");
246
- const target = join(root, encodePackageName(packageName));
247
- assertInside(root, target, "Backup path");
248
- return target;
249
- }
250
- /** Normalize a file path to use forward slashes (for cross-platform consistency). */
251
- function normalizePath(p) {
252
- return p.replace(/\\/g, "/");
253
- }
254
- /** Get node_modules/<pkg> path for a package in a consumer */
255
- function getNodeModulesPackagePath(consumerPath, packageName) {
256
- validatePackageName(packageName);
257
- const root = join(consumerPath, "node_modules");
258
- const target = join(root, packageName);
259
- assertInside(root, target, "node_modules package path");
260
- return target;
261
- }
262
- let _dryRun = false;
263
- let _jsonOutput = false;
264
- function isDryRun() {
265
- return _dryRun;
266
- }
267
- function isJsonOutput() {
268
- return _jsonOutput;
269
- }
270
- /** Log a debug message only when --verbose is active */
271
- function verbose(msg, ...args) {}
272
- // src/utils/hash.ts
273
- /** Lazy-initialized xxhash-wasm singleton (follows dynamic import pattern used elsewhere) */
274
- let _xxhash = null;
275
- function getXXHash() {
276
- if (!_xxhash) _xxhash = import("xxhash-wasm").then((mod) => mod.default()).catch((err) => {
277
- _xxhash = null;
278
- throw err;
279
- });
280
- return _xxhash;
281
- }
282
- /** Files larger than this threshold use streaming hash */
283
- const STREAM_THRESHOLD = 1048576;
284
- /** Concurrency limit for parallel file reads in computeContentHash */
285
- const limit = pLimit(Math.max(availableParallelism(), 8));
286
- /**
287
- * Compute a SHA-256 content hash for a list of files.
288
- * The hash is deterministic: sorted by relative path, each entry is `path\0content`.
289
- * Reads files in parallel (up to CPU count concurrent) then feeds into hash in sorted order.
290
- */
291
- async function computeContentHash(files, baseDir, contentOverrides = /* @__PURE__ */ new Map()) {
292
- const fileByRel = new Map(files.map((file) => [normalizePath(relative(baseDir, file)), file]));
293
- for (const rel of contentOverrides.keys()) if (!fileByRel.has(rel)) fileByRel.set(rel, join(baseDir, rel));
294
- const sorted = [...fileByRel.entries()].sort(([relA], [relB]) => relA.localeCompare(relB));
295
- const contents = await Promise.all(sorted.map(([rel, file]) => limit(async () => {
296
- const override = contentOverrides.get(rel);
297
- if (override !== void 0) return {
298
- rel,
299
- content: Buffer.isBuffer(override) ? override : Buffer.from(override)
300
- };
301
- return {
302
- rel,
303
- content: await readFile(file)
304
- };
305
- })));
306
- `${sorted.length}`;
307
- const hash = createHash("sha256");
308
- const lenBuf = Buffer.alloc(4);
309
- for (const { rel, content } of contents) {
310
- hash.update(rel);
311
- hash.update("\0");
312
- lenBuf.writeUInt32LE(content.length);
313
- hash.update(lenBuf);
314
- hash.update(content);
315
- }
316
- const result = "sha256v2:" + hash.digest("hex");
317
- `${result.slice(0, 20)}`;
318
- return result;
319
- }
320
- /**
321
- * Compute xxHash64 of a single file's content.
322
- * Used for per-file change detection during incremental copy — not persisted,
323
- * so no need for cryptographic strength. xxHash64 is ~5-10x faster than SHA-256.
324
- * - Files ≤1MB: buffered read + h64Raw
325
- * - Files >1MB: streaming via create64() hasher
326
- */
327
- async function hashFile(filePath, knownSize) {
328
- const size = knownSize ?? (await stat(filePath)).size;
329
- const xx = await getXXHash();
330
- if (size > STREAM_THRESHOLD) return hashFileStream(filePath, xx);
331
- const content = await readFile(filePath);
332
- return xx.h64Raw(content).toString(16);
333
- }
334
- /**
335
- * Compute xxHash64 using streaming for large files.
336
- * Reads the file in 64KB chunks to avoid loading multi-MB files into memory.
337
- */
338
- async function hashFileStream(filePath, xx) {
339
- const { createReadStream } = await import("node:fs");
340
- const hasher = xx.create64();
341
- return new Promise((resolve, reject) => {
342
- const stream = createReadStream(filePath);
343
- stream.on("data", (chunk) => hasher.update(chunk));
344
- stream.on("end", () => resolve(hasher.digest().toString(16)));
345
- stream.on("error", reject);
346
- });
347
- }
348
- // src/utils/dry-run.ts
349
- /**
350
- * Shorten a path for the human report: relative to cwd when inside it,
351
- * `~` for the home directory (where the store usually lives). JSON keeps absolute paths.
352
- */
353
- function displayMutationPath(p, cwd = process.cwd(), home = homedir()) {
354
- const inside = (base) => {
355
- const rel = relative(base, p);
356
- return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel : rel === "" ? "." : null;
357
- };
358
- const fromCwd = inside(cwd);
359
- if (fromCwd !== null) return fromCwd;
360
- const fromHome = inside(home);
361
- if (fromHome !== null) return fromHome === "." ? "~" : `~${sep}${fromHome}`;
362
- return p;
363
- }
364
- const mutations = [];
365
- let jsonReportPrinted = false;
366
- /** Record a mutation that was skipped due to --dry-run */
367
- function recordMutation(mutation) {
368
- mutations.push(mutation);
369
- }
370
- function getMutations() {
371
- return [...mutations];
372
- }
373
- function markDryRunJsonReportPrinted() {
374
- jsonReportPrinted = true;
375
- }
376
- /** Print a summary of all recorded dry-run mutations */
377
- function printDryRunReport() {
378
- if (mutations.length === 0) {
379
- consola.info("[dry-run] No mutations would be performed");
380
- return;
381
- }
382
- if (isJsonOutput()) {
383
- if (jsonReportPrinted) return;
384
- console.log(JSON.stringify({
385
- dryRun: true,
386
- mutations
387
- }, null, 2));
388
- jsonReportPrinted = true;
389
- return;
390
- }
391
- const grouped = /* @__PURE__ */ new Map();
392
- for (const m of mutations) {
393
- let list = grouped.get(m.type);
394
- if (!list) {
395
- list = [];
396
- grouped.set(m.type, list);
397
- }
398
- list.push(m);
399
- }
400
- consola.info(`\n[dry-run] ${mutations.length} mutation(s) would be performed:\n`);
401
- const labels = {
402
- copy: "Copy",
403
- remove: "Remove",
404
- move: "Move",
405
- mkdir: "Create directory",
406
- write: "Write file",
407
- "bin-link": "Create bin link",
408
- "bin-unlink": "Remove bin link",
409
- "cache-invalidate": "Invalidate cache",
410
- "lock-skip": "Skip lock",
411
- "lifecycle-skip": "Skip lifecycle hook",
412
- "command-skip": "Skip command"
413
- };
414
- for (const [type, items] of grouped) {
415
- consola.info(` ${labels[type]} (${items.length}):`);
416
- for (const item of items.slice(0, 20)) {
417
- const dest = item.dest ? ` → ${displayMutationPath(item.dest)}` : "";
418
- const detail = item.detail ? ` (${item.detail})` : "";
419
- consola.info(` ${displayMutationPath(item.path)}${dest}${detail}`);
420
- }
421
- if (items.length > 20) consola.info(` ... and ${items.length - 20} more`);
422
- }
423
- }
424
- /** Reset recorded mutations (for testing) */
425
- function resetMutations() {
426
- mutations.length = 0;
427
- jsonReportPrinted = false;
428
- }
429
- // src/utils/fs.ts
430
- var fs_exports = /* @__PURE__ */ __exportAll({ exists: () => exists });
431
- /** Concurrency limit for parallel file I/O, auto-tuned to available CPUs */
432
- const ioLimit = pLimit(Math.max(availableParallelism(), 8));
433
- /** Type guard for Node.js system errors with an error code */
434
- function isNodeError(err) {
435
- return err instanceof Error && "code" in err;
436
- }
437
- const reflinkSupported = /* @__PURE__ */ new Map();
438
- function volumeRoot(filePath) {
439
- const { root } = parse(filePath);
440
- return root || "/";
441
- }
442
- /**
443
- * Copy a file using CoW (reflink) when available, with per-volume caching.
444
- *
445
- * On the first copy per volume, tries COPYFILE_FICLONE_FORCE to probe
446
- * for reflink support. If it fails, caches the result and all subsequent
447
- * copies on that volume go straight to a plain copy — no wasted syscalls.
448
- *
449
- * Writes to a temp sibling and renames it over `dest`, so `dest` always gets a
450
- * new inode. Package managers (pnpm, Bun) hardlink installed files to a global
451
- * store; overwriting in place would change every project sharing that inode.
452
- */
453
- async function copyWithCoW(src, dest, options) {
454
- if (isDryRun()) {
455
- `${src}${dest}`;
456
- recordMutation({
457
- type: "copy",
458
- path: src,
459
- dest
460
- });
461
- return;
462
- }
463
- if (options?.ensureParent !== false) await mkdir(dirname(dest), { recursive: true });
464
- const tmp = `${dest}${COPY_TEMP_MARKER}${process.pid}-${randomUUID()}`;
465
- try {
466
- await copyToFreshFile(src, tmp, volumeRoot(dest));
467
- await renameOverLockedTarget(tmp, dest);
468
- } catch (err) {
469
- await rm(tmp, { force: true });
470
- throw err;
471
- }
472
- }
473
- const COPY_TEMP_MARKER = ".knarr-tmp-";
474
- const COPY_TEMP_PATTERN = /\.knarr-tmp-(\d+)-[0-9a-f-]{36}$/;
475
- function isInFlightCopyTemp(path) {
476
- const pid = COPY_TEMP_PATTERN.exec(path)?.[1];
477
- if (pid === void 0) return false;
478
- try {
479
- process.kill(Number(pid), 0);
480
- return true;
481
- } catch (err) {
482
- return isNodeError(err) && err.code === "EPERM";
483
- }
484
- }
485
- const RENAME_RETRY_DELAYS_MS = [
486
- 10,
487
- 20,
488
- 40,
489
- 80,
490
- 160,
491
- 300,
492
- 400
493
- ];
494
- const WINDOWS_LOCK_CODES = /* @__PURE__ */ new Set([
495
- "EPERM",
496
- "EACCES",
497
- "EBUSY"
498
- ]);
499
- async function renameOverLockedTarget(from, to) {
500
- for (const delay of RENAME_RETRY_DELAYS_MS) try {
501
- await rename(from, to);
502
- return;
503
- } catch (err) {
504
- if (process.platform !== "win32" || !isNodeError(err) || !WINDOWS_LOCK_CODES.has(err.code ?? "")) throw err;
505
- await setTimeout(delay);
506
- }
507
- await rename(from, to);
508
- }
509
- async function copyToFreshFile(src, dest, root) {
510
- const supportsReflink = reflinkSupported.get(root);
511
- if (supportsReflink === false) {
512
- await copyFile(src, dest);
513
- return;
514
- }
515
- if (supportsReflink === true) {
516
- await copyFile(src, dest, constants.COPYFILE_FICLONE);
517
- return;
518
- }
519
- try {
520
- await copyFile(src, dest, constants.COPYFILE_FICLONE_FORCE);
521
- reflinkSupported.set(root, true);
522
- } catch {
523
- reflinkSupported.set(root, false);
524
- `${root}`;
525
- await copyFile(src, dest);
526
- }
527
- }
528
- /**
529
- * Recursively collect all file paths in a directory.
530
- * Uses Node 22+ recursive readdir with withFileTypes to avoid separate stat calls.
531
- */
532
- async function collectFiles(dir) {
533
- return (await readdir(dir, {
534
- recursive: true,
535
- withFileTypes: true
536
- })).filter((e) => e.isFile()).map((e) => join(e.parentPath, e.name));
537
- }
538
- async function removeDestinationConflicts(destDir, relPath) {
539
- const parts = relPath.split(/[\\/]/).filter(Boolean);
540
- let current = destDir;
541
- for (const [i, part] of parts.entries()) {
542
- current = join(current, part);
543
- try {
544
- const s = await stat(current);
545
- const isLeaf = i === parts.length - 1;
546
- if (s.isDirectory()) {
547
- if (isLeaf) {
548
- if (isDryRun()) recordMutation({
549
- type: "remove",
550
- path: current
551
- });
552
- else await rm(current, {
553
- recursive: true,
554
- force: true
555
- });
556
- }
557
- continue;
558
- }
559
- if (!isLeaf) {
560
- if (isDryRun()) {
561
- recordMutation({
562
- type: "remove",
563
- path: current
564
- });
565
- return;
566
- } else await rm(current, { force: true });
567
- }
568
- } catch (err) {
569
- if (isNodeError(err) && err.code === "ENOENT") return;
570
- throw err;
571
- }
572
- }
573
- }
574
- /**
575
- * Incrementally copy files from src to dest directory.
576
- * Only copies files whose content has changed (stat size check + hash comparison).
577
- * Also removes files in dest that don't exist in src.
578
- * Returns the number of files actually copied.
579
- */
580
- async function incrementalCopy(srcDir, destDir, options = {}) {
581
- const srcFilesPromise = collectFiles(srcDir);
582
- const destFilesPromise = collectFiles(destDir).catch((err) => {
583
- if (isNodeError(err) && err.code === "ENOENT") return [];
584
- throw err;
585
- });
586
- const [srcFiles, destFiles] = await Promise.all([srcFilesPromise, destFilesPromise]);
587
- let copied = 0;
588
- let skipped = 0;
589
- const results = await Promise.all(srcFiles.map((srcFile) => ioLimit(async () => {
590
- const rel = relative(srcDir, srcFile);
591
- const destFile = join(destDir, rel);
592
- let needsCopy = true;
593
- if (options.force) `${rel}`;
594
- else try {
595
- const [srcStat, destStat] = await Promise.all([stat(srcFile), stat(destFile)]);
596
- if (srcStat.size !== destStat.size) `${rel}${srcStat.size}${destStat.size}`;
597
- else {
598
- const [srcHash, destHash] = await Promise.all([hashFile(srcFile, srcStat.size), hashFile(destFile, destStat.size)]);
599
- if (srcHash === destHash) {
600
- needsCopy = false;
601
- `${rel}`;
602
- } else `${rel}`;
603
- }
604
- } catch (err) {
605
- if (isNodeError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR")) `${rel}`;
606
- else throw err;
607
- }
608
- if (needsCopy) {
609
- await removeDestinationConflicts(destDir, rel);
610
- await copyWithCoW(srcFile, destFile);
611
- return "copied";
612
- }
613
- return "skipped";
614
- })));
615
- for (const r of results) if (r === "copied") copied++;
616
- else skipped++;
617
- const srcRelPaths = new Set(srcFiles.map((f) => relative(srcDir, f)));
618
- const filesToRemove = destFiles.filter((f) => !srcRelPaths.has(relative(destDir, f)) && !isInFlightCopyTemp(f));
619
- await Promise.all(filesToRemove.map((destFile) => ioLimit(async () => {
620
- `${relative(destDir, destFile)}`;
621
- if (isDryRun()) recordMutation({
622
- type: "remove",
623
- path: destFile
624
- });
625
- else await rm(destFile, { force: true }).catch((err) => {
626
- if (isNodeError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR" || err.code === "EISDIR" || err.code === "ERR_FS_EISDIR")) return;
627
- throw err;
628
- });
629
- })));
630
- const removed = filesToRemove.length;
631
- return {
632
- copied,
633
- removed,
634
- skipped
635
- };
636
- }
637
- /**
638
- * Move a directory, handling cross-filesystem (EXDEV) scenarios.
639
- * Tries rename first (fast, atomic on same FS), falls back to cp+rm.
640
- */
641
- async function moveDir(src, dest) {
642
- if (isDryRun()) {
643
- `${src}${dest}`;
644
- recordMutation({
645
- type: "move",
646
- path: src,
647
- dest
648
- });
649
- return;
650
- }
651
- try {
652
- await rename(src, dest);
653
- } catch (err) {
654
- if (isNodeError(err) && err.code === "EXDEV") {
655
- await cp(src, dest, { recursive: true });
656
- await rm(src, {
657
- recursive: true,
658
- force: true
659
- });
660
- } else throw err;
661
- }
662
- }
663
- /** Remove a directory recursively, no error if it doesn't exist */
664
- async function removeDir(dir) {
665
- if (isDryRun()) {
666
- `${dir}`;
667
- recordMutation({
668
- type: "remove",
669
- path: dir
670
- });
671
- return;
672
- }
673
- await rm(dir, {
674
- recursive: true,
675
- force: true
676
- });
677
- }
678
- /** Ensure a directory exists */
679
- async function ensureDir(dir) {
680
- if (isDryRun()) {
681
- `${dir}`;
682
- recordMutation({
683
- type: "mkdir",
684
- path: dir
685
- });
686
- return;
687
- }
688
- await mkdir(dir, { recursive: true });
689
- }
690
- /** Ensure a directory exists with private permissions (0o700). */
691
- async function ensurePrivateDir(dir) {
692
- if (isDryRun()) {
693
- `${dir}`;
694
- recordMutation({
695
- type: "mkdir",
696
- path: dir
697
- });
698
- return;
699
- }
700
- await mkdir(dir, {
701
- recursive: true,
702
- mode: 448
703
- });
704
- }
705
- /** Check if a path exists */
706
- async function exists(path) {
707
- try {
708
- await stat(path);
709
- return true;
710
- } catch {
711
- return false;
712
- }
713
- }
714
- /**
715
- * Write a file atomically by writing to a temp file then renaming.
716
- * Prevents corruption if the process crashes mid-write.
717
- */
718
- async function atomicWriteFile(filePath, data) {
719
- if (isDryRun()) {
720
- `${filePath}`;
721
- recordMutation({
722
- type: "write",
723
- path: filePath
724
- });
725
- return;
726
- }
727
- const tmpPath = `${filePath}.tmp-${process.pid}-${randomUUID()}`;
728
- try {
729
- await writeFile(tmpPath, data);
730
- await rename(tmpPath, filePath);
731
- } catch (err) {
732
- await rm(tmpPath, { force: true });
733
- throw err;
734
- }
735
- }
736
- /** Copy an entire directory recursively using native fs.cp */
737
- async function copyDir(src, dest) {
738
- if (isDryRun()) {
739
- `${src}${dest}`;
740
- recordMutation({
741
- type: "copy",
742
- path: src,
743
- dest
744
- });
745
- return;
746
- }
747
- try {
748
- await cp(src, dest, { recursive: true });
749
- } catch (err) {
750
- if (process.platform !== "win32" || !isNodeError(err) || err.code !== "EPERM" || err.syscall !== "symlink" || !(await lstat(src)).isSymbolicLink()) throw err;
751
- const target = await realpath(src);
752
- if (!(await stat(target)).isDirectory()) throw err;
753
- await mkdir(dirname(dest), { recursive: true });
754
- await symlink(target, dest, "junction");
755
- }
756
- }
757
- export { getStoreMetaPath as A, isJsonObject as B, getConsumerKnarrDir as C, getNodeModulesPackagePath as D, getHistoryEntryPath as E, parseConsumerState as F, readJsonObject as G, ownRecord as H, parseConsumersRegistry as I, pLimit as J, stringField as K, validatePackageIdentity as L, getStorePath as M, normalizePath as N, getStoreEntryPath as O, isKnarrMeta as P, validatePackageName as R, getConsumerBackupPath as S, getConsumersPath as T, parseJson as U, objectField as V, parseJsonObject as W, __exportAll as Y, computeContentHash as _, ensurePrivateDir as a, verbose as b, incrementalCopy as c, removeDir as d, getMutations as f, resetMutations as g, recordMutation as h, ensureDir as i, getStorePackagePath as j, getStoreHistoryPath as k, isNodeError as l, printDryRunReport as m, copyDir as n, exists as o, markDryRunJsonReportPrinted as p, stringRecordField as q, copyWithCoW as r, fs_exports as s, atomicWriteFile as t, moveDir as u, isDryRun as v, getConsumerStatePath as w, decodePackageName as x, isJsonOutput as y, asPackageJson as z };