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.
- package/README.md +1 -1
- package/dist/add-CyrFHzUe.mjs +1 -0
- package/dist/add-flow-BjjRSNWm.mjs +3 -0
- package/dist/batch-push-Cee2SPW3.mjs +1 -0
- package/dist/build-detect-Bo1fe8OV.mjs +1 -0
- package/dist/bundler-detect-BaShXORS.mjs +1 -0
- package/dist/check-ChNlHxR5.mjs +1 -0
- package/dist/chokidar-DoHpObCq.mjs +1 -0
- package/dist/clean-oNr4nUNk.mjs +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +2 -3
- package/dist/config-D0TqqAAJ.mjs +2 -0
- package/dist/console-C8XtlRyM.mjs +1 -0
- package/dist/dev-vA8K5egW.mjs +1 -0
- package/dist/dist-jMqCJR3W.mjs +5 -0
- package/dist/doctor-ITFcIVoj.mjs +4 -0
- package/dist/dry-run-DPoN8bZo.mjs +1 -0
- package/dist/errors-DRugrv36.mjs +1 -0
- package/dist/explain-xtY13-Ex.mjs +1 -0
- package/dist/format-IsfSiyGV.mjs +1 -0
- package/dist/fs-Ce7wcxvx.mjs +1 -0
- package/dist/fs-DusqxRQR.mjs +1 -0
- package/dist/hints-BKo_2axg.mjs +1 -0
- package/dist/history-540r0BHF.mjs +1 -0
- package/dist/history-B3E1DMFO.mjs +1 -0
- package/dist/index.mjs +1 -3637
- package/dist/init-KBwXbX7j.mjs +2 -0
- package/dist/init-helpers-DGSTVbNx.mjs +13 -0
- package/dist/injector-BMOi1uN3.mjs +1 -0
- package/dist/json-1jsvqdBb.mjs +1 -0
- package/dist/list-BkniWIlD.mjs +1 -0
- package/dist/logger-Oo2Slehd.mjs +1 -0
- package/dist/migrate-DM80YXOF.mjs +3 -0
- package/dist/nextjs-config-BlbmHmCb.mjs +1 -0
- package/dist/nextjs-config-m83qz9Qp.mjs +2 -0
- package/dist/output-B7NC4xgj.mjs +1 -0
- package/dist/package-manager-Cs9kCsjJ.mjs +11 -0
- package/dist/paths-B5sEvS_7.mjs +1 -0
- package/dist/picomatch-DEttMFSR.mjs +1 -0
- package/dist/preflight-C_Zr3uyO.mjs +1 -0
- package/dist/preflight-fF8g1t6F.mjs +1 -0
- package/dist/publish-PaTRQ5Ga.mjs +1 -0
- package/dist/publisher-oHVy3LA2.mjs +2 -0
- package/dist/push-DX9dRKDw.mjs +1 -0
- package/dist/push-engine-ByiNZr52.mjs +1 -0
- package/dist/remove-BEBkMPak.mjs +1 -0
- package/dist/remove-DxezmGfU.mjs +1 -0
- package/dist/reset-B9Xcepo1.mjs +1 -0
- package/dist/restore-B8aEJn3N.mjs +1 -0
- package/dist/rollback-pqomySb-.mjs +1 -0
- package/dist/shell-DQfdqK0J.mjs +1 -0
- package/dist/status-2-lE-2hH.mjs +1 -0
- package/dist/store-CAzxNmpU.mjs +1 -0
- package/dist/tailwind-source-Ho_nKVtd.mjs +3 -0
- package/dist/timer-BZNWRS3O.mjs +1 -0
- package/dist/topo-sort-CNCKE3Ap.mjs +1 -0
- package/dist/topo-sort-I086ZoiN.mjs +1 -0
- package/dist/tracker-OhIA445x.mjs +1 -0
- package/dist/tracker-nsfA6PWa.mjs +1 -0
- package/dist/update-CjAl0ZO9.mjs +1 -0
- package/dist/use-BCXyvJf2.mjs +1 -0
- package/dist/vite-config-B6bZDoGe.mjs +1 -0
- package/dist/vite-config-D_iXaoHh.mjs +10 -0
- package/dist/vite-plugin.mjs +1 -210
- package/dist/watch-orchestrator-DGe9gBjj.mjs +1 -0
- package/dist/watch-orchestrator-DkuwJOEb.mjs +1 -0
- package/dist/watcher-DN6vT6nw.mjs +1 -0
- package/dist/watcher-LcNLwOgA.mjs +1 -0
- package/dist/webpack-plugin.mjs +1 -145
- package/dist/workspace-7rWwh6jI.mjs +1 -0
- package/dist/workspace-CSQVbAw4.mjs +1 -0
- package/package.json +4 -7
- package/dist/add-B_xzUp5y.mjs +0 -3
- package/dist/add-flow-cvrMO_aV.mjs +0 -5
- package/dist/batch-push-DXtZxRx0.mjs +0 -3
- package/dist/build-detect-BTHh2OBm.mjs +0 -3
- package/dist/bundler-detect-Dq-QAbQj.mjs +0 -3
- package/dist/check-CbVdpTsw.mjs +0 -3
- package/dist/chokidar-BkIWf7Ix.mjs +0 -3
- package/dist/clean-CyDDqbBD.mjs +0 -3
- package/dist/config-BJsL6NqN.mjs +0 -4
- package/dist/console-CIiXr7ge.mjs +0 -3
- package/dist/console-CyaBcUd-.mjs +0 -98
- package/dist/dev-kqgY9NjI.mjs +0 -3
- package/dist/dist-CFkjiIqD.mjs +0 -7
- package/dist/doctor-D-S1P0UG.mjs +0 -6
- package/dist/dry-run-BkdMYSIx.mjs +0 -3
- package/dist/errors-BlOfexcH.mjs +0 -3
- package/dist/explain-9Y4SZHjC.mjs +0 -3
- package/dist/format-DRqD29u-.mjs +0 -3
- package/dist/fs-C4juVCTd.mjs +0 -3
- package/dist/fs-CPnWm9CR.mjs +0 -3
- package/dist/fs-DzsciYAL.mjs +0 -757
- package/dist/hints-Hz3V4h3A.mjs +0 -3
- package/dist/history-DRhLwzhq.mjs +0 -3
- package/dist/history-vS3w4EGu.mjs +0 -3
- package/dist/init-TN84d5jM.mjs +0 -4
- package/dist/init-helpers-CYYWQm-P.mjs +0 -15
- package/dist/injector-nt40JxVt.mjs +0 -3
- package/dist/json-DbSkpxtr.mjs +0 -3
- package/dist/list-9hWJjw19.mjs +0 -3
- package/dist/logger-9C6B9Na8.mjs +0 -3
- package/dist/migrate-Co4qcFt6.mjs +0 -5
- package/dist/nextjs-config-BQgTWZ96.mjs +0 -3
- package/dist/nextjs-config-dUw2J6B9.mjs +0 -4
- package/dist/output-BxR2v-jn.mjs +0 -3
- package/dist/package-manager-DJ8CE0zL.mjs +0 -13
- package/dist/picomatch-B0_Pxgms.mjs +0 -3
- package/dist/preflight-BDsxR2Ct.mjs +0 -3
- package/dist/preflight-MzNjLXiy.mjs +0 -3
- package/dist/publish-C7ZUvHkE.mjs +0 -3
- package/dist/publisher-CvXTbkLP.mjs +0 -4
- package/dist/push-B5KrkILW.mjs +0 -3
- package/dist/push-engine-BpNr8qXR.mjs +0 -3
- package/dist/remove-DkOgVQMZ.mjs +0 -3
- package/dist/remove-J5tY_BFk.mjs +0 -3
- package/dist/reset-ClGouUb5.mjs +0 -3
- package/dist/restore-Bx2V59SL.mjs +0 -3
- package/dist/rollback-RPjHZWtG.mjs +0 -3
- package/dist/rolldown-runtime-BZbIAPMk.mjs +0 -3
- package/dist/shell-RQ7Hf1kp.mjs +0 -3
- package/dist/status-Rnvw6dG2.mjs +0 -3
- package/dist/store-DjPdOKqg.mjs +0 -3
- package/dist/tailwind-source-D1cUiG-t.mjs +0 -5
- package/dist/timer-DqgB175x.mjs +0 -3
- package/dist/topo-sort-DOCpHjT7.mjs +0 -3
- package/dist/topo-sort-yd4jxr_E.mjs +0 -3
- package/dist/tracker-89eW0ArT.mjs +0 -3
- package/dist/tracker-B3Fqx94J.mjs +0 -3
- package/dist/update-CAKFICZu.mjs +0 -3
- package/dist/use-CCx6J0mc.mjs +0 -3
- package/dist/vite-config-BHmawlD2.mjs +0 -12
- package/dist/vite-config-BRlYc4ni.mjs +0 -3
- package/dist/watch-orchestrator-BfuCaZLA.mjs +0 -3
- package/dist/watcher-T123sBDg.mjs +0 -3
- package/dist/workspace-CdLSxPFS.mjs +0 -3
- package/dist/workspace-DBxNrowu.mjs +0 -3
- package/dist/xxhash-wasm-D_QjdUuv.mjs +0 -3
package/dist/index.mjs
CHANGED
|
@@ -1,3637 +1 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import { A as getStoreMetaPath, B as isJsonObject, C as getConsumerKnarrDir, D as getNodeModulesPackagePath, E as getHistoryEntryPath, F as parseConsumerState, G as readJsonObject, H as ownRecord, I as parseConsumersRegistry, J as pLimit, K as stringField, L as validatePackageIdentity, M as getStorePath, N as normalizePath, O as getStoreEntryPath, P as isKnarrMeta, R as validatePackageName, S as getConsumerBackupPath, T as getConsumersPath, U as parseJson, V as objectField, W as parseJsonObject, Y as __exportAll, _ as computeContentHash, a as ensurePrivateDir, b as verbose, c as incrementalCopy, d as removeDir, f as getMutations, g as resetMutations, h as recordMutation, i as ensureDir, j as getStorePackagePath, k as getStoreHistoryPath, l as isNodeError, m as printDryRunReport, n as copyDir, o as exists, p as markDryRunJsonReportPrinted, q as stringRecordField, r as copyWithCoW, t as atomicWriteFile, u as moveDir, v as isDryRun, w as getConsumerStatePath, x as decodePackageName, y as isJsonOutput, z as asPackageJson } from "./fs-DzsciYAL.mjs";
|
|
3
|
-
import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
4
|
-
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
5
|
-
import { spawn } from "node:child_process";
|
|
6
|
-
import { availableParallelism, platform, release } from "node:os";
|
|
7
|
-
import picomatch from "picomatch";
|
|
8
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
9
|
-
// src/utils/shell.ts
|
|
10
|
-
/**
|
|
11
|
-
* Run a user-supplied command line through the platform shell.
|
|
12
|
-
*
|
|
13
|
-
* Uses Node's `shell: true`, which runs `/bin/sh -c` on POSIX and
|
|
14
|
-
* `cmd.exe /d /s /c "<command>"` with verbatim arguments on Windows.
|
|
15
|
-
* Spawning `cmd` with `["/c", command]` manually is wrong: Node escapes
|
|
16
|
-
* embedded quotes with backslashes, which cmd.exe does not understand, so
|
|
17
|
-
* commands such as `node "C:\Program Files\x\build.js"` break.
|
|
18
|
-
*/
|
|
19
|
-
function spawnShell(command, options = {}) {
|
|
20
|
-
return spawn(command, {
|
|
21
|
-
...options,
|
|
22
|
-
shell: true
|
|
23
|
-
});
|
|
24
|
-
}
|
|
25
|
-
/** Quote one argument for a cmd.exe command line. */
|
|
26
|
-
function quoteWindowsArg(arg) {
|
|
27
|
-
if (arg !== "" && !/[\s"&|<>^()%!]/.test(arg)) return arg;
|
|
28
|
-
return `"${arg.replaceAll("\"", "\"\"")}"`;
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Run an executable with an argument list (no user command line).
|
|
32
|
-
*
|
|
33
|
-
* POSIX: spawned directly, no shell. Windows: package managers are `.cmd`
|
|
34
|
-
* shims, which Node only runs through a shell, and passing an args array with
|
|
35
|
-
* `shell: true` concatenates the args unescaped (and triggers DEP0190). Build
|
|
36
|
-
* one properly quoted command line instead.
|
|
37
|
-
*/
|
|
38
|
-
function spawnCommand(executable, args, options = {}, platform = process.platform) {
|
|
39
|
-
if (platform === "win32") return spawnShell([executable, ...args].map(quoteWindowsArg).join(" "), options);
|
|
40
|
-
return spawn(executable, args, options);
|
|
41
|
-
}
|
|
42
|
-
// src/utils/pack-list.ts
|
|
43
|
-
/**
|
|
44
|
-
* Resolve the list of publishable files for a package.
|
|
45
|
-
* Mimics `npm pack` logic:
|
|
46
|
-
* 1. If `files` field exists in package.json, use those globs (always includes package.json)
|
|
47
|
-
* 2. If no `files` field, include everything except common ignores
|
|
48
|
-
* 3. Respect .npmignore, falling back to .gitignore when .npmignore is absent
|
|
49
|
-
*
|
|
50
|
-
* Returns absolute file paths.
|
|
51
|
-
*/
|
|
52
|
-
async function resolvePackFiles(packageDir, pkg) {
|
|
53
|
-
const files = [];
|
|
54
|
-
const absDir = resolve(packageDir);
|
|
55
|
-
files.push(join(absDir, "package.json"));
|
|
56
|
-
const allFiles = await collectAllFiles(absDir, absDir);
|
|
57
|
-
const allRelPaths = allFiles.map((f) => normalizePath(relative(absDir, f)));
|
|
58
|
-
if (pkg.files && pkg.files.length > 0) for (const pattern of pkg.files) {
|
|
59
|
-
const target = join(absDir, pattern);
|
|
60
|
-
const resolved = resolve(target);
|
|
61
|
-
if (!resolved.startsWith(absDir + sep) && resolved !== absDir) {
|
|
62
|
-
consola.warn(`files pattern "${pattern}" escapes package directory, skipping`);
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
let matched = false;
|
|
66
|
-
try {
|
|
67
|
-
if ((await stat(target)).isDirectory()) {
|
|
68
|
-
const prefix = normalizePath(relative(absDir, target)) + "/";
|
|
69
|
-
for (const [i, file] of allFiles.entries()) if (allRelPaths[i]?.startsWith(prefix)) files.push(file);
|
|
70
|
-
matched = true;
|
|
71
|
-
} else {
|
|
72
|
-
files.push(target);
|
|
73
|
-
matched = true;
|
|
74
|
-
}
|
|
75
|
-
} catch (err) {
|
|
76
|
-
if (isNodeError(err) && err.code !== "ENOENT") throw err;
|
|
77
|
-
}
|
|
78
|
-
if (!matched) {
|
|
79
|
-
const isMatch = picomatch(pattern, { dot: true });
|
|
80
|
-
let globMatched = 0;
|
|
81
|
-
for (const [i, file] of allFiles.entries()) {
|
|
82
|
-
const relPath = allRelPaths[i];
|
|
83
|
-
if (relPath !== void 0 && isMatch(relPath)) {
|
|
84
|
-
const absFile = resolve(file);
|
|
85
|
-
if (!absFile.startsWith(absDir + sep) && absFile !== absDir) continue;
|
|
86
|
-
files.push(file);
|
|
87
|
-
globMatched++;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
if (globMatched === 0) consola.warn(`files pattern "${pattern}" matched no files`);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
const ignoreMatchers = await loadNpmIgnore(absDir);
|
|
95
|
-
for (const [i, file] of allFiles.entries()) {
|
|
96
|
-
const relPath = allRelPaths[i];
|
|
97
|
-
if (relPath !== void 0 && !shouldIgnore(relPath, ignoreMatchers)) files.push(file);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
const fileSet = new Set(files);
|
|
101
|
-
const allFileSet = new Set(allFiles);
|
|
102
|
-
for (const name of [
|
|
103
|
-
"README.md",
|
|
104
|
-
"README",
|
|
105
|
-
"LICENSE",
|
|
106
|
-
"LICENCE",
|
|
107
|
-
"CHANGELOG.md"
|
|
108
|
-
]) {
|
|
109
|
-
const p = join(absDir, name);
|
|
110
|
-
if (fileSet.has(p)) continue;
|
|
111
|
-
if (!allFileSet.has(p)) continue;
|
|
112
|
-
files.push(p);
|
|
113
|
-
fileSet.add(p);
|
|
114
|
-
}
|
|
115
|
-
return [...fileSet];
|
|
116
|
-
}
|
|
117
|
-
/** Default directories/files to ignore when no `files` field */
|
|
118
|
-
const DEFAULT_IGNORES = /* @__PURE__ */ new Set([
|
|
119
|
-
"node_modules",
|
|
120
|
-
".git",
|
|
121
|
-
".svn",
|
|
122
|
-
".hg",
|
|
123
|
-
".DS_Store",
|
|
124
|
-
".npmrc",
|
|
125
|
-
".gitignore",
|
|
126
|
-
".knarr",
|
|
127
|
-
"test",
|
|
128
|
-
"tests",
|
|
129
|
-
"__tests__",
|
|
130
|
-
".github",
|
|
131
|
-
".vscode",
|
|
132
|
-
".idea",
|
|
133
|
-
"coverage",
|
|
134
|
-
".nyc_output",
|
|
135
|
-
"tsconfig.json",
|
|
136
|
-
"tsconfig.build.json",
|
|
137
|
-
".eslintrc",
|
|
138
|
-
".eslintrc.js",
|
|
139
|
-
".eslintrc.json",
|
|
140
|
-
".prettierrc",
|
|
141
|
-
".prettierrc.js",
|
|
142
|
-
"jest.config.js",
|
|
143
|
-
"jest.config.ts",
|
|
144
|
-
"vitest.config.ts",
|
|
145
|
-
"vitest.config.js"
|
|
146
|
-
]);
|
|
147
|
-
function shouldIgnore(relPath, matchers) {
|
|
148
|
-
for (const isMatch of matchers.negations) if (isMatch(relPath)) return false;
|
|
149
|
-
const parts = relPath.split(/[\\/]/);
|
|
150
|
-
for (const part of parts) {
|
|
151
|
-
if (DEFAULT_IGNORES.has(part)) return true;
|
|
152
|
-
if (matchers.literals.has(part)) return true;
|
|
153
|
-
}
|
|
154
|
-
if (matchers.literals.has(relPath)) return true;
|
|
155
|
-
for (const isMatch of matchers.patterns) if (isMatch(relPath)) return true;
|
|
156
|
-
return false;
|
|
157
|
-
}
|
|
158
|
-
async function loadNpmIgnore(dir) {
|
|
159
|
-
const npmIgnore = await readIgnoreFile(dir, ".npmignore");
|
|
160
|
-
if (npmIgnore !== null) return parseIgnoreFile(npmIgnore);
|
|
161
|
-
const gitIgnore = await readIgnoreFile(dir, ".gitignore");
|
|
162
|
-
return gitIgnore === null ? createIgnoreMatchers() : parseIgnoreFile(gitIgnore);
|
|
163
|
-
}
|
|
164
|
-
async function readIgnoreFile(dir, filename) {
|
|
165
|
-
try {
|
|
166
|
-
return await readFile(join(dir, filename), "utf-8");
|
|
167
|
-
} catch (err) {
|
|
168
|
-
if (isNodeError(err) && err.code === "ENOENT") return null;
|
|
169
|
-
throw err;
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
function createIgnoreMatchers() {
|
|
173
|
-
return {
|
|
174
|
-
literals: /* @__PURE__ */ new Set(),
|
|
175
|
-
patterns: [],
|
|
176
|
-
negations: []
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function parseIgnoreFile(content) {
|
|
180
|
-
const matchers = {
|
|
181
|
-
literals: /* @__PURE__ */ new Set(),
|
|
182
|
-
patterns: [],
|
|
183
|
-
negations: []
|
|
184
|
-
};
|
|
185
|
-
for (const line of content.split("\n")) {
|
|
186
|
-
const trimmed = line.trim();
|
|
187
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
188
|
-
if (trimmed.startsWith("!")) {
|
|
189
|
-
const pat = trimmed.slice(1);
|
|
190
|
-
if (hasGlobChars(pat)) matchers.negations.push(picomatch(pat, { dot: true }));
|
|
191
|
-
else matchers.negations.push(picomatch(pat, { dot: true }));
|
|
192
|
-
} else if (hasGlobChars(trimmed)) matchers.patterns.push(picomatch(trimmed, { dot: true }));
|
|
193
|
-
else matchers.literals.add(trimmed.replace(/\/$/, ""));
|
|
194
|
-
}
|
|
195
|
-
return matchers;
|
|
196
|
-
}
|
|
197
|
-
function hasGlobChars(pattern) {
|
|
198
|
-
return /[*?[\]{}()]/.test(pattern);
|
|
199
|
-
}
|
|
200
|
-
async function collectAllFiles(dir, rootDir) {
|
|
201
|
-
const results = [];
|
|
202
|
-
try {
|
|
203
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
204
|
-
for (const entry of entries) {
|
|
205
|
-
const full = join(dir, entry.name);
|
|
206
|
-
if (entry.isDirectory()) {
|
|
207
|
-
if (entry.name === ".git") continue;
|
|
208
|
-
if (dir === rootDir && entry.name === "node_modules") continue;
|
|
209
|
-
if (entry.isSymbolicLink()) continue;
|
|
210
|
-
results.push(...await collectAllFiles(full, rootDir));
|
|
211
|
-
} else if (!entry.isSymbolicLink()) results.push(full);
|
|
212
|
-
}
|
|
213
|
-
} catch (err) {
|
|
214
|
-
if (isNodeError(err) && err.code === "ENOENT") return [];
|
|
215
|
-
throw err;
|
|
216
|
-
}
|
|
217
|
-
return results;
|
|
218
|
-
}
|
|
219
|
-
// src/core/store.ts
|
|
220
|
-
/** Read the .knarr-meta.json for a store entry */
|
|
221
|
-
async function readMeta(name, version) {
|
|
222
|
-
const metaPath = getStoreMetaPath(name, version);
|
|
223
|
-
try {
|
|
224
|
-
const content = await readFile(metaPath, "utf-8");
|
|
225
|
-
const parsed = parseJson(content);
|
|
226
|
-
if (!isKnarrMeta(parsed)) {
|
|
227
|
-
consola.warn(`Invalid metadata for ${name}@${version}, ignoring`);
|
|
228
|
-
return null;
|
|
229
|
-
}
|
|
230
|
-
return parsed;
|
|
231
|
-
} catch (err) {
|
|
232
|
-
if (isNodeError(err) && err.code !== "ENOENT") consola.warn(`Failed to read metadata for ${name}@${version}: ${err instanceof Error ? err.message : String(err)}`);
|
|
233
|
-
return null;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/** Get a store entry if it exists */
|
|
237
|
-
async function getStoreEntry(name, version) {
|
|
238
|
-
const packageDir = getStorePackagePath(name, version);
|
|
239
|
-
const meta = await readMeta(name, version);
|
|
240
|
-
if (!meta) return null;
|
|
241
|
-
if (!await exists(packageDir)) return null;
|
|
242
|
-
return {
|
|
243
|
-
name,
|
|
244
|
-
version,
|
|
245
|
-
packageDir,
|
|
246
|
-
meta
|
|
247
|
-
};
|
|
248
|
-
}
|
|
249
|
-
/** Find a store entry by name (any version). Returns the latest by publishedAt. */
|
|
250
|
-
async function findStoreEntry(name) {
|
|
251
|
-
const matching = (await listStoreEntries()).filter((e) => e.name === name);
|
|
252
|
-
if (matching.length === 0) return null;
|
|
253
|
-
return matching.reduce((latest, entry) => new Date(entry.meta.publishedAt).getTime() > new Date(latest.meta.publishedAt).getTime() ? entry : latest);
|
|
254
|
-
}
|
|
255
|
-
const PUBLISH_TEMP_SUFFIX = /\.(?:tmp-\d+|old)-(\d{13})$/;
|
|
256
|
-
function publishTempDir(storeEntryDir, kind) {
|
|
257
|
-
return `${storeEntryDir}.${kind === "tmp" ? `tmp-${process.pid}` : "old"}-${Date.now()}`;
|
|
258
|
-
}
|
|
259
|
-
function publishTempDirStartedAt(dirName) {
|
|
260
|
-
const startedAt = PUBLISH_TEMP_SUFFIX.exec(dirName)?.[1];
|
|
261
|
-
return startedAt === void 0 ? null : Number(startedAt);
|
|
262
|
-
}
|
|
263
|
-
function parseStoreDirName(dirName) {
|
|
264
|
-
if (publishTempDirStartedAt(dirName) !== null) return null;
|
|
265
|
-
const atIdx = dirName.lastIndexOf("@");
|
|
266
|
-
if (atIdx <= 0) return null;
|
|
267
|
-
const name = decodePackageName(dirName.slice(0, atIdx));
|
|
268
|
-
const version = dirName.slice(atIdx + 1);
|
|
269
|
-
try {
|
|
270
|
-
validatePackageIdentity(name, version);
|
|
271
|
-
} catch {
|
|
272
|
-
return null;
|
|
273
|
-
}
|
|
274
|
-
return {
|
|
275
|
-
name,
|
|
276
|
-
version
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
/** List all entries in the store */
|
|
280
|
-
async function listStoreEntries() {
|
|
281
|
-
const storePath = getStorePath();
|
|
282
|
-
if (!await exists(storePath)) return [];
|
|
283
|
-
const dirs = await readdir(storePath, { withFileTypes: true });
|
|
284
|
-
return (await Promise.all(dirs.map(async (dir) => {
|
|
285
|
-
const identity = dir.isDirectory() ? parseStoreDirName(dir.name) : null;
|
|
286
|
-
if (!identity) return null;
|
|
287
|
-
const { name, version } = identity;
|
|
288
|
-
const meta = await readMeta(name, version);
|
|
289
|
-
if (!meta) return null;
|
|
290
|
-
return {
|
|
291
|
-
name,
|
|
292
|
-
version,
|
|
293
|
-
packageDir: getStorePackagePath(name, version),
|
|
294
|
-
meta
|
|
295
|
-
};
|
|
296
|
-
}))).filter((r) => r !== null);
|
|
297
|
-
}
|
|
298
|
-
// src/utils/lockfile.ts
|
|
299
|
-
const DEFAULTS = {
|
|
300
|
-
retries: 5,
|
|
301
|
-
minTimeout: 100,
|
|
302
|
-
maxTimeout: 1e3,
|
|
303
|
-
factor: 2,
|
|
304
|
-
stale: 3e4
|
|
305
|
-
};
|
|
306
|
-
/**
|
|
307
|
-
* Execute a function while holding a directory-based lock.
|
|
308
|
-
* Uses `mkdir` (non-recursive) as an atomic lock primitive — mkdir is atomic on all OSes.
|
|
309
|
-
* Implements retry with exponential backoff and stale detection via stat mtime.
|
|
310
|
-
*/
|
|
311
|
-
async function withFileLock(filePath, fn, lockOptions) {
|
|
312
|
-
if (isDryRun()) {
|
|
313
|
-
recordMutation({
|
|
314
|
-
type: "lock-skip",
|
|
315
|
-
path: filePath
|
|
316
|
-
});
|
|
317
|
-
return fn();
|
|
318
|
-
}
|
|
319
|
-
await mkdir(dirname(filePath), { recursive: true });
|
|
320
|
-
const lockDir = filePath + ".lk";
|
|
321
|
-
const stale = lockOptions?.stale ?? DEFAULTS.stale;
|
|
322
|
-
let acquired = false;
|
|
323
|
-
for (let attempt = 0; attempt <= DEFAULTS.retries; attempt++) try {
|
|
324
|
-
await mkdir(lockDir);
|
|
325
|
-
acquired = true;
|
|
326
|
-
break;
|
|
327
|
-
} catch (err) {
|
|
328
|
-
if (isNodeError(err) && err.code === "EEXIST") {
|
|
329
|
-
try {
|
|
330
|
-
const s = await stat(lockDir);
|
|
331
|
-
if (Date.now() - s.mtimeMs > stale) {
|
|
332
|
-
await rm(lockDir, {
|
|
333
|
-
recursive: true,
|
|
334
|
-
force: true
|
|
335
|
-
});
|
|
336
|
-
continue;
|
|
337
|
-
}
|
|
338
|
-
} catch {
|
|
339
|
-
continue;
|
|
340
|
-
}
|
|
341
|
-
if (attempt < DEFAULTS.retries) {
|
|
342
|
-
const delay = Math.min(DEFAULTS.minTimeout * DEFAULTS.factor ** attempt, DEFAULTS.maxTimeout);
|
|
343
|
-
await setTimeout$1(delay);
|
|
344
|
-
}
|
|
345
|
-
} else throw err;
|
|
346
|
-
}
|
|
347
|
-
if (!acquired) throw new Error(`Failed to acquire lock after ${DEFAULTS.retries} attempts. Another Knarr process may be running. If this persists, delete ${lockDir} and retry.`);
|
|
348
|
-
try {
|
|
349
|
-
return await fn();
|
|
350
|
-
} finally {
|
|
351
|
-
await rm(lockDir, {
|
|
352
|
-
recursive: true,
|
|
353
|
-
force: true
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
// src/utils/pm-detect.ts
|
|
358
|
-
/** Valid package manager names */
|
|
359
|
-
const VALID_PMS = /* @__PURE__ */ new Set([
|
|
360
|
-
"npm",
|
|
361
|
-
"pnpm",
|
|
362
|
-
"yarn",
|
|
363
|
-
"bun"
|
|
364
|
-
]);
|
|
365
|
-
/** Lockfile → package manager mapping (checked in order) */
|
|
366
|
-
const LOCKFILES = [
|
|
367
|
-
["pnpm-lock.yaml", "pnpm"],
|
|
368
|
-
["bun.lockb", "bun"],
|
|
369
|
-
["bun.lock", "bun"],
|
|
370
|
-
["yarn.lock", "yarn"],
|
|
371
|
-
["package-lock.json", "npm"],
|
|
372
|
-
["npm-shrinkwrap.json", "npm"]
|
|
373
|
-
];
|
|
374
|
-
const YARN_PNP_MANIFESTS = [
|
|
375
|
-
".pnp.cjs",
|
|
376
|
-
".pnp.js",
|
|
377
|
-
".pnp.loader.mjs"
|
|
378
|
-
];
|
|
379
|
-
const YARN_PROJECT_ARTIFACTS = [".yarnrc.yml", ...YARN_PNP_MANIFESTS];
|
|
380
|
-
function parsePackageManagerSpec(value) {
|
|
381
|
-
if (typeof value !== "string") return null;
|
|
382
|
-
const match = value.trim().match(/^([^@\s]+)(?:@(.+))?$/);
|
|
383
|
-
if (!match) return null;
|
|
384
|
-
const name = match[1];
|
|
385
|
-
if (!name || !VALID_PMS.has(name)) return null;
|
|
386
|
-
return {
|
|
387
|
-
name,
|
|
388
|
-
version: match[2]?.trim() ?? ""
|
|
389
|
-
};
|
|
390
|
-
}
|
|
391
|
-
/**
|
|
392
|
-
* Read the `packageManager` field from package.json (Corepack convention).
|
|
393
|
-
* Parses values like "pnpm@9.0.0" or "bun@1.0.0+sha256.abc" → PackageManager.
|
|
394
|
-
* Returns null if the field is missing, empty, or not a recognized PM.
|
|
395
|
-
*/
|
|
396
|
-
async function readPackageManagerSpec(dir) {
|
|
397
|
-
try {
|
|
398
|
-
const raw = await readFile(join(dir, "package.json"), "utf-8");
|
|
399
|
-
return parsePackageManagerSpec(parseJsonObject(raw)["packageManager"]);
|
|
400
|
-
} catch {
|
|
401
|
-
return null;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
async function findPackageManagerSpec(projectDir) {
|
|
405
|
-
let dir = projectDir;
|
|
406
|
-
for (;;) {
|
|
407
|
-
const spec = await readPackageManagerSpec(dir);
|
|
408
|
-
if (spec) return spec;
|
|
409
|
-
const parent = dirname(dir);
|
|
410
|
-
if (parent === dir) return null;
|
|
411
|
-
dir = parent;
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
function yarnDefaultsToPnp(version) {
|
|
415
|
-
const normalized = version.trim().replace(/^npm:/, "");
|
|
416
|
-
if (normalized === "classic") return false;
|
|
417
|
-
const major = normalized.match(/^v?(\d+)(?:[.+-]|$)/);
|
|
418
|
-
if (major) return Number(major[1]) >= 2;
|
|
419
|
-
return normalized.length > 0;
|
|
420
|
-
}
|
|
421
|
-
/**
|
|
422
|
-
* Detect the package manager used in a project directory.
|
|
423
|
-
* Checks `packageManager` field in package.json first (Corepack convention),
|
|
424
|
-
* then falls back to lockfile presence, walking up to the filesystem root.
|
|
425
|
-
* Closest match wins. Within the same directory, priority order is maintained.
|
|
426
|
-
* Falls back to "npm" if nothing is found.
|
|
427
|
-
*/
|
|
428
|
-
async function detectPackageManager(projectDir) {
|
|
429
|
-
return (await detectPackageManagerInfo(projectDir)).packageManager;
|
|
430
|
-
}
|
|
431
|
-
/**
|
|
432
|
-
* Detect the package manager and return where the decision came from.
|
|
433
|
-
* Useful for distinguishing an explicit npm project from the npm fallback.
|
|
434
|
-
*/
|
|
435
|
-
async function detectPackageManagerInfo(projectDir) {
|
|
436
|
-
let dir = projectDir;
|
|
437
|
-
for (;;) {
|
|
438
|
-
const fromField = await readPackageManagerSpec(dir);
|
|
439
|
-
if (fromField) return {
|
|
440
|
-
packageManager: fromField.name,
|
|
441
|
-
source: "packageManager",
|
|
442
|
-
dir,
|
|
443
|
-
file: join(dir, "package.json")
|
|
444
|
-
};
|
|
445
|
-
const found = (await Promise.all(LOCKFILES.map(async ([lockfile, packageManager]) => {
|
|
446
|
-
try {
|
|
447
|
-
await stat(join(dir, lockfile));
|
|
448
|
-
return {
|
|
449
|
-
lockfile,
|
|
450
|
-
packageManager
|
|
451
|
-
};
|
|
452
|
-
} catch {
|
|
453
|
-
return null;
|
|
454
|
-
}
|
|
455
|
-
}))).find((result) => result !== null);
|
|
456
|
-
if (found) return {
|
|
457
|
-
packageManager: found.packageManager,
|
|
458
|
-
source: "lockfile",
|
|
459
|
-
dir,
|
|
460
|
-
file: join(dir, found.lockfile)
|
|
461
|
-
};
|
|
462
|
-
const yarnArtifact = await findExistingFile(dir, YARN_PROJECT_ARTIFACTS);
|
|
463
|
-
if (yarnArtifact) return {
|
|
464
|
-
packageManager: "yarn",
|
|
465
|
-
source: "yarnArtifact",
|
|
466
|
-
dir,
|
|
467
|
-
file: join(dir, yarnArtifact)
|
|
468
|
-
};
|
|
469
|
-
const parent = dirname(dir);
|
|
470
|
-
if (parent === dir) return {
|
|
471
|
-
packageManager: "npm",
|
|
472
|
-
source: "default",
|
|
473
|
-
dir: projectDir
|
|
474
|
-
};
|
|
475
|
-
dir = parent;
|
|
476
|
-
}
|
|
477
|
-
}
|
|
478
|
-
async function findExistingFile(dir, filenames) {
|
|
479
|
-
for (const filename of filenames) try {
|
|
480
|
-
await stat(join(dir, filename));
|
|
481
|
-
return filename;
|
|
482
|
-
} catch {}
|
|
483
|
-
return null;
|
|
484
|
-
}
|
|
485
|
-
function readYarnrcScalar(content, key) {
|
|
486
|
-
for (const line of content.split("\n")) {
|
|
487
|
-
const trimmed = line.trim();
|
|
488
|
-
if (trimmed.startsWith("#") || !trimmed.includes(key)) continue;
|
|
489
|
-
const match = trimmed.match(new RegExp(`^${key}:\\s*(.+)$`));
|
|
490
|
-
if (!match?.[1]) continue;
|
|
491
|
-
const value = match[1].trim().replace(/\s+#.*$/, "").trim().replace(/^["']|["']$/g, "");
|
|
492
|
-
if (value) return value;
|
|
493
|
-
}
|
|
494
|
-
return null;
|
|
495
|
-
}
|
|
496
|
-
async function findYarnrcScalar(projectDir, key) {
|
|
497
|
-
let dir = projectDir;
|
|
498
|
-
for (;;) {
|
|
499
|
-
try {
|
|
500
|
-
const value = readYarnrcScalar(await readFile(join(dir, ".yarnrc.yml"), "utf-8"), key);
|
|
501
|
-
if (value) return value;
|
|
502
|
-
} catch {}
|
|
503
|
-
const parent = dirname(dir);
|
|
504
|
-
if (parent === dir) return null;
|
|
505
|
-
dir = parent;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Detect the Yarn Berry nodeLinker mode from .yarnrc.yml.
|
|
510
|
-
* Walks up from projectDir to find the nearest configured value.
|
|
511
|
-
* Returns null if the file is missing or the key is absent.
|
|
512
|
-
*/
|
|
513
|
-
async function detectYarnNodeLinker(projectDir) {
|
|
514
|
-
const value = await findYarnrcScalar(projectDir, "nodeLinker");
|
|
515
|
-
if (value === "node-modules" || value === "pnpm" || value === "pnp") return value;
|
|
516
|
-
return null;
|
|
517
|
-
}
|
|
518
|
-
/**
|
|
519
|
-
* Detect the optional Yarn pnpm-linker store folder from .yarnrc.yml.
|
|
520
|
-
*/
|
|
521
|
-
async function detectYarnPnpmStoreFolder(projectDir) {
|
|
522
|
-
return findYarnrcScalar(projectDir, "pnpmStoreFolder");
|
|
523
|
-
}
|
|
524
|
-
/**
|
|
525
|
-
* Check whether a .yarnrc.yml file exists at or above the project directory.
|
|
526
|
-
* Presence of this file indicates Yarn Berry (v2+) rather than Yarn Classic.
|
|
527
|
-
*/
|
|
528
|
-
async function hasYarnrcYml(projectDir) {
|
|
529
|
-
let dir = projectDir;
|
|
530
|
-
for (;;) try {
|
|
531
|
-
await stat(join(dir, ".yarnrc.yml"));
|
|
532
|
-
return true;
|
|
533
|
-
} catch {
|
|
534
|
-
const parent = dirname(dir);
|
|
535
|
-
if (parent === dir) return false;
|
|
536
|
-
dir = parent;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Check whether a Yarn PnP manifest exists at or above the project directory.
|
|
541
|
-
*/
|
|
542
|
-
async function hasYarnPnpManifest(projectDir) {
|
|
543
|
-
let dir = projectDir;
|
|
544
|
-
for (;;) {
|
|
545
|
-
if ((await Promise.all(YARN_PNP_MANIFESTS.map(async (manifest) => {
|
|
546
|
-
try {
|
|
547
|
-
await stat(join(dir, manifest));
|
|
548
|
-
return true;
|
|
549
|
-
} catch {
|
|
550
|
-
return false;
|
|
551
|
-
}
|
|
552
|
-
}))).some(Boolean)) return true;
|
|
553
|
-
const parent = dirname(dir);
|
|
554
|
-
if (parent === dir) return false;
|
|
555
|
-
dir = parent;
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* Detect whether a Yarn project is using, or will default to, Plug'n'Play.
|
|
560
|
-
* Knarr requires a node_modules-compatible linker for package injection.
|
|
561
|
-
*/
|
|
562
|
-
async function isYarnPnpProject(projectDir) {
|
|
563
|
-
const linker = await detectYarnNodeLinker(projectDir);
|
|
564
|
-
if (linker === "pnp") return true;
|
|
565
|
-
if (linker === "node-modules" || linker === "pnpm") return false;
|
|
566
|
-
if (await hasYarnPnpManifest(projectDir)) return true;
|
|
567
|
-
if (await hasYarnrcYml(projectDir)) return true;
|
|
568
|
-
const spec = await findPackageManagerSpec(projectDir);
|
|
569
|
-
return spec?.name === "yarn" && yarnDefaultsToPnp(spec.version);
|
|
570
|
-
}
|
|
571
|
-
// src/utils/package-manager.ts
|
|
572
|
-
const PACKAGE_MANAGER_ADAPTERS = {
|
|
573
|
-
npm: {
|
|
574
|
-
layout: () => "node-modules",
|
|
575
|
-
installArgs: (dependencies, dev) => [
|
|
576
|
-
"install",
|
|
577
|
-
...dev ? ["-D"] : [],
|
|
578
|
-
...dependencies
|
|
579
|
-
]
|
|
580
|
-
},
|
|
581
|
-
pnpm: {
|
|
582
|
-
layout: () => "pnpm",
|
|
583
|
-
installArgs: (dependencies, dev) => [
|
|
584
|
-
"add",
|
|
585
|
-
...dev ? ["-D"] : [],
|
|
586
|
-
...dependencies
|
|
587
|
-
]
|
|
588
|
-
},
|
|
589
|
-
yarn: {
|
|
590
|
-
layout: (nodeLinker) => nodeLinker === "pnpm" ? "yarn-pnpm" : "node-modules",
|
|
591
|
-
installArgs: (dependencies, dev) => [
|
|
592
|
-
"add",
|
|
593
|
-
...dev ? ["-D"] : [],
|
|
594
|
-
...dependencies
|
|
595
|
-
]
|
|
596
|
-
},
|
|
597
|
-
bun: {
|
|
598
|
-
layout: () => "bun",
|
|
599
|
-
installArgs: (dependencies, dev) => [
|
|
600
|
-
"add",
|
|
601
|
-
...dev ? ["-d"] : [],
|
|
602
|
-
...dependencies
|
|
603
|
-
]
|
|
604
|
-
}
|
|
605
|
-
};
|
|
606
|
-
const YARN_PNP_INCOMPATIBILITY = "Yarn PnP mode is not compatible with Knarr.\n\nKnarr works by copying files into node_modules/, but PnP eliminates\nnode_modules/ entirely. To use Knarr with Yarn Berry, add one of these\nto .yarnrc.yml:\n\n nodeLinker: node-modules\n nodeLinker: pnpm\n\nThen run: yarn install";
|
|
607
|
-
async function inspectProjectPackageManager(projectDir, options = {}) {
|
|
608
|
-
const [detection, configExists, pnpManifestExists, nodeLinker, pnpmStoreFolder, yarnPnpByPolicy] = await Promise.all([
|
|
609
|
-
detectPackageManagerInfo(projectDir),
|
|
610
|
-
hasYarnrcYml(projectDir),
|
|
611
|
-
hasYarnPnpManifest(projectDir),
|
|
612
|
-
detectYarnNodeLinker(projectDir),
|
|
613
|
-
detectYarnPnpmStoreFolder(projectDir),
|
|
614
|
-
isYarnPnpProject(projectDir)
|
|
615
|
-
]);
|
|
616
|
-
const resolvePackageManager = (trackedPackageManager) => {
|
|
617
|
-
const packageManager = options.packageManager ?? (detection.source === "default" && trackedPackageManager ? trackedPackageManager : detection.packageManager);
|
|
618
|
-
const adapter = PACKAGE_MANAGER_ADAPTERS[packageManager];
|
|
619
|
-
const isPnp = pnpManifestExists || nodeLinker === "pnp" || packageManager === "yarn" && yarnPnpByPolicy;
|
|
620
|
-
const layout = adapter.layout(nodeLinker);
|
|
621
|
-
const base = {
|
|
622
|
-
packageManager,
|
|
623
|
-
layout,
|
|
624
|
-
virtualStoreFolder: layout === "yarn-pnpm" ? pnpmStoreFolder : null,
|
|
625
|
-
yarnLinkerDiagnostic: getYarnLinkerDiagnostic({
|
|
626
|
-
packageManager,
|
|
627
|
-
configExists,
|
|
628
|
-
pnpManifestExists,
|
|
629
|
-
nodeLinker,
|
|
630
|
-
isPnp
|
|
631
|
-
}),
|
|
632
|
-
installCommand(dependencies, commandOptions = {}) {
|
|
633
|
-
return createInstallCommand(packageManager, dependencies, commandOptions.dev === true);
|
|
634
|
-
},
|
|
635
|
-
formatCommand,
|
|
636
|
-
run(command) {
|
|
637
|
-
return runPackageManagerCommand(command, projectDir);
|
|
638
|
-
}
|
|
639
|
-
};
|
|
640
|
-
return isPnp ? {
|
|
641
|
-
...base,
|
|
642
|
-
nodeModulesCompatible: false,
|
|
643
|
-
incompatibilityReason: YARN_PNP_INCOMPATIBILITY
|
|
644
|
-
} : {
|
|
645
|
-
...base,
|
|
646
|
-
nodeModulesCompatible: true,
|
|
647
|
-
incompatibilityReason: null
|
|
648
|
-
};
|
|
649
|
-
};
|
|
650
|
-
return { resolve: resolvePackageManager };
|
|
651
|
-
}
|
|
652
|
-
function getYarnLinkerDiagnostic(options) {
|
|
653
|
-
const { packageManager, configExists, pnpManifestExists, nodeLinker, isPnp } = options;
|
|
654
|
-
if (packageManager !== "yarn" && !configExists && !pnpManifestExists) return null;
|
|
655
|
-
if (nodeLinker === "node-modules") return {
|
|
656
|
-
status: "pass",
|
|
657
|
-
message: "Yarn Berry with node-modules linker"
|
|
658
|
-
};
|
|
659
|
-
if (nodeLinker === "pnpm") return {
|
|
660
|
-
status: "pass",
|
|
661
|
-
message: "Yarn pnpm linker mode (.store virtual store)"
|
|
662
|
-
};
|
|
663
|
-
if (isPnp) return {
|
|
664
|
-
status: "fail",
|
|
665
|
-
message: `${nodeLinker === "pnp" || pnpManifestExists ? "Yarn PnP is not compatible." : "Yarn Berry defaults to PnP."} Set \`nodeLinker: node-modules\` or \`nodeLinker: pnpm\` in .yarnrc.yml`
|
|
666
|
-
};
|
|
667
|
-
if (!configExists) return {
|
|
668
|
-
status: "pass",
|
|
669
|
-
message: "Yarn Classic, node_modules mode"
|
|
670
|
-
};
|
|
671
|
-
return {
|
|
672
|
-
status: "warn",
|
|
673
|
-
message: "Yarn Berry defaults to PnP. Add `nodeLinker: node-modules` or `nodeLinker: pnpm` to .yarnrc.yml"
|
|
674
|
-
};
|
|
675
|
-
}
|
|
676
|
-
function createInstallCommand(packageManager, dependencies, dev) {
|
|
677
|
-
if (dependencies.length === 0) throw new Error("No dependencies provided");
|
|
678
|
-
for (const dependency of dependencies) validatePackageName(dependency);
|
|
679
|
-
return {
|
|
680
|
-
executable: packageManager,
|
|
681
|
-
args: PACKAGE_MANAGER_ADAPTERS[packageManager].installArgs(dependencies, dev)
|
|
682
|
-
};
|
|
683
|
-
}
|
|
684
|
-
function formatCommand(command) {
|
|
685
|
-
return [command.executable, ...command.args].join(" ");
|
|
686
|
-
}
|
|
687
|
-
function runPackageManagerCommand(command, cwd) {
|
|
688
|
-
const display = formatCommand(command);
|
|
689
|
-
if (isDryRun()) {
|
|
690
|
-
recordMutation({
|
|
691
|
-
type: "command-skip",
|
|
692
|
-
path: cwd,
|
|
693
|
-
detail: display
|
|
694
|
-
});
|
|
695
|
-
return Promise.resolve(true);
|
|
696
|
-
}
|
|
697
|
-
return new Promise((resolve) => {
|
|
698
|
-
const child = spawnCommand(command.executable, command.args, {
|
|
699
|
-
cwd,
|
|
700
|
-
stdio: "inherit"
|
|
701
|
-
});
|
|
702
|
-
child.on("close", (code) => resolve(code === 0));
|
|
703
|
-
child.on("error", () => resolve(false));
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
// src/core/publisher.ts
|
|
707
|
-
const copyLimit = pLimit(Math.max(availableParallelism(), 8));
|
|
708
|
-
/**
|
|
709
|
-
* Publish a package from a directory to the Knarr store.
|
|
710
|
-
*
|
|
711
|
-
* 1. Read package.json, validate name and version
|
|
712
|
-
* 2. Resolve publishable files
|
|
713
|
-
* 3. Compute content hash
|
|
714
|
-
* 4. Skip if hash matches existing store entry
|
|
715
|
-
* 5. Copy files to temp dir, then atomic rename to store
|
|
716
|
-
* 6. Write .knarr-meta.json
|
|
717
|
-
*/
|
|
718
|
-
async function publish(packageDir, options = {}) {
|
|
719
|
-
const pkgPath = join(packageDir, "package.json");
|
|
720
|
-
let pkgContent;
|
|
721
|
-
try {
|
|
722
|
-
pkgContent = await readFile(pkgPath, "utf-8");
|
|
723
|
-
} catch {
|
|
724
|
-
throw new Error(`No package.json found in ${packageDir}`);
|
|
725
|
-
}
|
|
726
|
-
const pkgObject = parseJsonObject(pkgContent, pkgPath);
|
|
727
|
-
if (typeof pkgObject["name"] !== "string" || !pkgObject["name"]) throw new Error("package.json missing 'name' field");
|
|
728
|
-
if (typeof pkgObject["version"] !== "string" || !pkgObject["version"]) throw new Error("package.json missing 'version' field");
|
|
729
|
-
const pkg = asPackageJson(pkgObject);
|
|
730
|
-
if (!pkg) throw new Error("package.json missing 'name' or 'version' field");
|
|
731
|
-
validatePackageIdentity(pkg.name, pkg.version);
|
|
732
|
-
await runLifecycleHook(packageDir, pkg, "preknarr");
|
|
733
|
-
if (options.runScripts !== false) await runLifecycleHook(packageDir, pkg, "prepack");
|
|
734
|
-
let publishDir = packageDir;
|
|
735
|
-
if (pkg.publishConfig?.directory) {
|
|
736
|
-
publishDir = resolve(packageDir, pkg.publishConfig.directory);
|
|
737
|
-
try {
|
|
738
|
-
if (!(await stat(publishDir)).isDirectory()) throw new Error(`publishConfig.directory "${pkg.publishConfig.directory}" is not a directory`);
|
|
739
|
-
} catch (err) {
|
|
740
|
-
if (err instanceof Error && "code" in err && err.code === "ENOENT") throw new Error(`publishConfig.directory "${pkg.publishConfig.directory}" does not exist`, { cause: err });
|
|
741
|
-
throw err;
|
|
742
|
-
}
|
|
743
|
-
verbose(`[publish] Using publishConfig.directory: ${publishDir}`);
|
|
744
|
-
}
|
|
745
|
-
const publishPkgPath = join(publishDir, "package.json");
|
|
746
|
-
const publishDirHasPackageJson = publishDir === packageDir || await exists(publishPkgPath);
|
|
747
|
-
const filePkg = publishDirHasPackageJson ? asPackageJson(parseJsonObject(await readFile(publishPkgPath, "utf-8"), publishPkgPath)) : pkg;
|
|
748
|
-
if (!filePkg?.name) throw new Error("publish package.json missing 'name' field");
|
|
749
|
-
if (!filePkg.version) throw new Error("publish package.json missing 'version' field");
|
|
750
|
-
validatePackageIdentity(filePkg.name, filePkg.version);
|
|
751
|
-
if (filePkg.private && !options.allowPrivate) throw new Error(`Package "${filePkg.name}" is private. Use --private flag to publish private packages.`);
|
|
752
|
-
const packListPkg = publishDirHasPackageJson ? filePkg : {
|
|
753
|
-
...filePkg,
|
|
754
|
-
files: void 0
|
|
755
|
-
};
|
|
756
|
-
const files = await resolvePackFiles(publishDir, packListPkg);
|
|
757
|
-
if (files.length === 0) throw new Error("No publishable files found");
|
|
758
|
-
verbose(`[publish] Resolved ${files.length} files for ${filePkg.name}@${filePkg.version}`);
|
|
759
|
-
await preloadWorkspaceVersions(filePkg, packageDir);
|
|
760
|
-
await preloadCatalogs(filePkg, packageDir);
|
|
761
|
-
let processedPkg = rewriteProtocolVersions(filePkg);
|
|
762
|
-
processedPkg = applyPublishConfig(processedPkg);
|
|
763
|
-
const contentOverrides = /* @__PURE__ */ new Map();
|
|
764
|
-
if (processedPkg !== filePkg || !publishDirHasPackageJson) contentOverrides.set("package.json", JSON.stringify(processedPkg, null, 2));
|
|
765
|
-
const hashFiles = [...files];
|
|
766
|
-
const hashFileRels = new Set(files.map((file) => relative(publishDir, file).replace(/\\/g, "/")));
|
|
767
|
-
for (const rel of contentOverrides.keys()) if (!hashFileRels.has(rel)) hashFiles.push(join(publishDir, rel));
|
|
768
|
-
const contentHash = await computeContentHash(hashFiles, publishDir, contentOverrides);
|
|
769
|
-
if (!options.force) {
|
|
770
|
-
const existingMeta = await readMeta(filePkg.name, filePkg.version);
|
|
771
|
-
if (existingMeta && existingMeta.contentHash === contentHash) {
|
|
772
|
-
consola.info(`${filePkg.name}@${filePkg.version} already up to date (no changes since last publish)`);
|
|
773
|
-
return {
|
|
774
|
-
name: filePkg.name,
|
|
775
|
-
version: filePkg.version,
|
|
776
|
-
fileCount: files.length,
|
|
777
|
-
skipped: true,
|
|
778
|
-
contentHash,
|
|
779
|
-
buildId: existingMeta.buildId ?? ""
|
|
780
|
-
};
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
const storeEntryDir = getStoreEntryPath(filePkg.name, filePkg.version);
|
|
784
|
-
const result = await withFileLock(storeEntryDir + ".lock", async () => {
|
|
785
|
-
if (!options.force) {
|
|
786
|
-
const metaUnderLock = await readMeta(filePkg.name, filePkg.version);
|
|
787
|
-
if (metaUnderLock && metaUnderLock.contentHash === contentHash) {
|
|
788
|
-
consola.info(`${filePkg.name}@${filePkg.version} already up to date (no changes since last publish)`);
|
|
789
|
-
return {
|
|
790
|
-
name: filePkg.name,
|
|
791
|
-
version: filePkg.version,
|
|
792
|
-
fileCount: files.length,
|
|
793
|
-
skipped: true,
|
|
794
|
-
contentHash,
|
|
795
|
-
buildId: metaUnderLock.buildId ?? ""
|
|
796
|
-
};
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
const tmpDir = publishTempDir(storeEntryDir, "tmp");
|
|
800
|
-
const tmpPackageDir = join(tmpDir, "package");
|
|
801
|
-
const buildId = contentHash.slice(9, 17);
|
|
802
|
-
try {
|
|
803
|
-
await ensurePrivateDir(tmpPackageDir);
|
|
804
|
-
verbose(`[publish] Copying files to temp store...`);
|
|
805
|
-
const uniqueDirs = new Set(files.map((file) => dirname(join(tmpPackageDir, relative(publishDir, file)))));
|
|
806
|
-
await Promise.all([...uniqueDirs].map((d) => ensureDir(d)));
|
|
807
|
-
await Promise.all(files.map((file) => copyLimit(async () => {
|
|
808
|
-
const rel = relative(publishDir, file);
|
|
809
|
-
const normalizedRel = rel.replace(/\\/g, "/");
|
|
810
|
-
const dest = join(tmpPackageDir, rel);
|
|
811
|
-
const override = contentOverrides.get(normalizedRel);
|
|
812
|
-
if (override !== void 0) await atomicWriteFile(dest, Buffer.isBuffer(override) ? override.toString("utf-8") : override);
|
|
813
|
-
else await copyWithCoW(file, dest, { ensureParent: false });
|
|
814
|
-
})));
|
|
815
|
-
if (contentOverrides.has("package.json")) await atomicWriteFile(join(tmpPackageDir, "package.json"), JSON.stringify(processedPkg, null, 2));
|
|
816
|
-
const meta = {
|
|
817
|
-
schemaVersion: 1,
|
|
818
|
-
contentHash,
|
|
819
|
-
publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
820
|
-
sourcePath: packageDir,
|
|
821
|
-
buildId
|
|
822
|
-
};
|
|
823
|
-
await atomicWriteFile(join(tmpDir, ".knarr-meta.json"), JSON.stringify(meta, null, 2));
|
|
824
|
-
const hadOld = await exists(storeEntryDir);
|
|
825
|
-
const oldDir = publishTempDir(storeEntryDir, "old");
|
|
826
|
-
let oldMoved = false;
|
|
827
|
-
try {
|
|
828
|
-
if (hadOld) {
|
|
829
|
-
await moveDir(storeEntryDir, oldDir);
|
|
830
|
-
oldMoved = !isDryRun();
|
|
831
|
-
}
|
|
832
|
-
await moveDir(tmpDir, storeEntryDir);
|
|
833
|
-
} catch (err) {
|
|
834
|
-
if (oldMoved && await exists(oldDir)) {
|
|
835
|
-
if (await exists(storeEntryDir)) await removeDir(storeEntryDir);
|
|
836
|
-
await moveDir(oldDir, storeEntryDir);
|
|
837
|
-
}
|
|
838
|
-
throw err;
|
|
839
|
-
}
|
|
840
|
-
if (hadOld && !isDryRun()) {
|
|
841
|
-
try {
|
|
842
|
-
const { captureHistory } = await Promise.resolve().then(() => history_exports);
|
|
843
|
-
await captureHistory(filePkg.name, filePkg.version, oldDir, options.historyLimit);
|
|
844
|
-
} catch (err) {
|
|
845
|
-
verbose(`[publish] History capture failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
846
|
-
}
|
|
847
|
-
await removeDir(oldDir);
|
|
848
|
-
}
|
|
849
|
-
verbose(`[publish] Stored at ${storeEntryDir}`);
|
|
850
|
-
} catch (err) {
|
|
851
|
-
await removeDir(tmpDir);
|
|
852
|
-
throw err;
|
|
853
|
-
}
|
|
854
|
-
return {
|
|
855
|
-
name: filePkg.name,
|
|
856
|
-
version: filePkg.version,
|
|
857
|
-
fileCount: files.length,
|
|
858
|
-
skipped: false,
|
|
859
|
-
contentHash,
|
|
860
|
-
buildId
|
|
861
|
-
};
|
|
862
|
-
}, { stale: 6e4 });
|
|
863
|
-
if (result.skipped) return result;
|
|
864
|
-
if (options.runScripts !== false) await runLifecycleHook(packageDir, pkg, "postpack");
|
|
865
|
-
await runLifecycleHook(packageDir, pkg, "postknarr");
|
|
866
|
-
consola.success(`Published ${filePkg.name}@${filePkg.version} (${files.length} files) [${result.buildId}]`);
|
|
867
|
-
return result;
|
|
868
|
-
}
|
|
869
|
-
const HOOK_TIMEOUT = parseInt(process.env.KNARR_HOOK_TIMEOUT ?? "30000", 10);
|
|
870
|
-
function pathEnvKey(env) {
|
|
871
|
-
if (platform() !== "win32") return "PATH";
|
|
872
|
-
return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "Path";
|
|
873
|
-
}
|
|
874
|
-
function setEnvVar(env, key, value) {
|
|
875
|
-
if (platform() === "win32") {
|
|
876
|
-
const lowered = key.toLowerCase();
|
|
877
|
-
for (const existingKey of Object.keys(env)) if (existingKey.toLowerCase() === lowered) delete env[existingKey];
|
|
878
|
-
}
|
|
879
|
-
env[key] = value;
|
|
880
|
-
}
|
|
881
|
-
function buildLifecycleEnv(packageDir, pkg, hookName, script) {
|
|
882
|
-
const env = { ...process.env };
|
|
883
|
-
const key = pathEnvKey(env);
|
|
884
|
-
const existingPath = env[key] ?? "";
|
|
885
|
-
setEnvVar(env, key, [join(packageDir, "node_modules", ".bin"), existingPath].filter(Boolean).join(delimiter));
|
|
886
|
-
if (!("INIT_CWD" in env) || !env.INIT_CWD) setEnvVar(env, "INIT_CWD", packageDir);
|
|
887
|
-
setEnvVar(env, "npm_lifecycle_event", hookName);
|
|
888
|
-
setEnvVar(env, "npm_lifecycle_script", script);
|
|
889
|
-
setEnvVar(env, "npm_package_name", pkg.name);
|
|
890
|
-
setEnvVar(env, "npm_package_version", pkg.version);
|
|
891
|
-
return env;
|
|
892
|
-
}
|
|
893
|
-
/**
|
|
894
|
-
* Run a lifecycle hook script if defined in package.json scripts.
|
|
895
|
-
*/
|
|
896
|
-
async function runLifecycleHook(packageDir, pkg, hookName) {
|
|
897
|
-
const script = pkg.scripts?.[hookName];
|
|
898
|
-
if (!script) return;
|
|
899
|
-
if (isDryRun()) {
|
|
900
|
-
recordMutation({
|
|
901
|
-
type: "lifecycle-skip",
|
|
902
|
-
path: packageDir,
|
|
903
|
-
detail: `${hookName}: ${script}`
|
|
904
|
-
});
|
|
905
|
-
return;
|
|
906
|
-
}
|
|
907
|
-
const command = await resolveLifecycleCommand(packageDir, hookName, script);
|
|
908
|
-
verbose(`[lifecycle] Running ${hookName}: ${command}`);
|
|
909
|
-
return new Promise((resolve, reject) => {
|
|
910
|
-
const env = buildLifecycleEnv(packageDir, pkg, hookName, script);
|
|
911
|
-
const child = spawnShell(command, {
|
|
912
|
-
cwd: packageDir,
|
|
913
|
-
env,
|
|
914
|
-
stdio: "inherit"
|
|
915
|
-
});
|
|
916
|
-
const timer = setTimeout(() => {
|
|
917
|
-
child.kill("SIGTERM");
|
|
918
|
-
reject(/* @__PURE__ */ new Error(`${hookName} script timed out after ${HOOK_TIMEOUT / 1e3}s. Increase KNARR_HOOK_TIMEOUT env var if the script needs more time.`));
|
|
919
|
-
}, HOOK_TIMEOUT);
|
|
920
|
-
child.on("close", (code) => {
|
|
921
|
-
clearTimeout(timer);
|
|
922
|
-
if (code === 0) resolve();
|
|
923
|
-
else reject(/* @__PURE__ */ new Error(`${hookName} script failed with exit code ${code}`));
|
|
924
|
-
});
|
|
925
|
-
child.on("error", (err) => {
|
|
926
|
-
clearTimeout(timer);
|
|
927
|
-
reject(/* @__PURE__ */ new Error(`${hookName} script error: ${err.message}`));
|
|
928
|
-
});
|
|
929
|
-
});
|
|
930
|
-
}
|
|
931
|
-
async function resolveLifecycleCommand(packageDir, hookName, script) {
|
|
932
|
-
return !(await inspectProjectPackageManager(packageDir)).resolve().nodeModulesCompatible ? `yarn run ${hookName}` : script;
|
|
933
|
-
}
|
|
934
|
-
/** Fields from publishConfig that override the corresponding package.json fields */
|
|
935
|
-
const PUBLISH_CONFIG_OVERRIDES = [
|
|
936
|
-
"main",
|
|
937
|
-
"module",
|
|
938
|
-
"exports",
|
|
939
|
-
"types",
|
|
940
|
-
"typings",
|
|
941
|
-
"browser",
|
|
942
|
-
"bin"
|
|
943
|
-
];
|
|
944
|
-
/**
|
|
945
|
-
* Apply publishConfig field overrides to a package.json object.
|
|
946
|
-
* Shallow-merges overridable fields and strips publishConfig from the result.
|
|
947
|
-
* Always returns a new object when publishConfig is present (npm strips it at pack time).
|
|
948
|
-
*/
|
|
949
|
-
function applyPublishConfig(pkg) {
|
|
950
|
-
if (!pkg.publishConfig) return pkg;
|
|
951
|
-
const result = { ...pkg };
|
|
952
|
-
for (const field of PUBLISH_CONFIG_OVERRIDES) if (field in pkg.publishConfig) result[field] = pkg.publishConfig[field];
|
|
953
|
-
delete result.publishConfig;
|
|
954
|
-
return result;
|
|
955
|
-
}
|
|
956
|
-
/**
|
|
957
|
-
* Rewrite workspace:* and catalog:* protocol versions to actual versions.
|
|
958
|
-
* Only modifies dependencies/devDependencies/peerDependencies.
|
|
959
|
-
* Returns a new object if changes were made, the same object if not.
|
|
960
|
-
*/
|
|
961
|
-
function rewriteProtocolVersions(pkg) {
|
|
962
|
-
let changed = false;
|
|
963
|
-
const result = { ...pkg };
|
|
964
|
-
let catalogs = null;
|
|
965
|
-
let catalogsLoaded = false;
|
|
966
|
-
for (const depField of [
|
|
967
|
-
"dependencies",
|
|
968
|
-
"devDependencies",
|
|
969
|
-
"peerDependencies",
|
|
970
|
-
"optionalDependencies"
|
|
971
|
-
]) {
|
|
972
|
-
const deps = pkg[depField];
|
|
973
|
-
if (!deps) continue;
|
|
974
|
-
let fieldChanged = false;
|
|
975
|
-
const newDeps = { ...deps };
|
|
976
|
-
for (const [name, version] of Object.entries(deps)) if (version.startsWith("workspace:")) {
|
|
977
|
-
const resolved = resolveWorkspaceSpecifier(name, version);
|
|
978
|
-
if (!resolved) continue;
|
|
979
|
-
newDeps[name] = resolved;
|
|
980
|
-
fieldChanged = true;
|
|
981
|
-
changed = true;
|
|
982
|
-
} else if (version.startsWith("catalog:")) {
|
|
983
|
-
if (!catalogsLoaded) {
|
|
984
|
-
catalogs = loadCatalogsFromCache();
|
|
985
|
-
catalogsLoaded = true;
|
|
986
|
-
}
|
|
987
|
-
if (catalogs) {
|
|
988
|
-
const resolved = resolveCatalogVersion(version, name, catalogs);
|
|
989
|
-
if (resolved) {
|
|
990
|
-
newDeps[name] = resolved;
|
|
991
|
-
fieldChanged = true;
|
|
992
|
-
changed = true;
|
|
993
|
-
} else consola.warn(`catalog: specifier for "${name}" could not be resolved — published package.json will contain "${version}" which may cause install failures`);
|
|
994
|
-
} else verbose(`[publish] No pnpm-workspace.yaml found, cannot resolve catalog: for "${name}"`);
|
|
995
|
-
}
|
|
996
|
-
if (fieldChanged) result[depField] = newDeps;
|
|
997
|
-
}
|
|
998
|
-
return changed ? result : pkg;
|
|
999
|
-
}
|
|
1000
|
-
function resolveWorkspaceSpecifier(depName, specifier) {
|
|
1001
|
-
const raw = specifier.slice(10);
|
|
1002
|
-
const alias = parseWorkspaceAlias(raw);
|
|
1003
|
-
const targetName = alias?.name ?? depName;
|
|
1004
|
-
const versionPart = alias?.range ?? raw;
|
|
1005
|
-
if (versionPart === "*" || versionPart === "^" || versionPart === "~") {
|
|
1006
|
-
const depVersion = _cachedWorkspaceVersions?.versions.get(targetName);
|
|
1007
|
-
if (!depVersion) {
|
|
1008
|
-
consola.warn(`workspace: specifier for "${targetName}" could not be resolved — published package.json will contain "${specifier}" which may cause install failures`);
|
|
1009
|
-
return null;
|
|
1010
|
-
}
|
|
1011
|
-
const resolved = versionPart === "*" ? depVersion : versionPart + depVersion;
|
|
1012
|
-
return alias && targetName !== depName ? `npm:${targetName}@${resolved}` : resolved;
|
|
1013
|
-
}
|
|
1014
|
-
return alias && targetName !== depName ? `npm:${targetName}@${versionPart}` : versionPart;
|
|
1015
|
-
}
|
|
1016
|
-
function parseWorkspaceAlias(specifierBody) {
|
|
1017
|
-
const atIndex = specifierBody.lastIndexOf("@");
|
|
1018
|
-
if (atIndex <= 0) return null;
|
|
1019
|
-
const name = specifierBody.slice(0, atIndex);
|
|
1020
|
-
const range = specifierBody.slice(atIndex + 1);
|
|
1021
|
-
if (!name || !range) return null;
|
|
1022
|
-
return {
|
|
1023
|
-
name,
|
|
1024
|
-
range
|
|
1025
|
-
};
|
|
1026
|
-
}
|
|
1027
|
-
/**
|
|
1028
|
-
* Resolve a catalog: specifier to the actual version string.
|
|
1029
|
-
* - `catalog:` or `catalog:default` → default catalog
|
|
1030
|
-
* - `catalog:<name>` → named catalog
|
|
1031
|
-
*/
|
|
1032
|
-
function resolveCatalogVersion(specifier, depName, catalogs) {
|
|
1033
|
-
const catalogRef = specifier.slice(8);
|
|
1034
|
-
if (catalogRef === "" || catalogRef === "default") return catalogs.default[depName] ?? null;
|
|
1035
|
-
return catalogs.named[catalogRef]?.[depName] ?? null;
|
|
1036
|
-
}
|
|
1037
|
-
let _cachedWorkspaceRoot = null;
|
|
1038
|
-
async function getWorkspaceRoot(packageDir) {
|
|
1039
|
-
if (_cachedWorkspaceRoot?.dir === packageDir) return _cachedWorkspaceRoot.root;
|
|
1040
|
-
const { findWorkspacePackageRoot } = await Promise.resolve().then(() => workspace_exports);
|
|
1041
|
-
const root = await findWorkspacePackageRoot(packageDir);
|
|
1042
|
-
_cachedWorkspaceRoot = {
|
|
1043
|
-
dir: packageDir,
|
|
1044
|
-
root
|
|
1045
|
-
};
|
|
1046
|
-
return root;
|
|
1047
|
-
}
|
|
1048
|
-
let _cachedWorkspaceVersions = null;
|
|
1049
|
-
/**
|
|
1050
|
-
* Pre-load workspace package versions so workspace:* resolves to the
|
|
1051
|
-
* dependency's own version rather than the publisher's version.
|
|
1052
|
-
*/
|
|
1053
|
-
async function preloadWorkspaceVersions(pkg, packageDir) {
|
|
1054
|
-
if (![
|
|
1055
|
-
"dependencies",
|
|
1056
|
-
"devDependencies",
|
|
1057
|
-
"peerDependencies",
|
|
1058
|
-
"optionalDependencies"
|
|
1059
|
-
].some((field) => {
|
|
1060
|
-
const deps = pkg[field];
|
|
1061
|
-
return deps && Object.values(deps).some((v) => v.startsWith("workspace:"));
|
|
1062
|
-
})) return;
|
|
1063
|
-
const root = await getWorkspaceRoot(packageDir);
|
|
1064
|
-
if (!root) {
|
|
1065
|
-
_cachedWorkspaceVersions = null;
|
|
1066
|
-
return;
|
|
1067
|
-
}
|
|
1068
|
-
const { findWorkspacePackages } = await Promise.resolve().then(() => workspace_exports);
|
|
1069
|
-
const pkgDirs = await findWorkspacePackages(root);
|
|
1070
|
-
const versions = /* @__PURE__ */ new Map();
|
|
1071
|
-
await Promise.all(pkgDirs.map(async (dir) => {
|
|
1072
|
-
try {
|
|
1073
|
-
const depPkg = asPackageJson(await readJsonObject(join(dir, "package.json")));
|
|
1074
|
-
if (depPkg?.name && depPkg.version) versions.set(depPkg.name, depPkg.version);
|
|
1075
|
-
} catch {}
|
|
1076
|
-
}));
|
|
1077
|
-
_cachedWorkspaceVersions = {
|
|
1078
|
-
root,
|
|
1079
|
-
versions
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
let _cachedCatalogs = null;
|
|
1083
|
-
/**
|
|
1084
|
-
* Return pre-loaded catalogs from the module-level cache.
|
|
1085
|
-
* Must be called after preloadCatalogs() has populated _cachedCatalogs.
|
|
1086
|
-
*/
|
|
1087
|
-
function loadCatalogsFromCache() {
|
|
1088
|
-
return _cachedCatalogs?.catalogs ?? null;
|
|
1089
|
-
}
|
|
1090
|
-
/**
|
|
1091
|
-
* Pre-load catalog definitions from pnpm-workspace.yaml if any deps use catalog: protocol.
|
|
1092
|
-
*/
|
|
1093
|
-
async function preloadCatalogs(pkg, packageDir) {
|
|
1094
|
-
if (![
|
|
1095
|
-
"dependencies",
|
|
1096
|
-
"devDependencies",
|
|
1097
|
-
"peerDependencies",
|
|
1098
|
-
"optionalDependencies"
|
|
1099
|
-
].some((field) => {
|
|
1100
|
-
const deps = pkg[field];
|
|
1101
|
-
return deps && Object.values(deps).some((v) => v.startsWith("catalog:"));
|
|
1102
|
-
})) return;
|
|
1103
|
-
const root = await getWorkspaceRoot(packageDir);
|
|
1104
|
-
if (!root) {
|
|
1105
|
-
_cachedCatalogs = null;
|
|
1106
|
-
return;
|
|
1107
|
-
}
|
|
1108
|
-
const workspaceFile = join(root, "pnpm-workspace.yaml");
|
|
1109
|
-
const mtimeMs = (await stat(workspaceFile).catch(() => null))?.mtimeMs ?? 0;
|
|
1110
|
-
if (_cachedCatalogs?.root === root && _cachedCatalogs.mtimeMs === mtimeMs) return;
|
|
1111
|
-
const { parseCatalogs } = await Promise.resolve().then(() => workspace_exports);
|
|
1112
|
-
_cachedCatalogs = {
|
|
1113
|
-
root,
|
|
1114
|
-
mtimeMs,
|
|
1115
|
-
catalogs: await parseCatalogs(root)
|
|
1116
|
-
};
|
|
1117
|
-
}
|
|
1118
|
-
// src/utils/bin-linker.ts
|
|
1119
|
-
const CONTROL_CHARS_RE = /[\x00-\x1F\x7F]/;
|
|
1120
|
-
const SAFE_INTERPRETER_RE = /^[A-Za-z0-9._+-]+$/;
|
|
1121
|
-
function safeInterpreter(value) {
|
|
1122
|
-
return value && SAFE_INTERPRETER_RE.test(value) ? value : "node";
|
|
1123
|
-
}
|
|
1124
|
-
function parseShebangInterpreter(content) {
|
|
1125
|
-
const firstLine = content.split(/\r?\n/, 1)[0]?.trim();
|
|
1126
|
-
if (!firstLine?.startsWith("#!")) return "node";
|
|
1127
|
-
const parts = firstLine.slice(2).trim().split(/\s+/).filter(Boolean);
|
|
1128
|
-
const [first] = parts;
|
|
1129
|
-
if (first === void 0) return "node";
|
|
1130
|
-
const executable = first.replace(/\\/g, "/").split("/").pop();
|
|
1131
|
-
if (executable === "env") {
|
|
1132
|
-
const args = parts.slice(1);
|
|
1133
|
-
return safeInterpreter(args[0] === "-S" ? args[1] : args[0]);
|
|
1134
|
-
}
|
|
1135
|
-
return safeInterpreter(executable);
|
|
1136
|
-
}
|
|
1137
|
-
async function readBinInterpreter(targetAbsolute) {
|
|
1138
|
-
try {
|
|
1139
|
-
return parseShebangInterpreter(await readFile(targetAbsolute, "utf-8"));
|
|
1140
|
-
} catch {
|
|
1141
|
-
return "node";
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
function resolveBinPath(binDir, binName, suffix = "") {
|
|
1145
|
-
if (!binName || binName === "." || binName === ".." || CONTROL_CHARS_RE.test(binName) || binName.includes("/") || binName.includes("\\") || binName.includes(":")) return null;
|
|
1146
|
-
const path = join(binDir, `${binName}${suffix}`);
|
|
1147
|
-
const resolvedBinDir = resolve(binDir);
|
|
1148
|
-
const resolvedPath = resolve(path);
|
|
1149
|
-
if (resolvedPath !== resolvedBinDir && resolvedPath.startsWith(resolvedBinDir + sep)) return path;
|
|
1150
|
-
return null;
|
|
1151
|
-
}
|
|
1152
|
-
/**
|
|
1153
|
-
* Resolve the bin entries from a package.json.
|
|
1154
|
-
* Returns a map of bin name → relative file path.
|
|
1155
|
-
*/
|
|
1156
|
-
function resolveBinEntries(pkg) {
|
|
1157
|
-
if (!pkg.bin) return {};
|
|
1158
|
-
if (typeof pkg.bin === "string") return { [pkg.name.startsWith("@") ? pkg.name.split("/")[1] || pkg.name : pkg.name]: pkg.bin };
|
|
1159
|
-
return pkg.bin;
|
|
1160
|
-
}
|
|
1161
|
-
/**
|
|
1162
|
-
* Create bin links in node_modules/.bin/ for a package.
|
|
1163
|
-
* On Unix: symlinks (with shell wrapper fallback for permission errors)
|
|
1164
|
-
* On Windows: .cmd wrapper scripts
|
|
1165
|
-
*/
|
|
1166
|
-
async function createBinLinks(consumerPath, packageName, pkg) {
|
|
1167
|
-
const entries = resolveBinEntries(pkg);
|
|
1168
|
-
if (Object.keys(entries).length === 0) return 0;
|
|
1169
|
-
const binDir = join(consumerPath, "node_modules", ".bin");
|
|
1170
|
-
const safeEntries = Object.entries(entries).map(([binName, binPath]) => ({
|
|
1171
|
-
binName,
|
|
1172
|
-
binPath,
|
|
1173
|
-
linkPath: resolveBinPath(binDir, binName),
|
|
1174
|
-
cmdPath: resolveBinPath(binDir, binName, ".cmd"),
|
|
1175
|
-
ps1Path: resolveBinPath(binDir, binName, ".ps1")
|
|
1176
|
-
})).filter((entry) => {
|
|
1177
|
-
if (!entry.linkPath || !entry.cmdPath || !entry.ps1Path) {
|
|
1178
|
-
consola.warn(`bin name "${entry.binName}" is not safe, skipping`);
|
|
1179
|
-
return false;
|
|
1180
|
-
}
|
|
1181
|
-
return true;
|
|
1182
|
-
});
|
|
1183
|
-
const packageRoot = join(consumerPath, "node_modules", packageName);
|
|
1184
|
-
const resolvedPackageRoot = resolve(packageRoot);
|
|
1185
|
-
const validEntries = safeEntries.filter(({ binName, binPath }) => {
|
|
1186
|
-
const resolvedTarget = resolve(join(packageRoot, binPath));
|
|
1187
|
-
if (resolvedTarget.startsWith(resolvedPackageRoot + sep) || resolvedTarget === resolvedPackageRoot) return true;
|
|
1188
|
-
consola.warn(`bin "${binName}" points outside package directory, skipping`);
|
|
1189
|
-
return false;
|
|
1190
|
-
});
|
|
1191
|
-
if (validEntries.length === 0) return 0;
|
|
1192
|
-
if (isDryRun()) {
|
|
1193
|
-
for (const { linkPath } of validEntries) recordMutation({
|
|
1194
|
-
type: "bin-link",
|
|
1195
|
-
path: linkPath,
|
|
1196
|
-
detail: packageName
|
|
1197
|
-
});
|
|
1198
|
-
verbose(`[dry-run] would create ${validEntries.length} bin link(s) for ${packageName}`);
|
|
1199
|
-
return validEntries.length;
|
|
1200
|
-
}
|
|
1201
|
-
await mkdir(binDir, { recursive: true });
|
|
1202
|
-
const isWindows = platform() === "win32";
|
|
1203
|
-
let count = 0;
|
|
1204
|
-
for (const { binName, binPath, linkPath, cmdPath, ps1Path } of validEntries) {
|
|
1205
|
-
const targetAbsolute = join(packageRoot, binPath);
|
|
1206
|
-
const targetRelative = normalizePath(relative(binDir, targetAbsolute));
|
|
1207
|
-
const interpreter = await readBinInterpreter(targetAbsolute);
|
|
1208
|
-
if (isWindows) {
|
|
1209
|
-
const cmdContent = `@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nCALL :find_dp0\r\n${interpreter} "%dp0%\\${targetRelative.replace(/\//g, "\\")}" %*\r\n`;
|
|
1210
|
-
await writeFile(cmdPath, cmdContent);
|
|
1211
|
-
const ps1Content = `#!/usr/bin/env pwsh\n$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n& ${interpreter} "$basedir/${targetRelative}" $args\nexit $LASTEXITCODE\n`;
|
|
1212
|
-
await writeFile(ps1Path, ps1Content);
|
|
1213
|
-
const shContent = `#!/bin/sh\nbasedir=$(dirname "$0")\nexec ${interpreter} "$basedir/${targetRelative}" "$@"\n`;
|
|
1214
|
-
await writeFile(linkPath, shContent);
|
|
1215
|
-
} else {
|
|
1216
|
-
try {
|
|
1217
|
-
await rm(linkPath, { force: true });
|
|
1218
|
-
} catch {}
|
|
1219
|
-
try {
|
|
1220
|
-
await symlink(targetRelative, linkPath);
|
|
1221
|
-
await chmod(targetAbsolute, 493);
|
|
1222
|
-
} catch (err) {
|
|
1223
|
-
if (isNodeError(err) && (err.code === "EPERM" || err.code === "EACCES")) {
|
|
1224
|
-
verbose(`[bin-linker] Symlink failed (${err.code}), using shell wrapper for ${binName}`);
|
|
1225
|
-
const shContent = `#!/bin/sh\nbasedir=$(dirname "$0")\nexec ${interpreter} "$basedir/${targetRelative}" "$@"\n`;
|
|
1226
|
-
await writeFile(linkPath, shContent);
|
|
1227
|
-
await chmod(linkPath, 493);
|
|
1228
|
-
} else throw err;
|
|
1229
|
-
}
|
|
1230
|
-
}
|
|
1231
|
-
count++;
|
|
1232
|
-
}
|
|
1233
|
-
return count;
|
|
1234
|
-
}
|
|
1235
|
-
/**
|
|
1236
|
-
* Remove bin links for a package from node_modules/.bin/
|
|
1237
|
-
*/
|
|
1238
|
-
async function removeBinLinks(consumerPath, pkg) {
|
|
1239
|
-
const entries = resolveBinEntries(pkg);
|
|
1240
|
-
const binDir = join(consumerPath, "node_modules", ".bin");
|
|
1241
|
-
const safeEntries = Object.keys(entries).map((binName) => ({
|
|
1242
|
-
binName,
|
|
1243
|
-
linkPath: resolveBinPath(binDir, binName),
|
|
1244
|
-
cmdPath: resolveBinPath(binDir, binName, ".cmd"),
|
|
1245
|
-
ps1Path: resolveBinPath(binDir, binName, ".ps1")
|
|
1246
|
-
})).filter((entry) => !!entry.linkPath && !!entry.cmdPath && !!entry.ps1Path);
|
|
1247
|
-
if (isDryRun()) {
|
|
1248
|
-
for (const { linkPath } of safeEntries) recordMutation({
|
|
1249
|
-
type: "bin-unlink",
|
|
1250
|
-
path: linkPath
|
|
1251
|
-
});
|
|
1252
|
-
verbose(`[dry-run] would remove ${safeEntries.length} bin link(s)`);
|
|
1253
|
-
return;
|
|
1254
|
-
}
|
|
1255
|
-
const isWindows = platform() === "win32";
|
|
1256
|
-
const packageRoot = join(consumerPath, "node_modules", pkg.name);
|
|
1257
|
-
for (const { linkPath, cmdPath, ps1Path } of safeEntries) try {
|
|
1258
|
-
if (await binFileBelongsToPackage(binDir, linkPath, packageRoot)) await rm(linkPath, { force: true });
|
|
1259
|
-
if (isWindows) {
|
|
1260
|
-
if (await binFileBelongsToPackage(binDir, cmdPath, packageRoot)) await rm(cmdPath, { force: true });
|
|
1261
|
-
if (await binFileBelongsToPackage(binDir, ps1Path, packageRoot)) await rm(ps1Path, { force: true });
|
|
1262
|
-
}
|
|
1263
|
-
} catch {}
|
|
1264
|
-
}
|
|
1265
|
-
async function binFileBelongsToPackage(binDir, linkPath, packageRoot) {
|
|
1266
|
-
let fileStat;
|
|
1267
|
-
try {
|
|
1268
|
-
fileStat = await lstat(linkPath);
|
|
1269
|
-
} catch (err) {
|
|
1270
|
-
if (isNodeError(err) && err.code === "ENOENT") return false;
|
|
1271
|
-
throw err;
|
|
1272
|
-
}
|
|
1273
|
-
const resolvedPackageRoot = resolve(packageRoot);
|
|
1274
|
-
if (fileStat.isSymbolicLink()) {
|
|
1275
|
-
const target = await readlink(linkPath);
|
|
1276
|
-
const resolvedTarget = resolve(binDir, target);
|
|
1277
|
-
return resolvedTarget === resolvedPackageRoot || resolvedTarget.startsWith(resolvedPackageRoot + sep);
|
|
1278
|
-
}
|
|
1279
|
-
if (!fileStat.isFile()) return false;
|
|
1280
|
-
const content = await readFile(linkPath, "utf-8");
|
|
1281
|
-
const relPackageRoot = normalizePath(relative(binDir, packageRoot));
|
|
1282
|
-
const relWindowsPackageRoot = relPackageRoot.replace(/\//g, "\\");
|
|
1283
|
-
return content.includes(`${relPackageRoot}/`) || content.includes(`${relPackageRoot}"`) || content.includes(`${relWindowsPackageRoot}\\`) || content.includes(`${relWindowsPackageRoot}"`);
|
|
1284
|
-
}
|
|
1285
|
-
// src/utils/bundler-detect.ts
|
|
1286
|
-
/** Config file patterns to check, in priority order */
|
|
1287
|
-
const BUNDLER_CONFIGS = [
|
|
1288
|
-
["vite", [
|
|
1289
|
-
"vite.config.ts",
|
|
1290
|
-
"vite.config.js",
|
|
1291
|
-
"vite.config.mts",
|
|
1292
|
-
"vite.config.mjs"
|
|
1293
|
-
]],
|
|
1294
|
-
["next", [
|
|
1295
|
-
"next.config.js",
|
|
1296
|
-
"next.config.ts",
|
|
1297
|
-
"next.config.mjs"
|
|
1298
|
-
]],
|
|
1299
|
-
["webpack", ["webpack.config.js", "webpack.config.ts"]],
|
|
1300
|
-
["turbo", ["turbo.json"]],
|
|
1301
|
-
["rollup", [
|
|
1302
|
-
"rollup.config.js",
|
|
1303
|
-
"rollup.config.ts",
|
|
1304
|
-
"rollup.config.mjs"
|
|
1305
|
-
]]
|
|
1306
|
-
];
|
|
1307
|
-
/**
|
|
1308
|
-
* Detect ALL bundlers present in a project directory.
|
|
1309
|
-
* A Next.js project may also have webpack caches, etc.
|
|
1310
|
-
* Checks all config files in parallel for speed.
|
|
1311
|
-
*/
|
|
1312
|
-
async function detectAllBundlers(projectDir) {
|
|
1313
|
-
const checks = BUNDLER_CONFIGS.flatMap(([type, configFiles]) => configFiles.map(async (configFile) => ({
|
|
1314
|
-
type,
|
|
1315
|
-
configFile: join(projectDir, configFile),
|
|
1316
|
-
found: await exists(join(projectDir, configFile))
|
|
1317
|
-
})));
|
|
1318
|
-
const all = await Promise.all(checks);
|
|
1319
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1320
|
-
const results = [];
|
|
1321
|
-
for (const { type, configFile, found } of all) if (found && !seen.has(type)) {
|
|
1322
|
-
seen.add(type);
|
|
1323
|
-
results.push({
|
|
1324
|
-
type,
|
|
1325
|
-
configFile
|
|
1326
|
-
});
|
|
1327
|
-
}
|
|
1328
|
-
return results;
|
|
1329
|
-
}
|
|
1330
|
-
// src/utils/bundler-cache.ts
|
|
1331
|
-
/** Cache directories to clear for each bundler type.
|
|
1332
|
-
* Vite is intentionally excluded — linked packages are served directly
|
|
1333
|
-
* (excluded from optimizeDeps), so the .vite pre-bundle cache doesn't
|
|
1334
|
-
* contain them. Clearing it just forces Vite to re-optimize unrelated
|
|
1335
|
-
* deps and triggers an unnecessary full page reload. The Vite plugin
|
|
1336
|
-
* handles cache clearing when it's actually needed (new package linked). */
|
|
1337
|
-
const CACHE_DIRS = {
|
|
1338
|
-
next: [".next/cache"],
|
|
1339
|
-
webpack: ["node_modules/.cache"]
|
|
1340
|
-
};
|
|
1341
|
-
/** Per-consumer cache of detected bundlers to avoid redundant fs checks */
|
|
1342
|
-
const bundlerCache = /* @__PURE__ */ new Map();
|
|
1343
|
-
async function invalidateBundlerCache(consumerPath) {
|
|
1344
|
-
if (isDryRun()) {
|
|
1345
|
-
verbose(`[dry-run] would invalidate bundler caches for ${consumerPath}`);
|
|
1346
|
-
recordMutation({
|
|
1347
|
-
type: "cache-invalidate",
|
|
1348
|
-
path: consumerPath
|
|
1349
|
-
});
|
|
1350
|
-
return 0;
|
|
1351
|
-
}
|
|
1352
|
-
let bundlers = bundlerCache.get(consumerPath);
|
|
1353
|
-
if (!bundlers) {
|
|
1354
|
-
bundlers = await detectAllBundlers(consumerPath);
|
|
1355
|
-
bundlerCache.set(consumerPath, bundlers);
|
|
1356
|
-
}
|
|
1357
|
-
let invalidated = 0;
|
|
1358
|
-
for (const bundler of bundlers) {
|
|
1359
|
-
if (!bundler.type) continue;
|
|
1360
|
-
const dirs = CACHE_DIRS[bundler.type];
|
|
1361
|
-
if (!dirs) continue;
|
|
1362
|
-
for (const dir of dirs) {
|
|
1363
|
-
const cacheDir = join(consumerPath, dir);
|
|
1364
|
-
if (await exists(cacheDir)) try {
|
|
1365
|
-
await removeDir(cacheDir);
|
|
1366
|
-
invalidated++;
|
|
1367
|
-
verbose(`[inject] Invalidated ${bundler.type} cache: ${dir}`);
|
|
1368
|
-
} catch {
|
|
1369
|
-
verbose(`[inject] Could not clear ${bundler.type} cache: ${dir} (locked?)`);
|
|
1370
|
-
}
|
|
1371
|
-
}
|
|
1372
|
-
}
|
|
1373
|
-
return invalidated;
|
|
1374
|
-
}
|
|
1375
|
-
// src/core/injector.ts
|
|
1376
|
-
/**
|
|
1377
|
-
* Inject a package from the store into a consumer's node_modules.
|
|
1378
|
-
* Strategy depends on the package manager:
|
|
1379
|
-
* - npm/yarn/bun: direct node_modules/<pkg>/ (Bun isolated symlinks must stay local)
|
|
1380
|
-
* - pnpm: follow .pnpm/ structure
|
|
1381
|
-
* - yarn with nodeLinker: pnpm: follow .store/ structure
|
|
1382
|
-
*/
|
|
1383
|
-
async function inject(storeEntry, consumerPath, pm, options = {}) {
|
|
1384
|
-
const targetDir = await resolveInjectionTarget(consumerPath, storeEntry.name, pm, storeEntry.version, { repairMissingLink: true });
|
|
1385
|
-
verbose(`[inject] ${storeEntry.name}@${storeEntry.version} → ${targetDir}`);
|
|
1386
|
-
await ensureDir(targetDir);
|
|
1387
|
-
const previousPkg = await readPackageJson(targetDir);
|
|
1388
|
-
const { copied, removed, skipped } = await incrementalCopy(storeEntry.packageDir, targetDir, { force: options.force });
|
|
1389
|
-
verbose(`[inject] ${copied} copied, ${removed} removed, ${skipped} skipped`);
|
|
1390
|
-
const cacheInvalidations = copied > 0 || removed > 0 ? await invalidateBundlerCache(consumerPath) : 0;
|
|
1391
|
-
const pkg = await readPackageJson(storeEntry.packageDir);
|
|
1392
|
-
if (previousPkg) await removeBinLinks(consumerPath, previousPkg);
|
|
1393
|
-
const binLinks = pkg ? await createBinLinks(consumerPath, storeEntry.name, pkg) : 0;
|
|
1394
|
-
if (binLinks > 0) verbose(`[inject] Created ${binLinks} bin link(s)`);
|
|
1395
|
-
return {
|
|
1396
|
-
copied,
|
|
1397
|
-
removed,
|
|
1398
|
-
skipped,
|
|
1399
|
-
binLinks,
|
|
1400
|
-
cacheInvalidations
|
|
1401
|
-
};
|
|
1402
|
-
}
|
|
1403
|
-
/**
|
|
1404
|
-
* Back up the existing installed version of a package before overwriting.
|
|
1405
|
-
*/
|
|
1406
|
-
async function backupExisting(consumerPath, packageName, pm) {
|
|
1407
|
-
const installedDir = await resolveInjectionTarget(consumerPath, packageName, pm, void 0, { warnOnFallback: false });
|
|
1408
|
-
if (!await exists(installedDir)) return false;
|
|
1409
|
-
const backupDir = getConsumerBackupPath(consumerPath, packageName);
|
|
1410
|
-
await removeDir(backupDir);
|
|
1411
|
-
await copyDir(installedDir, backupDir);
|
|
1412
|
-
return true;
|
|
1413
|
-
}
|
|
1414
|
-
/**
|
|
1415
|
-
* Restore a backed-up package to node_modules.
|
|
1416
|
-
*/
|
|
1417
|
-
async function restoreBackup(consumerPath, packageName, pm, version) {
|
|
1418
|
-
const backupDir = getConsumerBackupPath(consumerPath, packageName);
|
|
1419
|
-
if (!await exists(backupDir)) return false;
|
|
1420
|
-
const targetDir = await resolveInjectionTarget(consumerPath, packageName, pm, version);
|
|
1421
|
-
const currentPkg = await readPackageJson(targetDir);
|
|
1422
|
-
if (currentPkg) await removeBinLinks(consumerPath, currentPkg);
|
|
1423
|
-
await removeDir(targetDir);
|
|
1424
|
-
await copyDir(backupDir, targetDir);
|
|
1425
|
-
const restoredPkg = await readPackageJson(isDryRun() ? backupDir : targetDir);
|
|
1426
|
-
if (restoredPkg) {
|
|
1427
|
-
const binLinks = await createBinLinks(consumerPath, packageName, restoredPkg);
|
|
1428
|
-
if (binLinks > 0) verbose(`[restore] Restored ${binLinks} original bin link(s) for ${packageName}`);
|
|
1429
|
-
}
|
|
1430
|
-
await removeDir(backupDir);
|
|
1431
|
-
return true;
|
|
1432
|
-
}
|
|
1433
|
-
/**
|
|
1434
|
-
* Remove an injected package from node_modules.
|
|
1435
|
-
*/
|
|
1436
|
-
async function removeInjected(consumerPath, packageName, pm, version) {
|
|
1437
|
-
const directPath = getNodeModulesPackagePath(consumerPath, packageName);
|
|
1438
|
-
const targetDir = await resolveInjectionTarget(consumerPath, packageName, pm, version);
|
|
1439
|
-
const pkg = await readPackageJson(targetDir);
|
|
1440
|
-
if (pkg) await removeBinLinks(consumerPath, pkg);
|
|
1441
|
-
await removeDir(targetDir);
|
|
1442
|
-
if (resolve(targetDir) !== resolve(directPath)) await removeDir(directPath);
|
|
1443
|
-
}
|
|
1444
|
-
/**
|
|
1445
|
-
* Check for missing transitive dependencies.
|
|
1446
|
-
* Returns a list of dependency names that are in the linked package's
|
|
1447
|
-
* dependencies but not installed in the consumer's node_modules.
|
|
1448
|
-
*/
|
|
1449
|
-
async function checkMissingDeps(storeEntry, consumerPath, pm) {
|
|
1450
|
-
const pkg = await readPackageJson(storeEntry.packageDir);
|
|
1451
|
-
if (!pkg) return [];
|
|
1452
|
-
const allDeps = {
|
|
1453
|
-
...pkg.dependencies,
|
|
1454
|
-
...Object.fromEntries(Object.entries(pkg.peerDependencies ?? {}).filter(([name]) => !pkg.peerDependenciesMeta?.[name]?.optional))
|
|
1455
|
-
};
|
|
1456
|
-
if (Object.keys(allDeps).length === 0) return [];
|
|
1457
|
-
const depNames = Object.keys(allDeps);
|
|
1458
|
-
return (await Promise.all(depNames.map(async (dep) => ({
|
|
1459
|
-
dep,
|
|
1460
|
-
installed: await isDependencyInstalledForPackage(dep, storeEntry, consumerPath, pm)
|
|
1461
|
-
})))).filter((r) => !r.installed).map((r) => r.dep);
|
|
1462
|
-
}
|
|
1463
|
-
async function isDependencyInstalledForPackage(dependencyName, storeEntry, consumerPath, pm) {
|
|
1464
|
-
if (await exists(join(consumerPath, "node_modules", dependencyName))) return true;
|
|
1465
|
-
if (!pm) return false;
|
|
1466
|
-
return dependencyVisibleFromDirectory(await resolveInjectionTarget(consumerPath, storeEntry.name, pm, storeEntry.version, { warnOnFallback: false }), dependencyName);
|
|
1467
|
-
}
|
|
1468
|
-
async function dependencyVisibleFromDirectory(startDir, dependencyName) {
|
|
1469
|
-
let dir = await realpath(startDir).catch((err) => {
|
|
1470
|
-
if (isNodeError(err) && err.code === "ENOENT") return startDir;
|
|
1471
|
-
throw err;
|
|
1472
|
-
});
|
|
1473
|
-
for (;;) {
|
|
1474
|
-
if (await exists(join(dir, "node_modules", dependencyName))) return true;
|
|
1475
|
-
const parent = dirname(dir);
|
|
1476
|
-
if (parent === dir) return false;
|
|
1477
|
-
dir = parent;
|
|
1478
|
-
}
|
|
1479
|
-
}
|
|
1480
|
-
/**
|
|
1481
|
-
* Resolve the actual target directory in node_modules for a given
|
|
1482
|
-
* package manager strategy.
|
|
1483
|
-
*/
|
|
1484
|
-
async function resolveInjectionTarget(consumerPath, packageName, pm, version, options = {}) {
|
|
1485
|
-
const directPath = getNodeModulesPackagePath(consumerPath, packageName);
|
|
1486
|
-
const resolvedPackageManager = (await inspectProjectPackageManager(consumerPath)).resolve(pm);
|
|
1487
|
-
if (!resolvedPackageManager.nodeModulesCompatible) throw new Error(resolvedPackageManager.incompatibilityReason);
|
|
1488
|
-
const storeKind = resolvedPackageManager.layout === "pnpm" || resolvedPackageManager.layout === "yarn-pnpm" ? resolvedPackageManager.layout : null;
|
|
1489
|
-
if (!storeKind) {
|
|
1490
|
-
if (resolvedPackageManager.layout === "bun") return resolveBunTarget(consumerPath, directPath, packageName);
|
|
1491
|
-
return directPath;
|
|
1492
|
-
}
|
|
1493
|
-
const virtualStoreDirs = storeKind === "pnpm" ? await getPnpmVirtualStoreDirs(consumerPath) : await getYarnPnpmStoreDirs(consumerPath, resolvedPackageManager.virtualStoreFolder);
|
|
1494
|
-
try {
|
|
1495
|
-
const realPath = await resolvePackageEntrySymlink(directPath);
|
|
1496
|
-
if (realPath) {
|
|
1497
|
-
if (!(storeKind === "pnpm" ? await isPnpmVirtualStorePackageRealPath(virtualStoreDirs, packageName, realPath) : await isYarnPnpmStorePackageRealPath(virtualStoreDirs, realPath))) throw new Error(`Refusing to inject ${packageName}: node_modules entry resolves outside a configured ${storeKindLabel(storeKind)} virtual store (${realPath})`);
|
|
1498
|
-
await validateResolvedPackageIdentity(realPath, packageName, void 0, storeKind);
|
|
1499
|
-
verbose(`[inject] ${storeKindLabel(storeKind)}: resolved symlink → ${realPath}`);
|
|
1500
|
-
return realPath;
|
|
1501
|
-
}
|
|
1502
|
-
} catch (err) {
|
|
1503
|
-
if (isNodeError(err) && err.code === "ENOENT") {} else {
|
|
1504
|
-
if (isNodeError(err)) verbose(`${storeKindLabel(storeKind)} symlink resolution error: ${err instanceof Error ? err.message : String(err)}`);
|
|
1505
|
-
throw err;
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1508
|
-
const existingStoreDirs = [];
|
|
1509
|
-
for (const storeDir of virtualStoreDirs) if (await exists(storeDir)) existingStoreDirs.push(storeDir);
|
|
1510
|
-
if (existingStoreDirs.length > 0) {
|
|
1511
|
-
if (!await isDeclaredConsumerDependency(consumerPath, packageName)) {
|
|
1512
|
-
verbose(`[inject] ${storeKindLabel(storeKind)}: ${packageName} is not declared by the consumer, skipping virtual store scan`);
|
|
1513
|
-
return directPath;
|
|
1514
|
-
}
|
|
1515
|
-
if (storeKind === "yarn-pnpm") {
|
|
1516
|
-
const matches = [];
|
|
1517
|
-
for (const storeDir of existingStoreDirs) {
|
|
1518
|
-
verbose(`[inject] yarn-pnpm: scanning ${relative(consumerPath, storeDir) || "."} for ${packageName}`);
|
|
1519
|
-
const candidate = await resolveYarnPnpmCandidate(storeDir, packageName, version);
|
|
1520
|
-
if (candidate) matches.push(candidate);
|
|
1521
|
-
}
|
|
1522
|
-
const candidate = requireSingleVirtualStoreCandidate(packageName, storeKind, matches);
|
|
1523
|
-
if (candidate) {
|
|
1524
|
-
verbose(`[inject] yarn-pnpm: found in virtual store → ${candidate}`);
|
|
1525
|
-
if (options.repairMissingLink) await repairMissingVirtualStoreLink(directPath, candidate, packageName, storeKind);
|
|
1526
|
-
return candidate;
|
|
1527
|
-
}
|
|
1528
|
-
}
|
|
1529
|
-
if (storeKind === "pnpm") {
|
|
1530
|
-
const encodedName = packageName.replaceAll("/", "+");
|
|
1531
|
-
for (const pnpmDir of existingStoreDirs) {
|
|
1532
|
-
verbose(`[inject] pnpm: scanning ${relative(consumerPath, pnpmDir) || "."} for ${packageName}`);
|
|
1533
|
-
if (version) {
|
|
1534
|
-
const exactEntry = `${encodedName}@${version}`;
|
|
1535
|
-
const candidate = await resolvePnpmCandidate(pnpmDir, packageName, version, join(pnpmDir, exactEntry, "node_modules", packageName));
|
|
1536
|
-
if (candidate) {
|
|
1537
|
-
verbose(`[inject] pnpm: exact version match in virtual store → ${candidate}`);
|
|
1538
|
-
if (options.repairMissingLink) await repairMissingVirtualStoreLink(directPath, candidate, packageName, storeKind);
|
|
1539
|
-
return candidate;
|
|
1540
|
-
}
|
|
1541
|
-
}
|
|
1542
|
-
const entries = await readdir(pnpmDir);
|
|
1543
|
-
const matches = [];
|
|
1544
|
-
for (const entry of entries) if (matchesPnpmPackageEntry(encodedName, version, entry)) {
|
|
1545
|
-
const candidate = await resolvePnpmCandidate(pnpmDir, packageName, version, join(pnpmDir, entry, "node_modules", packageName));
|
|
1546
|
-
if (candidate) matches.push(candidate);
|
|
1547
|
-
}
|
|
1548
|
-
const candidate = requireSingleVirtualStoreCandidate(packageName, storeKind, matches);
|
|
1549
|
-
if (candidate) {
|
|
1550
|
-
verbose(`[inject] pnpm: found in virtual store → ${candidate}`);
|
|
1551
|
-
if (options.repairMissingLink) await repairMissingVirtualStoreLink(directPath, candidate, packageName, storeKind);
|
|
1552
|
-
return candidate;
|
|
1553
|
-
}
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
if (options.warnOnFallback !== false) {
|
|
1558
|
-
if (await isDeclaredConsumerDependency(consumerPath, packageName)) {
|
|
1559
|
-
const pmName = storeKind === "pnpm" ? "pnpm" : "yarn";
|
|
1560
|
-
consola.warn(`${packageName} is in package.json but not installed in the ${storeKindLabel(storeKind)} virtual store, so Knarr is linking it at node_modules/${packageName} directly. Run \`${pmName} install\` and then \`knarr add ${packageName}\` to update the installed copy instead.`);
|
|
1561
|
-
} else verbose(`[inject] ${storeKindLabel(storeKind)}: ${packageName} not installed yet, linking at node_modules/${packageName}`);
|
|
1562
|
-
}
|
|
1563
|
-
return directPath;
|
|
1564
|
-
}
|
|
1565
|
-
function storeKindLabel(kind) {
|
|
1566
|
-
return kind === "pnpm" ? "pnpm" : "Yarn pnpm-linker";
|
|
1567
|
-
}
|
|
1568
|
-
async function resolveBunTarget(consumerPath, directPath, packageName) {
|
|
1569
|
-
try {
|
|
1570
|
-
if (!(await lstat(directPath)).isSymbolicLink()) return directPath;
|
|
1571
|
-
} catch (err) {
|
|
1572
|
-
if (isNodeError(err) && err.code === "ENOENT") return directPath;
|
|
1573
|
-
throw err;
|
|
1574
|
-
}
|
|
1575
|
-
const realPath = await realpath(directPath);
|
|
1576
|
-
const bunStoreDir = join(consumerPath, "node_modules", ".bun");
|
|
1577
|
-
if (!isPathInside(await realpath(bunStoreDir).catch((err) => {
|
|
1578
|
-
if (isNodeError(err) && err.code === "ENOENT") return bunStoreDir;
|
|
1579
|
-
throw err;
|
|
1580
|
-
}), realPath)) throw new Error(`Refusing to inject ${packageName}: Bun target resolves outside the local node_modules/.bun store (${realPath})`);
|
|
1581
|
-
await validateResolvedPackageIdentity(realPath, packageName, void 0, "Bun isolated");
|
|
1582
|
-
verbose(`[inject] Bun isolated: resolved symlink → ${realPath}`);
|
|
1583
|
-
return realPath;
|
|
1584
|
-
}
|
|
1585
|
-
function isPathInside(parentDir, childPath) {
|
|
1586
|
-
const rel = relative(resolve(parentDir), resolve(childPath));
|
|
1587
|
-
return rel === "" || !!rel && !rel.startsWith("..") && !isAbsolute(rel);
|
|
1588
|
-
}
|
|
1589
|
-
async function resolvePackageEntrySymlink(linkPath) {
|
|
1590
|
-
if (!(await lstat(linkPath)).isSymbolicLink()) return null;
|
|
1591
|
-
return realpath(linkPath);
|
|
1592
|
-
}
|
|
1593
|
-
async function validateResolvedPackageIdentity(targetDir, packageName, version, storeKind) {
|
|
1594
|
-
const label = storeKind === "Bun isolated" ? storeKind : storeKindLabel(storeKind);
|
|
1595
|
-
const pkg = await readPackageJson(targetDir);
|
|
1596
|
-
if (!pkg) return;
|
|
1597
|
-
if (pkg.name && pkg.name !== packageName) throw new Error(`Refusing to inject ${packageName}: ${label} target contains package "${pkg.name}"`);
|
|
1598
|
-
if (version && pkg.version && pkg.version !== version) throw new Error(`Refusing to inject ${packageName}@${version}: ${label} target contains version ${pkg.version}`);
|
|
1599
|
-
}
|
|
1600
|
-
async function repairMissingVirtualStoreLink(directPath, targetDir, packageName, storeKind) {
|
|
1601
|
-
let removeDanglingSymlink = false;
|
|
1602
|
-
try {
|
|
1603
|
-
if (!(await lstat(directPath)).isSymbolicLink()) return;
|
|
1604
|
-
removeDanglingSymlink = true;
|
|
1605
|
-
} catch (err) {
|
|
1606
|
-
if (!isNodeError(err) || err.code !== "ENOENT") throw err;
|
|
1607
|
-
}
|
|
1608
|
-
const linkParent = dirname(directPath);
|
|
1609
|
-
if (isDryRun()) {
|
|
1610
|
-
const targetRelative = relative(linkParent, targetDir);
|
|
1611
|
-
verbose(`[inject] ${storeKindLabel(storeKind)}: would restore node_modules symlink for ${packageName} → ${targetRelative}`);
|
|
1612
|
-
recordMutation({
|
|
1613
|
-
type: "write",
|
|
1614
|
-
path: directPath,
|
|
1615
|
-
dest: targetDir,
|
|
1616
|
-
detail: `${storeKindLabel(storeKind)} package symlink`
|
|
1617
|
-
});
|
|
1618
|
-
return;
|
|
1619
|
-
}
|
|
1620
|
-
const isWindows = platform() === "win32";
|
|
1621
|
-
await ensureDir(linkParent);
|
|
1622
|
-
const linkParentReal = await realpath(linkParent).catch(() => linkParent);
|
|
1623
|
-
const targetRelative = relative(linkParentReal, targetDir);
|
|
1624
|
-
verbose(`[inject] ${storeKindLabel(storeKind)}: restoring node_modules symlink for ${packageName} → ${targetRelative}`);
|
|
1625
|
-
if (removeDanglingSymlink) await rm(directPath, { force: true });
|
|
1626
|
-
await symlink(isWindows ? targetDir : targetRelative, directPath, isWindows ? "junction" : "dir");
|
|
1627
|
-
}
|
|
1628
|
-
async function resolvePnpmCandidate(pnpmDir, packageName, version, candidatePath) {
|
|
1629
|
-
if (!isPnpmVirtualStorePackagePathFromRoot(pnpmDir, packageName, candidatePath)) return null;
|
|
1630
|
-
try {
|
|
1631
|
-
const [pnpmRoot, realPath] = await Promise.all([realpath(pnpmDir), realpath(candidatePath)]);
|
|
1632
|
-
if (!isPnpmVirtualStorePackagePathFromRoot(pnpmRoot, packageName, realPath)) throw new Error(`Refusing to inject ${packageName}: virtual store candidate resolves outside a configured pnpm virtual store (${realPath})`);
|
|
1633
|
-
await validateResolvedPackageIdentity(realPath, packageName, version, "pnpm");
|
|
1634
|
-
return realPath;
|
|
1635
|
-
} catch (err) {
|
|
1636
|
-
if (isNodeError(err) && err.code === "ENOENT") return null;
|
|
1637
|
-
throw err;
|
|
1638
|
-
}
|
|
1639
|
-
}
|
|
1640
|
-
async function resolveYarnPnpmCandidate(storeDir, packageName, version) {
|
|
1641
|
-
const entries = await readdir(storeDir);
|
|
1642
|
-
const matches = [];
|
|
1643
|
-
for (const entry of entries) {
|
|
1644
|
-
const candidatePath = join(storeDir, entry, "package");
|
|
1645
|
-
const pkg = await readPackageJson(candidatePath);
|
|
1646
|
-
if (!pkg || pkg.name !== packageName) continue;
|
|
1647
|
-
if (version && pkg.version !== version) continue;
|
|
1648
|
-
const [storeRoot, realPath] = await Promise.all([realpath(storeDir), realpath(candidatePath)]);
|
|
1649
|
-
if (!isYarnPnpmStorePackagePathFromRoot(storeRoot, realPath)) throw new Error(`Refusing to inject ${packageName}: virtual store candidate resolves outside a configured Yarn pnpm-linker virtual store (${realPath})`);
|
|
1650
|
-
matches.push(realPath);
|
|
1651
|
-
}
|
|
1652
|
-
return requireSingleVirtualStoreCandidate(packageName, "yarn-pnpm", matches);
|
|
1653
|
-
}
|
|
1654
|
-
function matchesPnpmPackageEntry(encodedName, version, entry) {
|
|
1655
|
-
if (!version) return entry.startsWith(`${encodedName}@`);
|
|
1656
|
-
const exactEntry = `${encodedName}@${version}`;
|
|
1657
|
-
return entry === exactEntry || entry.startsWith(`${exactEntry}_`);
|
|
1658
|
-
}
|
|
1659
|
-
function requireSingleVirtualStoreCandidate(packageName, storeKind, matches) {
|
|
1660
|
-
if (matches.length <= 1) return matches[0] ?? null;
|
|
1661
|
-
throw new Error(`Refusing to repair ${packageName}: multiple ${storeKindLabel(storeKind)} virtual-store entries match. Run your package manager's install command, then try again.`);
|
|
1662
|
-
}
|
|
1663
|
-
async function getPnpmVirtualStoreDirs(consumerPath) {
|
|
1664
|
-
const nodeModulesDir = join(consumerPath, "node_modules");
|
|
1665
|
-
const dirs = [];
|
|
1666
|
-
const defaultDir = join(nodeModulesDir, ".pnpm");
|
|
1667
|
-
if (await isLocalVirtualStoreDir(consumerPath, defaultDir)) dirs.push(defaultDir);
|
|
1668
|
-
const configured = await readConfiguredPnpmVirtualStoreDir(nodeModulesDir);
|
|
1669
|
-
if (!configured) return dirs;
|
|
1670
|
-
const configuredDir = isAbsolute(configured) ? configured : resolve(nodeModulesDir, configured);
|
|
1671
|
-
if (!await isLocalVirtualStoreDir(consumerPath, configuredDir)) {
|
|
1672
|
-
verbose(`[inject] pnpm: ignoring external virtualStoreDir ${configuredDir}`);
|
|
1673
|
-
return dirs;
|
|
1674
|
-
}
|
|
1675
|
-
if (!dirs.some((dir) => resolve(dir) === resolve(configuredDir))) dirs.push(configuredDir);
|
|
1676
|
-
return dirs;
|
|
1677
|
-
}
|
|
1678
|
-
async function getYarnPnpmStoreDirs(consumerPath, configured) {
|
|
1679
|
-
const nodeModulesDir = join(consumerPath, "node_modules");
|
|
1680
|
-
const dirs = [];
|
|
1681
|
-
const defaultDir = join(nodeModulesDir, ".store");
|
|
1682
|
-
if (await isLocalVirtualStoreDir(consumerPath, defaultDir)) dirs.push(defaultDir);
|
|
1683
|
-
if (!configured) return dirs;
|
|
1684
|
-
const configuredDir = isAbsolute(configured) ? configured : resolve(consumerPath, configured);
|
|
1685
|
-
if (!await isLocalVirtualStoreDir(consumerPath, configuredDir)) {
|
|
1686
|
-
verbose(`[inject] yarn-pnpm: ignoring external pnpmStoreFolder ${configuredDir}`);
|
|
1687
|
-
return dirs;
|
|
1688
|
-
}
|
|
1689
|
-
if (!dirs.some((dir) => resolve(dir) === resolve(configuredDir))) dirs.push(configuredDir);
|
|
1690
|
-
return dirs;
|
|
1691
|
-
}
|
|
1692
|
-
async function isLocalVirtualStoreDir(consumerPath, storeDir) {
|
|
1693
|
-
return isPathInside(await realpath(consumerPath).catch(() => resolve(consumerPath)), await realpath(storeDir).catch((err) => {
|
|
1694
|
-
if (isNodeError(err) && err.code === "ENOENT") return resolve(storeDir);
|
|
1695
|
-
throw err;
|
|
1696
|
-
}));
|
|
1697
|
-
}
|
|
1698
|
-
async function readConfiguredPnpmVirtualStoreDir(nodeModulesDir) {
|
|
1699
|
-
try {
|
|
1700
|
-
return parsePnpmVirtualStoreDir(await readFile(join(nodeModulesDir, ".modules.yaml"), "utf-8"));
|
|
1701
|
-
} catch (err) {
|
|
1702
|
-
if (isNodeError(err) && err.code === "ENOENT") return null;
|
|
1703
|
-
throw err;
|
|
1704
|
-
}
|
|
1705
|
-
}
|
|
1706
|
-
function parsePnpmVirtualStoreDir(content) {
|
|
1707
|
-
try {
|
|
1708
|
-
const virtualStoreDir = stringField(parseJsonObject(content), "virtualStoreDir")?.trim();
|
|
1709
|
-
if (virtualStoreDir) return virtualStoreDir;
|
|
1710
|
-
} catch {}
|
|
1711
|
-
const match = content.match(/^virtualStoreDir:\s*(.+?)\s*$/m);
|
|
1712
|
-
if (!match) return null;
|
|
1713
|
-
let value = (match[1] ?? "").trim().replace(/\s+#.*$/, "");
|
|
1714
|
-
if (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
|
1715
|
-
return value || null;
|
|
1716
|
-
}
|
|
1717
|
-
async function isPnpmVirtualStorePackageRealPath(pnpmDirs, packageName, targetPath) {
|
|
1718
|
-
for (const pnpmDir of pnpmDirs) try {
|
|
1719
|
-
if (isPnpmVirtualStorePackagePathFromRoot(await realpath(pnpmDir), packageName, targetPath)) return true;
|
|
1720
|
-
} catch (err) {
|
|
1721
|
-
if (isNodeError(err) && err.code === "ENOENT") continue;
|
|
1722
|
-
throw err;
|
|
1723
|
-
}
|
|
1724
|
-
return false;
|
|
1725
|
-
}
|
|
1726
|
-
async function isYarnPnpmStorePackageRealPath(storeDirs, targetPath) {
|
|
1727
|
-
for (const storeDir of storeDirs) try {
|
|
1728
|
-
if (isYarnPnpmStorePackagePathFromRoot(await realpath(storeDir), targetPath)) return true;
|
|
1729
|
-
} catch (err) {
|
|
1730
|
-
if (isNodeError(err) && err.code === "ENOENT") continue;
|
|
1731
|
-
throw err;
|
|
1732
|
-
}
|
|
1733
|
-
return false;
|
|
1734
|
-
}
|
|
1735
|
-
function isPnpmVirtualStorePackagePathFromRoot(pnpmDir, packageName, targetPath) {
|
|
1736
|
-
if (!isPathInside(pnpmDir, targetPath)) return false;
|
|
1737
|
-
const rel = relative(pnpmDir, targetPath).replace(/\\/g, "/");
|
|
1738
|
-
const suffix = `node_modules/${packageName}`.replace(/\\/g, "/");
|
|
1739
|
-
return rel === suffix || rel.endsWith(`/${suffix}`);
|
|
1740
|
-
}
|
|
1741
|
-
function isYarnPnpmStorePackagePathFromRoot(storeDir, targetPath) {
|
|
1742
|
-
if (!isPathInside(storeDir, targetPath)) return false;
|
|
1743
|
-
const parts = relative(storeDir, targetPath).replace(/\\/g, "/").split("/");
|
|
1744
|
-
return parts.length === 2 && parts[1] === "package";
|
|
1745
|
-
}
|
|
1746
|
-
/** Whether the consumer's package.json declares packageName in any dependency field. */
|
|
1747
|
-
async function isDeclaredConsumerDependency(consumerPath, packageName) {
|
|
1748
|
-
const pkg = await readPackageJson(consumerPath);
|
|
1749
|
-
if (!pkg) return false;
|
|
1750
|
-
return Boolean(pkg.dependencies?.[packageName] || pkg.devDependencies?.[packageName] || pkg.optionalDependencies?.[packageName] || pkg.peerDependencies?.[packageName]);
|
|
1751
|
-
}
|
|
1752
|
-
async function readPackageJson(dir) {
|
|
1753
|
-
try {
|
|
1754
|
-
const content = await readFile(join(dir, "package.json"), "utf-8");
|
|
1755
|
-
return asPackageJson(parseJsonObject(content, join(dir, "package.json")));
|
|
1756
|
-
} catch (err) {
|
|
1757
|
-
if (isNodeError(err) && err.code !== "ENOENT") consola.warn(`Failed to read package.json in ${dir}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1758
|
-
return null;
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
// src/core/tracker.ts
|
|
1762
|
-
/** Read the consumer state file, or return an empty state if not found */
|
|
1763
|
-
async function readConsumerState(consumerPath) {
|
|
1764
|
-
const { state } = await readConsumerStateSafe(consumerPath);
|
|
1765
|
-
return state;
|
|
1766
|
-
}
|
|
1767
|
-
/**
|
|
1768
|
-
* Read consumer state with reliability information.
|
|
1769
|
-
* Returns `reliable: true` when the state is trustworthy (valid file or ENOENT).
|
|
1770
|
-
* Returns `reliable: false` when the file exists but is corrupt/unreadable,
|
|
1771
|
-
* meaning the consumer might have links we can't see.
|
|
1772
|
-
*/
|
|
1773
|
-
async function readConsumerStateSafe(consumerPath) {
|
|
1774
|
-
const statePath = getConsumerStatePath(consumerPath);
|
|
1775
|
-
try {
|
|
1776
|
-
const content = await readFile(statePath, "utf-8");
|
|
1777
|
-
const state = parseConsumerState(parseJson(content));
|
|
1778
|
-
if (!state) {
|
|
1779
|
-
consola.warn(`Invalid consumer state in ${statePath}, using defaults`);
|
|
1780
|
-
return {
|
|
1781
|
-
state: {
|
|
1782
|
-
version: "1",
|
|
1783
|
-
links: ownRecord()
|
|
1784
|
-
},
|
|
1785
|
-
reliable: false
|
|
1786
|
-
};
|
|
1787
|
-
}
|
|
1788
|
-
return {
|
|
1789
|
-
state,
|
|
1790
|
-
reliable: true
|
|
1791
|
-
};
|
|
1792
|
-
} catch (err) {
|
|
1793
|
-
if (isNodeError(err) && err.code === "ENOENT") return {
|
|
1794
|
-
state: {
|
|
1795
|
-
version: "1",
|
|
1796
|
-
links: ownRecord()
|
|
1797
|
-
},
|
|
1798
|
-
reliable: true
|
|
1799
|
-
};
|
|
1800
|
-
consola.warn(`Failed to read consumer state: ${err instanceof Error ? err.message : String(err)}`);
|
|
1801
|
-
return {
|
|
1802
|
-
state: {
|
|
1803
|
-
version: "1",
|
|
1804
|
-
links: ownRecord()
|
|
1805
|
-
},
|
|
1806
|
-
reliable: false
|
|
1807
|
-
};
|
|
1808
|
-
}
|
|
1809
|
-
}
|
|
1810
|
-
async function writeConsumerState(consumerPath, state) {
|
|
1811
|
-
await ensureDir(getConsumerKnarrDir(consumerPath));
|
|
1812
|
-
const statePath = getConsumerStatePath(consumerPath);
|
|
1813
|
-
await atomicWriteFile(statePath, JSON.stringify(state, null, 2));
|
|
1814
|
-
}
|
|
1815
|
-
/**
|
|
1816
|
-
* Read, change, and write `.knarr/state.json` under its file lock.
|
|
1817
|
-
* Creates the file when it is missing, skips the write when `mutate` changes nothing,
|
|
1818
|
-
* and throws instead of overwriting a corrupt file, which may hold links we can't read.
|
|
1819
|
-
*/
|
|
1820
|
-
async function updateConsumerState(consumerPath, mutate) {
|
|
1821
|
-
const statePath = getConsumerStatePath(consumerPath);
|
|
1822
|
-
await withFileLock(statePath, async () => {
|
|
1823
|
-
const { state, reliable } = await readConsumerStateSafe(consumerPath);
|
|
1824
|
-
if (!reliable) throw new Error(`Consumer state in ${statePath} is corrupt — refusing to write to avoid destroying existing links. Delete .knarr/state.json and re-run 'knarr add' for each package.`);
|
|
1825
|
-
const before = JSON.stringify(state);
|
|
1826
|
-
mutate(state);
|
|
1827
|
-
if (JSON.stringify(state) === before && await exists(statePath)) return;
|
|
1828
|
-
await writeConsumerState(consumerPath, state);
|
|
1829
|
-
});
|
|
1830
|
-
}
|
|
1831
|
-
/** Add or update a link entry in the consumer state */
|
|
1832
|
-
async function addLink(consumerPath, packageName, entry) {
|
|
1833
|
-
await updateConsumerState(consumerPath, (state) => {
|
|
1834
|
-
state.links[packageName] = entry;
|
|
1835
|
-
});
|
|
1836
|
-
}
|
|
1837
|
-
/** Remove a link entry from the consumer state */
|
|
1838
|
-
async function removeLink(consumerPath, packageName) {
|
|
1839
|
-
await updateConsumerState(consumerPath, (state) => {
|
|
1840
|
-
delete state.links[packageName];
|
|
1841
|
-
});
|
|
1842
|
-
}
|
|
1843
|
-
/** Get a specific link entry */
|
|
1844
|
-
async function getLink(consumerPath, packageName) {
|
|
1845
|
-
return (await readConsumerState(consumerPath)).links[packageName] ?? null;
|
|
1846
|
-
}
|
|
1847
|
-
/**
|
|
1848
|
-
* Read the global consumers registry with reliability information.
|
|
1849
|
-
* `reliable: false` means the file exists but is corrupt or unreadable, so
|
|
1850
|
-
* writing the returned (empty) registry back would drop registrations.
|
|
1851
|
-
*/
|
|
1852
|
-
async function readConsumersRegistrySafe() {
|
|
1853
|
-
const regPath = getConsumersPath();
|
|
1854
|
-
try {
|
|
1855
|
-
const registry = parseConsumersRegistry(parseJson(await readFile(regPath, "utf-8")));
|
|
1856
|
-
if (!registry) {
|
|
1857
|
-
consola.warn(`Invalid consumers registry in ${regPath}, using empty registry`);
|
|
1858
|
-
return {
|
|
1859
|
-
registry: ownRecord(),
|
|
1860
|
-
reliable: false
|
|
1861
|
-
};
|
|
1862
|
-
}
|
|
1863
|
-
return {
|
|
1864
|
-
registry,
|
|
1865
|
-
reliable: true
|
|
1866
|
-
};
|
|
1867
|
-
} catch (err) {
|
|
1868
|
-
if (isNodeError(err) && err.code === "ENOENT") return {
|
|
1869
|
-
registry: ownRecord(),
|
|
1870
|
-
reliable: true
|
|
1871
|
-
};
|
|
1872
|
-
consola.warn(`Failed to read consumers registry: ${err instanceof Error ? err.message : String(err)}`);
|
|
1873
|
-
return {
|
|
1874
|
-
registry: ownRecord(),
|
|
1875
|
-
reliable: false
|
|
1876
|
-
};
|
|
1877
|
-
}
|
|
1878
|
-
}
|
|
1879
|
-
/** Read the global consumers registry */
|
|
1880
|
-
async function readConsumersRegistry() {
|
|
1881
|
-
return (await readConsumersRegistrySafe()).registry;
|
|
1882
|
-
}
|
|
1883
|
-
function corruptRegistryHint() {
|
|
1884
|
-
return `Fix or delete ${getConsumersPath()}, then re-run 'knarr add' in each consumer project.`;
|
|
1885
|
-
}
|
|
1886
|
-
var CorruptRegistryError = class extends Error {
|
|
1887
|
-
constructor() {
|
|
1888
|
-
super(`Consumers registry ${getConsumersPath()} is corrupt; refusing to overwrite it. ${corruptRegistryHint()}`);
|
|
1889
|
-
this.name = "CorruptRegistryError";
|
|
1890
|
-
}
|
|
1891
|
-
};
|
|
1892
|
-
async function readConsumersRegistryForWrite() {
|
|
1893
|
-
const { registry, reliable } = await readConsumersRegistrySafe();
|
|
1894
|
-
if (!reliable) throw new CorruptRegistryError();
|
|
1895
|
-
return registry;
|
|
1896
|
-
}
|
|
1897
|
-
/** Write the global consumers registry */
|
|
1898
|
-
async function writeConsumersRegistry(registry) {
|
|
1899
|
-
const regPath = getConsumersPath();
|
|
1900
|
-
await ensurePrivateDir(dirname(getConsumersPath()));
|
|
1901
|
-
await atomicWriteFile(regPath, JSON.stringify(registry, null, 2));
|
|
1902
|
-
}
|
|
1903
|
-
/** Register a consumer for a package */
|
|
1904
|
-
async function registerConsumer(packageName, consumerPath) {
|
|
1905
|
-
await withFileLock(getConsumersPath(), async () => {
|
|
1906
|
-
const registry = await readConsumersRegistryForWrite();
|
|
1907
|
-
if (!registry[packageName]) registry[packageName] = [];
|
|
1908
|
-
const normalized = normalizePath(consumerPath);
|
|
1909
|
-
if (!registry[packageName].includes(normalized)) registry[packageName].push(normalized);
|
|
1910
|
-
await writeConsumersRegistry(registry);
|
|
1911
|
-
});
|
|
1912
|
-
}
|
|
1913
|
-
/** Unregister a consumer for a package */
|
|
1914
|
-
async function unregisterConsumer(packageName, consumerPath) {
|
|
1915
|
-
await withFileLock(getConsumersPath(), async () => {
|
|
1916
|
-
const registry = await readConsumersRegistryForWrite();
|
|
1917
|
-
if (!registry[packageName]) return;
|
|
1918
|
-
const normalized = normalizePath(consumerPath);
|
|
1919
|
-
registry[packageName] = registry[packageName].filter((p) => p !== normalized);
|
|
1920
|
-
if (registry[packageName].length === 0) delete registry[packageName];
|
|
1921
|
-
await writeConsumersRegistry(registry);
|
|
1922
|
-
});
|
|
1923
|
-
}
|
|
1924
|
-
/** Get all consumers for a package */
|
|
1925
|
-
async function getConsumers(packageName) {
|
|
1926
|
-
return (await readConsumersRegistry())[packageName] ?? [];
|
|
1927
|
-
}
|
|
1928
|
-
/**
|
|
1929
|
-
* Clean stale consumers — remove registrations for directories that no longer exist.
|
|
1930
|
-
* Returns the number of stale entries removed.
|
|
1931
|
-
*/
|
|
1932
|
-
async function cleanStaleConsumers(options = {}) {
|
|
1933
|
-
const regPath = getConsumersPath();
|
|
1934
|
-
let removedConsumers = 0;
|
|
1935
|
-
let removedPackages = 0;
|
|
1936
|
-
let removedMissingLinks = 0;
|
|
1937
|
-
let skippedUnreliableConsumers = 0;
|
|
1938
|
-
await withFileLock(regPath, async () => {
|
|
1939
|
-
const registry = await readConsumersRegistryForWrite();
|
|
1940
|
-
const updated = ownRecord();
|
|
1941
|
-
for (const [pkgName, consumers] of Object.entries(registry)) {
|
|
1942
|
-
const results = await Promise.all(consumers.map(async (consumerPath) => {
|
|
1943
|
-
if (!await exists(consumerPath)) return {
|
|
1944
|
-
consumerPath,
|
|
1945
|
-
valid: false,
|
|
1946
|
-
reason: "missing-dir"
|
|
1947
|
-
};
|
|
1948
|
-
if (options.removeMissingLinks) {
|
|
1949
|
-
const { state, reliable } = await readConsumerStateSafe(consumerPath);
|
|
1950
|
-
if (!reliable) {
|
|
1951
|
-
skippedUnreliableConsumers++;
|
|
1952
|
-
return {
|
|
1953
|
-
consumerPath,
|
|
1954
|
-
valid: true,
|
|
1955
|
-
reason: "unreliable-state"
|
|
1956
|
-
};
|
|
1957
|
-
}
|
|
1958
|
-
if (!state.links[pkgName]) return {
|
|
1959
|
-
consumerPath,
|
|
1960
|
-
valid: false,
|
|
1961
|
-
reason: "missing-link"
|
|
1962
|
-
};
|
|
1963
|
-
}
|
|
1964
|
-
return {
|
|
1965
|
-
consumerPath,
|
|
1966
|
-
valid: true,
|
|
1967
|
-
reason: null
|
|
1968
|
-
};
|
|
1969
|
-
}));
|
|
1970
|
-
const validConsumers = results.filter((r) => r.valid).map((r) => r.consumerPath);
|
|
1971
|
-
removedConsumers += consumers.length - validConsumers.length;
|
|
1972
|
-
removedMissingLinks += results.filter((r) => r.reason === "missing-link").length;
|
|
1973
|
-
if (validConsumers.length > 0) updated[pkgName] = validConsumers;
|
|
1974
|
-
else removedPackages++;
|
|
1975
|
-
}
|
|
1976
|
-
await writeConsumersRegistry(updated);
|
|
1977
|
-
});
|
|
1978
|
-
return {
|
|
1979
|
-
removedConsumers,
|
|
1980
|
-
removedPackages,
|
|
1981
|
-
removedMissingLinks,
|
|
1982
|
-
skippedUnreliableConsumers
|
|
1983
|
-
};
|
|
1984
|
-
}
|
|
1985
|
-
// src/utils/build-detect.ts
|
|
1986
|
-
/**
|
|
1987
|
-
* Detect the build command from package.json scripts.
|
|
1988
|
-
* Returns a fully qualified run command (e.g. "pnpm build") or null if none found.
|
|
1989
|
-
* Non-interactive — callers can wrap with prompts if needed.
|
|
1990
|
-
*/
|
|
1991
|
-
async function detectBuildCommand(packageDir, pm) {
|
|
1992
|
-
const runPrefix = pm === "npm" || pm === "bun" ? `${pm} run ` : `${pm} `;
|
|
1993
|
-
try {
|
|
1994
|
-
const scripts = stringRecordField(await readJsonObject(join(packageDir, "package.json")), "scripts");
|
|
1995
|
-
for (const name of [
|
|
1996
|
-
"build",
|
|
1997
|
-
"compile",
|
|
1998
|
-
"bundle",
|
|
1999
|
-
"tsc"
|
|
2000
|
-
]) if (scripts[name]) return `${runPrefix}${name}`;
|
|
2001
|
-
} catch {}
|
|
2002
|
-
return null;
|
|
2003
|
-
}
|
|
2004
|
-
// src/utils/config.ts
|
|
2005
|
-
function finiteNumber(value) {
|
|
2006
|
-
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
2007
|
-
}
|
|
2008
|
-
/**
|
|
2009
|
-
* Load knarr configuration from package.json#knarr. Every field is validated:
|
|
2010
|
-
* wrong types are ignored rather than trusted.
|
|
2011
|
-
*/
|
|
2012
|
-
async function loadKnarrConfig(projectDir) {
|
|
2013
|
-
try {
|
|
2014
|
-
const raw = await readFile(join(projectDir, "package.json"), "utf-8");
|
|
2015
|
-
const source = objectField(parseJsonObject(raw, "package.json"), "knarr");
|
|
2016
|
-
if (!source) return {};
|
|
2017
|
-
const config = {};
|
|
2018
|
-
if (typeof source["buildCmd"] === "string") config.buildCmd = source["buildCmd"];
|
|
2019
|
-
const watchPatterns = source["watchPatterns"];
|
|
2020
|
-
if (Array.isArray(watchPatterns)) config.watchPatterns = watchPatterns.filter((v) => typeof v === "string");
|
|
2021
|
-
const debounce = finiteNumber(source["debounce"]);
|
|
2022
|
-
if (debounce !== void 0) config.debounce = debounce;
|
|
2023
|
-
const cooldown = finiteNumber(source["cooldown"]);
|
|
2024
|
-
if (cooldown !== void 0) config.cooldown = cooldown;
|
|
2025
|
-
const historyLimit = finiteNumber(source["historyLimit"]);
|
|
2026
|
-
if (historyLimit !== void 0) config.historyLimit = Math.max(0, Math.floor(historyLimit));
|
|
2027
|
-
if (typeof source["notify"] === "boolean") config.notify = source["notify"];
|
|
2028
|
-
verbose(`[config] Loaded knarr config from package.json: ${JSON.stringify(config)}`);
|
|
2029
|
-
return config;
|
|
2030
|
-
} catch {
|
|
2031
|
-
return {};
|
|
2032
|
-
}
|
|
2033
|
-
}
|
|
2034
|
-
// src/utils/timer.ts
|
|
2035
|
-
/**
|
|
2036
|
-
* Simple timer for measuring command execution time.
|
|
2037
|
-
*/
|
|
2038
|
-
var Timer = class {
|
|
2039
|
-
start = performance.now();
|
|
2040
|
-
/** Return elapsed time in ms */
|
|
2041
|
-
elapsedMs() {
|
|
2042
|
-
return performance.now() - this.start;
|
|
2043
|
-
}
|
|
2044
|
-
/** Return human-readable elapsed time (e.g., "1.2s" or "150ms") */
|
|
2045
|
-
elapsed() {
|
|
2046
|
-
const ms = this.elapsedMs();
|
|
2047
|
-
if (ms >= 1e3) return `${(ms / 1e3).toFixed(1)}s`;
|
|
2048
|
-
return `${Math.round(ms)}ms`;
|
|
2049
|
-
}
|
|
2050
|
-
};
|
|
2051
|
-
// src/utils/output.ts
|
|
2052
|
-
/**
|
|
2053
|
-
* Print structured data. When --json is active, prints JSON to stdout.
|
|
2054
|
-
* When not, does nothing (human-readable output is handled by commands).
|
|
2055
|
-
*/
|
|
2056
|
-
function output(data) {
|
|
2057
|
-
if (isJsonOutput()) {
|
|
2058
|
-
if (isDryRun()) {
|
|
2059
|
-
markDryRunJsonReportPrinted();
|
|
2060
|
-
if (data && typeof data === "object" && !Array.isArray(data)) console.log(JSON.stringify({
|
|
2061
|
-
...data,
|
|
2062
|
-
dryRun: true,
|
|
2063
|
-
mutations: getMutations()
|
|
2064
|
-
}, null, 2));
|
|
2065
|
-
else console.log(JSON.stringify({
|
|
2066
|
-
data,
|
|
2067
|
-
dryRun: true,
|
|
2068
|
-
mutations: getMutations()
|
|
2069
|
-
}, null, 2));
|
|
2070
|
-
return;
|
|
2071
|
-
}
|
|
2072
|
-
console.log(JSON.stringify(data, null, 2));
|
|
2073
|
-
}
|
|
2074
|
-
}
|
|
2075
|
-
// src/utils/errors.ts
|
|
2076
|
-
const SUGGESTIONS = [
|
|
2077
|
-
{
|
|
2078
|
-
pattern: /not found in store/i,
|
|
2079
|
-
message: "Run 'knarr publish' in the package directory first, or use --from <path>."
|
|
2080
|
-
},
|
|
2081
|
-
{
|
|
2082
|
-
pattern: /is not linked/i,
|
|
2083
|
-
message: "Run 'knarr add <package>' to link it first."
|
|
2084
|
-
},
|
|
2085
|
-
{
|
|
2086
|
-
pattern: /No package\.json/i,
|
|
2087
|
-
message: "Make sure you're in a valid package directory with a package.json."
|
|
2088
|
-
},
|
|
2089
|
-
{
|
|
2090
|
-
pattern: /missing 'name'/i,
|
|
2091
|
-
message: "Add a 'name' field to your package.json."
|
|
2092
|
-
},
|
|
2093
|
-
{
|
|
2094
|
-
pattern: /missing 'version'/i,
|
|
2095
|
-
message: "Add a 'version' field to your package.json."
|
|
2096
|
-
},
|
|
2097
|
-
{
|
|
2098
|
-
pattern: /store entry missing/i,
|
|
2099
|
-
message: "Re-publish the package with 'knarr publish'."
|
|
2100
|
-
},
|
|
2101
|
-
{
|
|
2102
|
-
pattern: /EACCES|EPERM/i,
|
|
2103
|
-
message: "Permission denied. Try running with elevated privileges or check file ownership."
|
|
2104
|
-
},
|
|
2105
|
-
{
|
|
2106
|
-
pattern: /ENOSPC/i,
|
|
2107
|
-
message: "Disk is full. Free up some space and try again."
|
|
2108
|
-
},
|
|
2109
|
-
{
|
|
2110
|
-
pattern: /No publishable files/i,
|
|
2111
|
-
message: "Check the 'files' field in package.json, or ensure the build output exists."
|
|
2112
|
-
},
|
|
2113
|
-
{
|
|
2114
|
-
pattern: /private.*package/i,
|
|
2115
|
-
message: "Use --private flag to publish private packages."
|
|
2116
|
-
},
|
|
2117
|
-
{
|
|
2118
|
-
pattern: /Failed to read store entry/i,
|
|
2119
|
-
message: "The store may be corrupted. Try 'knarr clean' then re-publish."
|
|
2120
|
-
},
|
|
2121
|
-
{
|
|
2122
|
-
pattern: /Failed to acquire lock/i,
|
|
2123
|
-
message: "Another Knarr process may be running. Wait or delete stale .lk directories."
|
|
2124
|
-
},
|
|
2125
|
-
{
|
|
2126
|
-
pattern: /not a directory/i,
|
|
2127
|
-
message: "Check that the path exists and is a directory."
|
|
2128
|
-
},
|
|
2129
|
-
{
|
|
2130
|
-
pattern: /timed out/i,
|
|
2131
|
-
message: "Set KNARR_HOOK_TIMEOUT to a higher value (in ms) if your scripts need more time."
|
|
2132
|
-
},
|
|
2133
|
-
{
|
|
2134
|
-
pattern: /state.*corrupt|corrupt.*state/i,
|
|
2135
|
-
message: "Delete .knarr/state.json and re-run 'knarr add' for each package."
|
|
2136
|
-
},
|
|
2137
|
-
{
|
|
2138
|
-
pattern: /EBUSY/i,
|
|
2139
|
-
message: "A file is locked by another process (e.g. dev server). Stop the process and retry."
|
|
2140
|
-
},
|
|
2141
|
-
{
|
|
2142
|
-
pattern: /Invalid package name/i,
|
|
2143
|
-
message: "Package names must be non-empty. Use format: package-name or @scope/package-name."
|
|
2144
|
-
}
|
|
2145
|
-
];
|
|
2146
|
-
/**
|
|
2147
|
-
* Log an error with an actionable suggestion if one matches.
|
|
2148
|
-
*/
|
|
2149
|
-
function errorWithSuggestion(message) {
|
|
2150
|
-
consola.error(message);
|
|
2151
|
-
for (const { pattern, message: suggestion } of SUGGESTIONS) if (pattern.test(message)) {
|
|
2152
|
-
consola.info(`${pc.dim("Suggestion:")} ${suggestion}`);
|
|
2153
|
-
break;
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
// src/core/push-engine.ts
|
|
2157
|
-
const consumerLimit = pLimit(4);
|
|
2158
|
-
/**
|
|
2159
|
-
* Publish a package to the store, then inject into all registered consumers.
|
|
2160
|
-
* Shared by both `push` and `dev` commands.
|
|
2161
|
-
*/
|
|
2162
|
-
async function doPush(packageDir, options = {}) {
|
|
2163
|
-
const timer = new Timer();
|
|
2164
|
-
const result = await publish(packageDir, {
|
|
2165
|
-
runScripts: options.runScripts,
|
|
2166
|
-
force: options.force,
|
|
2167
|
-
historyLimit: options.historyLimit
|
|
2168
|
-
});
|
|
2169
|
-
if (result.skipped) {
|
|
2170
|
-
const entry = await getStoreEntry(result.name, result.version);
|
|
2171
|
-
if (entry) return pushStoreEntry(entry, {
|
|
2172
|
-
force: options.force,
|
|
2173
|
-
timer,
|
|
2174
|
-
noConsumersStatus: "available",
|
|
2175
|
-
noChange: true,
|
|
2176
|
-
skippedReason: "content unchanged"
|
|
2177
|
-
});
|
|
2178
|
-
else {
|
|
2179
|
-
const summary = createEmptySummary(result.name, result.version, result.buildId, timer.elapsedMs());
|
|
2180
|
-
summary.noChange = true;
|
|
2181
|
-
summary.skippedReason = "content unchanged";
|
|
2182
|
-
consola.info(`No changes to push for ${result.name}@${result.version}` + (result.buildId ? ` [${result.buildId}]` : ""));
|
|
2183
|
-
output(summary);
|
|
2184
|
-
return summary;
|
|
2185
|
-
}
|
|
2186
|
-
}
|
|
2187
|
-
if (isDryRun()) {
|
|
2188
|
-
const consumers = await getConsumers(result.name);
|
|
2189
|
-
const summary = createEmptySummary(result.name, result.version, result.buildId, timer.elapsedMs());
|
|
2190
|
-
summary.skippedReason = "dry-run";
|
|
2191
|
-
summary.consumers = consumers.length;
|
|
2192
|
-
summary.skippedConsumers = consumers.length;
|
|
2193
|
-
summary.consumerResults = consumers.map((consumerPath) => ({
|
|
2194
|
-
consumerPath,
|
|
2195
|
-
status: "skipped",
|
|
2196
|
-
copied: 0,
|
|
2197
|
-
removed: 0,
|
|
2198
|
-
skipped: 0,
|
|
2199
|
-
binLinks: 0,
|
|
2200
|
-
cacheInvalidations: 0,
|
|
2201
|
-
reason: "dry-run publish preview; store entry was not written"
|
|
2202
|
-
}));
|
|
2203
|
-
consola.info(`Dry-run: would publish ${result.name}@${result.version}` + (result.buildId ? ` [${result.buildId}]` : "") + ". Skipping consumer injection preview because the store entry was not written.");
|
|
2204
|
-
output(summary);
|
|
2205
|
-
return summary;
|
|
2206
|
-
}
|
|
2207
|
-
const entry = await getStoreEntry(result.name, result.version);
|
|
2208
|
-
if (!entry) {
|
|
2209
|
-
errorWithSuggestion(`Failed to read store entry for ${result.name}@${result.version} after publish`);
|
|
2210
|
-
const summary = createEmptySummary(result.name, result.version, result.buildId, timer.elapsedMs());
|
|
2211
|
-
summary.failedConsumers = 1;
|
|
2212
|
-
summary.consumerResults = [{
|
|
2213
|
-
consumerPath: packageDir,
|
|
2214
|
-
status: "failed",
|
|
2215
|
-
copied: 0,
|
|
2216
|
-
removed: 0,
|
|
2217
|
-
skipped: 0,
|
|
2218
|
-
binLinks: 0,
|
|
2219
|
-
cacheInvalidations: 0,
|
|
2220
|
-
error: "store entry missing after publish"
|
|
2221
|
-
}];
|
|
2222
|
-
return summary;
|
|
2223
|
-
}
|
|
2224
|
-
return pushStoreEntry(entry, {
|
|
2225
|
-
force: options.force,
|
|
2226
|
-
timer,
|
|
2227
|
-
noConsumersStatus: "published"
|
|
2228
|
-
});
|
|
2229
|
-
}
|
|
2230
|
-
/**
|
|
2231
|
-
* Inject an already-published store entry into all registered consumers.
|
|
2232
|
-
* Used by rollback so restored history is pushed without republishing source.
|
|
2233
|
-
*/
|
|
2234
|
-
async function pushStoreEntry(entry, options = {}) {
|
|
2235
|
-
const timer = options.timer ?? new Timer();
|
|
2236
|
-
const consumers = await getConsumers(entry.name);
|
|
2237
|
-
if (consumers.length === 0) {
|
|
2238
|
-
const status = options.noConsumersStatus ?? "available";
|
|
2239
|
-
consola.success(`${entry.name}@${entry.version} ${status} in store`);
|
|
2240
|
-
consola.info("No consumers registered yet. Run 'knarr add " + entry.name + "' in a consumer project to start receiving pushes.");
|
|
2241
|
-
const summary = createEmptySummary(entry.name, entry.version, entry.meta.buildId ?? "", timer.elapsedMs());
|
|
2242
|
-
summary.noChange = options.noChange ?? false;
|
|
2243
|
-
summary.skippedReason = options.skippedReason;
|
|
2244
|
-
if (options.emitOutput !== false) output(summary);
|
|
2245
|
-
return summary;
|
|
2246
|
-
}
|
|
2247
|
-
let totalCopied = 0;
|
|
2248
|
-
let totalRemoved = 0;
|
|
2249
|
-
let totalSkipped = 0;
|
|
2250
|
-
let totalBinLinks = 0;
|
|
2251
|
-
let totalCacheInvalidations = 0;
|
|
2252
|
-
let updatedCount = 0;
|
|
2253
|
-
let skippedCount = 0;
|
|
2254
|
-
let failedCount = 0;
|
|
2255
|
-
const results = await Promise.all(consumers.map((consumerPath) => consumerLimit(async () => {
|
|
2256
|
-
const link = await getLink(consumerPath, entry.name);
|
|
2257
|
-
if (!link) {
|
|
2258
|
-
verbose(`[push] No link found for ${entry.name} in ${consumerPath}, skipping`);
|
|
2259
|
-
return {
|
|
2260
|
-
consumerPath,
|
|
2261
|
-
status: "skipped",
|
|
2262
|
-
copied: 0,
|
|
2263
|
-
removed: 0,
|
|
2264
|
-
skipped: 0,
|
|
2265
|
-
binLinks: 0,
|
|
2266
|
-
cacheInvalidations: 0,
|
|
2267
|
-
reason: "not linked in consumer state"
|
|
2268
|
-
};
|
|
2269
|
-
}
|
|
2270
|
-
try {
|
|
2271
|
-
const packageManager = (await inspectProjectPackageManager(consumerPath)).resolve(link.packageManager).packageManager;
|
|
2272
|
-
const injectResult = await inject(entry, consumerPath, packageManager, { force: options.force });
|
|
2273
|
-
await addLink(consumerPath, entry.name, {
|
|
2274
|
-
...link,
|
|
2275
|
-
version: entry.version,
|
|
2276
|
-
contentHash: entry.meta.contentHash,
|
|
2277
|
-
linkedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2278
|
-
buildId: entry.meta.buildId ?? "",
|
|
2279
|
-
packageManager
|
|
2280
|
-
});
|
|
2281
|
-
return {
|
|
2282
|
-
consumerPath,
|
|
2283
|
-
status: "updated",
|
|
2284
|
-
copied: injectResult.copied,
|
|
2285
|
-
removed: injectResult.removed,
|
|
2286
|
-
skipped: injectResult.skipped,
|
|
2287
|
-
binLinks: injectResult.binLinks,
|
|
2288
|
-
cacheInvalidations: injectResult.cacheInvalidations
|
|
2289
|
-
};
|
|
2290
|
-
} catch (err) {
|
|
2291
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
2292
|
-
consola.warn(`Failed to push to ${consumerPath}: ${message}`);
|
|
2293
|
-
return {
|
|
2294
|
-
consumerPath,
|
|
2295
|
-
status: "failed",
|
|
2296
|
-
copied: 0,
|
|
2297
|
-
removed: 0,
|
|
2298
|
-
skipped: 0,
|
|
2299
|
-
binLinks: 0,
|
|
2300
|
-
cacheInvalidations: 0,
|
|
2301
|
-
error: message
|
|
2302
|
-
};
|
|
2303
|
-
}
|
|
2304
|
-
})));
|
|
2305
|
-
for (const r of results) if (r.status === "updated") {
|
|
2306
|
-
totalCopied += r.copied;
|
|
2307
|
-
totalRemoved += r.removed;
|
|
2308
|
-
totalSkipped += r.skipped;
|
|
2309
|
-
totalBinLinks += r.binLinks;
|
|
2310
|
-
totalCacheInvalidations += r.cacheInvalidations;
|
|
2311
|
-
updatedCount++;
|
|
2312
|
-
} else if (r.status === "skipped") skippedCount++;
|
|
2313
|
-
else failedCount++;
|
|
2314
|
-
const buildId = entry.meta.buildId ?? "";
|
|
2315
|
-
const buildTag = buildId ? ` [${buildId}]` : "";
|
|
2316
|
-
const detailParts = [
|
|
2317
|
-
`${totalCopied} copied`,
|
|
2318
|
-
`${totalRemoved} removed`,
|
|
2319
|
-
`${totalSkipped} unchanged`
|
|
2320
|
-
];
|
|
2321
|
-
if (totalBinLinks > 0) detailParts.push(`${totalBinLinks} bin links`);
|
|
2322
|
-
if (totalCacheInvalidations > 0) detailParts.push(`${totalCacheInvalidations} cache invalidations`);
|
|
2323
|
-
if (skippedCount > 0) detailParts.push(`${skippedCount} consumer(s) skipped`);
|
|
2324
|
-
if (failedCount > 0) detailParts.push(`${failedCount} failed`);
|
|
2325
|
-
const consumerLabel = failedCount > 0 || skippedCount > 0 ? `${updatedCount}/${consumers.length} consumer(s)` : `${updatedCount} consumer(s)`;
|
|
2326
|
-
const message = `Pushed ${entry.name}@${entry.version}${buildTag} to ${consumerLabel} in ${timer.elapsed()} (${detailParts.join(", ")})`;
|
|
2327
|
-
if (failedCount > 0) consola.warn(message);
|
|
2328
|
-
else consola.success(message);
|
|
2329
|
-
const summary = {
|
|
2330
|
-
name: entry.name,
|
|
2331
|
-
version: entry.version,
|
|
2332
|
-
buildId,
|
|
2333
|
-
noChange: false,
|
|
2334
|
-
consumers: consumers.length,
|
|
2335
|
-
updatedConsumers: updatedCount,
|
|
2336
|
-
failedConsumers: failedCount,
|
|
2337
|
-
skippedConsumers: skippedCount,
|
|
2338
|
-
copied: totalCopied,
|
|
2339
|
-
removed: totalRemoved,
|
|
2340
|
-
skipped: totalSkipped,
|
|
2341
|
-
binLinks: totalBinLinks,
|
|
2342
|
-
cacheInvalidations: totalCacheInvalidations,
|
|
2343
|
-
elapsed: timer.elapsedMs(),
|
|
2344
|
-
consumerResults: results
|
|
2345
|
-
};
|
|
2346
|
-
summary.noChange = options.noChange ?? false;
|
|
2347
|
-
summary.skippedReason = options.skippedReason;
|
|
2348
|
-
if (options.emitOutput !== false) output(summary);
|
|
2349
|
-
return summary;
|
|
2350
|
-
}
|
|
2351
|
-
function createEmptySummary(name, version, buildId, elapsed) {
|
|
2352
|
-
return {
|
|
2353
|
-
name,
|
|
2354
|
-
version,
|
|
2355
|
-
buildId,
|
|
2356
|
-
noChange: false,
|
|
2357
|
-
consumers: 0,
|
|
2358
|
-
updatedConsumers: 0,
|
|
2359
|
-
failedConsumers: 0,
|
|
2360
|
-
skippedConsumers: 0,
|
|
2361
|
-
copied: 0,
|
|
2362
|
-
removed: 0,
|
|
2363
|
-
skipped: 0,
|
|
2364
|
-
binLinks: 0,
|
|
2365
|
-
cacheInvalidations: 0,
|
|
2366
|
-
elapsed,
|
|
2367
|
-
consumerResults: []
|
|
2368
|
-
};
|
|
2369
|
-
}
|
|
2370
|
-
/** resolveWatchConfig runs for the initial build and again for the watcher: log each choice once. */
|
|
2371
|
-
const announcedBuildCommands = /* @__PURE__ */ new Set();
|
|
2372
|
-
function announceBuildCommand(packageDir, message) {
|
|
2373
|
-
const key = JSON.stringify([packageDir, message]);
|
|
2374
|
-
if (announcedBuildCommands.has(key)) return;
|
|
2375
|
-
announcedBuildCommands.add(key);
|
|
2376
|
-
consola.info(message);
|
|
2377
|
-
}
|
|
2378
|
-
async function readOutputDirs(packageDir) {
|
|
2379
|
-
let pkg;
|
|
2380
|
-
try {
|
|
2381
|
-
pkg = await readJsonObject(join(packageDir, "package.json"));
|
|
2382
|
-
} catch {
|
|
2383
|
-
return /* @__PURE__ */ new Set();
|
|
2384
|
-
}
|
|
2385
|
-
const topDir = (p) => p?.replace(/^\.\//, "").split(/[\\/]/)[0] ?? [];
|
|
2386
|
-
const files = pkg["files"];
|
|
2387
|
-
const publishedDirs = (Array.isArray(files) ? files.filter((f) => typeof f === "string") : []).flatMap(topDir).filter((dir) => dir !== "src");
|
|
2388
|
-
const entryDirs = [
|
|
2389
|
-
"main",
|
|
2390
|
-
"module",
|
|
2391
|
-
"types"
|
|
2392
|
-
].flatMap((field) => topDir(stringField(pkg, field)));
|
|
2393
|
-
const exportDirs = exportTargets(pkg["exports"]).flatMap(topDir);
|
|
2394
|
-
return /* @__PURE__ */ new Set([
|
|
2395
|
-
...publishedDirs,
|
|
2396
|
-
...entryDirs,
|
|
2397
|
-
...exportDirs
|
|
2398
|
-
]);
|
|
2399
|
-
}
|
|
2400
|
-
function exportTargets(value) {
|
|
2401
|
-
if (typeof value === "string") return [value];
|
|
2402
|
-
if (Array.isArray(value)) return value.flatMap(exportTargets);
|
|
2403
|
-
if (isJsonObject(value)) return Object.values(value).flatMap(exportTargets);
|
|
2404
|
-
return [];
|
|
2405
|
-
}
|
|
2406
|
-
/**
|
|
2407
|
-
* Resolve build command and watch patterns from CLI args, config, and auto-detection.
|
|
2408
|
-
* Merge priority: CLI args > package.json#knarr > auto-detection.
|
|
2409
|
-
*/
|
|
2410
|
-
async function resolveWatchConfig(packageDir, args, config) {
|
|
2411
|
-
let buildCmd = args.build;
|
|
2412
|
-
let patterns = config?.watchPatterns;
|
|
2413
|
-
if (args.build) {} else if (args["skip-build"]) {} else if (config?.buildCmd) {
|
|
2414
|
-
buildCmd = config.buildCmd;
|
|
2415
|
-
announceBuildCommand(packageDir, `Using build command from config: ${buildCmd}`);
|
|
2416
|
-
} else {
|
|
2417
|
-
const pm = (await inspectProjectPackageManager(packageDir)).resolve().packageManager;
|
|
2418
|
-
const detected = await detectBuildCommand(packageDir, pm);
|
|
2419
|
-
if (detected) {
|
|
2420
|
-
buildCmd = detected;
|
|
2421
|
-
announceBuildCommand(packageDir, `Auto-detected build command: ${detected}`);
|
|
2422
|
-
}
|
|
2423
|
-
}
|
|
2424
|
-
if (buildCmd && !patterns) {
|
|
2425
|
-
const { exists } = await import("./fs-DzsciYAL.mjs").then((n) => n.s);
|
|
2426
|
-
const outputDirs = await readOutputDirs(packageDir);
|
|
2427
|
-
const candidates = [
|
|
2428
|
-
"src",
|
|
2429
|
-
"lib",
|
|
2430
|
-
"source",
|
|
2431
|
-
"app",
|
|
2432
|
-
"pages",
|
|
2433
|
-
"components"
|
|
2434
|
-
].filter((dir) => !outputDirs.has(dir));
|
|
2435
|
-
const existing = (await Promise.all(candidates.map(async (dir) => ({
|
|
2436
|
-
dir,
|
|
2437
|
-
exists: await exists(join(packageDir, dir))
|
|
2438
|
-
})))).filter((c) => c.exists).map((c) => c.dir);
|
|
2439
|
-
patterns = existing.length > 0 ? existing : ["src"];
|
|
2440
|
-
verbose(`[watch] Using source patterns with build command: ${patterns.join(", ")}`);
|
|
2441
|
-
} else if (buildCmd && patterns) verbose(`[watch] Using configured watch patterns with build command: ${patterns.join(", ")}`);
|
|
2442
|
-
else {
|
|
2443
|
-
announceBuildCommand(packageDir, "No build command detected — watching output directories directly");
|
|
2444
|
-
try {
|
|
2445
|
-
const files = (await readJsonObject(join(packageDir, "package.json")))["files"];
|
|
2446
|
-
const fileList = Array.isArray(files) ? files.filter((f) => typeof f === "string") : [];
|
|
2447
|
-
if (fileList.length > 0) {
|
|
2448
|
-
patterns = fileList;
|
|
2449
|
-
consola.info(`Watching from package.json "files": ${patterns.join(", ")}`);
|
|
2450
|
-
} else consola.warn("No \"files\" field in package.json — falling back to watching src/ and lib/. Add a \"files\" field or use --build to specify a build command.");
|
|
2451
|
-
} catch (err) {
|
|
2452
|
-
verbose(`[watch] Could not read package.json: ${err instanceof Error ? err.message : String(err)}`);
|
|
2453
|
-
}
|
|
2454
|
-
}
|
|
2455
|
-
return {
|
|
2456
|
-
buildCmd,
|
|
2457
|
-
patterns
|
|
2458
|
-
};
|
|
2459
|
-
}
|
|
2460
|
-
// src/utils/workspace.ts
|
|
2461
|
-
var workspace_exports = /* @__PURE__ */ __exportAll({
|
|
2462
|
-
buildReverseAdjacency: () => buildReverseAdjacency,
|
|
2463
|
-
buildWorkspaceGraph: () => buildWorkspaceGraph,
|
|
2464
|
-
filterPublishableWorkspaceGraph: () => filterPublishableWorkspaceGraph,
|
|
2465
|
-
findWorkspacePackageRoot: () => findWorkspacePackageRoot,
|
|
2466
|
-
findWorkspacePackages: () => findWorkspacePackages,
|
|
2467
|
-
parseCatalogs: () => parseCatalogs
|
|
2468
|
-
});
|
|
2469
|
-
/**
|
|
2470
|
-
* Walk up from startDir looking for pnpm-workspace.yaml.
|
|
2471
|
-
* Returns the directory containing it, or null if not found.
|
|
2472
|
-
*/
|
|
2473
|
-
async function findWorkspaceRoot(startDir) {
|
|
2474
|
-
let dir = startDir;
|
|
2475
|
-
for (;;) {
|
|
2476
|
-
if (await exists(join(dir, "pnpm-workspace.yaml"))) return dir;
|
|
2477
|
-
const parent = dirname(dir);
|
|
2478
|
-
if (parent === dir) return null;
|
|
2479
|
-
dir = parent;
|
|
2480
|
-
}
|
|
2481
|
-
}
|
|
2482
|
-
/**
|
|
2483
|
-
* Find a workspace root for package discovery. Prefer pnpm-workspace.yaml, then
|
|
2484
|
-
* fall back to npm/Yarn-style package.json#workspaces.
|
|
2485
|
-
*/
|
|
2486
|
-
async function findWorkspacePackageRoot(startDir) {
|
|
2487
|
-
return await findWorkspaceRoot(startDir) ?? await findPackageJsonWorkspaceRoot(startDir);
|
|
2488
|
-
}
|
|
2489
|
-
/**
|
|
2490
|
-
* Parse pnpm-workspace.yaml for catalog definitions.
|
|
2491
|
-
* Handles the flat key-value structure that catalogs use:
|
|
2492
|
-
*
|
|
2493
|
-
* catalog: (default catalog)
|
|
2494
|
-
* react: ^18.0.0
|
|
2495
|
-
*
|
|
2496
|
-
* catalogs: (named catalogs)
|
|
2497
|
-
* react17:
|
|
2498
|
-
* react: ^17.0.0
|
|
2499
|
-
*
|
|
2500
|
-
* This is a minimal line-by-line parser — no YAML library needed since
|
|
2501
|
-
* catalogs only use flat string key-value pairs (no anchors, multiline, etc).
|
|
2502
|
-
*/
|
|
2503
|
-
async function parseCatalogs(workspaceRoot) {
|
|
2504
|
-
const result = {
|
|
2505
|
-
default: ownRecord(),
|
|
2506
|
-
named: ownRecord()
|
|
2507
|
-
};
|
|
2508
|
-
const filePath = join(workspaceRoot, "pnpm-workspace.yaml");
|
|
2509
|
-
let content;
|
|
2510
|
-
try {
|
|
2511
|
-
content = await readFile(filePath, "utf-8");
|
|
2512
|
-
} catch {
|
|
2513
|
-
return result;
|
|
2514
|
-
}
|
|
2515
|
-
const lines = content.split(/\r?\n/);
|
|
2516
|
-
let state = "top";
|
|
2517
|
-
let currentNamedCatalog = "";
|
|
2518
|
-
for (const line of lines) {
|
|
2519
|
-
if (line.trim() === "" || line.trim().startsWith("#")) continue;
|
|
2520
|
-
const indent = line.length - line.trimStart().length;
|
|
2521
|
-
if (indent === 0) {
|
|
2522
|
-
if (line.startsWith("catalog:")) {
|
|
2523
|
-
state = "default-catalog";
|
|
2524
|
-
continue;
|
|
2525
|
-
}
|
|
2526
|
-
if (line.startsWith("catalogs:")) {
|
|
2527
|
-
state = "named-catalogs";
|
|
2528
|
-
continue;
|
|
2529
|
-
}
|
|
2530
|
-
state = "top";
|
|
2531
|
-
continue;
|
|
2532
|
-
}
|
|
2533
|
-
if (state === "default-catalog" && indent >= 2) {
|
|
2534
|
-
const kv = parseKeyValue(line);
|
|
2535
|
-
if (kv) result.default[kv[0]] = kv[1];
|
|
2536
|
-
continue;
|
|
2537
|
-
}
|
|
2538
|
-
if (state === "named-catalogs" && indent >= 2 && indent < 4) {
|
|
2539
|
-
const trimmed = line.trim();
|
|
2540
|
-
if (trimmed.endsWith(":")) {
|
|
2541
|
-
currentNamedCatalog = trimmed.slice(0, -1);
|
|
2542
|
-
result.named[currentNamedCatalog] = ownRecord();
|
|
2543
|
-
state = "named-catalog-entries";
|
|
2544
|
-
}
|
|
2545
|
-
continue;
|
|
2546
|
-
}
|
|
2547
|
-
if (state === "named-catalog-entries" && indent >= 4) {
|
|
2548
|
-
const kv = parseKeyValue(line);
|
|
2549
|
-
const catalog = currentNamedCatalog ? result.named[currentNamedCatalog] : void 0;
|
|
2550
|
-
if (kv && catalog) catalog[kv[0]] = kv[1];
|
|
2551
|
-
continue;
|
|
2552
|
-
}
|
|
2553
|
-
if (state === "named-catalog-entries" && indent >= 2 && indent < 4) {
|
|
2554
|
-
const trimmed = line.trim();
|
|
2555
|
-
if (trimmed.endsWith(":")) {
|
|
2556
|
-
currentNamedCatalog = trimmed.slice(0, -1);
|
|
2557
|
-
result.named[currentNamedCatalog] = ownRecord();
|
|
2558
|
-
} else state = "named-catalogs";
|
|
2559
|
-
continue;
|
|
2560
|
-
}
|
|
2561
|
-
}
|
|
2562
|
-
return result;
|
|
2563
|
-
}
|
|
2564
|
-
/**
|
|
2565
|
-
* Find all workspace package directories.
|
|
2566
|
-
* Supports pnpm (pnpm-workspace.yaml) and npm/yarn (package.json workspaces field).
|
|
2567
|
-
* Returns absolute paths to directories that contain a package.json.
|
|
2568
|
-
*/
|
|
2569
|
-
async function findWorkspacePackages(startDir) {
|
|
2570
|
-
const pnpmRoot = await findWorkspaceRoot(startDir);
|
|
2571
|
-
if (pnpmRoot) {
|
|
2572
|
-
const allPatterns = await parsePnpmWorkspacePackages(pnpmRoot);
|
|
2573
|
-
const positive = allPatterns.filter((p) => !p.startsWith("!"));
|
|
2574
|
-
const negations = allPatterns.filter((p) => p.startsWith("!")).map((p) => p.slice(1));
|
|
2575
|
-
if (positive.length > 0) return resolveWorkspaceGlobs(pnpmRoot, positive, negations);
|
|
2576
|
-
}
|
|
2577
|
-
const rootDir = pnpmRoot ?? await findPackageJsonWorkspaceRoot(startDir);
|
|
2578
|
-
if (!rootDir) return [];
|
|
2579
|
-
try {
|
|
2580
|
-
const field = (await readJsonObject(join(rootDir, "package.json")))["workspaces"];
|
|
2581
|
-
const list = Array.isArray(field) ? field : isJsonObject(field) ? field["packages"] : [];
|
|
2582
|
-
const workspaces = Array.isArray(list) ? list.filter((p) => typeof p === "string") : [];
|
|
2583
|
-
if (workspaces.length === 0) return [];
|
|
2584
|
-
return resolveWorkspaceGlobs(rootDir, workspaces.filter((p) => !p.startsWith("!")), workspaces.filter((p) => p.startsWith("!")).map((p) => p.slice(1)));
|
|
2585
|
-
} catch {
|
|
2586
|
-
return [];
|
|
2587
|
-
}
|
|
2588
|
-
}
|
|
2589
|
-
/**
|
|
2590
|
-
* Parse pnpm-workspace.yaml for the `packages:` field.
|
|
2591
|
-
* Returns glob patterns like ["packages/*", "apps/*"].
|
|
2592
|
-
* Negation patterns (e.g., "!packages/internal") are preserved.
|
|
2593
|
-
*/
|
|
2594
|
-
async function parsePnpmWorkspacePackages(workspaceRoot) {
|
|
2595
|
-
const filePath = join(workspaceRoot, "pnpm-workspace.yaml");
|
|
2596
|
-
let content;
|
|
2597
|
-
try {
|
|
2598
|
-
content = await readFile(filePath, "utf-8");
|
|
2599
|
-
} catch {
|
|
2600
|
-
return [];
|
|
2601
|
-
}
|
|
2602
|
-
const patterns = [];
|
|
2603
|
-
let inPackages = false;
|
|
2604
|
-
for (const line of content.split(/\r?\n/)) {
|
|
2605
|
-
const trimmed = line.trim();
|
|
2606
|
-
if (trimmed === "" || trimmed.startsWith("#")) continue;
|
|
2607
|
-
const indent = line.length - line.trimStart().length;
|
|
2608
|
-
if (indent === 0) {
|
|
2609
|
-
inPackages = trimmed === "packages:";
|
|
2610
|
-
continue;
|
|
2611
|
-
}
|
|
2612
|
-
if (inPackages && indent >= 2) {
|
|
2613
|
-
const match = trimmed.match(/^-\s+["']?([^"']+)["']?$/);
|
|
2614
|
-
if (match?.[1]) patterns.push(match[1]);
|
|
2615
|
-
}
|
|
2616
|
-
}
|
|
2617
|
-
return patterns;
|
|
2618
|
-
}
|
|
2619
|
-
/**
|
|
2620
|
-
* Walk up from startDir looking for a package.json with a `workspaces` field.
|
|
2621
|
-
*/
|
|
2622
|
-
async function findPackageJsonWorkspaceRoot(startDir) {
|
|
2623
|
-
let dir = startDir;
|
|
2624
|
-
for (;;) {
|
|
2625
|
-
try {
|
|
2626
|
-
if ((await readJsonObject(join(dir, "package.json")))["workspaces"]) return dir;
|
|
2627
|
-
} catch {}
|
|
2628
|
-
const parent = dirname(dir);
|
|
2629
|
-
if (parent === dir) return null;
|
|
2630
|
-
dir = parent;
|
|
2631
|
-
}
|
|
2632
|
-
}
|
|
2633
|
-
/**
|
|
2634
|
-
* Resolve workspace glob patterns to actual package directories.
|
|
2635
|
-
* Each pattern like "packages/*" is expanded to actual directories containing package.json.
|
|
2636
|
-
* Negation patterns (e.g., "packages/internal") are excluded from the results.
|
|
2637
|
-
*/
|
|
2638
|
-
async function resolveWorkspaceGlobs(rootDir, patterns, negations = []) {
|
|
2639
|
-
const results = [];
|
|
2640
|
-
for (const pattern of patterns) if (pattern.includes("*")) {
|
|
2641
|
-
const parts = pattern.split("/");
|
|
2642
|
-
let staticPrefix = rootDir;
|
|
2643
|
-
const globParts = [];
|
|
2644
|
-
let foundGlob = false;
|
|
2645
|
-
for (const part of parts) if (foundGlob || part.includes("*")) {
|
|
2646
|
-
foundGlob = true;
|
|
2647
|
-
globParts.push(part);
|
|
2648
|
-
} else staticPrefix = join(staticPrefix, part);
|
|
2649
|
-
if (globParts.length === 1 && globParts[0] === "*") try {
|
|
2650
|
-
const entries = await readdir(staticPrefix, { withFileTypes: true });
|
|
2651
|
-
for (const entry of entries) if (entry.isDirectory()) {
|
|
2652
|
-
const pkgDir = join(staticPrefix, entry.name);
|
|
2653
|
-
if (await exists(join(pkgDir, "package.json"))) results.push(pkgDir);
|
|
2654
|
-
}
|
|
2655
|
-
} catch {}
|
|
2656
|
-
else {
|
|
2657
|
-
const isMatch = picomatch(pattern);
|
|
2658
|
-
const candidates = await collectDirs(rootDir, 8);
|
|
2659
|
-
for (const candidate of candidates) if (isMatch(normalizePath(relative(rootDir, candidate))) && await exists(join(candidate, "package.json"))) results.push(candidate);
|
|
2660
|
-
}
|
|
2661
|
-
} else {
|
|
2662
|
-
const pkgDir = resolve(rootDir, pattern);
|
|
2663
|
-
if (await exists(join(pkgDir, "package.json"))) results.push(pkgDir);
|
|
2664
|
-
}
|
|
2665
|
-
const unique = [...new Set(results)];
|
|
2666
|
-
if (negations.length === 0) return unique;
|
|
2667
|
-
const isExcluded = picomatch(negations);
|
|
2668
|
-
return unique.filter((dir) => {
|
|
2669
|
-
const rel = normalizePath(relative(rootDir, dir));
|
|
2670
|
-
return !isExcluded(rel);
|
|
2671
|
-
});
|
|
2672
|
-
}
|
|
2673
|
-
/** Collect directories up to a given depth */
|
|
2674
|
-
async function collectDirs(dir, maxDepth) {
|
|
2675
|
-
if (maxDepth <= 0) return [];
|
|
2676
|
-
const results = [];
|
|
2677
|
-
try {
|
|
2678
|
-
const entries = await readdir(dir, { withFileTypes: true });
|
|
2679
|
-
for (const entry of entries) {
|
|
2680
|
-
if (!entry.isDirectory() || entry.name === "node_modules" || entry.name === ".git") continue;
|
|
2681
|
-
const full = join(dir, entry.name);
|
|
2682
|
-
results.push(full);
|
|
2683
|
-
results.push(...await collectDirs(full, maxDepth - 1));
|
|
2684
|
-
}
|
|
2685
|
-
} catch {}
|
|
2686
|
-
return results;
|
|
2687
|
-
}
|
|
2688
|
-
/**
|
|
2689
|
-
* Build a workspace dependency graph for topological sorting.
|
|
2690
|
-
* Reads all workspace packages and builds an adjacency map of
|
|
2691
|
-
* in-workspace dependencies (both dependencies and devDependencies).
|
|
2692
|
-
*/
|
|
2693
|
-
async function buildWorkspaceGraph(startDir) {
|
|
2694
|
-
const dirs = await findWorkspacePackages(startDir);
|
|
2695
|
-
const packages = [];
|
|
2696
|
-
for (const dir of dirs) try {
|
|
2697
|
-
const pkg = asPackageJson(await readJsonObject(join(dir, "package.json")));
|
|
2698
|
-
if (pkg?.name && pkg.version) packages.push({
|
|
2699
|
-
name: pkg.name,
|
|
2700
|
-
version: pkg.version,
|
|
2701
|
-
dir,
|
|
2702
|
-
pkg
|
|
2703
|
-
});
|
|
2704
|
-
} catch {}
|
|
2705
|
-
const wsNames = new Set(packages.map((p) => p.name));
|
|
2706
|
-
const adjacency = /* @__PURE__ */ new Map();
|
|
2707
|
-
for (const wp of packages) {
|
|
2708
|
-
const deps = /* @__PURE__ */ new Set();
|
|
2709
|
-
for (const field of ["dependencies", "devDependencies"]) {
|
|
2710
|
-
const depMap = wp.pkg[field];
|
|
2711
|
-
if (!depMap) continue;
|
|
2712
|
-
for (const depName of Object.keys(depMap)) if (wsNames.has(depName)) deps.add(depName);
|
|
2713
|
-
}
|
|
2714
|
-
adjacency.set(wp.name, deps);
|
|
2715
|
-
}
|
|
2716
|
-
return {
|
|
2717
|
-
packages,
|
|
2718
|
-
adjacency
|
|
2719
|
-
};
|
|
2720
|
-
}
|
|
2721
|
-
/**
|
|
2722
|
-
* Return a graph containing only publishable workspace packages.
|
|
2723
|
-
* Private packages cannot be pushed by push/dev --all because those commands do
|
|
2724
|
-
* not expose the publish --private override.
|
|
2725
|
-
*/
|
|
2726
|
-
function filterPublishableWorkspaceGraph(graph) {
|
|
2727
|
-
const packages = graph.packages.filter((pkg) => !pkg.pkg.private);
|
|
2728
|
-
const names = new Set(packages.map((pkg) => pkg.name));
|
|
2729
|
-
const adjacency = /* @__PURE__ */ new Map();
|
|
2730
|
-
for (const pkg of packages) {
|
|
2731
|
-
const deps = graph.adjacency.get(pkg.name) ?? /* @__PURE__ */ new Set();
|
|
2732
|
-
adjacency.set(pkg.name, new Set([...deps].filter((dep) => names.has(dep))));
|
|
2733
|
-
}
|
|
2734
|
-
return {
|
|
2735
|
-
packages,
|
|
2736
|
-
adjacency
|
|
2737
|
-
};
|
|
2738
|
-
}
|
|
2739
|
-
/**
|
|
2740
|
-
* Build a reverse adjacency map: for each package, which packages depend on it.
|
|
2741
|
-
* Used by WatchOrchestrator to trigger cascading rebuilds.
|
|
2742
|
-
*/
|
|
2743
|
-
function buildReverseAdjacency(adjacency) {
|
|
2744
|
-
const reverse = /* @__PURE__ */ new Map();
|
|
2745
|
-
for (const name of adjacency.keys()) reverse.set(name, /* @__PURE__ */ new Set());
|
|
2746
|
-
for (const [name, deps] of adjacency) for (const dep of deps) {
|
|
2747
|
-
let set = reverse.get(dep);
|
|
2748
|
-
if (!set) {
|
|
2749
|
-
set = /* @__PURE__ */ new Set();
|
|
2750
|
-
reverse.set(dep, set);
|
|
2751
|
-
}
|
|
2752
|
-
set.add(name);
|
|
2753
|
-
}
|
|
2754
|
-
return reverse;
|
|
2755
|
-
}
|
|
2756
|
-
/** Parse a YAML key-value line like ` react: ^18.0.0` */
|
|
2757
|
-
function parseKeyValue(line) {
|
|
2758
|
-
const trimmed = line.trim();
|
|
2759
|
-
const colonIdx = trimmed.indexOf(":");
|
|
2760
|
-
if (colonIdx <= 0) return null;
|
|
2761
|
-
const key = trimmed.slice(0, colonIdx).trim();
|
|
2762
|
-
const value = stripYamlInlineComment(trimmed.slice(colonIdx + 1)).trim();
|
|
2763
|
-
if (!key || !value) return null;
|
|
2764
|
-
return [key.replace(/^["']|["']$/g, ""), value.replace(/^["']|["']$/g, "")];
|
|
2765
|
-
}
|
|
2766
|
-
function stripYamlInlineComment(value) {
|
|
2767
|
-
let quote = null;
|
|
2768
|
-
for (let i = 0; i < value.length; i++) {
|
|
2769
|
-
const char = value[i];
|
|
2770
|
-
if ((char === "\"" || char === "'") && value[i - 1] !== "\\") {
|
|
2771
|
-
quote = quote === char ? null : quote ?? char;
|
|
2772
|
-
continue;
|
|
2773
|
-
}
|
|
2774
|
-
if (!quote && char === "#" && (i === 0 || /\s/.test(value[i - 1] ?? ""))) return value.slice(0, i);
|
|
2775
|
-
}
|
|
2776
|
-
return value;
|
|
2777
|
-
}
|
|
2778
|
-
// src/utils/topo-sort.ts
|
|
2779
|
-
var topo_sort_exports = /* @__PURE__ */ __exportAll({
|
|
2780
|
-
CycleError: () => CycleError,
|
|
2781
|
-
topoSort: () => topoSort
|
|
2782
|
-
});
|
|
2783
|
-
/**
|
|
2784
|
-
* Topological sort using Kahn's algorithm.
|
|
2785
|
-
* Used to order workspace packages so dependencies are processed first.
|
|
2786
|
-
*/
|
|
2787
|
-
var CycleError = class extends Error {
|
|
2788
|
-
cycle;
|
|
2789
|
-
constructor(cycle) {
|
|
2790
|
-
super(`Dependency cycle detected: ${cycle.join(" → ")}`);
|
|
2791
|
-
this.name = "CycleError";
|
|
2792
|
-
this.cycle = cycle;
|
|
2793
|
-
}
|
|
2794
|
-
};
|
|
2795
|
-
/**
|
|
2796
|
-
* Sort nodes topologically (dependency-first order).
|
|
2797
|
-
* @param graph Map of node → Set of its dependencies (nodes it depends on)
|
|
2798
|
-
* @returns Nodes in dependency-first order
|
|
2799
|
-
* @throws CycleError if a cycle is detected
|
|
2800
|
-
*/
|
|
2801
|
-
function topoSort(graph) {
|
|
2802
|
-
const inDegree = /* @__PURE__ */ new Map();
|
|
2803
|
-
const dependents = /* @__PURE__ */ new Map();
|
|
2804
|
-
for (const node of graph.keys()) {
|
|
2805
|
-
if (!inDegree.has(node)) inDegree.set(node, 0);
|
|
2806
|
-
if (!dependents.has(node)) dependents.set(node, []);
|
|
2807
|
-
}
|
|
2808
|
-
for (const [node, deps] of graph) for (const dep of deps) {
|
|
2809
|
-
if (!graph.has(dep)) continue;
|
|
2810
|
-
inDegree.set(node, (inDegree.get(node) ?? 0) + 1);
|
|
2811
|
-
const list = dependents.get(dep);
|
|
2812
|
-
if (list) list.push(node);
|
|
2813
|
-
else dependents.set(dep, [node]);
|
|
2814
|
-
}
|
|
2815
|
-
const queue = [];
|
|
2816
|
-
for (const [node, degree] of inDegree) if (degree === 0) queue.push(node);
|
|
2817
|
-
const sorted = [];
|
|
2818
|
-
for (let node = queue.shift(); node !== void 0; node = queue.shift()) {
|
|
2819
|
-
sorted.push(node);
|
|
2820
|
-
for (const dependent of dependents.get(node) ?? []) {
|
|
2821
|
-
const newDegree = (inDegree.get(dependent) ?? 1) - 1;
|
|
2822
|
-
inDegree.set(dependent, newDegree);
|
|
2823
|
-
if (newDegree === 0) queue.push(dependent);
|
|
2824
|
-
}
|
|
2825
|
-
}
|
|
2826
|
-
if (sorted.length !== graph.size) throw new CycleError([...graph.keys()].filter((n) => !sorted.includes(n)));
|
|
2827
|
-
return sorted;
|
|
2828
|
-
}
|
|
2829
|
-
// src/core/batch-push.ts
|
|
2830
|
-
/**
|
|
2831
|
-
* Push all workspace packages in topological (dependency-first) order.
|
|
2832
|
-
* Each package is published and injected sequentially to ensure
|
|
2833
|
-
* dependencies are available before dependents.
|
|
2834
|
-
*/
|
|
2835
|
-
async function doPushAll(startDir, options = {}) {
|
|
2836
|
-
const timer = new Timer();
|
|
2837
|
-
const discovered = await buildWorkspaceGraph(startDir);
|
|
2838
|
-
const graph = filterPublishableWorkspaceGraph(discovered);
|
|
2839
|
-
if (graph.packages.length === 0) {
|
|
2840
|
-
consola.warn("No publishable workspace packages found");
|
|
2841
|
-
return;
|
|
2842
|
-
}
|
|
2843
|
-
const privateCount = discovered.packages.length - graph.packages.length;
|
|
2844
|
-
if (privateCount > 0) consola.info(`Skipping ${privateCount} private workspace package(s)`);
|
|
2845
|
-
let ordered;
|
|
2846
|
-
try {
|
|
2847
|
-
ordered = topoSort(graph.adjacency);
|
|
2848
|
-
} catch (err) {
|
|
2849
|
-
if (err instanceof CycleError) {
|
|
2850
|
-
consola.error(`Cannot push: ${err.message}`);
|
|
2851
|
-
throw err;
|
|
2852
|
-
}
|
|
2853
|
-
throw err;
|
|
2854
|
-
}
|
|
2855
|
-
const nameToDir = new Map(graph.packages.map((p) => [p.name, p.dir]));
|
|
2856
|
-
consola.info(`Pushing ${ordered.length} packages in dependency order`);
|
|
2857
|
-
verbose(`[batch-push] Order: ${ordered.join(" → ")}`);
|
|
2858
|
-
const reverseAdjacency = buildReverseAdjacency(graph.adjacency);
|
|
2859
|
-
const blocked = new Set(options.skipPackages ?? []);
|
|
2860
|
-
for (const name of [...blocked]) markTransitiveDependentsBlocked(name, reverseAdjacency, blocked);
|
|
2861
|
-
let success = 0;
|
|
2862
|
-
let failed = 0;
|
|
2863
|
-
let skipped = 0;
|
|
2864
|
-
for (const name of ordered) {
|
|
2865
|
-
const dir = nameToDir.get(name);
|
|
2866
|
-
if (!dir) continue;
|
|
2867
|
-
if (blocked.has(name)) {
|
|
2868
|
-
verbose(`[batch-push] Skipping ${name}: dependency build/push failed`);
|
|
2869
|
-
skipped++;
|
|
2870
|
-
continue;
|
|
2871
|
-
}
|
|
2872
|
-
try {
|
|
2873
|
-
if ((await doPush(dir, options)).failedConsumers > 0) {
|
|
2874
|
-
failed++;
|
|
2875
|
-
markTransitiveDependentsBlocked(name, reverseAdjacency, blocked);
|
|
2876
|
-
} else success++;
|
|
2877
|
-
} catch (err) {
|
|
2878
|
-
consola.warn(`Failed to push ${name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2879
|
-
failed++;
|
|
2880
|
-
markTransitiveDependentsBlocked(name, reverseAdjacency, blocked);
|
|
2881
|
-
}
|
|
2882
|
-
}
|
|
2883
|
-
const details = [failed > 0 ? `${failed} failed` : null, skipped > 0 ? `${skipped} skipped` : null].filter((part) => part !== null);
|
|
2884
|
-
const summaryMessage = `Pushed ${success}/${ordered.length} packages in ${timer.elapsed()}` + (details.length > 0 ? ` (${details.join(", ")})` : "");
|
|
2885
|
-
if (failed > 0) {
|
|
2886
|
-
consola.warn(summaryMessage);
|
|
2887
|
-
throw new Error(`Failed to push ${failed} workspace package(s)`);
|
|
2888
|
-
}
|
|
2889
|
-
if (skipped > 0) {
|
|
2890
|
-
consola.warn(summaryMessage);
|
|
2891
|
-
return;
|
|
2892
|
-
}
|
|
2893
|
-
consola.success(summaryMessage);
|
|
2894
|
-
}
|
|
2895
|
-
function markTransitiveDependentsBlocked(name, reverseAdjacency, blocked) {
|
|
2896
|
-
for (const dependent of reverseAdjacency.get(name) ?? []) {
|
|
2897
|
-
if (blocked.has(dependent)) continue;
|
|
2898
|
-
blocked.add(dependent);
|
|
2899
|
-
markTransitiveDependentsBlocked(dependent, reverseAdjacency, blocked);
|
|
2900
|
-
}
|
|
2901
|
-
}
|
|
2902
|
-
// src/core/history.ts
|
|
2903
|
-
var history_exports = /* @__PURE__ */ __exportAll({ captureHistory: () => captureHistory });
|
|
2904
|
-
/** Read and validate a .knarr-meta.json file. Throws when it is missing or malformed. */
|
|
2905
|
-
async function readMetaFile(metaPath) {
|
|
2906
|
-
const meta = parseJson(await readFile(metaPath, "utf-8"));
|
|
2907
|
-
if (!isKnarrMeta(meta)) throw new Error(`Invalid build metadata: ${metaPath}`);
|
|
2908
|
-
return meta;
|
|
2909
|
-
}
|
|
2910
|
-
const DEFAULT_HISTORY_LIMIT = 3;
|
|
2911
|
-
/**
|
|
2912
|
-
* Capture the current store entry as a history entry before it gets replaced.
|
|
2913
|
-
* Moves the old package/ and .knarr-meta.json into history/<buildId>/.
|
|
2914
|
-
*/
|
|
2915
|
-
async function captureHistory(name, version, oldEntryDir, historyLimit) {
|
|
2916
|
-
const metaPath = join(oldEntryDir, ".knarr-meta.json");
|
|
2917
|
-
let meta;
|
|
2918
|
-
try {
|
|
2919
|
-
meta = await readMetaFile(metaPath);
|
|
2920
|
-
} catch {
|
|
2921
|
-
verbose(`[history] Could not read meta from ${metaPath}, skipping history capture`);
|
|
2922
|
-
return;
|
|
2923
|
-
}
|
|
2924
|
-
const buildId = meta.buildId;
|
|
2925
|
-
if (!buildId) {
|
|
2926
|
-
verbose(`[history] No buildId in meta, skipping history capture`);
|
|
2927
|
-
return;
|
|
2928
|
-
}
|
|
2929
|
-
const historyDir = getStoreHistoryPath(name, version);
|
|
2930
|
-
const entryDir = getHistoryEntryPath(name, version, buildId);
|
|
2931
|
-
if (await exists(entryDir)) {
|
|
2932
|
-
verbose(`[history] Build ${buildId} already in history, skipping`);
|
|
2933
|
-
return;
|
|
2934
|
-
}
|
|
2935
|
-
await ensureDir(historyDir);
|
|
2936
|
-
const tmpHistoryEntry = entryDir + `.tmp-${process.pid}`;
|
|
2937
|
-
try {
|
|
2938
|
-
await ensureDir(tmpHistoryEntry);
|
|
2939
|
-
const oldPkgDir = join(oldEntryDir, "package");
|
|
2940
|
-
if (await exists(oldPkgDir)) await moveDir(oldPkgDir, join(tmpHistoryEntry, "package"));
|
|
2941
|
-
await atomicWriteFile(join(tmpHistoryEntry, ".knarr-meta.json"), JSON.stringify(meta, null, 2));
|
|
2942
|
-
await moveDir(tmpHistoryEntry, entryDir);
|
|
2943
|
-
verbose(`[history] Captured build ${buildId} to history`);
|
|
2944
|
-
} catch (err) {
|
|
2945
|
-
verbose(`[history] Failed to capture history: ${err instanceof Error ? err.message : String(err)}`);
|
|
2946
|
-
await removeDir(tmpHistoryEntry);
|
|
2947
|
-
}
|
|
2948
|
-
await pruneHistory(name, version, historyLimit ?? DEFAULT_HISTORY_LIMIT);
|
|
2949
|
-
}
|
|
2950
|
-
/**
|
|
2951
|
-
* List all history entries for a package, sorted by publishedAt (newest first).
|
|
2952
|
-
*/
|
|
2953
|
-
async function listHistory(name, version) {
|
|
2954
|
-
const historyDir = getStoreHistoryPath(name, version);
|
|
2955
|
-
if (!await exists(historyDir)) return [];
|
|
2956
|
-
let entries;
|
|
2957
|
-
try {
|
|
2958
|
-
entries = await readdir(historyDir);
|
|
2959
|
-
} catch {
|
|
2960
|
-
return [];
|
|
2961
|
-
}
|
|
2962
|
-
const result = [];
|
|
2963
|
-
for (const buildId of entries) {
|
|
2964
|
-
const entryDir = join(historyDir, buildId);
|
|
2965
|
-
const metaPath = join(entryDir, ".knarr-meta.json");
|
|
2966
|
-
try {
|
|
2967
|
-
const meta = await readMetaFile(metaPath);
|
|
2968
|
-
result.push({
|
|
2969
|
-
buildId: meta.buildId ?? buildId,
|
|
2970
|
-
contentHash: meta.contentHash,
|
|
2971
|
-
publishedAt: meta.publishedAt,
|
|
2972
|
-
sourcePath: meta.sourcePath,
|
|
2973
|
-
packageDir: join(entryDir, "package")
|
|
2974
|
-
});
|
|
2975
|
-
} catch {}
|
|
2976
|
-
}
|
|
2977
|
-
result.sort((a, b) => new Date(b.publishedAt).getTime() - new Date(a.publishedAt).getTime());
|
|
2978
|
-
return result;
|
|
2979
|
-
}
|
|
2980
|
-
/**
|
|
2981
|
-
* Get a specific history entry by buildId.
|
|
2982
|
-
*/
|
|
2983
|
-
async function getHistoryEntry(name, version, buildId) {
|
|
2984
|
-
const entryDir = getHistoryEntryPath(name, version, buildId);
|
|
2985
|
-
const metaPath = join(entryDir, ".knarr-meta.json");
|
|
2986
|
-
try {
|
|
2987
|
-
const meta = await readMetaFile(metaPath);
|
|
2988
|
-
return {
|
|
2989
|
-
buildId: meta.buildId ?? buildId,
|
|
2990
|
-
contentHash: meta.contentHash,
|
|
2991
|
-
publishedAt: meta.publishedAt,
|
|
2992
|
-
sourcePath: meta.sourcePath,
|
|
2993
|
-
packageDir: join(entryDir, "package")
|
|
2994
|
-
};
|
|
2995
|
-
} catch {
|
|
2996
|
-
return null;
|
|
2997
|
-
}
|
|
2998
|
-
}
|
|
2999
|
-
/**
|
|
3000
|
-
* Restore a history entry as the current store entry.
|
|
3001
|
-
* Moves the history entry back to the main store position.
|
|
3002
|
-
*/
|
|
3003
|
-
async function restoreHistoryEntry(name, version, buildId, historyLimit) {
|
|
3004
|
-
const entry = await getHistoryEntry(name, version, buildId);
|
|
3005
|
-
if (!entry) return null;
|
|
3006
|
-
const storeEntryDir = getStoreEntryPath(name, version);
|
|
3007
|
-
const historyEntryDir = getHistoryEntryPath(name, version, buildId);
|
|
3008
|
-
const historyPkg = join(historyEntryDir, "package");
|
|
3009
|
-
const historyMeta = join(historyEntryDir, ".knarr-meta.json");
|
|
3010
|
-
const metaContent = await readFile(historyMeta, "utf-8");
|
|
3011
|
-
const storePkg = join(storeEntryDir, "package");
|
|
3012
|
-
const storeMeta = join(storeEntryDir, ".knarr-meta.json");
|
|
3013
|
-
if (!await exists(historyPkg)) throw new Error(`History entry ${buildId} is missing its package directory`);
|
|
3014
|
-
const currentMetaContent = await readFile(storeMeta, "utf-8").catch(() => null);
|
|
3015
|
-
const oldEntryDir = storeEntryDir + `.restore-old-${process.pid}-${Date.now()}`;
|
|
3016
|
-
const oldPkg = join(oldEntryDir, "package");
|
|
3017
|
-
let stagedOld = false;
|
|
3018
|
-
let historyMovedToStore = false;
|
|
3019
|
-
try {
|
|
3020
|
-
if (await exists(storePkg) || currentMetaContent) {
|
|
3021
|
-
await ensureDir(oldEntryDir);
|
|
3022
|
-
if (await exists(storePkg)) await moveDir(storePkg, oldPkg);
|
|
3023
|
-
if (currentMetaContent) await atomicWriteFile(join(oldEntryDir, ".knarr-meta.json"), currentMetaContent);
|
|
3024
|
-
stagedOld = true;
|
|
3025
|
-
}
|
|
3026
|
-
await moveDir(historyPkg, storePkg);
|
|
3027
|
-
historyMovedToStore = true;
|
|
3028
|
-
await atomicWriteFile(storeMeta, metaContent);
|
|
3029
|
-
await removeDir(historyEntryDir);
|
|
3030
|
-
if (stagedOld) try {
|
|
3031
|
-
await captureHistory(name, version, oldEntryDir, historyLimit);
|
|
3032
|
-
} finally {
|
|
3033
|
-
await removeDir(oldEntryDir);
|
|
3034
|
-
}
|
|
3035
|
-
} catch (err) {
|
|
3036
|
-
if (historyMovedToStore && await exists(storePkg)) {
|
|
3037
|
-
await ensureDir(historyEntryDir);
|
|
3038
|
-
await moveDir(storePkg, historyPkg);
|
|
3039
|
-
} else if (stagedOld && await exists(storePkg)) await removeDir(storePkg);
|
|
3040
|
-
if (stagedOld && await exists(oldPkg)) await moveDir(oldPkg, storePkg);
|
|
3041
|
-
if (currentMetaContent) await atomicWriteFile(storeMeta, currentMetaContent);
|
|
3042
|
-
await removeDir(oldEntryDir);
|
|
3043
|
-
throw err;
|
|
3044
|
-
}
|
|
3045
|
-
verbose(`[history] Restored build ${buildId} as current`);
|
|
3046
|
-
return entry;
|
|
3047
|
-
}
|
|
3048
|
-
/**
|
|
3049
|
-
* Prune history entries to keep only the most recent `limit` entries.
|
|
3050
|
-
*/
|
|
3051
|
-
async function pruneHistory(name, version, limit) {
|
|
3052
|
-
if (limit < 0) return 0;
|
|
3053
|
-
const entries = await listHistory(name, version);
|
|
3054
|
-
if (entries.length <= limit) return 0;
|
|
3055
|
-
const toRemove = entries.slice(limit);
|
|
3056
|
-
let removed = 0;
|
|
3057
|
-
for (const entry of toRemove) {
|
|
3058
|
-
const entryDir = getHistoryEntryPath(name, version, entry.buildId);
|
|
3059
|
-
try {
|
|
3060
|
-
await removeDir(entryDir);
|
|
3061
|
-
removed++;
|
|
3062
|
-
verbose(`[history] Pruned old build ${entry.buildId}`);
|
|
3063
|
-
} catch {}
|
|
3064
|
-
}
|
|
3065
|
-
return removed;
|
|
3066
|
-
}
|
|
3067
|
-
/**
|
|
3068
|
-
* Remove all history for a package.
|
|
3069
|
-
*/
|
|
3070
|
-
async function clearHistory(name, version) {
|
|
3071
|
-
const historyDir = getStoreHistoryPath(name, version);
|
|
3072
|
-
if (await exists(historyDir)) await removeDir(historyDir);
|
|
3073
|
-
}
|
|
3074
|
-
/** Resolve the effective history limit from config or default */
|
|
3075
|
-
function resolveHistoryLimit(configValue) {
|
|
3076
|
-
return configValue ?? DEFAULT_HISTORY_LIMIT;
|
|
3077
|
-
}
|
|
3078
|
-
// src/utils/bell.ts
|
|
3079
|
-
/**
|
|
3080
|
-
* Ring the terminal bell (BEL character).
|
|
3081
|
-
* Writes to stderr so it doesn't interfere with --json output on stdout.
|
|
3082
|
-
*/
|
|
3083
|
-
function ringBell(enabled) {
|
|
3084
|
-
if (enabled) process.stderr.write("\x07");
|
|
3085
|
-
}
|
|
3086
|
-
// src/core/watcher.ts
|
|
3087
|
-
var watcher_exports = /* @__PURE__ */ __exportAll({
|
|
3088
|
-
runBuildCommand: () => runBuildCommand,
|
|
3089
|
-
startWatcher: () => startWatcher
|
|
3090
|
-
});
|
|
3091
|
-
/** Module-level references to active child processes for signal cleanup */
|
|
3092
|
-
const activeChildren = /* @__PURE__ */ new Set();
|
|
3093
|
-
/** Kill the active build process if one is running */
|
|
3094
|
-
function killActiveBuild() {
|
|
3095
|
-
for (const child of activeChildren) if (!child.killed) child.kill("SIGTERM");
|
|
3096
|
-
activeChildren.clear();
|
|
3097
|
-
}
|
|
3098
|
-
const IGNORED_DIRS = /* @__PURE__ */ new Set([
|
|
3099
|
-
"node_modules",
|
|
3100
|
-
".git",
|
|
3101
|
-
".knarr"
|
|
3102
|
-
]);
|
|
3103
|
-
function shouldUsePolling(watchDir, env = {
|
|
3104
|
-
platform: platform(),
|
|
3105
|
-
release: release(),
|
|
3106
|
-
webcontainer: !!process.versions?.webcontainer
|
|
3107
|
-
}) {
|
|
3108
|
-
if (env.webcontainer) return true;
|
|
3109
|
-
return env.platform === "linux" && /microsoft|wsl/i.test(env.release) && /^\/mnt\/[a-z](?:\/|$)/i.test(watchDir);
|
|
3110
|
-
}
|
|
3111
|
-
/** Recursively walk a directory, collecting file paths and their mtimeMs. */
|
|
3112
|
-
async function walkDir(dir, snapshot) {
|
|
3113
|
-
let entries;
|
|
3114
|
-
try {
|
|
3115
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
3116
|
-
} catch {
|
|
3117
|
-
return;
|
|
3118
|
-
}
|
|
3119
|
-
for (const entry of entries) {
|
|
3120
|
-
if (IGNORED_DIRS.has(entry.name)) continue;
|
|
3121
|
-
const fullPath = join(dir, entry.name);
|
|
3122
|
-
if (entry.isDirectory()) await walkDir(fullPath, snapshot);
|
|
3123
|
-
else try {
|
|
3124
|
-
const st = await stat(fullPath);
|
|
3125
|
-
snapshot.set(fullPath, st.mtimeMs);
|
|
3126
|
-
} catch {}
|
|
3127
|
-
}
|
|
3128
|
-
}
|
|
3129
|
-
/** Build a snapshot of mtimeMs for all files under the given paths. */
|
|
3130
|
-
async function buildSnapshot(watchPaths) {
|
|
3131
|
-
const snapshot = /* @__PURE__ */ new Map();
|
|
3132
|
-
for (const p of watchPaths) try {
|
|
3133
|
-
const st = await stat(p);
|
|
3134
|
-
if (st.isDirectory()) await walkDir(p, snapshot);
|
|
3135
|
-
else snapshot.set(p, st.mtimeMs);
|
|
3136
|
-
} catch {}
|
|
3137
|
-
return snapshot;
|
|
3138
|
-
}
|
|
3139
|
-
/**
|
|
3140
|
-
* Start watching a directory for changes and trigger a callback.
|
|
3141
|
-
*
|
|
3142
|
-
* Uses a "debounce effects, not detection" strategy (inspired by Vite):
|
|
3143
|
-
* - File changes are detected immediately
|
|
3144
|
-
* - The push callback is coalesced: rapid changes within `debounceMs` are batched
|
|
3145
|
-
* - If a push is already running when new changes arrive, a re-push is queued
|
|
3146
|
-
* so the final state is always pushed
|
|
3147
|
-
*/
|
|
3148
|
-
async function startWatcher(watchDir, options, onChange) {
|
|
3149
|
-
const { watch } = await import("chokidar");
|
|
3150
|
-
const patterns = options.patterns ?? ["src", "lib"];
|
|
3151
|
-
const watchPaths = patterns.map((p) => p.startsWith("/") || p.includes(":") ? p : `${watchDir}/${p}`);
|
|
3152
|
-
const prefix = options.label ? `${options.label}: ` : "";
|
|
3153
|
-
const debounceMs = options.debounce ?? 500;
|
|
3154
|
-
const cooldownMs = options.cooldown ?? 500;
|
|
3155
|
-
let debounceTimer = null;
|
|
3156
|
-
let closed = false;
|
|
3157
|
-
let running = false;
|
|
3158
|
-
let lastBuildEndTime = 0;
|
|
3159
|
-
let cycle = 0;
|
|
3160
|
-
let lastSuccessfulPush = null;
|
|
3161
|
-
let hasPendingChanges = false;
|
|
3162
|
-
const doBuild = async () => {
|
|
3163
|
-
if (closed || running) return;
|
|
3164
|
-
const timeSinceLastBuild = Date.now() - lastBuildEndTime;
|
|
3165
|
-
if (lastBuildEndTime > 0 && timeSinceLastBuild < cooldownMs) {
|
|
3166
|
-
const remaining = cooldownMs - timeSinceLastBuild;
|
|
3167
|
-
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3168
|
-
debounceTimer = setTimeout(() => {
|
|
3169
|
-
debounceTimer = null;
|
|
3170
|
-
doBuild();
|
|
3171
|
-
}, remaining);
|
|
3172
|
-
return;
|
|
3173
|
-
}
|
|
3174
|
-
running = true;
|
|
3175
|
-
hasPendingChanges = false;
|
|
3176
|
-
cycle++;
|
|
3177
|
-
try {
|
|
3178
|
-
consola.info(`${prefix}Change cycle #${cycle} started`);
|
|
3179
|
-
if (options.buildCmd) {
|
|
3180
|
-
if (!await runBuildCommand(options.buildCmd, watchDir, options.label)) {
|
|
3181
|
-
consola.warn(prefix + "Build failed (see output above), skipping push. Consumers keep the last pushed build" + (lastSuccessfulPush ? ` (${lastSuccessfulPush.toLocaleTimeString()})` : "") + ". Fix the error and save to retry.");
|
|
3182
|
-
if (options.notify) ringBell(true);
|
|
3183
|
-
return;
|
|
3184
|
-
}
|
|
3185
|
-
}
|
|
3186
|
-
await onChange();
|
|
3187
|
-
lastSuccessfulPush = /* @__PURE__ */ new Date();
|
|
3188
|
-
if (options.notify) ringBell(true);
|
|
3189
|
-
} catch (err) {
|
|
3190
|
-
consola.error(`Push failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
3191
|
-
if (options.notify) ringBell(true);
|
|
3192
|
-
} finally {
|
|
3193
|
-
running = false;
|
|
3194
|
-
lastBuildEndTime = Date.now();
|
|
3195
|
-
if (hasPendingChanges && !closed) {
|
|
3196
|
-
hasPendingChanges = false;
|
|
3197
|
-
debounceTimer = setTimeout(() => {
|
|
3198
|
-
debounceTimer = null;
|
|
3199
|
-
doBuild();
|
|
3200
|
-
}, cooldownMs);
|
|
3201
|
-
}
|
|
3202
|
-
}
|
|
3203
|
-
};
|
|
3204
|
-
const onFileEvent = (_path) => {
|
|
3205
|
-
if (closed) return;
|
|
3206
|
-
if (running) {
|
|
3207
|
-
hasPendingChanges = true;
|
|
3208
|
-
return;
|
|
3209
|
-
}
|
|
3210
|
-
const timeSinceLastBuild = Date.now() - lastBuildEndTime;
|
|
3211
|
-
if (lastBuildEndTime > 0 && timeSinceLastBuild < cooldownMs) {
|
|
3212
|
-
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3213
|
-
const remainingCooldown = cooldownMs - timeSinceLastBuild;
|
|
3214
|
-
debounceTimer = setTimeout(() => {
|
|
3215
|
-
debounceTimer = null;
|
|
3216
|
-
doBuild();
|
|
3217
|
-
}, remainingCooldown + debounceMs);
|
|
3218
|
-
return;
|
|
3219
|
-
}
|
|
3220
|
-
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3221
|
-
debounceTimer = setTimeout(() => {
|
|
3222
|
-
debounceTimer = null;
|
|
3223
|
-
doBuild();
|
|
3224
|
-
}, debounceMs);
|
|
3225
|
-
};
|
|
3226
|
-
const awfOption = options.buildCmd ? false : options.awaitWriteFinish ?? {
|
|
3227
|
-
stabilityThreshold: 200,
|
|
3228
|
-
pollInterval: 50
|
|
3229
|
-
};
|
|
3230
|
-
const usePolling = shouldUsePolling(watchDir);
|
|
3231
|
-
const watcher = watch(watchPaths, {
|
|
3232
|
-
ignoreInitial: true,
|
|
3233
|
-
ignored: [
|
|
3234
|
-
/[/\\]node_modules[/\\]/,
|
|
3235
|
-
/[/\\]\.git[/\\]/,
|
|
3236
|
-
/[/\\]\.knarr[/\\]/
|
|
3237
|
-
],
|
|
3238
|
-
awaitWriteFinish: awfOption,
|
|
3239
|
-
backend: usePolling ? "polling" : "auto",
|
|
3240
|
-
...usePolling && { pollingInterval: 1e3 }
|
|
3241
|
-
});
|
|
3242
|
-
watcher.on("change", onFileEvent);
|
|
3243
|
-
watcher.on("add", onFileEvent);
|
|
3244
|
-
watcher.on("unlink", onFileEvent);
|
|
3245
|
-
watcher.on("error", (err) => {
|
|
3246
|
-
consola.error(`Watcher error: ${err instanceof Error ? err.message : String(err)}`);
|
|
3247
|
-
});
|
|
3248
|
-
let pollInterval = null;
|
|
3249
|
-
if (usePolling) {
|
|
3250
|
-
let lastSnapshot = await buildSnapshot(watchPaths);
|
|
3251
|
-
const poll = async () => {
|
|
3252
|
-
if (closed) return;
|
|
3253
|
-
try {
|
|
3254
|
-
const current = await buildSnapshot(watchPaths);
|
|
3255
|
-
for (const [path, mtime] of current) {
|
|
3256
|
-
const prev = lastSnapshot.get(path);
|
|
3257
|
-
if (prev === void 0 || prev !== mtime) {
|
|
3258
|
-
onFileEvent(path);
|
|
3259
|
-
break;
|
|
3260
|
-
}
|
|
3261
|
-
}
|
|
3262
|
-
if (!closed) {
|
|
3263
|
-
for (const path of lastSnapshot.keys()) if (!current.has(path)) {
|
|
3264
|
-
onFileEvent(path);
|
|
3265
|
-
break;
|
|
3266
|
-
}
|
|
3267
|
-
}
|
|
3268
|
-
lastSnapshot = current;
|
|
3269
|
-
} catch {}
|
|
3270
|
-
};
|
|
3271
|
-
pollInterval = setInterval(() => void poll(), 1e3);
|
|
3272
|
-
}
|
|
3273
|
-
const watcherHandle = { close: async () => {
|
|
3274
|
-
closed = true;
|
|
3275
|
-
if (pollInterval) clearInterval(pollInterval);
|
|
3276
|
-
if (debounceTimer) clearTimeout(debounceTimer);
|
|
3277
|
-
killActiveBuild();
|
|
3278
|
-
await watcher.close();
|
|
3279
|
-
} };
|
|
3280
|
-
consola.info(`${prefix}Watching for changes in: ${patterns.join(", ")}`);
|
|
3281
|
-
return watcherHandle;
|
|
3282
|
-
}
|
|
3283
|
-
/**
|
|
3284
|
-
* Run a build command and return true if it succeeds.
|
|
3285
|
-
*/
|
|
3286
|
-
function runBuildCommand(cmd, cwd, label) {
|
|
3287
|
-
return new Promise((resolve) => {
|
|
3288
|
-
consola.start(`${label ? `${label}: ` : ""}Running: ${cmd}`);
|
|
3289
|
-
const child = spawnShell(cmd, {
|
|
3290
|
-
cwd,
|
|
3291
|
-
stdio: "inherit"
|
|
3292
|
-
});
|
|
3293
|
-
activeChildren.add(child);
|
|
3294
|
-
child.on("close", (code) => {
|
|
3295
|
-
activeChildren.delete(child);
|
|
3296
|
-
if (code === 0) {
|
|
3297
|
-
consola.success("Build succeeded");
|
|
3298
|
-
resolve(true);
|
|
3299
|
-
} else {
|
|
3300
|
-
consola.error(`Build failed with code ${code}`);
|
|
3301
|
-
resolve(false);
|
|
3302
|
-
}
|
|
3303
|
-
});
|
|
3304
|
-
child.on("error", (err) => {
|
|
3305
|
-
activeChildren.delete(child);
|
|
3306
|
-
consola.error(`Build error: ${err.message}`);
|
|
3307
|
-
resolve(false);
|
|
3308
|
-
});
|
|
3309
|
-
});
|
|
3310
|
-
}
|
|
3311
|
-
// src/core/watch-orchestrator.ts
|
|
3312
|
-
/**
|
|
3313
|
-
* Orchestrates watch mode for all workspace packages with optional
|
|
3314
|
-
* cascading rebuilds. When a package is pushed, its dependents in
|
|
3315
|
-
* the workspace are automatically rebuilt and pushed.
|
|
3316
|
-
*
|
|
3317
|
-
* State machine per package prevents infinite loops:
|
|
3318
|
-
* idle → building → idle (normal)
|
|
3319
|
-
* building + trigger → queued → building (coalesced)
|
|
3320
|
-
* queued + trigger → queued (no-op)
|
|
3321
|
-
*/
|
|
3322
|
-
var WatchOrchestrator = class {
|
|
3323
|
-
packages = /* @__PURE__ */ new Map();
|
|
3324
|
-
dependents = /* @__PURE__ */ new Map();
|
|
3325
|
-
cascade;
|
|
3326
|
-
pushOptions = {};
|
|
3327
|
-
constructor(cascade) {
|
|
3328
|
-
this.cascade = cascade;
|
|
3329
|
-
}
|
|
3330
|
-
async start(startDir, args, pushOptions) {
|
|
3331
|
-
this.pushOptions = pushOptions;
|
|
3332
|
-
const { buildWorkspaceGraph, buildReverseAdjacency, filterPublishableWorkspaceGraph } = await Promise.resolve().then(() => workspace_exports);
|
|
3333
|
-
const { topoSort, CycleError } = await Promise.resolve().then(() => topo_sort_exports);
|
|
3334
|
-
const { startWatcher } = await Promise.resolve().then(() => watcher_exports);
|
|
3335
|
-
const discovered = await buildWorkspaceGraph(startDir);
|
|
3336
|
-
const graph = filterPublishableWorkspaceGraph(discovered);
|
|
3337
|
-
if (graph.packages.length === 0) {
|
|
3338
|
-
consola.warn("No publishable workspace packages found");
|
|
3339
|
-
return;
|
|
3340
|
-
}
|
|
3341
|
-
const privateCount = discovered.packages.length - graph.packages.length;
|
|
3342
|
-
if (privateCount > 0) consola.info(`Skipping ${privateCount} private workspace package(s)`);
|
|
3343
|
-
let ordered;
|
|
3344
|
-
try {
|
|
3345
|
-
ordered = topoSort(graph.adjacency);
|
|
3346
|
-
} catch (err) {
|
|
3347
|
-
if (err instanceof CycleError) {
|
|
3348
|
-
consola.error(`Cannot watch: ${err.message}`);
|
|
3349
|
-
return;
|
|
3350
|
-
}
|
|
3351
|
-
throw err;
|
|
3352
|
-
}
|
|
3353
|
-
if (this.cascade) {
|
|
3354
|
-
this.dependents = buildReverseAdjacency(graph.adjacency);
|
|
3355
|
-
consola.info("Cascade mode enabled");
|
|
3356
|
-
}
|
|
3357
|
-
const nameToDir = new Map(graph.packages.map((p) => [p.name, p.dir]));
|
|
3358
|
-
for (const name of ordered) {
|
|
3359
|
-
const dir = nameToDir.get(name);
|
|
3360
|
-
if (!dir) continue;
|
|
3361
|
-
const config = await loadKnarrConfig(dir);
|
|
3362
|
-
const { buildCmd, patterns } = await resolveWatchConfig(dir, args, config);
|
|
3363
|
-
const notify = args.notify ?? config.notify ?? false;
|
|
3364
|
-
const wrappedOnChange = async () => {
|
|
3365
|
-
await this.runExclusive(name, async () => {
|
|
3366
|
-
assertPushSucceeded(await doPush(dir, pushOptions), name);
|
|
3367
|
-
await this.onPackagePushed(name);
|
|
3368
|
-
});
|
|
3369
|
-
};
|
|
3370
|
-
const parseMs = (v) => {
|
|
3371
|
-
if (!v) return void 0;
|
|
3372
|
-
const n = parseInt(v, 10);
|
|
3373
|
-
return Number.isFinite(n) ? n : void 0;
|
|
3374
|
-
};
|
|
3375
|
-
const entry = {
|
|
3376
|
-
dir,
|
|
3377
|
-
buildCmd,
|
|
3378
|
-
state: "idle",
|
|
3379
|
-
watcher: { close: async () => {} }
|
|
3380
|
-
};
|
|
3381
|
-
this.packages.set(name, entry);
|
|
3382
|
-
entry.watcher = await startWatcher(dir, {
|
|
3383
|
-
patterns,
|
|
3384
|
-
buildCmd,
|
|
3385
|
-
debounce: parseMs(args.debounce) ?? config.debounce,
|
|
3386
|
-
cooldown: parseMs(args.cooldown) ?? config.cooldown,
|
|
3387
|
-
notify,
|
|
3388
|
-
label: name
|
|
3389
|
-
}, wrappedOnChange);
|
|
3390
|
-
}
|
|
3391
|
-
consola.info(`Watching ${this.packages.size} workspace packages`);
|
|
3392
|
-
await new Promise((resolve) => {
|
|
3393
|
-
const cleanup = () => {
|
|
3394
|
-
consola.info("Stopping watchers...");
|
|
3395
|
-
this.close().catch((err) => {
|
|
3396
|
-
consola.warn(`Watchers did not close cleanly: ${err instanceof Error ? err.message : String(err)}`);
|
|
3397
|
-
}).finally(resolve);
|
|
3398
|
-
};
|
|
3399
|
-
process.once("SIGINT", cleanup);
|
|
3400
|
-
process.once("SIGTERM", cleanup);
|
|
3401
|
-
});
|
|
3402
|
-
}
|
|
3403
|
-
async onPackagePushed(name) {
|
|
3404
|
-
if (!this.cascade) return;
|
|
3405
|
-
const deps = this.dependents.get(name);
|
|
3406
|
-
if (!deps || deps.size === 0) return;
|
|
3407
|
-
consola.info(`${name} changed, rebuilding dependents: ${[...deps].join(", ")}`);
|
|
3408
|
-
for (const depName of deps) await this.requestRebuild(depName);
|
|
3409
|
-
}
|
|
3410
|
-
async runExclusive(name, task) {
|
|
3411
|
-
const entry = this.packages.get(name);
|
|
3412
|
-
if (!entry) return;
|
|
3413
|
-
if (entry.state === "queued") {
|
|
3414
|
-
verbose(`[cascade] ${name} already queued, skipping`);
|
|
3415
|
-
return;
|
|
3416
|
-
}
|
|
3417
|
-
if (entry.state === "building") {
|
|
3418
|
-
verbose(`[cascade] ${name} is building, marking as queued`);
|
|
3419
|
-
entry.state = "queued";
|
|
3420
|
-
return;
|
|
3421
|
-
}
|
|
3422
|
-
entry.state = "building";
|
|
3423
|
-
try {
|
|
3424
|
-
await task(entry);
|
|
3425
|
-
} finally {
|
|
3426
|
-
const wasQueued = entry.state === "queued";
|
|
3427
|
-
entry.state = "idle";
|
|
3428
|
-
if (wasQueued) await this.requestRebuild(name);
|
|
3429
|
-
}
|
|
3430
|
-
}
|
|
3431
|
-
async requestRebuild(name) {
|
|
3432
|
-
await this.runExclusive(name, async (entry) => {
|
|
3433
|
-
verbose(`[cascade] Rebuilding ${name}`);
|
|
3434
|
-
if (entry.buildCmd) {
|
|
3435
|
-
const { runBuildCommand } = await Promise.resolve().then(() => watcher_exports);
|
|
3436
|
-
if (!await runBuildCommand(entry.buildCmd, entry.dir, name)) {
|
|
3437
|
-
consola.warn(`[cascade] Build failed for ${name}, skipping dependents`);
|
|
3438
|
-
return;
|
|
3439
|
-
}
|
|
3440
|
-
}
|
|
3441
|
-
assertPushSucceeded(await doPush(entry.dir, this.pushOptions), name);
|
|
3442
|
-
await this.onPackagePushed(name);
|
|
3443
|
-
}).catch((err) => {
|
|
3444
|
-
consola.warn(`[cascade] Push failed for ${name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
3445
|
-
});
|
|
3446
|
-
}
|
|
3447
|
-
async close() {
|
|
3448
|
-
await Promise.all([...this.packages.values()].map((p) => p.watcher.close()));
|
|
3449
|
-
this.packages.clear();
|
|
3450
|
-
}
|
|
3451
|
-
};
|
|
3452
|
-
function assertPushSucceeded(summary, packageName) {
|
|
3453
|
-
if (summary.failedConsumers === 0) return;
|
|
3454
|
-
throw new Error(`Push for ${packageName} failed for ${summary.failedConsumers} consumer(s)`);
|
|
3455
|
-
}
|
|
3456
|
-
// src/utils/preflight.ts
|
|
3457
|
-
/**
|
|
3458
|
-
* Run pre-flight validation checks on a package before publishing.
|
|
3459
|
-
* Checks entry points, exports, types, and bin paths exist on disk.
|
|
3460
|
-
* Returns an array of issues found (empty = all good).
|
|
3461
|
-
*/
|
|
3462
|
-
async function runPreflightChecks(packageDir) {
|
|
3463
|
-
const issues = [];
|
|
3464
|
-
let pkgContent;
|
|
3465
|
-
try {
|
|
3466
|
-
pkgContent = await readFile(join(packageDir, "package.json"), "utf-8");
|
|
3467
|
-
} catch {
|
|
3468
|
-
issues.push({
|
|
3469
|
-
code: "NO_PACKAGE_JSON",
|
|
3470
|
-
severity: "error",
|
|
3471
|
-
message: "No package.json found"
|
|
3472
|
-
});
|
|
3473
|
-
return issues;
|
|
3474
|
-
}
|
|
3475
|
-
let pkg;
|
|
3476
|
-
try {
|
|
3477
|
-
pkg = parseJsonObject(pkgContent, "package.json");
|
|
3478
|
-
} catch {
|
|
3479
|
-
issues.push({
|
|
3480
|
-
code: "INVALID_PACKAGE_JSON",
|
|
3481
|
-
severity: "error",
|
|
3482
|
-
message: "package.json is not valid JSON"
|
|
3483
|
-
});
|
|
3484
|
-
return issues;
|
|
3485
|
-
}
|
|
3486
|
-
const files = pkg.files;
|
|
3487
|
-
if (!files || files.length === 0) issues.push({
|
|
3488
|
-
code: "EMPTY_FILES",
|
|
3489
|
-
severity: "warn",
|
|
3490
|
-
message: "No \"files\" field in package.json — npm will include almost everything. Consider adding a \"files\" field to control what gets published."
|
|
3491
|
-
});
|
|
3492
|
-
if (typeof pkg.main === "string") await checkPath(packageDir, pkg.main, "main", issues);
|
|
3493
|
-
if (typeof pkg.module === "string") await checkPath(packageDir, pkg.module, "module", issues);
|
|
3494
|
-
if (typeof pkg.types === "string") await checkPath(packageDir, pkg.types, "types", issues);
|
|
3495
|
-
else if (typeof pkg.typings === "string") await checkPath(packageDir, pkg.typings, "typings", issues);
|
|
3496
|
-
if (typeof pkg.exports === "string") await checkPath(packageDir, pkg.exports, "exports", issues);
|
|
3497
|
-
else if (pkg.exports && typeof pkg.exports === "object") await checkExports(packageDir, pkg.exports, issues);
|
|
3498
|
-
if (typeof pkg.bin === "string") await checkPath(packageDir, pkg.bin, "bin", issues);
|
|
3499
|
-
else if (pkg.bin && typeof pkg.bin === "object") {
|
|
3500
|
-
for (const [name, binPath] of Object.entries(pkg.bin)) if (typeof binPath === "string") await checkPath(packageDir, binPath, `bin.${name}`, issues);
|
|
3501
|
-
}
|
|
3502
|
-
verbose(`[preflight] ${issues.length} issue(s) found in ${packageDir}`);
|
|
3503
|
-
return issues;
|
|
3504
|
-
}
|
|
3505
|
-
async function fileExists(filePath) {
|
|
3506
|
-
try {
|
|
3507
|
-
return (await stat(filePath)).isFile();
|
|
3508
|
-
} catch {
|
|
3509
|
-
return false;
|
|
3510
|
-
}
|
|
3511
|
-
}
|
|
3512
|
-
async function checkPath(packageDir, filePath, field, issues) {
|
|
3513
|
-
if (!await fileExists(resolve(packageDir, filePath))) issues.push({
|
|
3514
|
-
code: "MISSING_PATH",
|
|
3515
|
-
severity: "warn",
|
|
3516
|
-
message: `"${field}" points to "${filePath}" which does not exist`
|
|
3517
|
-
});
|
|
3518
|
-
}
|
|
3519
|
-
/**
|
|
3520
|
-
* Recursively walk an exports map and check that all file paths exist.
|
|
3521
|
-
* Handles nested conditions (import/require/types/default).
|
|
3522
|
-
*/
|
|
3523
|
-
async function checkExports(packageDir, exports, issues) {
|
|
3524
|
-
for (const [key, value] of Object.entries(exports)) if (typeof value === "string") {
|
|
3525
|
-
if (value.startsWith(".")) {
|
|
3526
|
-
if (!await fileExists(resolve(packageDir, value))) issues.push({
|
|
3527
|
-
code: "EXPORTS_PATH_MISSING",
|
|
3528
|
-
severity: "warn",
|
|
3529
|
-
message: `exports["${key}"] points to "${value}" which does not exist`
|
|
3530
|
-
});
|
|
3531
|
-
}
|
|
3532
|
-
} else if (value && typeof value === "object") await checkExportsConditions(packageDir, key, value, issues);
|
|
3533
|
-
}
|
|
3534
|
-
async function checkExportsConditions(packageDir, exportKey, conditions, issues) {
|
|
3535
|
-
const keys = Object.keys(conditions);
|
|
3536
|
-
const typesIdx = keys.indexOf("types");
|
|
3537
|
-
const importIdx = keys.indexOf("import");
|
|
3538
|
-
const requireIdx = keys.indexOf("require");
|
|
3539
|
-
const defaultIdx = keys.indexOf("default");
|
|
3540
|
-
if (typesIdx !== -1) {
|
|
3541
|
-
const firstCodeIdx = Math.min(importIdx === -1 ? Infinity : importIdx, requireIdx === -1 ? Infinity : requireIdx, defaultIdx === -1 ? Infinity : defaultIdx);
|
|
3542
|
-
if (typesIdx > firstCodeIdx && firstCodeIdx !== Infinity) issues.push({
|
|
3543
|
-
code: "TYPES_CONDITION_ORDER",
|
|
3544
|
-
severity: "warn",
|
|
3545
|
-
message: `exports["${exportKey}"].types should come before import/require/default for TypeScript to resolve it correctly`
|
|
3546
|
-
});
|
|
3547
|
-
}
|
|
3548
|
-
for (const [condition, value] of Object.entries(conditions)) if (typeof value === "string" && value.startsWith(".")) {
|
|
3549
|
-
if (!await fileExists(resolve(packageDir, value))) issues.push({
|
|
3550
|
-
code: "EXPORTS_PATH_MISSING",
|
|
3551
|
-
severity: "warn",
|
|
3552
|
-
message: `exports["${exportKey}"].${condition} points to "${value}" which does not exist`
|
|
3553
|
-
});
|
|
3554
|
-
} else if (value && typeof value === "object") await checkExportsConditions(packageDir, exportKey, value, issues);
|
|
3555
|
-
}
|
|
3556
|
-
// src/utils/vite-config.ts
|
|
3557
|
-
function defineConfigUsesTernary(content) {
|
|
3558
|
-
const callRegex = /(^|[^A-Za-z0-9_$])defineConfig\s*\(/g;
|
|
3559
|
-
let match;
|
|
3560
|
-
while ((match = callRegex.exec(content)) !== null) {
|
|
3561
|
-
const parenStart = match.index + match[0].length - 1;
|
|
3562
|
-
let depth = 1;
|
|
3563
|
-
let i = parenStart + 1;
|
|
3564
|
-
let inString = false;
|
|
3565
|
-
let escaped = false;
|
|
3566
|
-
while (i < content.length && depth > 0) {
|
|
3567
|
-
const ch = content[i];
|
|
3568
|
-
if (escaped) {
|
|
3569
|
-
escaped = false;
|
|
3570
|
-
i++;
|
|
3571
|
-
continue;
|
|
3572
|
-
}
|
|
3573
|
-
if (ch === "\\") {
|
|
3574
|
-
escaped = true;
|
|
3575
|
-
i++;
|
|
3576
|
-
continue;
|
|
3577
|
-
}
|
|
3578
|
-
if (inString) {
|
|
3579
|
-
if (ch === inString) inString = false;
|
|
3580
|
-
i++;
|
|
3581
|
-
continue;
|
|
3582
|
-
}
|
|
3583
|
-
if (ch === "\"" || ch === "'" || ch === "`") {
|
|
3584
|
-
inString = ch;
|
|
3585
|
-
i++;
|
|
3586
|
-
continue;
|
|
3587
|
-
}
|
|
3588
|
-
if (ch === "/" && content[i + 1] === "/") {
|
|
3589
|
-
const newline = content.indexOf("\n", i);
|
|
3590
|
-
i = newline === -1 ? content.length : newline + 1;
|
|
3591
|
-
continue;
|
|
3592
|
-
}
|
|
3593
|
-
if (ch === "/" && content[i + 1] === "*") {
|
|
3594
|
-
const end = content.indexOf("*/", i + 2);
|
|
3595
|
-
i = end === -1 ? content.length : end + 2;
|
|
3596
|
-
continue;
|
|
3597
|
-
}
|
|
3598
|
-
if (ch === "?") {
|
|
3599
|
-
const next = content[i + 1];
|
|
3600
|
-
if (next === "." || next === "?") {
|
|
3601
|
-
i += 2;
|
|
3602
|
-
continue;
|
|
3603
|
-
}
|
|
3604
|
-
return true;
|
|
3605
|
-
}
|
|
3606
|
-
if (ch === "(") depth++;
|
|
3607
|
-
if (ch === ")") depth--;
|
|
3608
|
-
i++;
|
|
3609
|
-
}
|
|
3610
|
-
callRegex.lastIndex = i;
|
|
3611
|
-
}
|
|
3612
|
-
return false;
|
|
3613
|
-
}
|
|
3614
|
-
/**
|
|
3615
|
-
* Heuristic to detect configs that are too complex for automatic rewriting.
|
|
3616
|
-
* Returns null if safe to rewrite, or a reason string if too complex.
|
|
3617
|
-
*/
|
|
3618
|
-
function isComplexConfig(content) {
|
|
3619
|
-
if (defineConfigUsesTernary(content)) return {
|
|
3620
|
-
complex: true,
|
|
3621
|
-
reason: "conditional defineConfig"
|
|
3622
|
-
};
|
|
3623
|
-
if (/export\s+default\s+function/.test(content)) return {
|
|
3624
|
-
complex: true,
|
|
3625
|
-
reason: "dynamic export (function)"
|
|
3626
|
-
};
|
|
3627
|
-
if (/plugins\s*:\s*\[\s*\.\.\./.test(content)) return {
|
|
3628
|
-
complex: true,
|
|
3629
|
-
reason: "spread operator in plugins array"
|
|
3630
|
-
};
|
|
3631
|
-
if (/defineConfig\s*\(\s*async/.test(content) || /mergeConfig\s*\(/.test(content)) return {
|
|
3632
|
-
complex: true,
|
|
3633
|
-
reason: "async or merged config"
|
|
3634
|
-
};
|
|
3635
|
-
return { complex: false };
|
|
3636
|
-
}
|
|
3637
|
-
export { CycleError, Timer, WatchOrchestrator, addLink, backupExisting, buildReverseAdjacency, buildWorkspaceGraph, captureHistory, checkMissingDeps, cleanStaleConsumers, clearHistory, detectPackageManager, detectPackageManagerInfo, doPush, doPushAll, findStoreEntry, getConsumers, getHistoryEntry, getLink, getStoreEntry, inject, isComplexConfig, isNodeError, killActiveBuild, listHistory, listStoreEntries, loadKnarrConfig, normalizePath, printDryRunReport, pruneHistory, publish, readConsumerState, readConsumerStateSafe, recordMutation, registerConsumer, removeInjected, removeLink, resetMutations, resolveHistoryLimit, restoreBackup, restoreHistoryEntry, ringBell, runBuildCommand, runPreflightChecks, startWatcher, topoSort, unregisterConsumer };
|
|
1
|
+
import{t as e}from"./publisher-oHVy3LA2.mjs";import{a as t,n,r,s as i,t as a}from"./injector-BMOi1uN3.mjs";import{n as o,r as s,t as c}from"./store-CAzxNmpU.mjs";import{a as l,c as u,d,f,n as p,o as m,p as h,r as g,s as _}from"./tracker-nsfA6PWa.mjs";import{t as v}from"./push-engine-ByiNZr52.mjs";import{t as y}from"./batch-push-Cee2SPW3.mjs";import{a as b,i as x,n as S,o as C,r as w,s as T,t as E}from"./history-540r0BHF.mjs";import{a as D,i as O,n as k,t as A}from"./watcher-DN6vT6nw.mjs";import{t as j}from"./watch-orchestrator-DkuwJOEb.mjs";import{n as M,r as N}from"./package-manager-Cs9kCsjJ.mjs";import{t as P}from"./config-D0TqqAAJ.mjs";import{n as F,t as I}from"./topo-sort-I086ZoiN.mjs";import{n as L,t as R}from"./workspace-7rWwh6jI.mjs";import{t as z}from"./preflight-fF8g1t6F.mjs";import{t as B}from"./timer-BZNWRS3O.mjs";import{u as V}from"./fs-DusqxRQR.mjs";import{p as H}from"./paths-B5sEvS_7.mjs";import{a as U,i as W,r as G}from"./dry-run-DPoN8bZo.mjs";import{r as K}from"./vite-config-D_iXaoHh.mjs";export{I as CycleError,B as Timer,j as WatchOrchestrator,p as addLink,a as backupExisting,R as buildReverseAdjacency,L as buildWorkspaceGraph,E as captureHistory,n as checkMissingDeps,g as cleanStaleConsumers,S as clearHistory,M as detectPackageManager,N as detectPackageManagerInfo,v as doPush,y as doPushAll,c as findStoreEntry,l as getConsumers,w as getHistoryEntry,m as getLink,o as getStoreEntry,r as inject,K as isComplexConfig,V as isNodeError,A as killActiveBuild,x as listHistory,s as listStoreEntries,P as loadKnarrConfig,H as normalizePath,G as printDryRunReport,b as pruneHistory,e as publish,_ as readConsumerState,u as readConsumerStateSafe,W as recordMutation,d as registerConsumer,t as removeInjected,f as removeLink,U as resetMutations,C as resolveHistoryLimit,i as restoreBackup,T as restoreHistoryEntry,D as ringBell,k as runBuildCommand,z as runPreflightChecks,O as startWatcher,F as topoSort,h as unregisterConsumer};
|