knarr 0.1.3 → 0.2.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.
- package/README.md +1 -1
- package/dist/add-Clbi3vJ2.mjs +3 -0
- package/dist/add-flow-DdDziP5M.mjs +5 -0
- package/dist/batch-push-pVkjhRbp.mjs +3 -0
- package/dist/bell-BJuCym_5.mjs +11 -0
- package/dist/bell-CIzHg0kw.mjs +3 -0
- package/dist/bell-UNNirKkz.mjs +3 -0
- package/dist/build-detect-mSo9jKXK.mjs +3 -0
- package/dist/bundler-detect-Cx8_R2hT.mjs +3 -0
- package/dist/check-Boh8WU_W.mjs +3 -0
- package/dist/chokidar-BkIWf7Ix.mjs +3 -0
- package/dist/clean-DHh6fpmR.mjs +3 -0
- package/dist/cli.mjs +4 -4
- package/dist/config-CQpgsGyL.mjs +4 -0
- package/dist/console-BxhMcj-D.mjs +81 -0
- package/dist/console-X31Y_QS5.mjs +3 -0
- package/dist/dev-DeOwxr_7.mjs +3 -0
- package/dist/dist-CFkjiIqD.mjs +7 -0
- package/dist/doctor-XEdsr84Q.mjs +6 -0
- package/dist/dry-run-BxVjpNqJ.mjs +3 -0
- package/dist/errors-CV7G61Hr.mjs +3 -0
- package/dist/explain-BBv3U-D3.mjs +3 -0
- package/dist/format-DRqD29u-.mjs +3 -0
- package/dist/fs-BjaNhdzt.mjs +683 -0
- package/dist/fs-Cf1JTFyh.mjs +3 -0
- package/dist/fs-DUcoWJ1g.mjs +3 -0
- package/dist/hints-Hz3V4h3A.mjs +3 -0
- package/dist/history-BZS2YUIt.mjs +3 -0
- package/dist/history-C5ehozRy.mjs +3 -0
- package/dist/index.d.ts +242 -260
- package/dist/index.mjs +3349 -4669
- package/dist/init-Dwf-EIG3.mjs +4 -0
- package/dist/init-helpers-BfDosqvf.mjs +15 -0
- package/dist/injector-XwK_LBUh.mjs +3 -0
- package/dist/json-C6XtcMC4.mjs +46 -0
- package/dist/json-CWzEb9Rt.mjs +3 -0
- package/dist/list-DcREV9JM.mjs +3 -0
- package/dist/logger-DlikgOlh.mjs +3 -0
- package/dist/migrate-DW5KQeDq.mjs +5 -0
- package/dist/nextjs-config-BfHv8mBE.mjs +3 -0
- package/dist/nextjs-config-CA4N_9VY.mjs +4 -0
- package/dist/output-BxyRer_F.mjs +3 -0
- package/dist/package-manager-DBBQ0XtZ.mjs +13 -0
- package/dist/picomatch-B0_Pxgms.mjs +3 -0
- package/dist/preflight-B17VQJs0.mjs +3 -0
- package/dist/preflight-B8ypfoKV.mjs +3 -0
- package/dist/publish-BLk5_qx1.mjs +3 -0
- package/dist/publisher-Br4Od-iL.mjs +4 -0
- package/dist/push-C6UFcNGO.mjs +3 -0
- package/dist/push-engine-D3rfg2Tj.mjs +3 -0
- package/dist/remove-Bz9dNgDM.mjs +3 -0
- package/dist/remove-DMj6k2PK.mjs +3 -0
- package/dist/reset--AuvAPTc.mjs +3 -0
- package/dist/restore-CIBe2F1d.mjs +3 -0
- package/dist/rollback-CFLIncnW.mjs +3 -0
- package/dist/rolldown-runtime-BZbIAPMk.mjs +3 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/dist/shell-RQ7Hf1kp.mjs +3 -0
- package/dist/status-Dy-e_RtI.mjs +3 -0
- package/dist/store-BNeGfW_b.mjs +3 -0
- package/dist/tailwind-source-Cgva0Hte.mjs +5 -0
- package/dist/timer-DqgB175x.mjs +3 -0
- package/dist/topo-sort-DOCpHjT7.mjs +3 -0
- package/dist/topo-sort-yd4jxr_E.mjs +3 -0
- package/dist/tracker-DXSo5wXO.mjs +3 -0
- package/dist/tracker-DofCXLTP.mjs +3 -0
- package/dist/update-Dacjzw4f.mjs +3 -0
- package/dist/use-BSCV4IQ5.mjs +3 -0
- package/dist/vite-config-CbYEhn5K.mjs +3 -0
- package/dist/vite-config-DqxvL5TW.mjs +12 -0
- package/dist/vite-plugin.d.ts +6 -5
- package/dist/vite-plugin.mjs +206 -211
- package/dist/watch-orchestrator-CghvwrNS.mjs +3 -0
- package/dist/watcher-Bw_qcI0M.mjs +3 -0
- package/dist/webpack-plugin.d.ts +29 -30
- package/dist/webpack-plugin.mjs +140 -138
- package/dist/workspace-D4vhzpO4.mjs +3 -0
- package/dist/workspace-DVY5o1g8.mjs +3 -0
- package/dist/xxhash-wasm-D_QjdUuv.mjs +3 -0
- package/package.json +21 -30
- package/dist/add-LQ6WMCGD.mjs +0 -3
- package/dist/bell-SIN4ERLS.mjs +0 -2
- package/dist/check-7CJHAF6Y.mjs +0 -6
- package/dist/chokidar-2G63V464.mjs +0 -4
- package/dist/chunk-3SXN6MQL.mjs +0 -4
- package/dist/chunk-7GCKCCHU.mjs +0 -3
- package/dist/chunk-BH2WXCLS.mjs +0 -4
- package/dist/chunk-CBOYKBSM.mjs +0 -13
- package/dist/chunk-E3HZCU3S.mjs +0 -5
- package/dist/chunk-G7HFTV5Y.mjs +0 -3
- package/dist/chunk-HVN6HBWZ.mjs +0 -3
- package/dist/chunk-ICU4V73X.mjs +0 -3
- package/dist/chunk-IP5ROSRE.mjs +0 -3
- package/dist/chunk-J6HZHQVL.mjs +0 -3
- package/dist/chunk-K6OAYJKS.mjs +0 -6
- package/dist/chunk-KRX4JX6V.mjs +0 -4
- package/dist/chunk-KUQULMM6.mjs +0 -3
- package/dist/chunk-L7O2RSTN.mjs +0 -3
- package/dist/chunk-M3TRMEJV.mjs +0 -3
- package/dist/chunk-MN4DV2NO.mjs +0 -3
- package/dist/chunk-N3B2JO4H.mjs +0 -13
- package/dist/chunk-NGPAGRK4.mjs +0 -7
- package/dist/chunk-NV3ASN6X.mjs +0 -3
- package/dist/chunk-OQDZJP55.mjs +0 -3
- package/dist/chunk-QEH5VHRO.mjs +0 -13
- package/dist/chunk-QFHYSC3K.mjs +0 -3
- package/dist/chunk-QHNHLR6T.mjs +0 -3
- package/dist/chunk-RIHOZDFW.mjs +0 -22
- package/dist/chunk-SMR4HT6A.mjs +0 -3
- package/dist/chunk-SPHWZS5P.mjs +0 -3
- package/dist/chunk-U6O35NZ7.mjs +0 -3
- package/dist/chunk-W2MMKBWU.mjs +0 -3
- package/dist/chunk-WBTSRLB6.mjs +0 -7
- package/dist/chunk-WN3DOKIM.mjs +0 -3
- package/dist/chunk-XDWZZBCM.mjs +0 -3
- package/dist/chunk-Z5K6DFA6.mjs +0 -3
- package/dist/clean-EJIYYQZM.mjs +0 -3
- package/dist/dev-WU5KB5PJ.mjs +0 -3
- package/dist/doctor-W2G34POC.mjs +0 -6
- package/dist/explain-LZLNIMVZ.mjs +0 -5
- package/dist/fs-NU36NNEG.mjs +0 -2
- package/dist/history-MLJHRV3Q.mjs +0 -2
- package/dist/init-SNG5LBZK.mjs +0 -7
- package/dist/list-4PTHMIQ4.mjs +0 -5
- package/dist/migrate-USY26Y5R.mjs +0 -8
- package/dist/nextjs-config-T5D6LOJE.mjs +0 -2
- package/dist/preflight-IXICTR6G.mjs +0 -2
- package/dist/publish-2IH7IQV4.mjs +0 -3
- package/dist/push-W3TM2QYK.mjs +0 -3
- package/dist/remove-MVQOIN2I.mjs +0 -2
- package/dist/reset-BTOJ54MJ.mjs +0 -3
- package/dist/restore-TWOOF2BN.mjs +0 -3
- package/dist/rollback-CFYSE5YG.mjs +0 -3
- package/dist/status-3ZXM3CRH.mjs +0 -4
- package/dist/tailwind-source-HCTY2XDU.mjs +0 -5
- package/dist/topo-sort-ZNGR6D7M.mjs +0 -2
- package/dist/tracker-QAKEXYUJ.mjs +0 -2
- package/dist/update-TGGCUOOO.mjs +0 -3
- package/dist/use-4Z5KXRVR.mjs +0 -3
- package/dist/vite-config-XOGAKYGQ.mjs +0 -2
- package/dist/watch-orchestrator-6BQYU5YS.mjs +0 -3
- package/dist/watcher-ES2APFH4.mjs +0 -3
- package/dist/workspace-T6PNO4L3.mjs +0 -2
- package/dist/xxhash-wasm-I6Q3T2SL.mjs +0 -3
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
+
import { t as consola } from "./console-BxhMcj-D.mjs";
|
|
3
|
+
import { constants, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { availableParallelism, homedir } from "node:os";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
// src/utils/concurrency.ts
|
|
8
|
+
/**
|
|
9
|
+
* Minimal p-limit replacement using a promise queue.
|
|
10
|
+
* Drop-in compatible: `const limit = pLimit(N); await limit(fn)`
|
|
11
|
+
*
|
|
12
|
+
* Uses a head pointer for O(1) dequeue instead of Array.shift() which is O(n).
|
|
13
|
+
* Compacts the queue array when it drains to prevent unbounded memory growth.
|
|
14
|
+
*/
|
|
15
|
+
function pLimit(concurrency) {
|
|
16
|
+
let active = 0;
|
|
17
|
+
const queue = [];
|
|
18
|
+
let head = 0;
|
|
19
|
+
const next = () => {
|
|
20
|
+
const task = active < concurrency ? queue[head] : void 0;
|
|
21
|
+
if (task) {
|
|
22
|
+
head++;
|
|
23
|
+
active++;
|
|
24
|
+
task();
|
|
25
|
+
}
|
|
26
|
+
if (head > 0 && head === queue.length) {
|
|
27
|
+
queue.length = 0;
|
|
28
|
+
head = 0;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
return (fn) => new Promise((resolve, reject) => {
|
|
32
|
+
const run = () => {
|
|
33
|
+
fn().then((val) => {
|
|
34
|
+
active--;
|
|
35
|
+
resolve(val);
|
|
36
|
+
next();
|
|
37
|
+
}, (err) => {
|
|
38
|
+
active--;
|
|
39
|
+
reject(err);
|
|
40
|
+
next();
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
if (active < concurrency) {
|
|
44
|
+
active++;
|
|
45
|
+
run();
|
|
46
|
+
} else queue.push(run);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
// src/utils/validators.ts
|
|
50
|
+
const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
|
|
51
|
+
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-]+)*)?$/;
|
|
52
|
+
const CONTROL_CHARS_RE = /[\x00-\x1F\x7F]/;
|
|
53
|
+
/**
|
|
54
|
+
* Validate an npm package name before using it in store/node_modules paths.
|
|
55
|
+
* This intentionally mirrors npm's modern lowercase package-name shape and
|
|
56
|
+
* rejects path separators/traversal segments before any filesystem mutation.
|
|
57
|
+
*/
|
|
58
|
+
function validatePackageName(name) {
|
|
59
|
+
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}"`);
|
|
60
|
+
}
|
|
61
|
+
/** Validate a package.json version string before it becomes part of a path. */
|
|
62
|
+
function validatePackageVersion(version) {
|
|
63
|
+
if (!version || CONTROL_CHARS_RE.test(version) || version.includes("/") || version.includes("\\") || version.includes("..") || !SEMVER_RE.test(version)) throw new Error(`Invalid package version "${version}"`);
|
|
64
|
+
}
|
|
65
|
+
function validatePackageIdentity(name, version) {
|
|
66
|
+
validatePackageName(name);
|
|
67
|
+
validatePackageVersion(version);
|
|
68
|
+
}
|
|
69
|
+
/** Check if a value is valid Knarr metadata. */
|
|
70
|
+
function isKnarrMeta(value) {
|
|
71
|
+
if (typeof value !== "object" || value === null) return false;
|
|
72
|
+
const v = value;
|
|
73
|
+
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");
|
|
74
|
+
}
|
|
75
|
+
/** Check if a value is a valid LinkEntry */
|
|
76
|
+
function isLinkEntry(value) {
|
|
77
|
+
if (typeof value !== "object" || value === null) return false;
|
|
78
|
+
const v = value;
|
|
79
|
+
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" && [
|
|
80
|
+
"npm",
|
|
81
|
+
"pnpm",
|
|
82
|
+
"yarn",
|
|
83
|
+
"bun"
|
|
84
|
+
].includes(v.packageManager) && (v.buildId === void 0 || typeof v.buildId === "string");
|
|
85
|
+
}
|
|
86
|
+
/** Check if a value is a valid ConsumerState */
|
|
87
|
+
function isConsumerState(value) {
|
|
88
|
+
if (typeof value !== "object" || value === null) return false;
|
|
89
|
+
const v = value;
|
|
90
|
+
if (v.version !== "1") return false;
|
|
91
|
+
if (typeof v.links !== "object" || v.links === null) return false;
|
|
92
|
+
const links = v.links;
|
|
93
|
+
for (const entry of Object.values(links)) if (!isLinkEntry(entry)) return false;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
/** Check if a value is a valid ConsumersRegistry */
|
|
97
|
+
function isConsumersRegistry(value) {
|
|
98
|
+
if (typeof value !== "object" || value === null) return false;
|
|
99
|
+
const v = value;
|
|
100
|
+
for (const val of Object.values(v)) {
|
|
101
|
+
if (!Array.isArray(val)) return false;
|
|
102
|
+
for (const item of val) if (typeof item !== "string") return false;
|
|
103
|
+
}
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
// src/utils/paths.ts
|
|
107
|
+
function assertInside(root, target, label) {
|
|
108
|
+
const resolvedRoot = resolve(root);
|
|
109
|
+
const resolvedTarget = resolve(target);
|
|
110
|
+
const rel = relative(resolvedRoot, resolvedTarget);
|
|
111
|
+
if (rel === "" || !rel.startsWith("..") && !isAbsolute(rel)) return;
|
|
112
|
+
throw new Error(`${label} escapes expected directory: ${target}`);
|
|
113
|
+
}
|
|
114
|
+
/** Root knarr directory: ~/.knarr/ (override with KNARR_HOME env var). */
|
|
115
|
+
function getKnarrHome() {
|
|
116
|
+
return process.env.KNARR_HOME || join(homedir(), ".knarr");
|
|
117
|
+
}
|
|
118
|
+
/** Store root: ~/.knarr/store/ */
|
|
119
|
+
function getStorePath() {
|
|
120
|
+
return join(getKnarrHome(), "store");
|
|
121
|
+
}
|
|
122
|
+
/** Consumers registry: ~/.knarr/consumers.json */
|
|
123
|
+
function getConsumersPath() {
|
|
124
|
+
return join(getKnarrHome(), "consumers.json");
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Encode a package name for use as a directory name.
|
|
128
|
+
* Scoped packages: `@scope/name` -> `@scope+name`
|
|
129
|
+
*/
|
|
130
|
+
function encodePackageName(name) {
|
|
131
|
+
validatePackageName(name);
|
|
132
|
+
return name.replace(/\//g, "+");
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Decode a directory name back to a package name.
|
|
136
|
+
* `@scope+name` -> `@scope/name`
|
|
137
|
+
*/
|
|
138
|
+
function decodePackageName(encoded) {
|
|
139
|
+
if (encoded.startsWith("@")) {
|
|
140
|
+
const plusIdx = encoded.indexOf("+");
|
|
141
|
+
if (plusIdx !== -1) return encoded.slice(0, plusIdx) + "/" + encoded.slice(plusIdx + 1);
|
|
142
|
+
}
|
|
143
|
+
return encoded;
|
|
144
|
+
}
|
|
145
|
+
/** Get the store directory for a specific package@version */
|
|
146
|
+
function getStoreEntryPath(name, version) {
|
|
147
|
+
validatePackageIdentity(name, version);
|
|
148
|
+
const root = getStorePath();
|
|
149
|
+
const target = join(root, `${encodePackageName(name)}@${version}`);
|
|
150
|
+
assertInside(root, target, "Store entry path");
|
|
151
|
+
return target;
|
|
152
|
+
}
|
|
153
|
+
/** Get the package directory within a store entry */
|
|
154
|
+
function getStorePackagePath(name, version) {
|
|
155
|
+
return join(getStoreEntryPath(name, version), "package");
|
|
156
|
+
}
|
|
157
|
+
/** Get the .knarr-meta.json path for a store entry */
|
|
158
|
+
function getStoreMetaPath(name, version) {
|
|
159
|
+
return join(getStoreEntryPath(name, version), ".knarr-meta.json");
|
|
160
|
+
}
|
|
161
|
+
/** Get the history directory for a store entry */
|
|
162
|
+
function getStoreHistoryPath(name, version) {
|
|
163
|
+
return join(getStoreEntryPath(name, version), "history");
|
|
164
|
+
}
|
|
165
|
+
/** Get a specific history entry directory */
|
|
166
|
+
function getHistoryEntryPath(name, version, buildId) {
|
|
167
|
+
if (!/^[a-f0-9]{8,64}$/i.test(buildId)) throw new Error(`Invalid build id "${buildId}"`);
|
|
168
|
+
return join(getStoreHistoryPath(name, version), buildId);
|
|
169
|
+
}
|
|
170
|
+
/** Get the .knarr/ directory in a consumer project */
|
|
171
|
+
function getConsumerKnarrDir(consumerPath) {
|
|
172
|
+
return join(consumerPath, ".knarr");
|
|
173
|
+
}
|
|
174
|
+
/** Get the state file in a consumer project */
|
|
175
|
+
function getConsumerStatePath(consumerPath) {
|
|
176
|
+
return join(consumerPath, ".knarr", "state.json");
|
|
177
|
+
}
|
|
178
|
+
/** Get the backups directory in a consumer project */
|
|
179
|
+
function getConsumerBackupPath(consumerPath, packageName) {
|
|
180
|
+
validatePackageName(packageName);
|
|
181
|
+
const root = join(consumerPath, ".knarr", "backups");
|
|
182
|
+
const target = join(root, encodePackageName(packageName));
|
|
183
|
+
assertInside(root, target, "Backup path");
|
|
184
|
+
return target;
|
|
185
|
+
}
|
|
186
|
+
/** Normalize a file path to use forward slashes (for cross-platform consistency). */
|
|
187
|
+
function normalizePath(p) {
|
|
188
|
+
return p.replace(/\\/g, "/");
|
|
189
|
+
}
|
|
190
|
+
/** Get node_modules/<pkg> path for a package in a consumer */
|
|
191
|
+
function getNodeModulesPackagePath(consumerPath, packageName) {
|
|
192
|
+
validatePackageName(packageName);
|
|
193
|
+
const root = join(consumerPath, "node_modules");
|
|
194
|
+
const target = join(root, packageName);
|
|
195
|
+
assertInside(root, target, "node_modules package path");
|
|
196
|
+
return target;
|
|
197
|
+
}
|
|
198
|
+
let _dryRun = false;
|
|
199
|
+
let _jsonOutput = false;
|
|
200
|
+
function isDryRun() {
|
|
201
|
+
return _dryRun;
|
|
202
|
+
}
|
|
203
|
+
function isJsonOutput() {
|
|
204
|
+
return _jsonOutput;
|
|
205
|
+
}
|
|
206
|
+
/** Log a debug message only when --verbose is active */
|
|
207
|
+
function verbose(msg, ...args) {}
|
|
208
|
+
// src/utils/hash.ts
|
|
209
|
+
/** Lazy-initialized xxhash-wasm singleton (follows dynamic import pattern used elsewhere) */
|
|
210
|
+
let _xxhash = null;
|
|
211
|
+
function getXXHash() {
|
|
212
|
+
if (!_xxhash) _xxhash = import("xxhash-wasm").then((mod) => mod.default()).catch((err) => {
|
|
213
|
+
_xxhash = null;
|
|
214
|
+
throw err;
|
|
215
|
+
});
|
|
216
|
+
return _xxhash;
|
|
217
|
+
}
|
|
218
|
+
/** Files larger than this threshold use streaming hash */
|
|
219
|
+
const STREAM_THRESHOLD = 1048576;
|
|
220
|
+
/** Concurrency limit for parallel file reads in computeContentHash */
|
|
221
|
+
const limit = pLimit(Math.max(availableParallelism(), 8));
|
|
222
|
+
const _contentCache = /* @__PURE__ */ new Map();
|
|
223
|
+
/**
|
|
224
|
+
* Compute a SHA-256 content hash for a list of files.
|
|
225
|
+
* The hash is deterministic: sorted by relative path, each entry is `path\0content`.
|
|
226
|
+
* Reads files in parallel (up to CPU count concurrent) then feeds into hash in sorted order.
|
|
227
|
+
*
|
|
228
|
+
* In watch mode, unchanged files are served from an in-memory cache (validated
|
|
229
|
+
* by mtime + size) so only modified files trigger actual disk reads.
|
|
230
|
+
*/
|
|
231
|
+
async function computeContentHash(files, baseDir, contentOverrides = /* @__PURE__ */ new Map()) {
|
|
232
|
+
const fileByRel = new Map(files.map((file) => [normalizePath(relative(baseDir, file)), file]));
|
|
233
|
+
for (const rel of contentOverrides.keys()) if (!fileByRel.has(rel)) fileByRel.set(rel, join(baseDir, rel));
|
|
234
|
+
const sorted = [...fileByRel.entries()].sort(([relA], [relB]) => relA.localeCompare(relB));
|
|
235
|
+
const currentFiles = new Set(fileByRel.values());
|
|
236
|
+
let cacheHits = 0;
|
|
237
|
+
const contents = await Promise.all(sorted.map(([rel, file]) => limit(async () => {
|
|
238
|
+
const override = contentOverrides.get(rel);
|
|
239
|
+
if (override !== void 0) return {
|
|
240
|
+
rel,
|
|
241
|
+
content: Buffer.isBuffer(override) ? override : Buffer.from(override)
|
|
242
|
+
};
|
|
243
|
+
const s = await stat(file);
|
|
244
|
+
const cached = _contentCache.get(file);
|
|
245
|
+
if (cached && cached.mtimeMs === s.mtimeMs && cached.size === s.size) {
|
|
246
|
+
cacheHits++;
|
|
247
|
+
return {
|
|
248
|
+
rel,
|
|
249
|
+
content: cached.content
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const content = await readFile(file);
|
|
253
|
+
_contentCache.set(file, {
|
|
254
|
+
mtimeMs: s.mtimeMs,
|
|
255
|
+
size: s.size,
|
|
256
|
+
content
|
|
257
|
+
});
|
|
258
|
+
return {
|
|
259
|
+
rel,
|
|
260
|
+
content
|
|
261
|
+
};
|
|
262
|
+
})));
|
|
263
|
+
for (const key of _contentCache.keys()) if (!currentFiles.has(key)) _contentCache.delete(key);
|
|
264
|
+
`${sorted.length}${cacheHits}`;
|
|
265
|
+
const hash = createHash("sha256");
|
|
266
|
+
const lenBuf = Buffer.alloc(4);
|
|
267
|
+
for (const { rel, content } of contents) {
|
|
268
|
+
hash.update(rel);
|
|
269
|
+
hash.update("\0");
|
|
270
|
+
lenBuf.writeUInt32LE(content.length);
|
|
271
|
+
hash.update(lenBuf);
|
|
272
|
+
hash.update(content);
|
|
273
|
+
}
|
|
274
|
+
const result = "sha256v2:" + hash.digest("hex");
|
|
275
|
+
`${result.slice(0, 20)}`;
|
|
276
|
+
return result;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Compute xxHash64 of a single file's content.
|
|
280
|
+
* Used for per-file change detection during incremental copy — not persisted,
|
|
281
|
+
* so no need for cryptographic strength. xxHash64 is ~5-10x faster than SHA-256.
|
|
282
|
+
* - Files ≤1MB: buffered read + h64Raw
|
|
283
|
+
* - Files >1MB: streaming via create64() hasher
|
|
284
|
+
*/
|
|
285
|
+
async function hashFile(filePath, knownSize) {
|
|
286
|
+
const size = knownSize ?? (await stat(filePath)).size;
|
|
287
|
+
const xx = await getXXHash();
|
|
288
|
+
if (size > STREAM_THRESHOLD) return hashFileStream(filePath, xx);
|
|
289
|
+
const content = await readFile(filePath);
|
|
290
|
+
return xx.h64Raw(content).toString(16);
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Compute xxHash64 using streaming for large files.
|
|
294
|
+
* Reads the file in 64KB chunks to avoid loading multi-MB files into memory.
|
|
295
|
+
*/
|
|
296
|
+
async function hashFileStream(filePath, xx) {
|
|
297
|
+
const { createReadStream } = await import("node:fs");
|
|
298
|
+
const hasher = xx.create64();
|
|
299
|
+
return new Promise((resolve, reject) => {
|
|
300
|
+
const stream = createReadStream(filePath);
|
|
301
|
+
stream.on("data", (chunk) => hasher.update(chunk));
|
|
302
|
+
stream.on("end", () => resolve(hasher.digest().toString(16)));
|
|
303
|
+
stream.on("error", reject);
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
// src/utils/dry-run.ts
|
|
307
|
+
/**
|
|
308
|
+
* Shorten a path for the human report: relative to cwd when inside it,
|
|
309
|
+
* `~` for the home directory (where the store usually lives). JSON keeps absolute paths.
|
|
310
|
+
*/
|
|
311
|
+
function displayMutationPath(p, cwd = process.cwd(), home = homedir()) {
|
|
312
|
+
const inside = (base) => {
|
|
313
|
+
const rel = relative(base, p);
|
|
314
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel : rel === "" ? "." : null;
|
|
315
|
+
};
|
|
316
|
+
const fromCwd = inside(cwd);
|
|
317
|
+
if (fromCwd !== null) return fromCwd;
|
|
318
|
+
const fromHome = inside(home);
|
|
319
|
+
if (fromHome !== null) return fromHome === "." ? "~" : `~${sep}${fromHome}`;
|
|
320
|
+
return p;
|
|
321
|
+
}
|
|
322
|
+
const mutations = [];
|
|
323
|
+
let jsonReportPrinted = false;
|
|
324
|
+
/** Record a mutation that was skipped due to --dry-run */
|
|
325
|
+
function recordMutation(mutation) {
|
|
326
|
+
mutations.push(mutation);
|
|
327
|
+
}
|
|
328
|
+
function getMutations() {
|
|
329
|
+
return [...mutations];
|
|
330
|
+
}
|
|
331
|
+
function markDryRunJsonReportPrinted() {
|
|
332
|
+
jsonReportPrinted = true;
|
|
333
|
+
}
|
|
334
|
+
/** Print a summary of all recorded dry-run mutations */
|
|
335
|
+
function printDryRunReport() {
|
|
336
|
+
if (mutations.length === 0) {
|
|
337
|
+
consola.info("[dry-run] No mutations would be performed");
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (isJsonOutput()) {
|
|
341
|
+
if (jsonReportPrinted) return;
|
|
342
|
+
console.log(JSON.stringify({
|
|
343
|
+
dryRun: true,
|
|
344
|
+
mutations
|
|
345
|
+
}, null, 2));
|
|
346
|
+
jsonReportPrinted = true;
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
350
|
+
for (const m of mutations) {
|
|
351
|
+
let list = grouped.get(m.type);
|
|
352
|
+
if (!list) {
|
|
353
|
+
list = [];
|
|
354
|
+
grouped.set(m.type, list);
|
|
355
|
+
}
|
|
356
|
+
list.push(m);
|
|
357
|
+
}
|
|
358
|
+
consola.info(`\n[dry-run] ${mutations.length} mutation(s) would be performed:\n`);
|
|
359
|
+
const labels = {
|
|
360
|
+
copy: "Copy",
|
|
361
|
+
remove: "Remove",
|
|
362
|
+
move: "Move",
|
|
363
|
+
mkdir: "Create directory",
|
|
364
|
+
write: "Write file",
|
|
365
|
+
"bin-link": "Create bin link",
|
|
366
|
+
"bin-unlink": "Remove bin link",
|
|
367
|
+
"cache-invalidate": "Invalidate cache",
|
|
368
|
+
"lock-skip": "Skip lock",
|
|
369
|
+
"lifecycle-skip": "Skip lifecycle hook",
|
|
370
|
+
"command-skip": "Skip command"
|
|
371
|
+
};
|
|
372
|
+
for (const [type, items] of grouped) {
|
|
373
|
+
consola.info(` ${labels[type]} (${items.length}):`);
|
|
374
|
+
for (const item of items.slice(0, 20)) {
|
|
375
|
+
const dest = item.dest ? ` → ${displayMutationPath(item.dest)}` : "";
|
|
376
|
+
const detail = item.detail ? ` (${item.detail})` : "";
|
|
377
|
+
consola.info(` ${displayMutationPath(item.path)}${dest}${detail}`);
|
|
378
|
+
}
|
|
379
|
+
if (items.length > 20) consola.info(` ... and ${items.length - 20} more`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/** Reset recorded mutations (for testing) */
|
|
383
|
+
function resetMutations() {
|
|
384
|
+
mutations.length = 0;
|
|
385
|
+
jsonReportPrinted = false;
|
|
386
|
+
}
|
|
387
|
+
// src/utils/fs.ts
|
|
388
|
+
var fs_exports = /* @__PURE__ */ __exportAll({ exists: () => exists });
|
|
389
|
+
/** Concurrency limit for parallel file I/O, auto-tuned to available CPUs */
|
|
390
|
+
const ioLimit = pLimit(Math.max(availableParallelism(), 8));
|
|
391
|
+
/** Type guard for Node.js system errors with an error code */
|
|
392
|
+
function isNodeError(err) {
|
|
393
|
+
return err instanceof Error && "code" in err;
|
|
394
|
+
}
|
|
395
|
+
const reflinkSupported = /* @__PURE__ */ new Map();
|
|
396
|
+
function volumeRoot(filePath) {
|
|
397
|
+
const { root } = parse(filePath);
|
|
398
|
+
return root || "/";
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Copy a file using CoW (reflink) when available, with per-volume caching.
|
|
402
|
+
*
|
|
403
|
+
* On the first copy per volume, tries COPYFILE_FICLONE_FORCE to probe
|
|
404
|
+
* for reflink support. If it fails, caches the result and all subsequent
|
|
405
|
+
* copies on that volume go straight to a plain copy — no wasted syscalls.
|
|
406
|
+
*
|
|
407
|
+
* Note: hardlinks are intentionally NOT used as a fallback because Knarr's
|
|
408
|
+
* incremental copy model compares source vs destination content. Hardlinks
|
|
409
|
+
* share an inode, so source mutations silently propagate to the destination,
|
|
410
|
+
* breaking change detection.
|
|
411
|
+
*/
|
|
412
|
+
async function copyWithCoW(src, dest, options) {
|
|
413
|
+
if (isDryRun()) {
|
|
414
|
+
`${src}${dest}`;
|
|
415
|
+
recordMutation({
|
|
416
|
+
type: "copy",
|
|
417
|
+
path: src,
|
|
418
|
+
dest
|
|
419
|
+
});
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
if (options?.ensureParent !== false) await mkdir(dirname(dest), { recursive: true });
|
|
423
|
+
const root = volumeRoot(dest);
|
|
424
|
+
const supportsReflink = reflinkSupported.get(root);
|
|
425
|
+
if (supportsReflink === false) {
|
|
426
|
+
await copyFile(src, dest);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (supportsReflink === true) {
|
|
430
|
+
await copyFile(src, dest, constants.COPYFILE_FICLONE);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
try {
|
|
434
|
+
await copyFile(src, dest, constants.COPYFILE_FICLONE_FORCE);
|
|
435
|
+
reflinkSupported.set(root, true);
|
|
436
|
+
} catch {
|
|
437
|
+
reflinkSupported.set(root, false);
|
|
438
|
+
`${root}`;
|
|
439
|
+
await copyFile(src, dest);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Recursively collect all file paths in a directory.
|
|
444
|
+
* Uses Node 22+ recursive readdir with withFileTypes to avoid separate stat calls.
|
|
445
|
+
*/
|
|
446
|
+
async function collectFiles(dir) {
|
|
447
|
+
return (await readdir(dir, {
|
|
448
|
+
recursive: true,
|
|
449
|
+
withFileTypes: true
|
|
450
|
+
})).filter((e) => e.isFile()).map((e) => join(e.parentPath, e.name));
|
|
451
|
+
}
|
|
452
|
+
async function removeDestinationConflicts(destDir, relPath) {
|
|
453
|
+
const parts = relPath.split(/[\\/]/).filter(Boolean);
|
|
454
|
+
let current = destDir;
|
|
455
|
+
for (const [i, part] of parts.entries()) {
|
|
456
|
+
current = join(current, part);
|
|
457
|
+
try {
|
|
458
|
+
const s = await stat(current);
|
|
459
|
+
const isLeaf = i === parts.length - 1;
|
|
460
|
+
if (s.isDirectory()) {
|
|
461
|
+
if (isLeaf) {
|
|
462
|
+
if (isDryRun()) recordMutation({
|
|
463
|
+
type: "remove",
|
|
464
|
+
path: current
|
|
465
|
+
});
|
|
466
|
+
else await rm(current, {
|
|
467
|
+
recursive: true,
|
|
468
|
+
force: true
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
if (!isLeaf) {
|
|
474
|
+
if (isDryRun()) {
|
|
475
|
+
recordMutation({
|
|
476
|
+
type: "remove",
|
|
477
|
+
path: current
|
|
478
|
+
});
|
|
479
|
+
return;
|
|
480
|
+
} else await rm(current, { force: true });
|
|
481
|
+
}
|
|
482
|
+
} catch (err) {
|
|
483
|
+
if (isNodeError(err) && err.code === "ENOENT") return;
|
|
484
|
+
throw err;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Incrementally copy files from src to dest directory.
|
|
490
|
+
* Only copies files whose content has changed (stat size check + hash comparison).
|
|
491
|
+
* Also removes files in dest that don't exist in src.
|
|
492
|
+
* Returns the number of files actually copied.
|
|
493
|
+
*/
|
|
494
|
+
async function incrementalCopy(srcDir, destDir, options = {}) {
|
|
495
|
+
const srcFilesPromise = collectFiles(srcDir);
|
|
496
|
+
const destFilesPromise = collectFiles(destDir).catch((err) => {
|
|
497
|
+
if (isNodeError(err) && err.code === "ENOENT") return [];
|
|
498
|
+
throw err;
|
|
499
|
+
});
|
|
500
|
+
const [srcFiles, destFiles] = await Promise.all([srcFilesPromise, destFilesPromise]);
|
|
501
|
+
let copied = 0;
|
|
502
|
+
let skipped = 0;
|
|
503
|
+
const results = await Promise.all(srcFiles.map((srcFile) => ioLimit(async () => {
|
|
504
|
+
const rel = relative(srcDir, srcFile);
|
|
505
|
+
const destFile = join(destDir, rel);
|
|
506
|
+
let needsCopy = true;
|
|
507
|
+
let srcTimes = null;
|
|
508
|
+
if (options.force) `${rel}`;
|
|
509
|
+
else try {
|
|
510
|
+
const [srcStat, destStat] = await Promise.all([stat(srcFile), stat(destFile)]);
|
|
511
|
+
srcTimes = {
|
|
512
|
+
atime: srcStat.atime,
|
|
513
|
+
mtime: srcStat.mtime
|
|
514
|
+
};
|
|
515
|
+
if (srcStat.size !== destStat.size) `${rel}${srcStat.size}${destStat.size}`;
|
|
516
|
+
else if (srcStat.mtimeMs === destStat.mtimeMs) {
|
|
517
|
+
needsCopy = false;
|
|
518
|
+
`${rel}`;
|
|
519
|
+
} else {
|
|
520
|
+
const [srcHash, destHash] = await Promise.all([hashFile(srcFile, srcStat.size), hashFile(destFile, destStat.size)]);
|
|
521
|
+
if (srcHash === destHash) {
|
|
522
|
+
needsCopy = false;
|
|
523
|
+
`${rel}`;
|
|
524
|
+
} else `${rel}`;
|
|
525
|
+
}
|
|
526
|
+
} catch (err) {
|
|
527
|
+
if (isNodeError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR")) `${rel}`;
|
|
528
|
+
else throw err;
|
|
529
|
+
}
|
|
530
|
+
if (needsCopy) {
|
|
531
|
+
await removeDestinationConflicts(destDir, rel);
|
|
532
|
+
await copyWithCoW(srcFile, destFile);
|
|
533
|
+
if (isDryRun()) return "copied";
|
|
534
|
+
if (!srcTimes) {
|
|
535
|
+
const s = await stat(srcFile);
|
|
536
|
+
srcTimes = {
|
|
537
|
+
atime: s.atime,
|
|
538
|
+
mtime: s.mtime
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
await utimes(destFile, srcTimes.atime, srcTimes.mtime);
|
|
542
|
+
return "copied";
|
|
543
|
+
}
|
|
544
|
+
return "skipped";
|
|
545
|
+
})));
|
|
546
|
+
for (const r of results) if (r === "copied") copied++;
|
|
547
|
+
else skipped++;
|
|
548
|
+
const srcRelPaths = new Set(srcFiles.map((f) => relative(srcDir, f)));
|
|
549
|
+
const filesToRemove = destFiles.filter((f) => !srcRelPaths.has(relative(destDir, f)));
|
|
550
|
+
await Promise.all(filesToRemove.map((destFile) => ioLimit(async () => {
|
|
551
|
+
`${relative(destDir, destFile)}`;
|
|
552
|
+
if (isDryRun()) recordMutation({
|
|
553
|
+
type: "remove",
|
|
554
|
+
path: destFile
|
|
555
|
+
});
|
|
556
|
+
else await rm(destFile, { force: true }).catch((err) => {
|
|
557
|
+
if (isNodeError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR" || err.code === "EISDIR" || err.code === "ERR_FS_EISDIR")) return;
|
|
558
|
+
throw err;
|
|
559
|
+
});
|
|
560
|
+
})));
|
|
561
|
+
const removed = filesToRemove.length;
|
|
562
|
+
return {
|
|
563
|
+
copied,
|
|
564
|
+
removed,
|
|
565
|
+
skipped
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Move a directory, handling cross-filesystem (EXDEV) scenarios.
|
|
570
|
+
* Tries rename first (fast, atomic on same FS), falls back to cp+rm.
|
|
571
|
+
*/
|
|
572
|
+
async function moveDir(src, dest) {
|
|
573
|
+
if (isDryRun()) {
|
|
574
|
+
`${src}${dest}`;
|
|
575
|
+
recordMutation({
|
|
576
|
+
type: "move",
|
|
577
|
+
path: src,
|
|
578
|
+
dest
|
|
579
|
+
});
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
try {
|
|
583
|
+
await rename(src, dest);
|
|
584
|
+
} catch (err) {
|
|
585
|
+
if (isNodeError(err) && err.code === "EXDEV") {
|
|
586
|
+
await cp(src, dest, { recursive: true });
|
|
587
|
+
await rm(src, {
|
|
588
|
+
recursive: true,
|
|
589
|
+
force: true
|
|
590
|
+
});
|
|
591
|
+
} else throw err;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/** Remove a directory recursively, no error if it doesn't exist */
|
|
595
|
+
async function removeDir(dir) {
|
|
596
|
+
if (isDryRun()) {
|
|
597
|
+
`${dir}`;
|
|
598
|
+
recordMutation({
|
|
599
|
+
type: "remove",
|
|
600
|
+
path: dir
|
|
601
|
+
});
|
|
602
|
+
return;
|
|
603
|
+
}
|
|
604
|
+
await rm(dir, {
|
|
605
|
+
recursive: true,
|
|
606
|
+
force: true
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
/** Ensure a directory exists */
|
|
610
|
+
async function ensureDir(dir) {
|
|
611
|
+
if (isDryRun()) {
|
|
612
|
+
`${dir}`;
|
|
613
|
+
recordMutation({
|
|
614
|
+
type: "mkdir",
|
|
615
|
+
path: dir
|
|
616
|
+
});
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
await mkdir(dir, { recursive: true });
|
|
620
|
+
}
|
|
621
|
+
/** Ensure a directory exists with private permissions (0o700). */
|
|
622
|
+
async function ensurePrivateDir(dir) {
|
|
623
|
+
if (isDryRun()) {
|
|
624
|
+
`${dir}`;
|
|
625
|
+
recordMutation({
|
|
626
|
+
type: "mkdir",
|
|
627
|
+
path: dir
|
|
628
|
+
});
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
await mkdir(dir, {
|
|
632
|
+
recursive: true,
|
|
633
|
+
mode: 448
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
/** Check if a path exists */
|
|
637
|
+
async function exists(path) {
|
|
638
|
+
try {
|
|
639
|
+
await stat(path);
|
|
640
|
+
return true;
|
|
641
|
+
} catch {
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Write a file atomically by writing to a temp file then renaming.
|
|
647
|
+
* Prevents corruption if the process crashes mid-write.
|
|
648
|
+
*/
|
|
649
|
+
async function atomicWriteFile(filePath, data) {
|
|
650
|
+
if (isDryRun()) {
|
|
651
|
+
`${filePath}`;
|
|
652
|
+
recordMutation({
|
|
653
|
+
type: "write",
|
|
654
|
+
path: filePath
|
|
655
|
+
});
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const tmpPath = filePath + `.tmp-${process.pid}-${Date.now()}`;
|
|
659
|
+
await writeFile(tmpPath, data);
|
|
660
|
+
await rename(tmpPath, filePath);
|
|
661
|
+
}
|
|
662
|
+
/** Copy an entire directory recursively using native fs.cp */
|
|
663
|
+
async function copyDir(src, dest) {
|
|
664
|
+
if (isDryRun()) {
|
|
665
|
+
`${src}${dest}`;
|
|
666
|
+
recordMutation({
|
|
667
|
+
type: "copy",
|
|
668
|
+
path: src,
|
|
669
|
+
dest
|
|
670
|
+
});
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
try {
|
|
674
|
+
await cp(src, dest, { recursive: true });
|
|
675
|
+
} catch (err) {
|
|
676
|
+
if (process.platform !== "win32" || !isNodeError(err) || err.code !== "EPERM" || err.syscall !== "symlink" || !(await lstat(src)).isSymbolicLink()) throw err;
|
|
677
|
+
const target = await realpath(src);
|
|
678
|
+
if (!(await stat(target)).isDirectory()) throw err;
|
|
679
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
680
|
+
await symlink(target, dest, "junction");
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
export { getStoreHistoryPath as A, pLimit as B, getConsumerBackupPath as C, getHistoryEntryPath as D, getConsumersPath as E, isConsumerState as F, isConsumersRegistry as I, isKnarrMeta as L, getStorePackagePath as M, getStorePath as N, getNodeModulesPackagePath as O, normalizePath as P, validatePackageIdentity as R, encodePackageName as S, getConsumerStatePath as T, 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, getStoreMetaPath as j, getStoreEntryPath as k, isNodeError as l, printDryRunReport as m, copyDir as n, exists as o, markDryRunJsonReportPrinted as p, copyWithCoW as r, fs_exports as s, atomicWriteFile as t, moveDir as u, isDryRun as v, getConsumerKnarrDir as w, decodePackageName as x, isJsonOutput as y, validatePackageName as z };
|