knarr 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -106
- package/dist/{add-Clbi3vJ2.mjs → add-B_xzUp5y.mjs} +1 -1
- package/dist/add-flow-cvrMO_aV.mjs +5 -0
- package/dist/{batch-push-pVkjhRbp.mjs → batch-push-DXtZxRx0.mjs} +1 -1
- package/dist/build-detect-BTHh2OBm.mjs +3 -0
- package/dist/{bundler-detect-Cx8_R2hT.mjs → bundler-detect-Dq-QAbQj.mjs} +1 -1
- package/dist/check-CbVdpTsw.mjs +3 -0
- package/dist/clean-CyDDqbBD.mjs +3 -0
- package/dist/cli.mjs +3 -3
- package/dist/{config-CQpgsGyL.mjs → config-BJsL6NqN.mjs} +1 -1
- package/dist/console-CIiXr7ge.mjs +3 -0
- package/dist/{console-BxhMcj-D.mjs → console-CyaBcUd-.mjs} +19 -2
- package/dist/{dev-DeOwxr_7.mjs → dev-kqgY9NjI.mjs} +1 -1
- package/dist/doctor-D-S1P0UG.mjs +6 -0
- package/dist/{dry-run-BxVjpNqJ.mjs → dry-run-BkdMYSIx.mjs} +1 -1
- package/dist/errors-BlOfexcH.mjs +3 -0
- package/dist/explain-9Y4SZHjC.mjs +3 -0
- package/dist/{fs-DUcoWJ1g.mjs → fs-C4juVCTd.mjs} +1 -1
- package/dist/fs-CPnWm9CR.mjs +3 -0
- package/dist/{fs-BjaNhdzt.mjs → fs-DzsciYAL.mjs} +147 -73
- package/dist/{bell-UNNirKkz.mjs → history-DRhLwzhq.mjs} +1 -1
- package/dist/history-vS3w4EGu.mjs +3 -0
- package/dist/index.d.ts +17 -14
- package/dist/index.mjs +158 -80
- package/dist/init-TN84d5jM.mjs +4 -0
- package/dist/init-helpers-CYYWQm-P.mjs +15 -0
- package/dist/injector-nt40JxVt.mjs +3 -0
- package/dist/json-DbSkpxtr.mjs +3 -0
- package/dist/list-9hWJjw19.mjs +3 -0
- package/dist/{logger-DlikgOlh.mjs → logger-9C6B9Na8.mjs} +1 -1
- package/dist/migrate-Co4qcFt6.mjs +5 -0
- package/dist/{nextjs-config-BfHv8mBE.mjs → nextjs-config-BQgTWZ96.mjs} +1 -1
- package/dist/{nextjs-config-CA4N_9VY.mjs → nextjs-config-dUw2J6B9.mjs} +1 -1
- package/dist/{output-BxyRer_F.mjs → output-BxR2v-jn.mjs} +1 -1
- package/dist/{package-manager-DBBQ0XtZ.mjs → package-manager-DJ8CE0zL.mjs} +1 -1
- package/dist/{preflight-B8ypfoKV.mjs → preflight-BDsxR2Ct.mjs} +1 -1
- package/dist/{preflight-B17VQJs0.mjs → preflight-MzNjLXiy.mjs} +1 -1
- package/dist/{publish-BLk5_qx1.mjs → publish-C7ZUvHkE.mjs} +1 -1
- package/dist/publisher-CvXTbkLP.mjs +4 -0
- package/dist/{push-C6UFcNGO.mjs → push-B5KrkILW.mjs} +1 -1
- package/dist/push-engine-BpNr8qXR.mjs +3 -0
- package/dist/{remove-Bz9dNgDM.mjs → remove-DkOgVQMZ.mjs} +1 -1
- package/dist/remove-J5tY_BFk.mjs +3 -0
- package/dist/{reset--AuvAPTc.mjs → reset-ClGouUb5.mjs} +1 -1
- package/dist/{restore-CIBe2F1d.mjs → restore-Bx2V59SL.mjs} +1 -1
- package/dist/rollback-RPjHZWtG.mjs +3 -0
- package/dist/status-Rnvw6dG2.mjs +3 -0
- package/dist/store-DjPdOKqg.mjs +3 -0
- package/dist/{tailwind-source-Cgva0Hte.mjs → tailwind-source-D1cUiG-t.mjs} +1 -1
- package/dist/{history-BZS2YUIt.mjs → tracker-89eW0ArT.mjs} +1 -1
- package/dist/tracker-B3Fqx94J.mjs +3 -0
- package/dist/{update-Dacjzw4f.mjs → update-CAKFICZu.mjs} +1 -1
- package/dist/{use-BSCV4IQ5.mjs → use-CCx6J0mc.mjs} +1 -1
- package/dist/{vite-config-DqxvL5TW.mjs → vite-config-BHmawlD2.mjs} +1 -1
- package/dist/{vite-config-CbYEhn5K.mjs → vite-config-BRlYc4ni.mjs} +1 -1
- package/dist/{watch-orchestrator-CghvwrNS.mjs → watch-orchestrator-BfuCaZLA.mjs} +1 -1
- package/dist/watcher-T123sBDg.mjs +3 -0
- package/dist/workspace-CdLSxPFS.mjs +3 -0
- package/dist/{workspace-D4vhzpO4.mjs → workspace-DBxNrowu.mjs} +1 -1
- package/package.json +3 -2
- package/dist/add-flow-DdDziP5M.mjs +0 -5
- package/dist/bell-BJuCym_5.mjs +0 -11
- package/dist/bell-CIzHg0kw.mjs +0 -3
- package/dist/build-detect-mSo9jKXK.mjs +0 -3
- package/dist/check-Boh8WU_W.mjs +0 -3
- package/dist/clean-DHh6fpmR.mjs +0 -3
- package/dist/console-X31Y_QS5.mjs +0 -3
- package/dist/doctor-XEdsr84Q.mjs +0 -6
- package/dist/errors-CV7G61Hr.mjs +0 -3
- package/dist/explain-BBv3U-D3.mjs +0 -3
- package/dist/fs-Cf1JTFyh.mjs +0 -3
- package/dist/history-C5ehozRy.mjs +0 -3
- package/dist/init-Dwf-EIG3.mjs +0 -4
- package/dist/init-helpers-BfDosqvf.mjs +0 -15
- package/dist/injector-XwK_LBUh.mjs +0 -3
- package/dist/json-C6XtcMC4.mjs +0 -46
- package/dist/json-CWzEb9Rt.mjs +0 -3
- package/dist/list-DcREV9JM.mjs +0 -3
- package/dist/migrate-DW5KQeDq.mjs +0 -5
- package/dist/publisher-Br4Od-iL.mjs +0 -4
- package/dist/push-engine-D3rfg2Tj.mjs +0 -3
- package/dist/remove-DMj6k2PK.mjs +0 -3
- package/dist/rollback-CFLIncnW.mjs +0 -3
- package/dist/rolldown-runtime-D3KUYPsf.mjs +0 -12
- package/dist/status-Dy-e_RtI.mjs +0 -3
- package/dist/store-BNeGfW_b.mjs +0 -3
- package/dist/tracker-DXSo5wXO.mjs +0 -3
- package/dist/tracker-DofCXLTP.mjs +0 -3
- package/dist/watcher-Bw_qcI0M.mjs +0 -3
- package/dist/workspace-DVY5o1g8.mjs +0 -3
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import { t as
|
|
3
|
-
import { A as getStoreHistoryPath, B as pLimit, C as getConsumerBackupPath, D as getHistoryEntryPath, E as getConsumersPath, F as isConsumerState, I as isConsumersRegistry, L as isKnarrMeta, M as getStorePackagePath, N as getStorePath, O as getNodeModulesPackagePath, P as normalizePath, R as validatePackageIdentity, S as encodePackageName, T as getConsumerStatePath, _ 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 getStoreMetaPath, k as getStoreEntryPath, l as isNodeError, m as printDryRunReport, n as copyDir, o as exists, p as markDryRunJsonReportPrinted, r as copyWithCoW, t as atomicWriteFile, u as moveDir, v as isDryRun, w as getConsumerKnarrDir, x as decodePackageName, y as isJsonOutput, z as validatePackageName } from "./fs-BjaNhdzt.mjs";
|
|
4
|
-
import { a as parseJsonObject, c as stringRecordField, i as parseJson, n as isJsonObject, o as readJsonObject, r as objectField, s as stringField, t as asPackageJson } from "./json-C6XtcMC4.mjs";
|
|
5
|
-
import { n as ringBell } from "./bell-BJuCym_5.mjs";
|
|
1
|
+
import { n as pc, t as consola } from "./console-CyaBcUd-.mjs";
|
|
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";
|
|
6
3
|
import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
7
4
|
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
5
|
import { spawn } from "node:child_process";
|
|
9
6
|
import { availableParallelism, platform, release } from "node:os";
|
|
10
|
-
import pc from "picocolors";
|
|
11
7
|
import picomatch from "picomatch";
|
|
12
8
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
13
9
|
// src/utils/shell.ts
|
|
@@ -252,37 +248,43 @@ async function getStoreEntry(name, version) {
|
|
|
252
248
|
}
|
|
253
249
|
/** Find a store entry by name (any version). Returns the latest by publishedAt. */
|
|
254
250
|
async function findStoreEntry(name) {
|
|
255
|
-
const
|
|
256
|
-
if (!await exists(storePath)) return null;
|
|
257
|
-
const encodedPrefix = encodePackageName(name) + "@";
|
|
258
|
-
const candidates = (await readdir(storePath, { withFileTypes: true })).filter((d) => d.isDirectory() && d.name.startsWith(encodedPrefix));
|
|
259
|
-
const matching = (await Promise.all(candidates.map(async (dir) => {
|
|
260
|
-
const version = dir.name.slice(encodedPrefix.length);
|
|
261
|
-
const meta = await readMeta(name, version);
|
|
262
|
-
if (!meta) return null;
|
|
263
|
-
return {
|
|
264
|
-
name,
|
|
265
|
-
version,
|
|
266
|
-
packageDir: getStorePackagePath(name, version),
|
|
267
|
-
meta
|
|
268
|
-
};
|
|
269
|
-
}))).filter((r) => r !== null);
|
|
251
|
+
const matching = (await listStoreEntries()).filter((e) => e.name === name);
|
|
270
252
|
if (matching.length === 0) return null;
|
|
271
253
|
return matching.reduce((latest, entry) => new Date(entry.meta.publishedAt).getTime() > new Date(latest.meta.publishedAt).getTime() ? entry : latest);
|
|
272
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
|
+
}
|
|
273
279
|
/** List all entries in the store */
|
|
274
280
|
async function listStoreEntries() {
|
|
275
281
|
const storePath = getStorePath();
|
|
276
282
|
if (!await exists(storePath)) return [];
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
const atIdx = dir.name.lastIndexOf("@");
|
|
283
|
-
const encodedName = dir.name.slice(0, atIdx);
|
|
284
|
-
const version = dir.name.slice(atIdx + 1);
|
|
285
|
-
const name = decodePackageName(encodedName);
|
|
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;
|
|
286
288
|
const meta = await readMeta(name, version);
|
|
287
289
|
if (!meta) return null;
|
|
288
290
|
return {
|
|
@@ -794,7 +796,7 @@ async function publish(packageDir, options = {}) {
|
|
|
794
796
|
};
|
|
795
797
|
}
|
|
796
798
|
}
|
|
797
|
-
const tmpDir = storeEntryDir
|
|
799
|
+
const tmpDir = publishTempDir(storeEntryDir, "tmp");
|
|
798
800
|
const tmpPackageDir = join(tmpDir, "package");
|
|
799
801
|
const buildId = contentHash.slice(9, 17);
|
|
800
802
|
try {
|
|
@@ -820,7 +822,7 @@ async function publish(packageDir, options = {}) {
|
|
|
820
822
|
};
|
|
821
823
|
await atomicWriteFile(join(tmpDir, ".knarr-meta.json"), JSON.stringify(meta, null, 2));
|
|
822
824
|
const hadOld = await exists(storeEntryDir);
|
|
823
|
-
const oldDir = storeEntryDir
|
|
825
|
+
const oldDir = publishTempDir(storeEntryDir, "old");
|
|
824
826
|
let oldMoved = false;
|
|
825
827
|
try {
|
|
826
828
|
if (hadOld) {
|
|
@@ -1654,10 +1656,6 @@ function matchesPnpmPackageEntry(encodedName, version, entry) {
|
|
|
1654
1656
|
const exactEntry = `${encodedName}@${version}`;
|
|
1655
1657
|
return entry === exactEntry || entry.startsWith(`${exactEntry}_`);
|
|
1656
1658
|
}
|
|
1657
|
-
function isInside(root, target) {
|
|
1658
|
-
const rel = relative(resolve(root), resolve(target));
|
|
1659
|
-
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
1660
|
-
}
|
|
1661
1659
|
function requireSingleVirtualStoreCandidate(packageName, storeKind, matches) {
|
|
1662
1660
|
if (matches.length <= 1) return matches[0] ?? null;
|
|
1663
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.`);
|
|
@@ -1692,7 +1690,7 @@ async function getYarnPnpmStoreDirs(consumerPath, configured) {
|
|
|
1692
1690
|
return dirs;
|
|
1693
1691
|
}
|
|
1694
1692
|
async function isLocalVirtualStoreDir(consumerPath, storeDir) {
|
|
1695
|
-
return
|
|
1693
|
+
return isPathInside(await realpath(consumerPath).catch(() => resolve(consumerPath)), await realpath(storeDir).catch((err) => {
|
|
1696
1694
|
if (isNodeError(err) && err.code === "ENOENT") return resolve(storeDir);
|
|
1697
1695
|
throw err;
|
|
1698
1696
|
}));
|
|
@@ -1735,13 +1733,13 @@ async function isYarnPnpmStorePackageRealPath(storeDirs, targetPath) {
|
|
|
1735
1733
|
return false;
|
|
1736
1734
|
}
|
|
1737
1735
|
function isPnpmVirtualStorePackagePathFromRoot(pnpmDir, packageName, targetPath) {
|
|
1738
|
-
if (!
|
|
1736
|
+
if (!isPathInside(pnpmDir, targetPath)) return false;
|
|
1739
1737
|
const rel = relative(pnpmDir, targetPath).replace(/\\/g, "/");
|
|
1740
1738
|
const suffix = `node_modules/${packageName}`.replace(/\\/g, "/");
|
|
1741
1739
|
return rel === suffix || rel.endsWith(`/${suffix}`);
|
|
1742
1740
|
}
|
|
1743
1741
|
function isYarnPnpmStorePackagePathFromRoot(storeDir, targetPath) {
|
|
1744
|
-
if (!
|
|
1742
|
+
if (!isPathInside(storeDir, targetPath)) return false;
|
|
1745
1743
|
const parts = relative(storeDir, targetPath).replace(/\\/g, "/").split("/");
|
|
1746
1744
|
return parts.length === 2 && parts[1] === "package";
|
|
1747
1745
|
}
|
|
@@ -1776,26 +1774,26 @@ async function readConsumerStateSafe(consumerPath) {
|
|
|
1776
1774
|
const statePath = getConsumerStatePath(consumerPath);
|
|
1777
1775
|
try {
|
|
1778
1776
|
const content = await readFile(statePath, "utf-8");
|
|
1779
|
-
const
|
|
1780
|
-
if (!
|
|
1777
|
+
const state = parseConsumerState(parseJson(content));
|
|
1778
|
+
if (!state) {
|
|
1781
1779
|
consola.warn(`Invalid consumer state in ${statePath}, using defaults`);
|
|
1782
1780
|
return {
|
|
1783
1781
|
state: {
|
|
1784
1782
|
version: "1",
|
|
1785
|
-
links:
|
|
1783
|
+
links: ownRecord()
|
|
1786
1784
|
},
|
|
1787
1785
|
reliable: false
|
|
1788
1786
|
};
|
|
1789
1787
|
}
|
|
1790
1788
|
return {
|
|
1791
|
-
state
|
|
1789
|
+
state,
|
|
1792
1790
|
reliable: true
|
|
1793
1791
|
};
|
|
1794
1792
|
} catch (err) {
|
|
1795
1793
|
if (isNodeError(err) && err.code === "ENOENT") return {
|
|
1796
1794
|
state: {
|
|
1797
1795
|
version: "1",
|
|
1798
|
-
links:
|
|
1796
|
+
links: ownRecord()
|
|
1799
1797
|
},
|
|
1800
1798
|
reliable: true
|
|
1801
1799
|
};
|
|
@@ -1803,58 +1801,99 @@ async function readConsumerStateSafe(consumerPath) {
|
|
|
1803
1801
|
return {
|
|
1804
1802
|
state: {
|
|
1805
1803
|
version: "1",
|
|
1806
|
-
links:
|
|
1804
|
+
links: ownRecord()
|
|
1807
1805
|
},
|
|
1808
1806
|
reliable: false
|
|
1809
1807
|
};
|
|
1810
1808
|
}
|
|
1811
1809
|
}
|
|
1812
|
-
/** Write the consumer state file */
|
|
1813
1810
|
async function writeConsumerState(consumerPath, state) {
|
|
1814
1811
|
await ensureDir(getConsumerKnarrDir(consumerPath));
|
|
1815
1812
|
const statePath = getConsumerStatePath(consumerPath);
|
|
1816
1813
|
await atomicWriteFile(statePath, JSON.stringify(state, null, 2));
|
|
1817
1814
|
}
|
|
1818
|
-
/**
|
|
1819
|
-
|
|
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) {
|
|
1820
1821
|
const statePath = getConsumerStatePath(consumerPath);
|
|
1821
1822
|
await withFileLock(statePath, async () => {
|
|
1822
1823
|
const { state, reliable } = await readConsumerStateSafe(consumerPath);
|
|
1823
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.`);
|
|
1824
|
-
|
|
1825
|
+
const before = JSON.stringify(state);
|
|
1826
|
+
mutate(state);
|
|
1827
|
+
if (JSON.stringify(state) === before && await exists(statePath)) return;
|
|
1825
1828
|
await writeConsumerState(consumerPath, state);
|
|
1826
1829
|
});
|
|
1827
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
|
+
}
|
|
1828
1837
|
/** Remove a link entry from the consumer state */
|
|
1829
1838
|
async function removeLink(consumerPath, packageName) {
|
|
1830
|
-
|
|
1831
|
-
await withFileLock(statePath, async () => {
|
|
1832
|
-
const { state, reliable } = await readConsumerStateSafe(consumerPath);
|
|
1833
|
-
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.`);
|
|
1839
|
+
await updateConsumerState(consumerPath, (state) => {
|
|
1834
1840
|
delete state.links[packageName];
|
|
1835
|
-
await writeConsumerState(consumerPath, state);
|
|
1836
1841
|
});
|
|
1837
1842
|
}
|
|
1838
1843
|
/** Get a specific link entry */
|
|
1839
1844
|
async function getLink(consumerPath, packageName) {
|
|
1840
1845
|
return (await readConsumerState(consumerPath)).links[packageName] ?? null;
|
|
1841
1846
|
}
|
|
1842
|
-
/**
|
|
1843
|
-
|
|
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() {
|
|
1844
1853
|
const regPath = getConsumersPath();
|
|
1845
1854
|
try {
|
|
1846
|
-
const
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
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
|
+
};
|
|
1851
1862
|
}
|
|
1852
|
-
return
|
|
1863
|
+
return {
|
|
1864
|
+
registry,
|
|
1865
|
+
reliable: true
|
|
1866
|
+
};
|
|
1853
1867
|
} catch (err) {
|
|
1854
|
-
if (isNodeError(err) && err.code
|
|
1855
|
-
|
|
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
|
+
};
|
|
1856
1877
|
}
|
|
1857
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
|
+
}
|
|
1858
1897
|
/** Write the global consumers registry */
|
|
1859
1898
|
async function writeConsumersRegistry(registry) {
|
|
1860
1899
|
const regPath = getConsumersPath();
|
|
@@ -1864,7 +1903,7 @@ async function writeConsumersRegistry(registry) {
|
|
|
1864
1903
|
/** Register a consumer for a package */
|
|
1865
1904
|
async function registerConsumer(packageName, consumerPath) {
|
|
1866
1905
|
await withFileLock(getConsumersPath(), async () => {
|
|
1867
|
-
const registry = await
|
|
1906
|
+
const registry = await readConsumersRegistryForWrite();
|
|
1868
1907
|
if (!registry[packageName]) registry[packageName] = [];
|
|
1869
1908
|
const normalized = normalizePath(consumerPath);
|
|
1870
1909
|
if (!registry[packageName].includes(normalized)) registry[packageName].push(normalized);
|
|
@@ -1874,7 +1913,7 @@ async function registerConsumer(packageName, consumerPath) {
|
|
|
1874
1913
|
/** Unregister a consumer for a package */
|
|
1875
1914
|
async function unregisterConsumer(packageName, consumerPath) {
|
|
1876
1915
|
await withFileLock(getConsumersPath(), async () => {
|
|
1877
|
-
const registry = await
|
|
1916
|
+
const registry = await readConsumersRegistryForWrite();
|
|
1878
1917
|
if (!registry[packageName]) return;
|
|
1879
1918
|
const normalized = normalizePath(consumerPath);
|
|
1880
1919
|
registry[packageName] = registry[packageName].filter((p) => p !== normalized);
|
|
@@ -1886,6 +1925,10 @@ async function unregisterConsumer(packageName, consumerPath) {
|
|
|
1886
1925
|
async function getConsumers(packageName) {
|
|
1887
1926
|
return (await readConsumersRegistry())[packageName] ?? [];
|
|
1888
1927
|
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Clean stale consumers — remove registrations for directories that no longer exist.
|
|
1930
|
+
* Returns the number of stale entries removed.
|
|
1931
|
+
*/
|
|
1889
1932
|
async function cleanStaleConsumers(options = {}) {
|
|
1890
1933
|
const regPath = getConsumersPath();
|
|
1891
1934
|
let removedConsumers = 0;
|
|
@@ -1893,8 +1936,8 @@ async function cleanStaleConsumers(options = {}) {
|
|
|
1893
1936
|
let removedMissingLinks = 0;
|
|
1894
1937
|
let skippedUnreliableConsumers = 0;
|
|
1895
1938
|
await withFileLock(regPath, async () => {
|
|
1896
|
-
const registry = await
|
|
1897
|
-
const updated =
|
|
1939
|
+
const registry = await readConsumersRegistryForWrite();
|
|
1940
|
+
const updated = ownRecord();
|
|
1898
1941
|
for (const [pkgName, consumers] of Object.entries(registry)) {
|
|
1899
1942
|
const results = await Promise.all(consumers.map(async (consumerPath) => {
|
|
1900
1943
|
if (!await exists(consumerPath)) return {
|
|
@@ -2332,6 +2375,34 @@ function announceBuildCommand(packageDir, message) {
|
|
|
2332
2375
|
announcedBuildCommands.add(key);
|
|
2333
2376
|
consola.info(message);
|
|
2334
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
|
+
}
|
|
2335
2406
|
/**
|
|
2336
2407
|
* Resolve build command and watch patterns from CLI args, config, and auto-detection.
|
|
2337
2408
|
* Merge priority: CLI args > package.json#knarr > auto-detection.
|
|
@@ -2351,19 +2422,21 @@ async function resolveWatchConfig(packageDir, args, config) {
|
|
|
2351
2422
|
}
|
|
2352
2423
|
}
|
|
2353
2424
|
if (buildCmd && !patterns) {
|
|
2354
|
-
const { exists } = await import("./fs-
|
|
2355
|
-
const
|
|
2425
|
+
const { exists } = await import("./fs-DzsciYAL.mjs").then((n) => n.s);
|
|
2426
|
+
const outputDirs = await readOutputDirs(packageDir);
|
|
2427
|
+
const candidates = [
|
|
2356
2428
|
"src",
|
|
2357
2429
|
"lib",
|
|
2358
2430
|
"source",
|
|
2359
2431
|
"app",
|
|
2360
2432
|
"pages",
|
|
2361
2433
|
"components"
|
|
2362
|
-
].
|
|
2434
|
+
].filter((dir) => !outputDirs.has(dir));
|
|
2435
|
+
const existing = (await Promise.all(candidates.map(async (dir) => ({
|
|
2363
2436
|
dir,
|
|
2364
2437
|
exists: await exists(join(packageDir, dir))
|
|
2365
2438
|
})))).filter((c) => c.exists).map((c) => c.dir);
|
|
2366
|
-
patterns = existing.length > 0 ? existing : ["src"
|
|
2439
|
+
patterns = existing.length > 0 ? existing : ["src"];
|
|
2367
2440
|
verbose(`[watch] Using source patterns with build command: ${patterns.join(", ")}`);
|
|
2368
2441
|
} else if (buildCmd && patterns) verbose(`[watch] Using configured watch patterns with build command: ${patterns.join(", ")}`);
|
|
2369
2442
|
else {
|
|
@@ -2429,8 +2502,8 @@ async function findWorkspacePackageRoot(startDir) {
|
|
|
2429
2502
|
*/
|
|
2430
2503
|
async function parseCatalogs(workspaceRoot) {
|
|
2431
2504
|
const result = {
|
|
2432
|
-
default:
|
|
2433
|
-
named:
|
|
2505
|
+
default: ownRecord(),
|
|
2506
|
+
named: ownRecord()
|
|
2434
2507
|
};
|
|
2435
2508
|
const filePath = join(workspaceRoot, "pnpm-workspace.yaml");
|
|
2436
2509
|
let content;
|
|
@@ -2466,7 +2539,7 @@ async function parseCatalogs(workspaceRoot) {
|
|
|
2466
2539
|
const trimmed = line.trim();
|
|
2467
2540
|
if (trimmed.endsWith(":")) {
|
|
2468
2541
|
currentNamedCatalog = trimmed.slice(0, -1);
|
|
2469
|
-
result.named[currentNamedCatalog] =
|
|
2542
|
+
result.named[currentNamedCatalog] = ownRecord();
|
|
2470
2543
|
state = "named-catalog-entries";
|
|
2471
2544
|
}
|
|
2472
2545
|
continue;
|
|
@@ -2481,7 +2554,7 @@ async function parseCatalogs(workspaceRoot) {
|
|
|
2481
2554
|
const trimmed = line.trim();
|
|
2482
2555
|
if (trimmed.endsWith(":")) {
|
|
2483
2556
|
currentNamedCatalog = trimmed.slice(0, -1);
|
|
2484
|
-
result.named[currentNamedCatalog] =
|
|
2557
|
+
result.named[currentNamedCatalog] = ownRecord();
|
|
2485
2558
|
} else state = "named-catalogs";
|
|
2486
2559
|
continue;
|
|
2487
2560
|
}
|
|
@@ -3002,6 +3075,14 @@ async function clearHistory(name, version) {
|
|
|
3002
3075
|
function resolveHistoryLimit(configValue) {
|
|
3003
3076
|
return configValue ?? DEFAULT_HISTORY_LIMIT;
|
|
3004
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
|
+
}
|
|
3005
3086
|
// src/core/watcher.ts
|
|
3006
3087
|
var watcher_exports = /* @__PURE__ */ __exportAll({
|
|
3007
3088
|
runBuildCommand: () => runBuildCommand,
|
|
@@ -3098,10 +3179,7 @@ async function startWatcher(watchDir, options, onChange) {
|
|
|
3098
3179
|
if (options.buildCmd) {
|
|
3099
3180
|
if (!await runBuildCommand(options.buildCmd, watchDir, options.label)) {
|
|
3100
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.");
|
|
3101
|
-
if (options.notify)
|
|
3102
|
-
const { ringBell } = await import("./bell-BJuCym_5.mjs").then((n) => n.t);
|
|
3103
|
-
ringBell(true);
|
|
3104
|
-
}
|
|
3182
|
+
if (options.notify) ringBell(true);
|
|
3105
3183
|
return;
|
|
3106
3184
|
}
|
|
3107
3185
|
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{c as r,t as i}from"./fs-CPnWm9CR.mjs";import{t as a}from"./package-manager-DJ8CE0zL.mjs";import{n as o}from"./bundler-detect-Dq-QAbQj.mjs";import{t as s}from"./build-detect-BTHh2OBm.mjs";import{a as c,d as l,r as u}from"./init-helpers-CYYWQm-P.mjs";import{t as d}from"./timer-DqgB175x.mjs";import{n as f,t as p}from"./output-BxR2v-jn.mjs";import{n as m}from"./logger-9C6B9Na8.mjs";import{r as h}from"./dry-run-BkdMYSIx.mjs";import{n as g}from"./config-BJsL6NqN.mjs";import{m as _}from"./tracker-B3Fqx94J.mjs";import{n as v}from"./hints-Hz3V4h3A.mjs";import{i as y,n as b,s as x}from"./json-DbSkpxtr.mjs";import{readFile as S}from"node:fs/promises";import{basename as C,join as w,resolve as T}from"node:path";var E=e({meta:{name:`init`,description:`Set up knarr in the current project`},args:{yes:{type:`boolean`,alias:`y`,description:`Skip confirmation prompts`,default:!1},role:{type:`string`,description:`Project role: "consumer" or "library"`}},async run({args:e}){f();let i=new d,s=T(`.`),y=e.yes,b=!1,x=[];n.info(`Initializing knarr in ${t.cyan(s)}\n`);let S=await a(s),E=S.resolve().packageManager;n.success(`Detected package manager: ${t.cyan(E)}`);let D=E;if(!y&&await n.prompt(`Use ${E}?`,{type:`confirm`,initial:!0})===!1){let e=[`npm`,`pnpm`,`yarn`,`bun`].filter(e=>e!==E),t=await n.prompt(`Select package manager:`,{type:`select`,options:e.map(e=>({label:e,value:e}))});typeof t==`string`&&(D=t)}let O=`consumer`;e.role===`consumer`||e.role===`library`?O=e.role:y||await n.prompt(`How will you use knarr in this project?`,{type:`select`,nonInteractiveHint:`Pass --role consumer or --role library (or --yes for consumer).`,options:[{label:`Consumer (app) - I want to link packages INTO this project`,value:`consumer`},{label:`Library (package) - I want to publish this package FOR other projects`,value:`library`}]})===`library`&&(O=`library`),n.success(`Project role: ${t.cyan(O)}`);let k=(D===E?S:await a(s,{packageManager:D})).resolve();O===`consumer`&&!k.nodeModulesCompatible&&(n.error(k.incompatibilityReason),process.exit(1));let A=w(s,`.gitignore`);await c(A)&&n.success(`Added .knarr/ to .gitignore`);let j=w(s,`package.json`),M;if(await r(j)){if(O===`consumer`){if(await l(s),await u(j)&&n.success(`Added a postinstall hook so installs re-apply linked packages (a no-op for teammates without Knarr)`),!y){let e=await n.prompt(`Package name to link (leave blank to skip):`,{type:`text`,default:``});if(typeof e==`string`&&e.trim()){let t=e.trim();await addScript(j,`knarr:add`,`knarr add ${t}`)&&n.success(`Added "knarr:add": "knarr add ${t}" to package.json scripts`)}}}else{M=await detectBuildCommand(j,D,y),b=await g(j,M),b&&M&&n.success(`Saved build command to package.json#knarr.buildCmd`);let e=await addLibraryScripts(j);for(let t of e)n.success(`Added "${t}" script to package.json`)}}let N=!await r(w(s,`.knarr`));if(await _(s,e=>{e.packageManager=D,e.role=O}),N&&n.success(`Created .knarr/ state directory`),O===`consumer`){let e=await o(s);if(e.type===`vite`&&e.configFile){n.success(`Detected bundler: ${t.cyan(`Vite`)} (${C(e.configFile)})`);let{addKnarrVitePlugin:r}=await import(`./vite-config-BRlYc4ni.mjs`),i=await r(e.configFile);if(i.modified){n.success(`Added knarr plugin to ${C(e.configFile)}`);let t=k.installCommand([`knarr`],{dev:!0}),r=k.formatCommand(t);n.info(m()?`[dry-run] Would install knarr as devDependency`:`Installing knarr as devDependency...`);let i=await k.run(t);i&&!m()?n.success(`Installed knarr`):i||n.warn(`Install failed. Run manually: ${r}`)}else i.error&&n.info(`Add the Vite plugin for automatic dev server restarts:\n ${t.cyan(`import knarr from "knarr/vite"`)}\n ${t.cyan(`plugins: [knarr()]`)}`)}else e.type===`next`&&e.configFile?(n.success(`Detected bundler: ${t.cyan(`Next.js`)} (${C(e.configFile)})`),n.info(`Next.js transpilePackages will be auto-configured when you run ${t.cyan(`knarr add`)}`)):e.type&&n.success(`Detected bundler: ${t.cyan({webpack:`Webpack`,turbo:`Turbopack`,rollup:`Rollup`}[e.type]||e.type)} - no config needed, works out of the box`);n.log(``),n.info(`${t.bold(`Next steps:`)}`);let r=`${v()} use ../my-lib`,i=`cd ../my-lib && ${v()} dev`;x.push(r,i);let a=Math.max(r.length,i.length)+2;n.log(` 1. ${t.cyan(r.padEnd(a))}<- publish + link a local package`),n.log(` 2. ${t.cyan(i.padEnd(a))}<- watch + rebuild + auto-push`)}else{n.log(``),n.info(`${t.bold(`Next steps:`)}`);let e=`${D} run knarr:publish`,r=`${D} run knarr:dev`,i=`${v()} use ${s}`;x.push(e,r,i);let a=Math.max(e.length,r.length)+2;n.log(` 1. ${t.cyan(e.padEnd(a))}<- copy built files to knarr store`),n.log(` 2. ${t.cyan(r.padEnd(a))}<- watch + rebuild + auto-push to consumers`),n.log(` 3. In consumer project: ${t.cyan(i)}`)}n.info(`Done in ${i.elapsed()}`),p({packageManager:D,role:O,buildCmd:M??null,configUpdated:b,nextSteps:x,elapsed:i.elapsedMs()}),m()&&h()}});async function addScript(e,t,n){let r=await S(e,`utf-8`),a=x(r,e),o=y(a,`scripts`)??{};return!o[t]&&(o[t]=n,a.scripts=o,await i(e,JSON.stringify(a,null,b(r))+`
|
|
4
|
+
`),!0)}async function detectBuildCommand(e,r,i){let a=w(e,`..`),o=await s(a,r);if(o)return n.success(`Detected build script: ${t.cyan(o)}`),o;if(!i){n.warn(`No build script found in package.json`);let e=await n.prompt(`Build command (e.g. tsc, tsup, rollup -c):`,{type:`text`,default:``});if(typeof e==`string`&&e.trim())return e.trim()}n.warn(`No build command saved - add a "build" script to package.json or configure package.json#knarr.buildCmd`)}async function addLibraryScripts(e){let t=[],n=x(await S(e,`utf-8`),e),r=y(n,`dependencies`)?.knarr||y(n,`devDependencies`)?.knarr?`knarr`:`npx --yes knarr`;return await addScript(e,`knarr:publish`,`${r} publish`)&&t.push(`knarr:publish`),await addScript(e,`knarr:dev`,`${r} dev`)&&t.push(`knarr:dev`),t}export{E as default};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{n as e,t}from"./console-CIiXr7ge.mjs";import{_ as n,c as r,o as i,t as a}from"./fs-CPnWm9CR.mjs";import{i as o,n as s,s as c}from"./json-DbSkpxtr.mjs";import{m as l}from"./tracker-B3Fqx94J.mjs";import{existsSync as u}from"node:fs";import{readFile as d}from"node:fs/promises";import{dirname as f,join as p}from"node:path";import{fileURLToPath as m}from"node:url";const h=`node -e "try{require('./.knarr/restore.cjs')}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e}"`,g=`knarr restore --silent || node -e "process.exit(0)"`,_=`restore.cjs`;function usesLocalRestoreScript(e){return e.includes(`.knarr/${_}`)}function currentCliPath(){let e=p(f(m(import.meta.url)),`cli.mjs`);return u(e)?e:null}function renderRestoreScript(e){return[`// Generated by Knarr. Re-applies Knarr-linked packages after an install.`,`// Local only (.knarr/ is gitignored). knarr add, use, and restore rewrite it.`,`"use strict";`,`const { spawnSync } = require("node:child_process");`,`const { existsSync } = require("node:fs");`,``,`const cli = ${JSON.stringify(e)};`,`const args = ["restore", "--silent"];`,`const result = cli && existsSync(cli)`,` ? spawnSync(process.execPath, [cli, ...args], { stdio: "inherit" })`,` : spawnSync("knarr " + args.join(" "), { stdio: ["inherit", "inherit", "pipe"], shell: true });`,``,`if (result.error || result.status !== 0) {`,` console.warn("[knarr] Linked packages were NOT restored after this install. Run: npx knarr restore");`,`}`,``].join(`
|
|
4
|
+
`)}async function writeRestoreScript(e){let t=n(e);await i(t),await a(p(t,_),renderRestoreScript(currentCliPath()))}function usesSelfResolvingKnarrCommand(e){return/\b(?:npx(?:\s+--yes|\s+-y)?|pnpm\s+dlx|yarn\s+dlx|bunx)\s+knarr\s+restore(?:\s|$)/.test(e)}function usesKnarrRestoreCommand(e){return usesLocalRestoreScript(e)?!0:/(?:^|[;&|()\s])(?:(?:npx(?:\s+(?:--yes|-y))?|pnpm\s+dlx|yarn\s+dlx|bunx)\s+)?knarr\s+restore(?:\s|$)/.test(e)}function isStandaloneKnarrRestoreCommand(e){let t=e.trim();return t===`node -e "try{require('./.knarr/restore.cjs')}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e}"`||t===`knarr restore --silent || node -e "process.exit(0)"`||t===`knarr restore --silent`||usesSelfResolvingKnarrCommand(t)}async function ensureGitignore(e){let t=``;try{t=await d(e,`utf-8`)}catch{}if(t.split(`
|
|
5
|
+
`).some(e=>e.trim()===`.knarr/`||e.trim()===`.knarr`||e.trim()===`/.knarr/`||e.trim()===`/.knarr`))return!1;let n=t.length>0&&!t.endsWith(`
|
|
6
|
+
`)?`
|
|
7
|
+
`:``,r=t.length>0?`
|
|
8
|
+
# knarr local links
|
|
9
|
+
.knarr/
|
|
10
|
+
`:`# knarr local links
|
|
11
|
+
.knarr/
|
|
12
|
+
`;return await a(e,t+n+r),!0}async function addPostinstall(n){let r=await d(n,`utf-8`),i=c(r,n),l=s(r),u=o(i,`scripts`)??{},f=u.postinstall;return typeof f==`string`&&f?f.includes(`knarr restore --silent || node -e "process.exit(0)"`)?(u.postinstall=f.replace(g,h),i.scripts=u,await a(n,JSON.stringify(i,null,l)+`
|
|
13
|
+
`),!0):(usesKnarrRestoreCommand(f)||t.warn(`Existing postinstall script found. Add ${e.cyan(h)} manually if needed.`),!1):(u.postinstall=h,i.scripts=u,await a(n,JSON.stringify(i,null,l)+`
|
|
14
|
+
`),!0)}async function ensureRestoreHook(e){await writeRestoreScript(e);let t=p(e,`package.json`);await r(t)&&await addPostinstall(t)}async function removePostinstall(e){let t;try{t=await d(e,`utf-8`)}catch{return!1}let n=c(t,e),r=o(n,`scripts`),i=r?.postinstall;return!r||typeof i!=`string`||!isStandaloneKnarrRestoreCommand(i)?!1:(delete r.postinstall,Object.keys(r).length===0&&delete n.scripts,await a(e,JSON.stringify(n,null,s(t))+`
|
|
15
|
+
`),!0)}async function ensureConsumerInit(e,t){await l(e,e=>{e.packageManager||(e.packageManager=t,e.role??=`consumer`)}),await ensureGitignore(p(e,`.gitignore`)),await ensureRestoreHook(e)}export{ensureGitignore as a,usesKnarrRestoreCommand as c,writeRestoreScript as d,ensureConsumerInit as i,usesLocalRestoreScript as l,_ as n,ensureRestoreHook as o,addPostinstall as r,removePostinstall as s,g as t,usesSelfResolvingKnarrCommand as u};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-CIiXr7ge.mjs";import{D as t,c as n,f as r,g as i,l as a,o,r as s,u as c,x as l}from"./fs-CPnWm9CR.mjs";import{i as u,n as d}from"./logger-9C6B9Na8.mjs";import{i as f}from"./dry-run-BkdMYSIx.mjs";import{t as p}from"./package-manager-DJ8CE0zL.mjs";import{t as m}from"./bundler-detect-Dq-QAbQj.mjs";import{l as h,s as g,t as _}from"./json-DbSkpxtr.mjs";import{platform as v}from"node:os";import{chmod as y,lstat as b,mkdir as x,readFile as S,readdir as C,readlink as w,realpath as T,rm as E,symlink as D,writeFile as O}from"node:fs/promises";import{dirname as k,isAbsolute as A,join as j,relative as M,resolve as N,sep as P}from"node:path";const F=/[\x00-\x1F\x7F]/,I=/^[A-Za-z0-9._+-]+$/;function safeInterpreter(e){return e&&I.test(e)?e:`node`}function parseShebangInterpreter(e){let t=e.split(/\r?\n/,1)[0]?.trim();if(!t?.startsWith(`#!`))return`node`;let n=t.slice(2).trim().split(/\s+/).filter(Boolean),[r]=n;if(r===void 0)return`node`;let i=r.replace(/\\/g,`/`).split(`/`).pop();if(i===`env`){let e=n.slice(1);return safeInterpreter(e[0]===`-S`?e[1]:e[0])}return safeInterpreter(i)}async function readBinInterpreter(e){try{return parseShebangInterpreter(await S(e,`utf-8`))}catch{return`node`}}function resolveBinPath(e,t,n=``){if(!t||t===`.`||t===`..`||F.test(t)||t.includes(`/`)||t.includes(`\\`)||t.includes(`:`))return null;let r=j(e,`${t}${n}`),i=N(e),a=N(r);return a!==i&&a.startsWith(i+P)?r:null}function resolveBinEntries(e){return e.bin?typeof e.bin==`string`?{[e.name.startsWith(`@`)&&e.name.split(`/`)[1]||e.name]:e.bin}:e.bin:{}}async function createBinLinks(n,r,i){let a=resolveBinEntries(i);if(Object.keys(a).length===0)return 0;let o=j(n,`node_modules`,`.bin`),s=Object.entries(a).map(([e,t])=>({binName:e,binPath:t,linkPath:resolveBinPath(o,e),cmdPath:resolveBinPath(o,e,`.cmd`),ps1Path:resolveBinPath(o,e,`.ps1`)})).filter(t=>!t.linkPath||!t.cmdPath||!t.ps1Path?(e.warn(`bin name "${t.binName}" is not safe, skipping`),!1):!0),l=j(n,`node_modules`,r),p=N(l),m=s.filter(({binName:t,binPath:n})=>{let r=N(j(l,n));return r.startsWith(p+P)||r===p?!0:(e.warn(`bin "${t}" points outside package directory, skipping`),!1)});if(m.length===0)return 0;if(d()){for(let{linkPath:e}of m)f({type:`bin-link`,path:e,detail:r});return u(`[dry-run] would create ${m.length} bin link(s) for ${r}`),m.length}await x(o,{recursive:!0});let h=v()===`win32`,g=0;for(let{binName:e,binPath:n,linkPath:r,cmdPath:i,ps1Path:a}of m){let s=j(l,n),d=t(M(o,s)),f=await readBinInterpreter(s);if(h){let e=`@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${f} "%dp0%\\${d.replace(/\//g,`\\`)}" %*\r\n`;await O(i,e);let t=`#!/usr/bin/env pwsh\n$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n& ${f} "$basedir/${d}" $args\nexit $LASTEXITCODE\n`;await O(a,t);let n=`#!/bin/sh\nbasedir=$(dirname "$0")\nexec ${f} "$basedir/${d}" "$@"\n`;await O(r,n)}else{try{await E(r,{force:!0})}catch{}try{await D(d,r),await y(s,493)}catch(t){if(c(t)&&(t.code===`EPERM`||t.code===`EACCES`)){u(`[bin-linker] Symlink failed (${t.code}), using shell wrapper for ${e}`);let n=`#!/bin/sh\nbasedir=$(dirname "$0")\nexec ${f} "$basedir/${d}" "$@"\n`;await O(r,n),await y(r,493)}else throw t}}g++}return g}async function removeBinLinks(e,t){let n=resolveBinEntries(t),r=j(e,`node_modules`,`.bin`),i=Object.keys(n).map(e=>({binName:e,linkPath:resolveBinPath(r,e),cmdPath:resolveBinPath(r,e,`.cmd`),ps1Path:resolveBinPath(r,e,`.ps1`)})).filter(e=>!!e.linkPath&&!!e.cmdPath&&!!e.ps1Path);if(d()){for(let{linkPath:e}of i)f({type:`bin-unlink`,path:e});u(`[dry-run] would remove ${i.length} bin link(s)`);return}let a=v()===`win32`,o=j(e,`node_modules`,t.name);for(let{linkPath:e,cmdPath:t,ps1Path:n}of i)try{await binFileBelongsToPackage(r,e,o)&&await E(e,{force:!0}),a&&(await binFileBelongsToPackage(r,t,o)&&await E(t,{force:!0}),await binFileBelongsToPackage(r,n,o)&&await E(n,{force:!0}))}catch{}}async function binFileBelongsToPackage(e,n,r){let i;try{i=await b(n)}catch(e){if(c(e)&&e.code===`ENOENT`)return!1;throw e}let a=N(r);if(i.isSymbolicLink()){let t=await w(n),r=N(e,t);return r===a||r.startsWith(a+P)}if(!i.isFile())return!1;let o=await S(n,`utf-8`),s=t(M(e,r)),l=s.replace(/\//g,`\\`);return o.includes(`${s}/`)||o.includes(`${s}"`)||o.includes(`${l}\\`)||o.includes(`${l}"`)}const L={next:[`.next/cache`],webpack:[`node_modules/.cache`]},R=/* @__PURE__ */ new Map;async function invalidateBundlerCache(e){if(d())return u(`[dry-run] would invalidate bundler caches for ${e}`),f({type:`cache-invalidate`,path:e}),0;let t=R.get(e);t||(t=await m(e),R.set(e,t));let i=0;for(let a of t){if(!a.type)continue;let t=L[a.type];if(t)for(let o of t){let t=j(e,o);if(await n(t))try{await r(t),i++,u(`[inject] Invalidated ${a.type} cache: ${o}`)}catch{u(`[inject] Could not clear ${a.type} cache: ${o} (locked?)`)}}}return i}async function inject(e,t,n,r={}){let i=await resolveInjectionTarget(t,e.name,n,e.version,{repairMissingLink:!0});u(`[inject] ${e.name}@${e.version} → ${i}`),await o(i);let s=await readPackageJson(i),{copied:c,removed:l,skipped:d}=await a(e.packageDir,i,{force:r.force});u(`[inject] ${c} copied, ${l} removed, ${d} skipped`);let f=c>0||l>0?await invalidateBundlerCache(t):0,p=await readPackageJson(e.packageDir);s&&await removeBinLinks(t,s);let m=p?await createBinLinks(t,e.name,p):0;return m>0&&u(`[inject] Created ${m} bin link(s)`),{copied:c,removed:l,skipped:d,binLinks:m,cacheInvalidations:f}}async function backupExisting(e,t,a){let o=await resolveInjectionTarget(e,t,a,void 0,{warnOnFallback:!1});if(!await n(o))return!1;let c=i(e,t);return await r(c),await s(o,c),!0}async function restoreBackup(e,t,a,o){let c=i(e,t);if(!await n(c))return!1;let l=await resolveInjectionTarget(e,t,a,o),f=await readPackageJson(l);f&&await removeBinLinks(e,f),await r(l),await s(c,l);let p=await readPackageJson(d()?c:l);if(p){let n=await createBinLinks(e,t,p);n>0&&u(`[restore] Restored ${n} original bin link(s) for ${t}`)}return await r(c),!0}async function removeInjected(e,t,n,i){let a=l(e,t),o=await resolveInjectionTarget(e,t,n,i),s=await readPackageJson(o);s&&await removeBinLinks(e,s),await r(o),N(o)!==N(a)&&await r(a)}async function checkMissingDeps(e,t,n){let r=await readPackageJson(e.packageDir);if(!r)return[];let i={...r.dependencies,...Object.fromEntries(Object.entries(r.peerDependencies??{}).filter(([e])=>!r.peerDependenciesMeta?.[e]?.optional))};if(Object.keys(i).length===0)return[];let a=Object.keys(i);return(await Promise.all(a.map(async r=>({dep:r,installed:await isDependencyInstalledForPackage(r,e,t,n)})))).filter(e=>!e.installed).map(e=>e.dep)}async function isDependencyInstalledForPackage(e,t,r,i){return await n(j(r,`node_modules`,e))?!0:i?dependencyVisibleFromDirectory(await resolveInjectionTarget(r,t.name,i,t.version,{warnOnFallback:!1}),e):!1}async function dependencyVisibleFromDirectory(e,t){let r=await T(e).catch(t=>{if(c(t)&&t.code===`ENOENT`)return e;throw t});for(;;){if(await n(j(r,`node_modules`,t)))return!0;let e=k(r);if(e===r)return!1;r=e}}async function resolveInjectionTarget(t,r,i,a,o={}){let s=l(t,r),d=(await p(t)).resolve(i);if(!d.nodeModulesCompatible)throw Error(d.incompatibilityReason);let f=d.layout===`pnpm`||d.layout===`yarn-pnpm`?d.layout:null;if(!f)return d.layout===`bun`?resolveBunTarget(t,s,r):s;let m=f===`pnpm`?await getPnpmVirtualStoreDirs(t):await getYarnPnpmStoreDirs(t,d.virtualStoreFolder);try{let e=await resolvePackageEntrySymlink(s);if(e){if(!(f===`pnpm`?await isPnpmVirtualStorePackageRealPath(m,r,e):await isYarnPnpmStorePackageRealPath(m,e)))throw Error(`Refusing to inject ${r}: node_modules entry resolves outside a configured ${storeKindLabel(f)} virtual store (${e})`);return await validateResolvedPackageIdentity(e,r,void 0,f),u(`[inject] ${storeKindLabel(f)}: resolved symlink → ${e}`),e}}catch(e){if(!(c(e)&&e.code===`ENOENT`))throw c(e)&&u(`${storeKindLabel(f)} symlink resolution error: ${e instanceof Error?e.message:String(e)}`),e}let h=[];for(let e of m)await n(e)&&h.push(e);if(h.length>0){if(!await isDeclaredConsumerDependency(t,r))return u(`[inject] ${storeKindLabel(f)}: ${r} is not declared by the consumer, skipping virtual store scan`),s;if(f===`yarn-pnpm`){let e=[];for(let n of h){u(`[inject] yarn-pnpm: scanning ${M(t,n)||`.`} for ${r}`);let i=await resolveYarnPnpmCandidate(n,r,a);i&&e.push(i)}let n=requireSingleVirtualStoreCandidate(r,f,e);if(n)return u(`[inject] yarn-pnpm: found in virtual store → ${n}`),o.repairMissingLink&&await repairMissingVirtualStoreLink(s,n,r,f),n}if(f===`pnpm`){let e=r.replaceAll(`/`,`+`);for(let n of h){if(u(`[inject] pnpm: scanning ${M(t,n)||`.`} for ${r}`),a){let t=`${e}@${a}`,i=await resolvePnpmCandidate(n,r,a,j(n,t,`node_modules`,r));if(i)return u(`[inject] pnpm: exact version match in virtual store → ${i}`),o.repairMissingLink&&await repairMissingVirtualStoreLink(s,i,r,f),i}let i=await C(n),c=[];for(let t of i)if(matchesPnpmPackageEntry(e,a,t)){let e=await resolvePnpmCandidate(n,r,a,j(n,t,`node_modules`,r));e&&c.push(e)}let l=requireSingleVirtualStoreCandidate(r,f,c);if(l)return u(`[inject] pnpm: found in virtual store → ${l}`),o.repairMissingLink&&await repairMissingVirtualStoreLink(s,l,r,f),l}}}if(o.warnOnFallback!==!1){if(await isDeclaredConsumerDependency(t,r)){let t=f===`pnpm`?`pnpm`:`yarn`;e.warn(`${r} is in package.json but not installed in the ${storeKindLabel(f)} virtual store, so Knarr is linking it at node_modules/${r} directly. Run \`${t} install\` and then \`knarr add ${r}\` to update the installed copy instead.`)}else u(`[inject] ${storeKindLabel(f)}: ${r} not installed yet, linking at node_modules/${r}`)}return s}function storeKindLabel(e){return e===`pnpm`?`pnpm`:`Yarn pnpm-linker`}async function resolveBunTarget(e,t,n){try{if(!(await b(t)).isSymbolicLink())return t}catch(e){if(c(e)&&e.code===`ENOENT`)return t;throw e}let r=await T(t),i=j(e,`node_modules`,`.bun`);if(!isPathInside(await T(i).catch(e=>{if(c(e)&&e.code===`ENOENT`)return i;throw e}),r))throw Error(`Refusing to inject ${n}: Bun target resolves outside the local node_modules/.bun store (${r})`);return await validateResolvedPackageIdentity(r,n,void 0,`Bun isolated`),u(`[inject] Bun isolated: resolved symlink → ${r}`),r}function isPathInside(e,t){let n=M(N(e),N(t));return n===``||!!n&&!n.startsWith(`..`)&&!A(n)}async function resolvePackageEntrySymlink(e){return(await b(e)).isSymbolicLink()?T(e):null}async function validateResolvedPackageIdentity(e,t,n,r){let i=r===`Bun isolated`?r:storeKindLabel(r),a=await readPackageJson(e);if(a){if(a.name&&a.name!==t)throw Error(`Refusing to inject ${t}: ${i} target contains package "${a.name}"`);if(n&&a.version&&a.version!==n)throw Error(`Refusing to inject ${t}@${n}: ${i} target contains version ${a.version}`)}}async function repairMissingVirtualStoreLink(e,t,n,r){let i=!1;try{if(!(await b(e)).isSymbolicLink())return;i=!0}catch(e){if(!c(e)||e.code!==`ENOENT`)throw e}let a=k(e);if(d()){let i=M(a,t);u(`[inject] ${storeKindLabel(r)}: would restore node_modules symlink for ${n} → ${i}`),f({type:`write`,path:e,dest:t,detail:`${storeKindLabel(r)} package symlink`});return}let s=v()===`win32`;await o(a);let l=await T(a).catch(()=>a),p=M(l,t);u(`[inject] ${storeKindLabel(r)}: restoring node_modules symlink for ${n} → ${p}`),i&&await E(e,{force:!0}),await D(s?t:p,e,s?`junction`:`dir`)}async function resolvePnpmCandidate(e,t,n,r){if(!isPnpmVirtualStorePackagePathFromRoot(e,t,r))return null;try{let[i,a]=await Promise.all([T(e),T(r)]);if(!isPnpmVirtualStorePackagePathFromRoot(i,t,a))throw Error(`Refusing to inject ${t}: virtual store candidate resolves outside a configured pnpm virtual store (${a})`);return await validateResolvedPackageIdentity(a,t,n,`pnpm`),a}catch(e){if(c(e)&&e.code===`ENOENT`)return null;throw e}}async function resolveYarnPnpmCandidate(e,t,n){let r=await C(e),i=[];for(let a of r){let r=j(e,a,`package`),o=await readPackageJson(r);if(!o||o.name!==t||n&&o.version!==n)continue;let[s,c]=await Promise.all([T(e),T(r)]);if(!isYarnPnpmStorePackagePathFromRoot(s,c))throw Error(`Refusing to inject ${t}: virtual store candidate resolves outside a configured Yarn pnpm-linker virtual store (${c})`);i.push(c)}return requireSingleVirtualStoreCandidate(t,`yarn-pnpm`,i)}function matchesPnpmPackageEntry(e,t,n){if(!t)return n.startsWith(`${e}@`);let r=`${e}@${t}`;return n===r||n.startsWith(`${r}_`)}function requireSingleVirtualStoreCandidate(e,t,n){if(n.length<=1)return n[0]??null;throw Error(`Refusing to repair ${e}: multiple ${storeKindLabel(t)} virtual-store entries match. Run your package manager's install command, then try again.`)}async function getPnpmVirtualStoreDirs(e){let t=j(e,`node_modules`),n=[],r=j(t,`.pnpm`);await isLocalVirtualStoreDir(e,r)&&n.push(r);let i=await readConfiguredPnpmVirtualStoreDir(t);if(!i)return n;let a=A(i)?i:N(t,i);return await isLocalVirtualStoreDir(e,a)?(n.some(e=>N(e)===N(a))||n.push(a),n):(u(`[inject] pnpm: ignoring external virtualStoreDir ${a}`),n)}async function getYarnPnpmStoreDirs(e,t){let n=j(e,`node_modules`),r=[],i=j(n,`.store`);if(await isLocalVirtualStoreDir(e,i)&&r.push(i),!t)return r;let a=A(t)?t:N(e,t);return await isLocalVirtualStoreDir(e,a)?(r.some(e=>N(e)===N(a))||r.push(a),r):(u(`[inject] yarn-pnpm: ignoring external pnpmStoreFolder ${a}`),r)}async function isLocalVirtualStoreDir(e,t){return isPathInside(await T(e).catch(()=>N(e)),await T(t).catch(e=>{if(c(e)&&e.code===`ENOENT`)return N(t);throw e}))}async function readConfiguredPnpmVirtualStoreDir(e){try{return parsePnpmVirtualStoreDir(await S(j(e,`.modules.yaml`),`utf-8`))}catch(e){if(c(e)&&e.code===`ENOENT`)return null;throw e}}function parsePnpmVirtualStoreDir(e){try{let t=h(g(e),`virtualStoreDir`)?.trim();if(t)return t}catch{}let t=e.match(/^virtualStoreDir:\s*(.+?)\s*$/m);if(!t)return null;let n=(t[1]??``).trim().replace(/\s+#.*$/,``);return(n.startsWith(`"`)&&n.endsWith(`"`)||n.startsWith(`'`)&&n.endsWith(`'`))&&(n=n.slice(1,-1)),n||null}async function isPnpmVirtualStorePackageRealPath(e,t,n){for(let r of e)try{if(isPnpmVirtualStorePackagePathFromRoot(await T(r),t,n))return!0}catch(e){if(c(e)&&e.code===`ENOENT`)continue;throw e}return!1}async function isYarnPnpmStorePackageRealPath(e,t){for(let n of e)try{if(isYarnPnpmStorePackagePathFromRoot(await T(n),t))return!0}catch(e){if(c(e)&&e.code===`ENOENT`)continue;throw e}return!1}function isPnpmVirtualStorePackagePathFromRoot(e,t,n){if(!isPathInside(e,n))return!1;let r=M(e,n).replace(/\\/g,`/`),i=`node_modules/${t}`.replace(/\\/g,`/`);return r===i||r.endsWith(`/${i}`)}function isYarnPnpmStorePackagePathFromRoot(e,t){if(!isPathInside(e,t))return!1;let n=M(e,t).replace(/\\/g,`/`).split(`/`);return n.length===2&&n[1]===`package`}async function isDeclaredConsumerDependency(e,t){let n=await readPackageJson(e);return n?!!(n.dependencies?.[t]||n.devDependencies?.[t]||n.optionalDependencies?.[t]||n.peerDependencies?.[t]):!1}async function readPackageJson(t){try{let e=await S(j(t,`package.json`),`utf-8`);return _(g(e,j(t,`package.json`)))}catch(n){return c(n)&&n.code!==`ENOENT`&&e.warn(`Failed to read package.json in ${t}: ${n instanceof Error?n.message:String(n)}`),null}}export{removeInjected as a,isDeclaredConsumerDependency as i,checkMissingDeps as n,resolveInjectionTarget as o,inject as r,restoreBackup as s,backupExisting as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{readFile as e}from"node:fs/promises";function ownRecord(e){let t=Object.create(null);if(e)for(let[n,r]of Object.entries(e))t[n]=r;return t}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function parseJson(e){return JSON.parse(e)}function parseJsonObject(e,t=`JSON`){let n=parseJson(e);if(!isJsonObject(n))throw Error(`${t} must contain a JSON object`);return n}async function readJsonObject(t,n=t){return parseJsonObject(await e(t,`utf-8`),n)}function stringField(e,t){let n=e[t];return typeof n==`string`?n:void 0}function objectField(e,t){let n=e[t];return isJsonObject(n)?n:void 0}function stringRecordField(e,t){let n=objectField(e,t),r=ownRecord();if(!n)return r;for(let[e,t]of Object.entries(n))typeof t==`string`&&(r[e]=t);return r}function asPackageJson(e){return typeof e.name!=`string`||typeof e.version!=`string`?null:e}function detectJsonIndent(e){return/^(\s+)"/m.exec(e)?.[1]??` `}export{ownRecord as a,readJsonObject as c,objectField as i,stringField as l,detectJsonIndent as n,parseJson as o,isJsonObject as r,parseJsonObject as s,asPackageJson as t,stringRecordField as u};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{l as r,s as i}from"./tracker-B3Fqx94J.mjs";import{r as a}from"./history-vS3w4EGu.mjs";import{n as o,r as s}from"./store-DjPdOKqg.mjs";import{a as c,m as l}from"./fs-CPnWm9CR.mjs";import{t as u}from"./format-DRqD29u-.mjs";import{a as d}from"./json-DbSkpxtr.mjs";import{n as f,t as p}from"./output-BxR2v-jn.mjs";import{resolve as m}from"node:path";var h=e({meta:{name:`list`,description:`List linked packages in current project or in the store`},args:{store:{type:`boolean`,description:`List all packages in the global Knarr store`,default:!1},history:{type:`boolean`,description:`Show build history for linked packages`,default:!1}},async run({args:e}){f(),e.store?await listStore():e.history?await listHistory():await listProject()}});async function listProject(){let e=await i(m(`.`)),r=Object.entries(e.links);if(r.length===0){n.info(`No linked packages in this project`),p({packages:[]});return}n.info(`Linked packages (${r.length}):\n`);let a=l(8),s=await Promise.all(r.map(([e,t])=>a(async()=>{let n=await o(e,t.version),r=!!(n&&n.meta.contentHash!==t.contentHash);return{name:e,version:t.version,buildId:t.buildId??null,stale:r,sourcePath:t.sourcePath}})));for(let e of s){let r=e.buildId?`[${e.buildId}]`:`[--------]`,i=e.stale?t.yellow(` (stale)`):``;n.log(` ${t.cyan(e.name)} ${t.dim(`@`+e.version)} ${t.dim(r)}${i} ← ${t.dim(e.sourcePath)}`)}p({packages:s})}async function listStore(){let[e,i]=await Promise.all([s(),r()]);if(e.length===0){n.info(`Knarr store is empty`),p({entries:[],totalSize:0});return}let a=l(8),o=await Promise.all(e.map(e=>a(()=>c(e.packageDir)))),d=o.reduce((e,t)=>e+t,0);n.info(`Store entries (${e.length}, ${u(d)} total):\n`);let f=[];for(let[r,a]of e.entries()){let e=o[r]??0,s=getRelativeTime(new Date(a.meta.publishedAt)),c=a.meta.buildId?`[${a.meta.buildId}]`:`[--------]`,l=i[a.name]?.length??0,d=l>0?t.green(`${l} consumer${l>1?`s`:``}`):t.dim(`no consumers`);n.log(` ${t.cyan(a.name)} ${t.dim(`@`+a.version)} ${t.dim(c)} ${t.dim(u(e))} ${t.dim(`published ${s}`)} ${d}`),n.log(` ${t.dim(`from: ${a.meta.sourcePath}`)}`),f.push({name:a.name,version:a.version,buildId:a.meta.buildId??null,publishedAt:a.meta.publishedAt,sourcePath:a.meta.sourcePath,consumers:l,size:e})}p({entries:f,totalSize:d})}async function listHistory(){let e=await i(m(`.`)),r=Object.entries(e.links);if(r.length===0){n.info(`No linked packages in this project`),p({packages:[]});return}let o=d();for(let[e,i]of r){let r=await a(e,i.version);n.info(`${t.cyan(e)} ${t.dim(`@`+i.version)} — ${r.length} historical build(s)`);for(let e of r){let r=getRelativeTime(new Date(e.publishedAt));n.log(` ${t.dim(e.buildId)} ${t.dim(`published ${r}`)}`)}o[e]=r.map(e=>({buildId:e.buildId,publishedAt:e.publishedAt,contentHash:e.contentHash}))}p({history:o})}function getRelativeTime(e){let t=Date.now()-e.getTime(),n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;let r=Math.floor(n/60);if(r<60)return`${r}m ago`;let i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}export{h as default};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-CIiXr7ge.mjs";let t=!1,n=!1,r=!1;function initFlags(){t=process.argv.includes(`--verbose`)||process.argv.includes(`-v`),n=process.argv.includes(`--dry-run`),r=process.argv.includes(`--json`),t&&(e.level=4)}function isDryRun(){return n}function isJsonOutput(){return r}function verbose(n,...r){t&&e.debug(n,...r)}export{verbose as i,isDryRun as n,isJsonOutput as r,initFlags as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./dist-CFkjiIqD.mjs";import{n as t,t as n}from"./console-CIiXr7ge.mjs";import{c as r,f as i,t as a}from"./fs-CPnWm9CR.mjs";import{t as o}from"./timer-DqgB175x.mjs";import{n as s,t as c}from"./output-BxR2v-jn.mjs";import{n as l,r as u}from"./logger-9C6B9Na8.mjs";import{i as d,r as f}from"./dry-run-BkdMYSIx.mjs";import{n as p,t as m}from"./add-flow-cvrMO_aV.mjs";import{t as h}from"./hints-Hz3V4h3A.mjs";import{i as g,s as _}from"./json-DbSkpxtr.mjs";import{readFile as v}from"node:fs/promises";import{join as y,resolve as b}from"node:path";var x=e({meta:{name:`migrate`,description:`Migrate from yalc to Knarr`},args:{from:{type:`string`,description:`Path to a local package source to publish and link after cleanup`},yes:{type:`boolean`,alias:`y`,description:`Skip confirmation prompts`,default:!1}},async run({args:e}){s(),await runMigrate({yes:e.yes,from:e.from})}});async function runMigrate(e={}){let a=new o,s=b(`.`);n.info(`Checking for yalc usage...
|
|
4
|
+
`);let u=y(s,`.yalc`),p=y(s,`yalc.lock`),g=y(s,`package.json`),_=await r(u),v=await r(p);if(!_&&!v){n.info(`No yalc usage detected in this project.`);let e={migrated:!1,packages:[],linkedPackages:[],plannedLinks:[],elapsed:a.elapsedMs()};return c(e),e}let x=await readYalcPackages(p,v);if(!e.yes){let e=await n.prompt(`Migrate from yalc to Knarr? This will modify package.json and remove .yalc/ and yalc.lock.`,{type:`confirm`});if(!e||typeof e==`symbol`){n.info(`Cancelled`);let e={migrated:!1,packages:x,linkedPackages:[],plannedLinks:[],elapsed:a.elapsedMs()};return c(e),e}}if(x.length>0&&n.info(`Found ${x.length} yalc-linked package(s): ${x.map(e=>t.cyan(e)).join(`, `)}`),await cleanupPackageJson(g),_&&(await i(u),n.success(`Removed .yalc/ directory`)),v){if(l())d({type:`remove`,path:p});else{let{rm:e}=await import(`node:fs/promises`);await e(p,{force:!0})}n.success(`Removed yalc.lock`)}let S=await resolveMigrationSources(x,e),C=[],w=[];if(S.length>0)for(let t of S){let n=`knarr add ${t.packageName} --from ${t.sourcePath}`;l()?(d({type:`command-skip`,path:s,detail:n}),w.push(n)):(await m({packageArg:t.packageName,from:t.sourcePath,yes:e.yes??!1,emitOutput:!1}),C.push(t.packageName))}if(n.log(``),n.info(`${t.bold(`Migration complete!`)} Next steps:\n`),S.length===0||w.length>0){n.log(` 1. ${t.cyan(`knarr init`)}`);let e=x.length>0?x:[`<package>`],r=2;for(let i of e){let e=w.find(e=>e.includes(` ${i} `))??`knarr add ${i} --from <path-to-${i}>`;n.log(` ${r}. ${t.cyan(e)}`),r++}}else{n.log(` 1. ${t.cyan(`knarr doctor --fix`)}`);for(let e of S)n.log(` 2. ${t.cyan(h(e.sourcePath))}`)}n.log(`\n Run ${t.cyan(`knarr doctor`)} to verify your setup.\n`),n.info(`Migrated in ${a.elapsed()}`);let T={migrated:!0,packages:x,linkedPackages:C,plannedLinks:w,elapsed:a.elapsedMs()};return c(T),l()&&f(),T}async function readYalcPackages(e,t){if(!t)return[];try{let t=await v(e,`utf-8`),n=g(_(t,`yalc.lock`),`packages`);return n?Object.keys(n):[]}catch{return n.warn(`Could not parse yalc.lock - the file may be corrupted. Continuing with cleanup.`),[]}}async function cleanupPackageJson(e){if(await r(e))try{let r=await v(e,`utf-8`),i=_(r,e),o=!1;for(let e of[`dependencies`,`devDependencies`,`peerDependencies`]){let r=g(i,e);if(r)for(let[e,i]of Object.entries(r))typeof i==`string`&&i.includes(`.yalc/`)&&(delete r[e],o=!0,n.info(`Removed file:.yalc/ reference for ${t.cyan(e)}`))}if(o){let t=r.match(/^(\s+)"/m)?.[1]||` `;await a(e,JSON.stringify(i,null,t)+`
|
|
5
|
+
`),n.success(`Cleaned up package.json`)}}catch(e){n.warn(`Could not clean package.json: ${e instanceof Error?e.message:String(e)}. You may need to manually remove file:.yalc/ references.`)}}async function resolveMigrationSources(e,t){if(t.from){if(e.length>1){if(n.warn(`--from is only used for one-package migrations; source paths are needed per package.`),t.yes||u())return[]}else{let r=b(t.from),i=await p(r);return e.length===1&&e[0]!==i&&n.warn(`yalc.lock lists ${e[0]}, but ${r} is ${i}; linking ${i}.`),[{packageName:i,sourcePath:r}]}}if(e.length<=1||t.yes||u())return[];let r=[];for(let t of e){let e=await n.prompt(`Source path for ${t} (leave blank to skip):`,{type:`text`,default:``});if(typeof e!=`string`||!e.trim())continue;let i=b(e.trim()),a=await p(i);a!==t&&n.warn(`yalc.lock lists ${t}, but ${i} is ${a}; linking ${a}.`),r.push({packageName:a,sourcePath:i})}return r}export{x as default};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
export{t as addToTranspilePackages,n as hasTranspilePackage}from"./nextjs-config-
|
|
3
|
+
export{t as addToTranspilePackages,n as hasTranspilePackage}from"./nextjs-config-dUw2J6B9.mjs";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./fs-
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./fs-CPnWm9CR.mjs";import{r as t}from"./vite-config-BHmawlD2.mjs";import{readFile as n}from"node:fs/promises";function detectIndent(e){return e.match(/^(\s+)\S/m)?.[1]||` `}function parseArrayItems(e){let t=[],n=/['"]([^'"]*)['"]/g,r;for(;(r=n.exec(e))!==null;)t.push(r[1]??``);return t}async function hasTranspilePackage(e,t){let r;try{r=await n(e,`utf-8`)}catch{return{configured:!1,error:`could not read config file`}}let i=/transpilePackages\s*:\s*\[([^\]]*)\]/s.exec(r);return i?{configured:parseArrayItems(i[1]??``).includes(t)}:{configured:!1}}function formatArray(e,t){return e.length===0?`[]`:e.length<=3?`[${e.map(e=>`'${e}'`).join(`, `)}]`:`[\n${e.map(e=>`${t}${t}'${e}',`).join(`
|
|
4
4
|
`)}\n${t}]`}function isComplexNextConfig(e){let n=t(e);return n.complex?n:/(?:module\.exports\s*=\s*|export\s+default\s+)[\w.]+\s*\(\s*\{/.test(e)?{complex:!0,reason:`wrapper function pattern`}:/\w+\s*\(\s*\w+\s*\(/.test(e)&&e.includes(`module.exports`)?{complex:!0,reason:`chained wrapper functions`}:{complex:!1}}async function addToTranspilePackages(t,r){let i;try{i=await n(t,`utf-8`)}catch{return{modified:!1,error:`could not read config file`}}let a=isComplexNextConfig(i);if(a.complex)return{modified:!1,error:`config too complex (${a.reason})`};let o=detectIndent(i),s=/transpilePackages\s*:\s*\[([^\]]*)\]/s,c=s.exec(i);if(c){let n=parseArrayItems(c[1]??``);if(n.includes(r))return{modified:!1};n.push(r);let a=formatArray(n,o),l=i.replace(s,`transpilePackages: ${a}`);return await e(t,l),{modified:!0}}for(let n of[/module\.exports\s*=\s*\{/,/export\s+default\s+\{/,/(?:const|let|var)\s+\w*[Cc]onfig\w*\s*=\s*\{/]){let a=n.exec(i);if(a){let n=a.index+a[0].length,s=`\n${o}transpilePackages: ['${r}'],`,c=i.slice(0,n)+s+i.slice(n);return await e(t,c),{modified:!0}}}return{modified:!1,error:`unrecognized config pattern`}}async function removeFromTranspilePackages(t,r){let i;try{i=await n(t,`utf-8`)}catch{return{modified:!1}}let a=detectIndent(i),o=/transpilePackages\s*:\s*\[([^\]]*)\]/s,s=o.exec(i);if(!s)return{modified:!1};let c=parseArrayItems(s[1]??``),l=c.filter(e=>e!==r);if(l.length===c.length)return{modified:!1};let u=formatArray(l,a),d=i.replace(o,`transpilePackages: ${u}`);return await e(t,d),{modified:!0}}export{hasTranspilePackage as n,removeFromTranspilePackages as r,addToTranspilePackages as t};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./console-CIiXr7ge.mjs";import{n as t,r as n}from"./logger-9C6B9Na8.mjs";import{n as r,t as i}from"./dry-run-BkdMYSIx.mjs";function output(e){if(n()){if(t()){r(),console.log(JSON.stringify(e&&typeof e==`object`&&!Array.isArray(e)?{...e,dryRun:!0,mutations:i()}:{data:e,dryRun:!0,mutations:i()},null,2));return}console.log(JSON.stringify(e,null,2))}}function suppressHumanOutput(){n()&&(e.level=-1)}export{suppressHumanOutput as n,output as t};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as __cr}from"node:module";globalThis.require=__cr(import.meta.url);
|
|
3
|
-
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./shell-RQ7Hf1kp.mjs";import{i as t}from"./dry-run-
|
|
3
|
+
import"./rolldown-runtime-BZbIAPMk.mjs";import{t as e}from"./shell-RQ7Hf1kp.mjs";import{i as t}from"./dry-run-BkdMYSIx.mjs";import{n}from"./logger-9C6B9Na8.mjs";import{s as r}from"./json-DbSkpxtr.mjs";import{M as i}from"./fs-CPnWm9CR.mjs";import{readFile as a,stat as o}from"node:fs/promises";import{dirname as s,join as c}from"node:path";const l=/* @__PURE__ */ new Set([`npm`,`pnpm`,`yarn`,`bun`]),u=[[`pnpm-lock.yaml`,`pnpm`],[`bun.lockb`,`bun`],[`bun.lock`,`bun`],[`yarn.lock`,`yarn`],[`package-lock.json`,`npm`],[`npm-shrinkwrap.json`,`npm`]],d=[`.pnp.cjs`,`.pnp.js`,`.pnp.loader.mjs`],f=[`.yarnrc.yml`,...d];function parsePackageManagerSpec(e){if(typeof e!=`string`)return null;let t=e.trim().match(/^([^@\s]+)(?:@(.+))?$/);if(!t)return null;let n=t[1];return!n||!l.has(n)?null:{name:n,version:t[2]?.trim()??``}}async function readPackageManagerSpec(e){try{let t=await a(c(e,`package.json`),`utf-8`);return parsePackageManagerSpec(r(t).packageManager)}catch{return null}}async function findPackageManagerSpec(e){let t=e;for(;;){let e=await readPackageManagerSpec(t);if(e)return e;let n=s(t);if(n===t)return null;t=n}}function yarnDefaultsToPnp(e){let t=e.trim().replace(/^npm:/,``);if(t===`classic`)return!1;let n=t.match(/^v?(\d+)(?:[.+-]|$)/);return n?Number(n[1])>=2:t.length>0}async function detectPackageManagerInfo(e){let t=e;for(;;){let n=await readPackageManagerSpec(t);if(n)return{packageManager:n.name,source:`packageManager`,dir:t,file:c(t,`package.json`)};let r=(await Promise.all(u.map(async([e,n])=>{try{return await o(c(t,e)),{lockfile:e,packageManager:n}}catch{return null}}))).find(e=>e!==null);if(r)return{packageManager:r.packageManager,source:`lockfile`,dir:t,file:c(t,r.lockfile)};let i=await findExistingFile(t,f);if(i)return{packageManager:`yarn`,source:`yarnArtifact`,dir:t,file:c(t,i)};let a=s(t);if(a===t)return{packageManager:`npm`,source:`default`,dir:e};t=a}}async function findExistingFile(e,t){for(let n of t)try{return await o(c(e,n)),n}catch{}return null}function readYarnrcScalar(e,t){for(let n of e.split(`
|
|
4
4
|
`)){let e=n.trim();if(e.startsWith(`#`)||!e.includes(t))continue;let r=e.match(RegExp(`^${t}:\\s*(.+)$`));if(!r?.[1])continue;let i=r[1].trim().replace(/\s+#.*$/,``).trim().replace(/^["']|["']$/g,``);if(i)return i}return null}async function findYarnrcScalar(e,t){let n=e;for(;;){try{let e=readYarnrcScalar(await a(c(n,`.yarnrc.yml`),`utf-8`),t);if(e)return e}catch{}let e=s(n);if(e===n)return null;n=e}}async function detectYarnNodeLinker(e){let t=await findYarnrcScalar(e,`nodeLinker`);return t===`node-modules`||t===`pnpm`||t===`pnp`?t:null}async function detectYarnPnpmStoreFolder(e){return findYarnrcScalar(e,`pnpmStoreFolder`)}async function hasYarnrcYml(e){let t=e;for(;;)try{return await o(c(t,`.yarnrc.yml`)),!0}catch{let e=s(t);if(e===t)return!1;t=e}}async function hasYarnPnpManifest(e){let t=e;for(;;){if((await Promise.all(d.map(async e=>{try{return await o(c(t,e)),!0}catch{return!1}}))).some(Boolean))return!0;let e=s(t);if(e===t)return!1;t=e}}async function isYarnPnpProject(e){let t=await detectYarnNodeLinker(e);if(t===`pnp`)return!0;if(t===`node-modules`||t===`pnpm`)return!1;if(await hasYarnPnpManifest(e)||await hasYarnrcYml(e))return!0;let n=await findPackageManagerSpec(e);return n?.name===`yarn`&&yarnDefaultsToPnp(n.version)}const p={npm:{layout:()=>`node-modules`,installArgs:(e,t)=>[`install`,...t?[`-D`]:[],...e]},pnpm:{layout:()=>`pnpm`,installArgs:(e,t)=>[`add`,...t?[`-D`]:[],...e]},yarn:{layout:e=>e===`pnpm`?`yarn-pnpm`:`node-modules`,installArgs:(e,t)=>[`add`,...t?[`-D`]:[],...e]},bun:{layout:()=>`bun`,installArgs:(e,t)=>[`add`,...t?[`-d`]:[],...e]}};async function inspectProjectPackageManager(e,t={}){let[n,r,i,a,o,s]=await Promise.all([detectPackageManagerInfo(e),hasYarnrcYml(e),hasYarnPnpManifest(e),detectYarnNodeLinker(e),detectYarnPnpmStoreFolder(e),isYarnPnpProject(e)]),resolvePackageManager=c=>{let l=t.packageManager??(n.source==="default"&&c?c:n.packageManager),u=p[l],d=i||a===`pnp`||l===`yarn`&&s,f=u.layout(a),m={packageManager:l,layout:f,virtualStoreFolder:f===`yarn-pnpm`?o:null,yarnLinkerDiagnostic:getYarnLinkerDiagnostic({packageManager:l,configExists:r,pnpManifestExists:i,nodeLinker:a,isPnp:d}),installCommand(e,t={}){return createInstallCommand(l,e,t.dev===!0)},formatCommand,run(t){return runPackageManagerCommand(t,e)}};return d?{...m,nodeModulesCompatible:!1,incompatibilityReason:`Yarn PnP mode is not compatible with Knarr.
|
|
5
5
|
|
|
6
6
|
Knarr works by copying files into node_modules/, but PnP eliminates
|