@visulima/package 5.0.0-alpha.3 → 5.0.0-alpha.31

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.
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Lockfiles the parser recognises. Both the modern text `bun.lock` and the
3
+ * legacy binary `bun.lockb` map to the `bun` type, but only `bun.lock`
4
+ * content is parseable — `bun.lockb` is a binary format and yields no entries.
5
+ */
6
+ type LockFileType = "bun" | "npm" | "pnpm" | "yarn";
7
+ /** SRI algorithms the parser can decode into hex. */
8
+ type LockFileIntegrityAlgorithm = "sha256" | "sha384" | "sha512";
9
+ /** Decoded integrity digest: algorithm + lowercase hex string. */
10
+ interface LockFileIntegrity {
11
+ algorithm: LockFileIntegrityAlgorithm;
12
+ hex: string;
13
+ }
14
+ /** A single resolved package extracted from a lockfile. */
15
+ interface LockFileEntry {
16
+ /**
17
+ * Declared runtime dependencies — `name → specifier[]` map. Values
18
+ * are arrays so pnpm v9+ peer-context variants (the same dep name
19
+ * resolved to different versions under different peer contexts)
20
+ * can all be preserved. npm, yarn v1, bun, and pnpm v6-v8 always
21
+ * produce single-element arrays; pnpm v9+ may produce multi-element
22
+ * arrays for peer-context-sensitive deps.
23
+ *
24
+ * Specifiers are whatever the lockfile recorded — a range
25
+ * (`^1.0.0`) for npm / yarn / bun, or an already-resolved exact
26
+ * version for pnpm. Callers resolve each specifier against
27
+ * {@link LockFileEntry.version} values elsewhere in the lockfile
28
+ * when they need a concrete edge.
29
+ */
30
+ dependencies?: Record<string, string[]>;
31
+ /** Decoded SRI digest, if the lockfile recorded one. */
32
+ integrity?: LockFileIntegrity;
33
+ /** Package name — `lodash` or `@scope/name`. */
34
+ name: string;
35
+ /** Declared optional dependencies, same shape as `dependencies`. */
36
+ optionalDependencies?: Record<string, string[]>;
37
+ /** Declared peer dependencies, same shape as `dependencies`. */
38
+ peerDependencies?: Record<string, string[]>;
39
+ /** Resolved exact version — e.g. `4.17.21`. */
40
+ version: string;
41
+ }
42
+ /** Result of locating + parsing a lockfile on disk. */
43
+ interface LockFileParseResult {
44
+ entries: LockFileEntry[];
45
+ /** Absolute path of the lockfile that was parsed. */
46
+ path: string;
47
+ type: LockFileType;
48
+ }
49
+ /**
50
+ * Decodes a Subresource Integrity string (`sha512-&lt;base64>`) into a
51
+ * `{ algorithm, hex }` pair. Returns `undefined` if the string is
52
+ * malformed, oversized, or uses an unsupported algorithm.
53
+ * @param sri Full SRI string, e.g. `sha512-&lt;base64>`.
54
+ * @returns Decoded algorithm + hex digest, or `undefined` when the
55
+ * input can't be parsed.
56
+ */
57
+ declare const decodeSriIntegrity: (sri: string) => LockFileIntegrity | undefined;
58
+ /**
59
+ * Parses `package-lock.json` (npm v2 / v3 format).
60
+ * @param content Raw JSON text of the lockfile.
61
+ * @returns One {@link LockFileEntry} per distinct `name@version`.
62
+ */
63
+ declare const parseNpmLockFile: (content: string) => LockFileEntry[];
64
+ /**
65
+ * Parses `pnpm-lock.yaml`. Regex-based; works for lockfile v6 through
66
+ * v9. v9 moves concrete resolved dependency versions out of `packages:`
67
+ * and into `snapshots:`; this parser reads both sections and unions
68
+ * their dep-maps onto the final entry.
69
+ * @param content Raw YAML text of the lockfile.
70
+ * @returns One {@link LockFileEntry} per distinct `name@version`.
71
+ */
72
+ declare const parsePnpmLockFile: (content: string) => LockFileEntry[];
73
+ /**
74
+ * Parses `yarn.lock` for Yarn Classic (v1) and Berry (v2+). Berry's
75
+ * XXH64 `checksum:` is not a cryptographic hash and is intentionally
76
+ * dropped; only v1's SRI `integrity:` flows through to
77
+ * {@link LockFileEntry.integrity}.
78
+ * @param content Raw text of the lockfile.
79
+ * @returns One {@link LockFileEntry} per distinct `name@version`.
80
+ */
81
+ declare const parseYarnLockFile: (content: string) => LockFileEntry[];
82
+ /**
83
+ * Parses `bun.lock` (Bun v1.1+, JSON-ish with trailing commas). The
84
+ * legacy binary `bun.lockb` format is recognised by {@link inferLockFileType}
85
+ * but cannot be decoded here — feeding its binary contents in returns an
86
+ * empty array (the `JSON.parse` fails and is swallowed).
87
+ *
88
+ * Attribution: format + tuple layout verified against lockparse
89
+ * (https://github.com/43081j/lockparse, MIT).
90
+ * @param content Raw text of the lockfile.
91
+ * @returns One {@link LockFileEntry} per distinct `name@version`.
92
+ */
93
+ declare const parseBunLockFile: (content: string) => LockFileEntry[];
94
+ /**
95
+ * Parses raw lockfile content of the given type. Returns an empty
96
+ * array if the content is malformed or doesn't contain any package
97
+ * entries.
98
+ * @param content Raw text of the lockfile.
99
+ * @param type Which parser to dispatch to.
100
+ * @returns One {@link LockFileEntry} per distinct `name@version`.
101
+ */
102
+ declare const parseLockFileContent: (content: string, type: LockFileType) => LockFileEntry[];
103
+ /**
104
+ * Walks up from `cwd`, locates the nearest supported lockfile, reads
105
+ * it, and returns the parsed entries alongside the lockfile type and
106
+ * absolute path.
107
+ * @param cwd Directory to start the search from. Defaults to
108
+ * `process.cwd()` (delegated to `findUp`).
109
+ * @returns The parsed result, keyed by the discovered lockfile path.
110
+ * @throws If no supported lockfile can be found above `cwd`.
111
+ */
112
+ declare const parseLockFile: (cwd?: URL | string) => Promise<LockFileParseResult>;
113
+ /**
114
+ * Synchronous counterpart to {@link parseLockFile}.
115
+ * @param cwd Directory to start the search from.
116
+ * @returns The parsed result, keyed by the discovered lockfile path.
117
+ * @throws If no supported lockfile can be found above `cwd`.
118
+ */
119
+ declare const parseLockFileSync: (cwd?: URL | string) => LockFileParseResult;
120
+ export { LockFileEntry, LockFileIntegrity, LockFileIntegrityAlgorithm, LockFileParseResult, LockFileType, decodeSriIntegrity, parseBunLockFile, parseLockFile, parseLockFileContent, parseLockFileSync, parseNpmLockFile, parsePnpmLockFile, parseYarnLockFile };
@@ -0,0 +1 @@
1
+ import{createRequire as E}from"node:module";import{findUp as I,findUpSync as N}from"@visulima/fs";const R=E(import.meta.url),h=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,$=n=>{if(typeof h<"u"&&h.versions&&h.versions.node){const[e,t]=h.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return h.getBuiltinModule(n)}return R(n)},{readFileSync:A}=$("node:fs"),{readFile:C}=$("node:fs/promises"),U={sha256:"sha256",sha384:"sha384",sha512:"sha512"},B=1024,M=/^[A-Z0-9+/]+={0,2}$/i,j="node_modules/",m=/^['"]/,k=/['"]$/,T=/^[a-z][a-zA-Z0-9]*:\s*$/m,q=/resolution:\s*\{[^}]*integrity:\s*([^,}\s]+)/,P=/^["']?((?:@[^/@"']+\/)?[^@"'\n]+)@[^\n]+\n((?:[\t ][^\n]*(?:\n|$))+)/gm,z=/^\s+version:?\s+"?([^"\n]+)"?/m,J=/^\s+integrity[\s:]+"?([^"\s]+)"?/m,v=n=>{if(n.length>B)return;const e=n.indexOf("-");if(e<=0)return;const t=U[n.slice(0,e).toLowerCase()];if(!t)return;const s=n.slice(e+1);if(M.test(s))try{const c=Buffer.from(s,"base64");return c.length===0?void 0:{algorithm:t,hex:c.toString("hex")}}catch{return}},w=(n,e,t)=>{const s=`${t.name}@${t.version}`;e.has(s)||(e.add(s),n.push(t))},u=(n,e,t)=>{t&&Object.keys(t).length>0&&(n[e]={...t})},g=n=>{if(!n)return;const e={};for(const[t,s]of Object.entries(n))e[t]=[s];return Object.keys(e).length>0?e:void 0},Z=n=>{const e=[],t=new Set;let s;try{s=JSON.parse(n)}catch{return e}if(!s.packages)return e;for(const[c,o]of Object.entries(s.packages)){if(!c||!o.version)continue;const p=c.lastIndexOf(j);if(p===-1)continue;const i=c.slice(p+j.length);if(i.length===0)continue;const r=i.split("/"),a=i.startsWith("@")?2:1;if(r.length!==a||r.some(f=>f.length===0))continue;const l=o.name??i;if(l.startsWith("."))continue;const d={name:l,version:o.version};if(o.integrity){const f=v(o.integrity);f&&(d.integrity=f)}u(d,"dependencies",g(o.dependencies)),u(d,"peerDependencies",g(o.peerDependencies)),u(d,"optionalDependencies",g(o.optionalDependencies)),w(e,t,d)}return e},O=n=>{let e=n.trim();e.startsWith("/")&&(e=e.slice(1)),e=e.replace(m,"").replace(k,"");const t=e.indexOf("(");t>0&&(e=e.slice(0,t));const s=e.lastIndexOf("@");if(s<=0)return;const c=e.slice(0,s),o=e.slice(s+1);if(!(!c||!o||o.startsWith("link:")||o.startsWith("workspace:")||o.startsWith("file:")))return{name:c,version:o}},S=(n,e)=>{const t=new RegExp(String.raw`^${e}:\s*$`,"m").exec(n);if(!t)return;const s=t.index+t[0].length,c=T.exec(n.slice(s));return n.slice(s,c?s+c.index:n.length)},Y=n=>{const e=new Map,t=S(n,"snapshots");if(!t)return e;const s=/^ {2}(['"]?[^\s:][^:\n]*?['"]?):\s*\n((?: {4}[^\n]*\n?)+)/gm;let c;for(;(c=s.exec(t)??void 0)!==void 0;){const o=O(c[1]);if(!o)continue;const p=`${o.name}@${o.version}`,i=c[2],r=e.get(p)??{};for(const a of["dependencies","peerDependencies","optionalDependencies"]){const l=y(i,a);if(!l)continue;const d=r[a]??{};for(const[f,L]of Object.entries(l)){const x=d[f]??[];for(const D of L)x.includes(D)||x.push(D);d[f]=x}r[a]=d}e.set(p,r)}return e},G=n=>{const e=[],t=new Set,s=S(n,"packages");if(!s)return e;const c=Y(n),o=/^ {2}(['"]?[^\s:][^:\n]*?['"]?):\s*\n((?: {4}[^\n]*\n?)+)/gm;let p;for(;(p=o.exec(s)??void 0)!==void 0;){const i=O(p[1]);if(!i)continue;const r=p[2],a=q.exec(r),l={name:i.name,version:i.version};if(a?.[1]){const f=v(a[1]);f&&(l.integrity=f)}const d=c.get(`${i.name}@${i.version}`);u(l,"dependencies",d?.dependencies??y(r,"dependencies")),u(l,"peerDependencies",d?.peerDependencies??y(r,"peerDependencies")),u(l,"optionalDependencies",d?.optionalDependencies??y(r,"optionalDependencies")),w(e,t,l)}return e},y=(n,e)=>{const t=new RegExp(String.raw`^ {4}${e}:\s*\n((?: {6,}[^\n]*\n?)+)`,"m").exec(n);if(!t?.[1])return;const s={},c=/^ {6}([^\s:]+):\s*([^\n]+)/gm;let o;for(;(o=c.exec(t[1])??void 0)!==void 0;){const p=o[1].replace(m,"").replace(k,"");let i=o[2].trim();i=i.replace(m,"").replace(k,"");const r=i.indexOf("(");if(r>0&&(i=i.slice(0,r).trim()),!p||!i)continue;const a=s[p]??[];a.includes(i)||a.push(i),s[p]=a}return Object.keys(s).length>0?s:void 0},H=n=>{const e=[],t=new Set,s=P;s.lastIndex=0;let c;for(;(c=s.exec(n)??void 0)!==void 0;){const o=c[1].replace(m,"").replace(k,"");if(!o)continue;const p=c[2],i=z.exec(p);if(!i?.[1])continue;const r={name:o,version:i[1].trim()},a=J.exec(p);if(a?.[1]){const l=v(a[1]);l&&(r.integrity=l)}u(r,"dependencies",b(p,"dependencies")),u(r,"peerDependencies",b(p,"peerDependencies")),u(r,"optionalDependencies",b(p,"optionalDependencies")),w(e,t,r)}return e},b=(n,e)=>{const t=new RegExp(String.raw`^ {2}${e}:\s*\n((?: {4,}[^\n]*\n?)+)`,"m").exec(n);if(!t?.[1])return;const s={},c=/^ {4}(['"]?[^\s:'"]+['"]?)\s*(?::\s*)?['"]([^'"\n]+)['"]/gm;let o;for(;(o=c.exec(t[1])??void 0)!==void 0;){const p=o[1].replace(m,"").replace(k,""),i=o[2];if(p&&i){const r=s[p]??[];r.includes(i)||r.push(i),s[p]=r}}return Object.keys(s).length>0?s:void 0},K=/,(?=\s*[}\]])/g,Q=n=>{const e=[],t=new Set;let s;try{s=JSON.parse(n.replaceAll(K,""))}catch{return e}if(!s.packages)return e;for(const c of Object.values(s.packages)){const o=c[0];if(typeof o!="string")continue;const p=o.indexOf("@",1);if(p<=0)continue;const i=o.slice(0,p),r=o.slice(p+1);if(!i||!r||r.startsWith("workspace:")||r.startsWith("link:")||r.startsWith("file:"))continue;const a={name:i,version:r},l=c[3];if(typeof l=="string"&&l.length>0){const f=v(l);f&&(a.integrity=f)}const d=c[2];if(d&&typeof d=="object"&&!Array.isArray(d)){const f=d;u(a,"dependencies",g(f.dependencies)),u(a,"peerDependencies",g(f.peerDependencies)),u(a,"optionalDependencies",g(f.optionalDependencies))}w(e,t,a)}return e},W=n=>{if(n.endsWith("pnpm-lock.yaml"))return"pnpm";if(n.endsWith("package-lock.json"))return"npm";if(n.endsWith("yarn.lock"))return"yarn";if(n.endsWith("bun.lockb")||n.endsWith("bun.lock"))return"bun"},_=(n,e)=>{switch(e){case"bun":return Q(n);case"npm":return Z(n);case"pnpm":return G(n);case"yarn":return H(n);default:return[]}},F=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","bun.lockb"],ee=async n=>{const e=await I(F,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find a supported lock file (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lock)");const t=W(e);if(!t)throw new Error(`Unsupported lock file: ${e}`);const s=await C(e,"utf8");return{entries:_(s,t),path:e,type:t}},ne=n=>{const e=N(F,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find a supported lock file (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lock)");const t=W(e);if(!t)throw new Error(`Unsupported lock file: ${e}`);return{entries:_(A(e,"utf8"),t),path:e,type:t}};export{v as decodeSriIntegrity,Q as parseBunLockFile,ee as parseLockFile,_ as parseLockFileContent,ne as parseLockFileSync,Z as parseNpmLockFile,G as parsePnpmLockFile,H as parseYarnLockFile};
@@ -1,25 +1,26 @@
1
- export type Strategy = "lerna" | "npm" | "pnpm" | "turbo" | "yarn";
2
- export interface RootMonorepo<T extends Strategy = Strategy> {
3
- path: string;
4
- strategy: T;
1
+ type Strategy = "lerna" | "npm" | "pnpm" | "turbo" | "yarn";
2
+ interface RootMonorepo<T extends Strategy = Strategy> {
3
+ path: string;
4
+ strategy: T;
5
5
  }
6
6
  /**
7
- * An asynchronous function to find the root directory path and strategy for a monorepo based on
8
- * the given current working directory (cwd).
9
- * @param cwd The current working directory. The type of `cwd` is part of an `Options` type, specifically `Options["cwd"]`.
10
- * Default is undefined.
11
- * @returns A `Promise` that resolves to the root directory path and strategy for the monorepo.
12
- * The type of the returned promise is `Promise&lt;RootMonorepo>`.
13
- * @throws An `Error` if no monorepo root can be found using lerna, yarn, pnpm, or npm as indicators.
14
- */
15
- export declare const findMonorepoRoot: (cwd?: URL | string) => Promise<RootMonorepo>;
7
+ * An asynchronous function to find the root directory path and strategy for a monorepo based on
8
+ * the given current working directory (cwd).
9
+ * @param cwd The current working directory. The type of `cwd` is part of an `Options` type, specifically `Options["cwd"]`.
10
+ * Default is undefined.
11
+ * @returns A `Promise` that resolves to the root directory path and strategy for the monorepo.
12
+ * The type of the returned promise is `Promise&lt;RootMonorepo>`.
13
+ * @throws An `Error` if no monorepo root can be found using lerna, yarn, pnpm, or npm as indicators.
14
+ */
15
+ declare const findMonorepoRoot: (cwd?: URL | string) => Promise<RootMonorepo>;
16
16
  /**
17
- * An function to find the root directory path and strategy for a monorepo based on
18
- * the given current working directory (cwd).
19
- * @param cwd The current working directory. The type of `cwd` is part of an `Options` type, specifically `Options["cwd"]`.
20
- * Default is undefined.
21
- * @returns A `Promise` that resolves to the root directory path and strategy for the monorepo.
22
- * The type of the returned promise is `Promise&lt;RootMonorepo>`.
23
- * @throws An `Error` if no monorepo root can be found using lerna, yarn, pnpm, or npm as indicators.
24
- */
25
- export declare const findMonorepoRootSync: (cwd?: URL | string) => RootMonorepo;
17
+ * An function to find the root directory path and strategy for a monorepo based on
18
+ * the given current working directory (cwd).
19
+ * @param cwd The current working directory. The type of `cwd` is part of an `Options` type, specifically `Options["cwd"]`.
20
+ * Default is undefined.
21
+ * @returns A `Promise` that resolves to the root directory path and strategy for the monorepo.
22
+ * The type of the returned promise is `Promise&lt;RootMonorepo>`.
23
+ * @throws An `Error` if no monorepo root can be found using lerna, yarn, pnpm, or npm as indicators.
24
+ */
25
+ declare const findMonorepoRootSync: (cwd?: URL | string) => RootMonorepo;
26
+ export { RootMonorepo, Strategy, findMonorepoRoot, findMonorepoRootSync };
package/dist/monorepo.js CHANGED
@@ -1 +1 @@
1
- var l=Object.defineProperty;var p=(r,e)=>l(r,"name",{value:e,configurable:!0});import{createRequire as y}from"node:module";import{findUp as j,readJson as w,findUpSync as b,readJsonSync as k}from"@visulima/fs";import{NotFoundError as u}from"@visulima/fs/error";import{dirname as d,join as a}from"@visulima/path";import{findPackageManager as _,findPackageManagerSync as M}from"./package-manager.js";const g=y(import.meta.url),i=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,h=p(r=>{if(typeof i<"u"&&i.versions&&i.versions.node){const[e,t]=i.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return i.getBuiltinModule(r)}return g(r)},"__cjs_getBuiltinModule"),{existsSync:c,readFileSync:f}=h("node:fs");var S=Object.defineProperty,m=p((r,e)=>S(r,"name",{value:e,configurable:!0}),"i");const E=m(async r=>{const e=await j(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const o=await w(e);if(o.useWorkspaces||o.packages)return{path:d(e),strategy:"lerna"}}const t=e?.endsWith("turbo.json");try{const{packageManager:o,path:n}=await _(r);if(["npm","yarn"].includes(o)){const s=a(n,"package.json");if(c(s)&&f(a(n,"package.json"),"utf8").includes("workspaces"))return{path:n,strategy:t?"turbo":o}}else if(o==="pnpm"){const s=a(n,"pnpm-workspace.yaml");if(c(s))return{path:n,strategy:t?"turbo":"pnpm"}}}catch(o){if(!(o instanceof u))throw o}throw new Error(`No monorepo root could be found upwards from the directory ${r} using lerna, yarn, pnpm, or npm as indicators.`)},"findMonorepoRoot"),T=m(r=>{const e=b(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const o=k(e);if(o.useWorkspaces||o.packages)return{path:d(e),strategy:"lerna"}}const t=e?.endsWith("turbo.json");try{const{packageManager:o,path:n}=M(r);if(["npm","yarn"].includes(o)){const s=a(n,"package.json");if(c(s)&&f(a(n,"package.json"),"utf8").includes("workspaces"))return{path:n,strategy:t?"turbo":o}}else if(o==="pnpm"){const s=a(n,"pnpm-workspace.yaml");if(c(s))return{path:n,strategy:t?"turbo":"pnpm"}}}catch(o){if(!(o instanceof u))throw o}throw new Error(`No monorepo root could be found upwards from the directory ${r} using lerna, yarn, pnpm, or npm as indicators.`)},"findMonorepoRootSync");export{E as findMonorepoRoot,T as findMonorepoRootSync};
1
+ import{createRequire as d}from"node:module";import{findUp as y,readJson as g,findUpSync as h,readJsonSync as j}from"@visulima/fs";import{NotFoundError as f}from"@visulima/fs/error";import{dirname as u,join as a}from"@visulima/path";import{findPackageManager as w,findPackageManagerSync as k}from"./package-manager.js";const m=d(import.meta.url),i=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,l=r=>{if(typeof i<"u"&&i.versions&&i.versions.node){const[e,t]=i.versions.node.split(".").map(Number);if(e>22||e===22&&t>=3||e===20&&t>=16)return i.getBuiltinModule(r)}return m(r)},{existsSync:c,readFileSync:p}=l("node:fs"),N=async r=>{const e=await y(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const n=await g(e);if(n&&typeof n=="object"&&!Array.isArray(n)){const o=n;if(o.useWorkspaces||o.packages)return{path:u(e),strategy:"lerna"}}}const t=e?.endsWith("turbo.json");try{const{packageManager:n,path:o}=await w(r);if(["npm","yarn"].includes(n)){const s=a(o,"package.json");if(c(s)&&p(a(o,"package.json"),"utf8").includes("workspaces"))return{path:o,strategy:t?"turbo":n}}else if(n==="pnpm"){const s=a(o,"pnpm-workspace.yaml");if(c(s))return{path:o,strategy:t?"turbo":"pnpm"}}}catch(n){if(!(n instanceof f))throw n}throw new Error(`No monorepo root could be found upwards from the directory ${String(r??process.cwd())} using lerna, yarn, pnpm, or npm as indicators.`)},R=r=>{const e=h(["lerna.json","turbo.json"],{type:"file",...r&&{cwd:r}});if(e?.endsWith("lerna.json")){const n=j(e);if(n.useWorkspaces||n.packages)return{path:u(e),strategy:"lerna"}}const t=e?.endsWith("turbo.json");try{const{packageManager:n,path:o}=k(r);if(["npm","yarn"].includes(n)){const s=a(o,"package.json");if(c(s)&&p(a(o,"package.json"),"utf8").includes("workspaces"))return{path:o,strategy:t?"turbo":n}}else if(n==="pnpm"){const s=a(o,"pnpm-workspace.yaml");if(c(s))return{path:o,strategy:t?"turbo":"pnpm"}}}catch(n){if(!(n instanceof f))throw n}throw new Error(`No monorepo root could be found upwards from the directory ${String(r??process.cwd())} using lerna, yarn, pnpm, or npm as indicators.`)};export{N as findMonorepoRoot,R as findMonorepoRootSync};
@@ -1,138 +1,7 @@
1
- import type { WriteJsonOptions } from "@visulima/fs";
2
- import type { JsonObject, Paths } from "type-fest";
3
- import type { Cache, EnsurePackagesOptions, NormalizedPackageJson, PackageJson } from "./types.d.ts";
4
- type ReadOptions = {
5
- cache?: FindPackageJsonCache | boolean;
6
- ignoreWarnings?: (RegExp | string)[];
7
- json5?: boolean;
8
- resolveCatalogs?: boolean;
9
- strict?: boolean;
10
- yaml?: boolean;
11
- };
12
- export type FindPackageJsonCache = Cache<NormalizedReadResult>;
13
- export type NormalizedReadResult = {
14
- packageJson: NormalizedPackageJson;
15
- path: string;
16
- };
17
- /**
18
- * An asynchronous function to find the package.json, package.yaml, or package.json5 file in the specified directory or its parent directories.
19
- * @param cwd The current working directory.
20
- * @param options Configuration options including yaml, json5, and resolveCatalogs flags.
21
- * @returns A `Promise` that resolves to an object containing the parsed package data and the file path.
22
- * The type of the returned promise is `Promise&lt;NormalizedReadResult>`.
23
- * @throws {Error} If no package file can be found or if strict mode is enabled and normalize warnings are thrown.
24
- */
25
- export declare const findPackageJson: (cwd?: URL | string, options?: ReadOptions) => Promise<NormalizedReadResult>;
26
- /**
27
- * A synchronous function to find the package.json, package.yaml, or package.json5 file in the specified directory or its parent directories.
28
- * @param cwd The current working directory.
29
- * @param options Configuration options including yaml, json5, and resolveCatalogs flags.
30
- * @returns An object containing the parsed package data and the file path.
31
- * @throws {Error} If no package file can be found or if strict mode is enabled and normalize warnings are thrown.
32
- */
33
- export declare const findPackageJsonSync: (cwd?: URL | string, options?: ReadOptions) => NormalizedReadResult;
34
- /**
35
- * An asynchronous function to write the package.json file with the given data.
36
- * @param data The package.json data to write. The data is an intersection type of `PackageJson` and a record where keys are `string` and values can be any type.
37
- * @param options Optional. The options for writing the package.json. If not provided, an empty object will be used `{}`.
38
- * This is an intersection type of `WriteJsonOptions` and a record with an optional `cwd` key which type is `Options["cwd"]`.
39
- * `cwd` represents the current working directory. If not specified, the default working directory will be used.
40
- * @returns A `Promise` that resolves once the package.json file has been written. The type of the returned promise is `Promise&lt;void>`.
41
- */
42
- export declare const writePackageJson: <T = PackageJson>(data: T, options?: WriteJsonOptions & {
43
- cwd?: URL | string;
44
- }) => Promise<void>;
45
- export declare const writePackageJsonSync: <T = PackageJson>(data: T, options?: WriteJsonOptions & {
46
- cwd?: URL | string;
47
- }) => void;
48
- /**
49
- * A synchronous function to parse the package.json, package.yaml, or package.json5 file/object/string and return normalize the data.
50
- * @param packageFile
51
- * @param options
52
- * @param options.cache Cache for parsed results (only applies to file paths)
53
- * @param options.ignoreWarnings List of warning messages or patterns to skip in strict mode
54
- * @param options.resolveCatalogs Whether to resolve pnpm catalog references
55
- * @param options.strict Whether to throw errors on normalization warnings
56
- * @param options.yaml Whether to enable package.yaml parsing (default: true)
57
- * @param options.json5 Whether to enable package.json5 parsing (default: true)
58
- * @returns
59
- * @throws {Error} If the packageFile parameter is not an object or a string or if strict mode is enabled and normalize warnings are thrown.
60
- */
61
- export declare const parsePackageJsonSync: (packageFile: JsonObject | string, options?: {
62
- cache?: Cache<NormalizedPackageJson> | boolean;
63
- ignoreWarnings?: (RegExp | string)[];
64
- json5?: boolean;
65
- resolveCatalogs?: boolean;
66
- strict?: boolean;
67
- yaml?: boolean;
68
- }) => NormalizedPackageJson;
69
- /**
70
- * An asynchronous function to parse the package.json, package.yaml, or package.json5 file/object/string and return normalize the data.
71
- * @param packageFile
72
- * @param options
73
- * @param options.cache Cache for parsed results (only applies to file paths)
74
- * @param options.ignoreWarnings List of warning messages or patterns to skip in strict mode
75
- * @param options.strict Whether to throw errors on normalization warnings
76
- * @param options.resolveCatalogs Whether to resolve pnpm catalog references
77
- * @param options.yaml Whether to enable package.yaml parsing (default: true)
78
- * @param options.json5 Whether to enable package.json5 parsing (default: true)
79
- * @returns
80
- * @throws {Error} If the packageFile parameter is not an object or a string or if strict mode is enabled and normalize warnings are thrown.
81
- */
82
- export declare const parsePackageJson: (packageFile: JsonObject | string, options?: {
83
- cache?: Cache<NormalizedPackageJson> | boolean;
84
- ignoreWarnings?: (RegExp | string)[];
85
- json5?: boolean;
86
- resolveCatalogs?: boolean;
87
- strict?: boolean;
88
- yaml?: boolean;
89
- }) => Promise<NormalizedPackageJson>;
90
- /**
91
- * An asynchronous function to get the value of a property from the package.json file.
92
- * @param packageJson
93
- * @param property
94
- * @param defaultValue
95
- * @returns
96
- */
97
- export declare const getPackageJsonProperty: <T = unknown>(packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>, defaultValue?: T) => T;
98
- /**
99
- * An asynchronous function to check if a property exists in the package.json file.
100
- * @param packageJson
101
- * @param property
102
- * @returns
103
- */
104
- export declare const hasPackageJsonProperty: (packageJson: NormalizedPackageJson, property: Paths<NormalizedPackageJson>) => boolean;
105
- /**
106
- * An asynchronous function to check if any of the specified dependencies exist in the package.json file.
107
- * @param packageJson
108
- * @param arguments_
109
- * @param options
110
- * @param options.peerDeps Whether to include peer dependencies
111
- * @returns
112
- */
113
- export declare const hasPackageJsonAnyDependency: (packageJson: NormalizedPackageJson, arguments_: string[], options?: {
114
- peerDeps?: boolean;
115
- }) => boolean;
116
- /**
117
- * An asynchronous function to ensure that the specified packages are installed in the package.json file.
118
- * If the packages are not installed, the user will be prompted to install them.
119
- * If the user agrees, the packages will be installed.
120
- * If the user declines, the function will return without installing the packages.
121
- * If the user does not respond, the function will return without installing the packages.
122
- * @param packageJson
123
- * @param packages
124
- * @param installKey
125
- * @param options
126
- * @param options.deps Whether to include regular dependencies
127
- * @param options.devDeps Whether to include development dependencies
128
- * @param options.peerDeps Whether to include peer dependencies
129
- * @param options.throwOnWarn Whether to throw an error when warnings are logged instead of just logging them
130
- * @param options.logger Whether to use a custom logger
131
- * @param options.confirm Whether to use a custom confirmation prompt
132
- * @param options.installPackage Whether to use a custom installation package
133
- * @param options.cwd Whether to use a custom current working directory
134
- * @param options.dev Whether to use a custom installation key
135
- * @returns
136
- */
137
- export declare const ensurePackages: (packageJson: NormalizedPackageJson, packages: string[], installKey?: "dependencies" | "devDependencies", options?: EnsurePackagesOptions) => Promise<void>;
138
- export {};
1
+ import '@visulima/fs';
2
+ import 'type-fest';
3
+ export { F as FindPackageJsonCache, a as NormalizedReadResult, c as clearPackageJsonCache, e as ensurePackages, f as findPackageJson, b as findPackageJsonSync, g as getPackageJsonProperty, h as hasPackageJsonAnyDependency, d as hasPackageJsonProperty, p as parsePackageJson, i as parsePackageJsonSync, w as writePackageJson, j as writePackageJsonSync } from "./packem_shared/package-json.d-BHWsl_Em.js";
4
+ import '@antfu/install-pkg';
5
+ import '@inquirer/core';
6
+ import '@inquirer/type';
7
+ import 'normalize-package-data';
@@ -1,4 +1,4 @@
1
- var K=Object.defineProperty;var f=(e,r)=>K(e,"name",{value:r,configurable:!0});import{createRequire as V}from"node:module";import{installPackage as X}from"@antfu/install-pkg";import{readJsonSync as L,readFileSync as H,findUp as Q,findUpSync as Z,writeJson as ee,writeJsonSync as re,readJson as ne,readFile as te}from"@visulima/fs";import{NotFoundError as I}from"@visulima/fs/error";import{parseJson as T,toPath as A}from"@visulima/fs/utils";import{readYamlSync as oe,readYaml as se}from"@visulima/fs/yaml";import{join as _}from"@visulima/path";import F from"json5";import ae from"normalize-package-data";import{readPnpmCatalogsSync as D,resolveCatalogReferences as E,readPnpmCatalogs as C}from"./pnpm.js";const U=V(import.meta.url),w=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,J=f(e=>{if(typeof w<"u"&&w.versions&&w.versions.node){const[r,t]=w.versions.node.split(".").map(Number);if(r>22||r===22&&t>=3||r===20&&t>=16)return w.getBuiltinModule(e)}return U(e)},"__cjs_getBuiltinModule"),{existsSync:N}=J("node:fs"),{createInterface:ie}=J("node:readline"),{styleText:g}=J("node:util");var ce=Object.defineProperty,l=f((e,r)=>ce(e,"name",{value:r,configurable:!0}),"f");const h=l(e=>{const r=typeof e;return e!==null&&(r==="object"||r==="function")},"isObject"),fe=l(e=>{if(!h(e))return!1;for(const r in e)if(Object.hasOwn(e,r))return!1;return!0},"isEmptyObject"),O=new Set(["__proto__","prototype","constructor"]),W=1e6,pe=l(e=>e>="0"&&e<="9","isDigit");function b(e){if(e==="0")return!0;if(/^[1-9]\d*$/.test(e)){const r=Number.parseInt(e,10);return r<=Number.MAX_SAFE_INTEGER&&r<=W}return!1}f(b,"p$1");l(b,"shouldCoerceToNumber");function k(e,r){return O.has(e)?!1:(e&&b(e)?r.push(Number.parseInt(e,10)):r.push(e),!0)}f(k,"y");l(k,"processSegment");function B(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);const r=[];let t="",n="start",o=!1,s=0;for(const a of e){if(s++,o){t+=a,o=!1;continue}if(a==="\\"){if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);o=!0,n=n==="start"?"property":n;continue}switch(a){case".":{if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd"){n="property";break}if(!k(t,r))return[];t="",n="property";break}case"[":{if(n==="index")throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd"){n="index";break}if(n==="property"||n==="start"){if((t||n==="property")&&!k(t,r))return[];t=""}n="index";break}case"]":{if(n==="index"){if(t==="")t=(r.pop()||"")+"[]",n="property";else{const i=Number.parseInt(t,10);!Number.isNaN(i)&&Number.isFinite(i)&&i>=0&&i<=Number.MAX_SAFE_INTEGER&&i<=W&&t===String(i)?r.push(i):r.push(t),t="",n="indexEnd"}break}if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);t+=a;break}default:{if(n==="index"&&!pe(a))throw new Error(`Invalid character '${a}' in an index at position ${s}`);if(n==="indexEnd")throw new Error(`Invalid character '${a}' after an index at position ${s}`);n==="start"&&(n="property"),t+=a}}}switch(o&&(t+="\\"),n){case"property":{if(!k(t,r))return[];break}case"index":throw new Error("Index was not closed");case"start":{r.push("");break}}return r}f(B,"parsePath");l(B,"parsePath");function $(e){if(typeof e=="string")return B(e);if(Array.isArray(e)){const r=[];for(const[t,n]of e.entries()){if(typeof n!="string"&&typeof n!="number")throw new TypeError(`Expected a string or number for path segment at index ${t}, got ${typeof n}`);if(typeof n=="number"&&!Number.isFinite(n))throw new TypeError(`Path segment at index ${t} must be a finite number, got ${n}`);if(O.has(n))return[];typeof n=="string"&&b(n)?r.push(Number.parseInt(n,10)):r.push(n)}return r}return[]}f($,"d");l($,"normalizePath");function d(e,r,t){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return t===void 0?e:t;const n=$(r);if(n.length===0)return t;for(let o=0;o<n.length;o++){const s=n[o];if(e=e[s],e==null){if(o!==n.length-1)return t;break}}return e===void 0?t:e}f(d,"getProperty");l(d,"getProperty");function M(e,r,t){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return e;const n=e,o=$(r);if(o.length===0)return e;for(let s=0;s<o.length;s++){const a=o[s];if(s===o.length-1)e[a]=t;else if(!h(e[a])){const i=typeof o[s+1]=="number";e[a]=i?[]:{}}e=e[a]}return n}f(M,"setProperty");l(M,"setProperty");function le(e,r){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return!1;const t=$(r);if(t.length===0)return!1;for(let n=0;n<t.length;n++){const o=t[n];if(n===t.length-1)return Object.hasOwn(e,o)?(delete e[o],!0):!1;if(e=e[o],!h(e))return!1}}f(le,"deleteProperty");l(le,"deleteProperty");function y(e,r){if(!h(e)||typeof r!="string"&&!Array.isArray(r))return!1;const t=$(r);if(t.length===0)return!1;for(const n of t){if(!h(e)||!(n in e))return!1;e=e[n]}return!0}f(y,"hasProperty");l(y,"hasProperty");function x(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.replaceAll(/[\\.[]/g,String.raw`\$&`)}f(x,"escapePath");l(x,"escapePath");function R(e){const r=Object.entries(e);return Array.isArray(e)?r.map(([t,n])=>[b(t)?Number.parseInt(t,10):t,n]):r}f(R,"m$2");l(R,"normalizeEntries");function Y(e,r={}){if(!Array.isArray(e))throw new TypeError(`Expected an array, got ${typeof e}`);const{preferDotForIndices:t=!1}=r,n=[];for(const[o,s]of e.entries()){if(typeof s!="string"&&typeof s!="number")throw new TypeError(`Expected a string or number for path segment at index ${o}, got ${typeof s}`);if(typeof s=="number")if(!Number.isInteger(s)||s<0){const a=x(String(s));n.push(o===0?a:`.${a}`)}else t&&o>0?n.push(`.${s}`):n.push(`[${s}]`);else if(typeof s=="string")if(s==="")o===0||n.push(".");else if(b(s)){const a=Number.parseInt(s,10);t&&o>0?n.push(`.${a}`):n.push(`[${a}]`)}else{const a=x(s);n.push(o===0?a:`.${a}`)}}return n.join("")}f(Y,"stringifyPath");l(Y,"stringifyPath");function*S(e,r=[],t=new Set){if(!h(e)||fe(e)){r.length>0&&(yield Y(r));return}if(!t.has(e)){t.add(e);for(const[n,o]of R(e))r.push(n),yield*S(o,r,t),r.pop();t.delete(e)}}f(S,"x");l(S,"deepKeysIterator");function ue(e){return[...S(e)]}f(ue,"deepKeys");l(ue,"deepKeys");function ge(e){const r={};if(!h(e))return r;for(const[t,n]of Object.entries(e))M(r,t,n);return r}f(ge,"unflatten");l(ge,"unflatten");var he=Object.defineProperty,j=f((e,r)=>he(e,"name",{value:r,configurable:!0}),"i");const de=j(async e=>{const{default:r=!1,message:t,transformer:n}=e,o=j(a=>{const i=g(["cyan","bold"],"?"),c=g(["bold"],a),u=r?`${g(["greenBright"],"Y")}${g(["gray"],"/n")}`:`y/${g(["yellowBright"],"N")}`;return`${i} ${c} ${g(["gray"],`(${u})`)}`},"formatMessage"),s=j(a=>n?n(a):a?g(["greenBright"],"Yes"):g(["yellowBright"],"No"),"formatAnswer");return new Promise(a=>{const i=ie({input:process.stdin,output:process.stdout}),c=o(t);i.question(c,u=>{i.close();const m=u.trim().toLowerCase();if(m===""){a(r);return}if(m==="y"||m==="yes"){console.log(`${g(["greenBright"],"✓")} ${s(!0)}`),a(!0);return}if(m==="n"||m==="no"){console.log(`${g(["yellowBright"],"✗")} ${s(!1)}`),a(!1);return}console.log(`${g(["gray"],"→")} ${s(r)}`),a(r)}),i.on("SIGINT",()=>{i.close(),console.log(`
2
- ${g(["gray"],"→")} ${s(r)}`),a(r)})})},"confirm"),ye=typeof process.stdout<"u"&&!process.versions.deno&&!globalThis.window;var me=Object.defineProperty,p=f((e,r)=>me(e,"name",{value:r,configurable:!0}),"l");const P=new Map,q=new Map;class we extends Error{static{f(this,"F")}static{p(this,"PackageJsonValidationError")}constructor(r){super(`The following warnings were encountered while normalizing package data:
3
- - ${r.join(`
4
- - `)}`),this.name="PackageJsonValidationError"}}const v=p((e,r,t=[])=>{const n=[];if(ae(e,o=>{n.push(o)},r),r&&n.length>0){const o=n.filter(s=>!t.some(a=>a instanceof RegExp?a.test(s):a===s));if(o.length>0)throw new we(o)}return e},"normalizeInput"),be=p(async e=>await se(e),"parseYamlFile"),$e=p(e=>oe(e),"parseYamlFileSync"),ke=p(async e=>{const r=await te(e);return F.parse(r)},"parseJson5File"),Pe=p(e=>{const r=H(e);return F.parse(r)},"parseJson5FileSync"),z=p(async(e,r)=>r?.yaml!==!1&&(e.endsWith(".yaml")||e.endsWith(".yml"))?be(e):r?.json5!==!1&&e.endsWith(".json5")?ke(e):ne(e),"parsePackageFile"),G=p((e,r)=>r?.yaml!==!1&&(e.endsWith(".yaml")||e.endsWith(".yml"))?$e(e):r?.json5!==!1&&e.endsWith(".json5")?Pe(e):L(e),"parsePackageFileSync"),Fe=p(async(e,r={})=>{const t={type:"file"};e&&(t.cwd=e);const n=["package.json"];r.yaml!==!1&&n.push("package.yaml","package.yml"),r.json5!==!1&&n.push("package.json5");let o;for await(const c of n)if(o=await Q(c,t),o)break;if(!o)throw new I(`No such file or directory, for ${n.join(", ").replace(/, ([^,]*)$/," or $1")} found.`);const s=r.cache&&typeof r.cache!="boolean"?r.cache:q;if(r.cache&&s.has(o))return s.get(o);const a=await z(o,r);if(r.resolveCatalogs){const c=await C(o);c&&E(a,c)}v(a,r.strict??!1,r.ignoreWarnings);const i={packageJson:a,path:o};return r.cache&&s.set(o,i),i},"findPackageJson"),De=p((e,r={})=>{const t={type:"file"};e&&(t.cwd=e);const n=["package.json"];r.yaml!==!1&&n.push("package.yaml","package.yml"),r.json5!==!1&&n.push("package.json5");let o;for(const c of n)if(o=Z(c,t),o)break;if(!o)throw new I(`No such file or directory, for ${n.join(", ").replace(/, ([^,]*)$/," or $1")} found.`);const s=r.cache&&typeof r.cache!="boolean"?r.cache:q;if(r.cache&&s.has(o))return s.get(o);const a=G(o,r);if(r.resolveCatalogs){const c=D(o);c&&E(a,c)}v(a,r.strict??!1,r.ignoreWarnings);const i={packageJson:a,path:o};return r.cache&&s.set(o,i),i},"findPackageJsonSync"),Ce=p(async(e,r={})=>{const{cwd:t,...n}=r,o=A(t??process.cwd());await ee(_(o,"package.json"),e,n)},"writePackageJson"),Oe=p((e,r={})=>{const{cwd:t,...n}=r,o=A(t??process.cwd());re(_(o,"package.json"),e,n)},"writePackageJsonSync"),We=p((e,r)=>{const t=e!==null&&typeof e=="object"&&!Array.isArray(e);if(!t&&typeof e!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let n,o=!1,s;if(t)n=structuredClone(e);else if(N(e)){s=e;const i=r?.cache&&typeof r.cache!="boolean"?r.cache:P;if(r?.cache&&i.has(s))return i.get(s);n=G(s,r),o=!0}else n=T(e);if(r?.resolveCatalogs)if(o){const i=D(e);i&&E(n,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");v(n,r?.strict??!1,r?.ignoreWarnings);const a=n;return o&&s&&r?.cache&&(r.cache&&typeof r.cache!="boolean"?r.cache:P).set(s,a),a},"parsePackageJsonSync"),Be=p(async(e,r)=>{const t=e!==null&&typeof e=="object"&&!Array.isArray(e);if(!t&&typeof e!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let n,o=!1,s;if(t)n=structuredClone(e);else if(N(e)){s=e;const i=r?.cache&&typeof r.cache!="boolean"?r.cache:P;if(r?.cache&&i.has(s))return i.get(s);n=await z(s,r),o=!0}else n=T(e);if(r?.resolveCatalogs)if(o){const i=await C(e);i&&E(n,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");v(n,r?.strict??!1,r?.ignoreWarnings);const a=n;return o&&s&&r?.cache&&(r.cache&&typeof r.cache!="boolean"?r.cache:P).set(s,a),a},"parsePackageJson"),Me=p((e,r,t)=>d(e,r,t),"getPackageJsonProperty"),Re=p((e,r)=>y(e,r),"hasPackageJsonProperty"),Ye=p((e,r,t)=>{const n=d(e,"dependencies",{}),o=d(e,"devDependencies",{}),s=d(e,"peerDependencies",{}),a={...n,...o,...t?.peerDeps===!1?{}:s};for(const i of r)if(y(a,i))return!0;return!1},"hasPackageJsonAnyDependency"),qe=p(async(e,r,t="dependencies",n={})=>{const o=d(e,"dependencies",{}),s=d(e,"devDependencies",{}),a=d(e,"peerDependencies",{}),i=[],c={deps:!0,devDeps:!0,peerDeps:!1,...n};for(const u of r)c.deps&&y(o,u)||c.devDeps&&y(s,u)||c.peerDeps&&y(a,u)||i.push(u);if(i.length!==0){if(process.env.CI||ye&&!process.stdout?.isTTY){const u=`Skipping package installation for [${r.join(", ")}] because the process is not interactive.`;if(n.throwOnWarn)throw new Error(u);n.logger?.warn?n.logger.warn(u):console.warn(u);return}if(typeof c.confirm?.message=="function"&&(c.confirm.message=c.confirm.message(i)),c.confirm?.message===void 0){const u=`${i.length===1?"Package is":"Packages are"} required for this config: ${i.join(", ")}. Do you want to install them?`;c.confirm===void 0?c.confirm={message:u}:c.confirm.message=u}await de(c.confirm)&&await X(i,{...c.installPackage,cwd:c.cwd?A(c.cwd):void 0,dev:t==="devDependencies"})}},"ensurePackages");export{qe as ensurePackages,Fe as findPackageJson,De as findPackageJsonSync,Me as getPackageJsonProperty,Ye as hasPackageJsonAnyDependency,Re as hasPackageJsonProperty,Be as parsePackageJson,We as parsePackageJsonSync,Ce as writePackageJson,Oe as writePackageJsonSync};
1
+ import{createRequire as q}from"node:module";import{installPackage as Y}from"@antfu/install-pkg";import{findUp as G,findUpSync as X,writeJson as z,writeJsonSync as U,readJson as V,readJsonSync as L,readFile as O,readFileSync as H}from"@visulima/fs";import{NotFoundError as x}from"@visulima/fs/error";import{toPath as v,parseJson as P}from"@visulima/fs/utils";import{readYaml as K,readYamlSync as Q}from"@visulima/fs/yaml";import{join as S}from"@visulima/path";import _ from"json5";import Z from"normalize-package-data";import{readPnpmCatalogs as N,resolveCatalogReferences as m,readPnpmCatalogsSync as I}from"./pnpm.js";const M=q(import.meta.url),h=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,E=r=>{if(typeof h<"u"&&h.versions&&h.versions.node){const[e,o]=h.versions.node.split(".").map(Number);if(e>22||e===22&&o>=3||e===20&&o>=16)return h.getBuiltinModule(r)}return M(r)},{existsSync:j}=E("node:fs"),{createInterface:ee}=E("node:readline"),{styleText:l}=E("node:util"),k=r=>{const e=typeof r;return r!==null&&(e==="object"||e==="function")},J=new Set(["__proto__","prototype","constructor"]),T=1e6,re=r=>r>="0"&&r<="9";function C(r){if(r==="0")return!0;if(/^[1-9]\d*$/.test(r)){const e=Number.parseInt(r,10);return e<=Number.MAX_SAFE_INTEGER&&e<=T}return!1}function b(r,e){return J.has(r)?!1:(r&&C(r)?e.push(Number.parseInt(r,10)):e.push(r),!0)}function te(r){if(typeof r!="string")throw new TypeError(`Expected a string, got ${typeof r}`);const e=[];let o="",t="start",a=!1,n=0;for(const s of r){if(n++,a){o+=s,a=!1;continue}if(s==="\\"){if(t==="index")throw new Error(`Invalid character '${s}' in an index at position ${n}`);if(t==="indexEnd")throw new Error(`Invalid character '${s}' after an index at position ${n}`);a=!0,t=t==="start"?"property":t;continue}switch(s){case".":{if(t==="index")throw new Error(`Invalid character '${s}' in an index at position ${n}`);if(t==="indexEnd"){t="property";break}if(!b(o,e))return[];o="",t="property";break}case"[":{if(t==="index")throw new Error(`Invalid character '${s}' in an index at position ${n}`);if(t==="indexEnd"){t="index";break}if(t==="property"||t==="start"){if((o||t==="property")&&!b(o,e))return[];o=""}t="index";break}case"]":{if(t==="index"){if(o==="")o=(e.pop()||"")+"[]",t="property";else{const i=Number.parseInt(o,10);!Number.isNaN(i)&&Number.isFinite(i)&&i>=0&&i<=Number.MAX_SAFE_INTEGER&&i<=T&&o===String(i)?e.push(i):e.push(o),o="",t="indexEnd"}break}if(t==="indexEnd")throw new Error(`Invalid character '${s}' after an index at position ${n}`);o+=s;break}default:{if(t==="index"&&!re(s))throw new Error(`Invalid character '${s}' in an index at position ${n}`);if(t==="indexEnd")throw new Error(`Invalid character '${s}' after an index at position ${n}`);t==="start"&&(t="property"),o+=s}}}switch(a&&(o+="\\"),t){case"property":{if(!b(o,e))return[];break}case"index":throw new Error("Index was not closed");case"start":{e.push("");break}}return e}function A(r){if(typeof r=="string")return te(r);if(Array.isArray(r)){const e=[];for(const[o,t]of r.entries()){if(typeof t!="string"&&typeof t!="number")throw new TypeError(`Expected a string or number for path segment at index ${o}, got ${typeof t}`);if(typeof t=="number"&&!Number.isFinite(t))throw new TypeError(`Path segment at index ${o} must be a finite number, got ${t}`);if(J.has(t))return[];typeof t=="string"&&C(t)?e.push(Number.parseInt(t,10)):e.push(t)}return e}return[]}function p(r,e,o){if(!k(r)||typeof e!="string"&&!Array.isArray(e))return o===void 0?r:o;const t=A(e);if(t.length===0)return o;for(let a=0;a<t.length;a++){const n=t[a];if(r=r[n],r==null){if(a!==t.length-1)return o;break}}return r===void 0?o:r}function y(r,e){if(!k(r)||typeof e!="string"&&!Array.isArray(e))return!1;const o=A(e);if(o.length===0)return!1;for(const t of o){if(!k(r)||!(t in r))return!1;r=r[t]}return!0}const oe=async r=>{const{default:e=!1,message:o,transformer:t}=r,a=s=>{const i=l(["cyan","bold"],"?"),c=l(["bold"],s),f=e?`${l(["greenBright"],"Y")}${l(["gray"],"/n")}`:`y/${l(["yellowBright"],"N")}`;return`${i} ${c} ${l(["gray"],`(${f})`)}`},n=s=>t?t(s):s?l(["greenBright"],"Yes"):l(["yellowBright"],"No");return new Promise(s=>{const i=ee({input:process.stdin,output:process.stdout}),c=a(o);i.question(c,f=>{i.close();const g=f.trim().toLowerCase();if(g===""){s(e);return}if(g==="y"||g==="yes"){console.log(`${l(["greenBright"],"✓")} ${n(!0)}`),s(!0);return}if(g==="n"||g==="no"){console.log(`${l(["yellowBright"],"✗")} ${n(!1)}`),s(!1);return}console.log(`${l(["gray"],"→")} ${n(e)}`),s(e)}),i.on("SIGINT",()=>{i.close(),console.log(`
2
+ ${l(["gray"],"→")} ${n(e)}`),s(e)})})},ne=typeof process.stdout<"u"&&!process.versions.deno&&!globalThis.window,W=/, ([^,]*)$/,u=new Map,w=new Map,d=(r,e={})=>`${r}|s${String(e.strict?1:0)}|c${String(e.resolveCatalogs?1:0)}|j${String(e.json5===!1?0:1)}|y${String(e.yaml===!1?0:1)}|w${String(e.ignoreWarnings?1:0)}`,D=r=>r.trimStart().startsWith("{"),F=r=>{const e=`${r}|`;for(const o of[w,u])for(const t of o.keys())t.startsWith(e)&&o.delete(t)};class se extends Error{constructor(e){super(`The following warnings were encountered while normalizing package data:
3
+ - ${e.join(`
4
+ - `)}`),this.name="PackageJsonValidationError"}}const $=(r,e,o=[])=>{const t=[];if(Z(r,a=>{t.push(a)},e),e&&t.length>0){const a=t.filter(n=>!o.some(s=>s instanceof RegExp?s.test(n):s===n));if(a.length>0)throw new se(a)}return r},ae=async r=>await K(r),ie=r=>Q(r),ce=async r=>{const e=await O(r);return _.parse(e)},fe=r=>{const e=H(r);return _.parse(e)},B=async(r,e)=>e?.yaml!==!1&&(r.endsWith(".yaml")||r.endsWith(".yml"))?ae(r):e?.json5!==!1&&r.endsWith(".json5")?ce(r):V(r),R=(r,e)=>e?.yaml!==!1&&(r.endsWith(".yaml")||r.endsWith(".yml"))?ie(r):e?.json5!==!1&&r.endsWith(".json5")?fe(r):L(r),be=async(r,e={})=>{const o={type:"file"};r&&(o.cwd=r);const t=["package.json"];e.yaml!==!1&&t.push("package.yaml","package.yml"),e.json5!==!1&&t.push("package.json5");const a=await G(t,o);if(!a)throw new x(`No such file or directory, for ${t.join(", ").replace(W," or $1")} found.`);const n=e.cache&&typeof e.cache!="boolean"?e.cache:w,s=d(a,e);if(e.cache&&n.has(s))return n.get(s);const i=await B(a,e);if(e.resolveCatalogs){const f=await N(a);f&&m(i,f)}$(i,e.strict??!1,e.ignoreWarnings);const c={packageJson:i,path:a};return e.cache&&n.set(s,c),c},ke=(r,e={})=>{const o={type:"file"};r&&(o.cwd=r);const t=["package.json"];e.yaml!==!1&&t.push("package.yaml","package.yml"),e.json5!==!1&&t.push("package.json5");const a=X(t,o);if(!a)throw new x(`No such file or directory, for ${t.join(", ").replace(W," or $1")} found.`);const n=e.cache&&typeof e.cache!="boolean"?e.cache:w,s=d(a,e);if(e.cache&&n.has(s))return n.get(s);const i=R(a,e);if(e.resolveCatalogs){const f=I(a);f&&m(i,f)}$(i,e.strict??!1,e.ignoreWarnings);const c={packageJson:i,path:a};return e.cache&&n.set(s,c),c},Ee=async(r,e={})=>{const{cwd:o,...t}=e,a=v(o??process.cwd()),n=S(a,"package.json");await z(n,r,t),F(n)},ve=(r,e={})=>{const{cwd:o,...t}=e,a=v(o??process.cwd()),n=S(a,"package.json");U(n,r,t),F(n)},je=()=>{w.clear(),u.clear()},xe=(r,e)=>{const o=typeof r=="object"&&!Array.isArray(r);if(!o&&typeof r!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let t,a=!1,n;if(o)t=structuredClone(r);else if(!D(r)&&j(r)){n=r;const i=e?.cache&&typeof e.cache!="boolean"?e.cache:u,c=d(n,e);if(e?.cache&&i.has(c))return i.get(c);t=R(n,e),a=!0}else t=P(r);if(e?.resolveCatalogs)if(a){const i=I(r);i&&m(t,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");$(t,e?.strict??!1,e?.ignoreWarnings);const s=t;return a&&e?.cache&&(typeof e.cache=="boolean"?u:e.cache).set(d(n,e),s),s},Pe=async(r,e)=>{const o=typeof r=="object"&&!Array.isArray(r);if(!o&&typeof r!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");let t,a=!1,n;if(o)t=structuredClone(r);else if(!D(r)&&j(r)){n=r;const i=e?.cache&&typeof e.cache!="boolean"?e.cache:u,c=d(n,e);if(e?.cache&&i.has(c))return i.get(c);t=await B(n,e),a=!0}else t=P(r);if(e?.resolveCatalogs)if(a){const i=await N(r);i&&m(t,i)}else throw new Error("The 'resolveCatalogs' option can only be used on a file path.");$(t,e?.strict??!1,e?.ignoreWarnings);const s=t;return a&&e?.cache&&(typeof e.cache=="boolean"?u:e.cache).set(d(n,e),s),s},Se=(r,e,o)=>p(r,e,o),_e=(r,e)=>y(r,e),Ne=(r,e,o)=>{const t=p(r,"dependencies",{}),a=p(r,"devDependencies",{}),n=p(r,"peerDependencies",{}),s={...t,...a,...o?.peerDeps===!1?{}:n};for(const i of e)if(y(s,i))return!0;return!1},Ie=async(r,e,o="dependencies",t={})=>{const a=p(r,"dependencies",{}),n=p(r,"devDependencies",{}),s=p(r,"peerDependencies",{}),i=[],c={deps:!0,devDeps:!0,peerDeps:!1,...t,...t.confirm?{confirm:{...t.confirm}}:{}};for(const f of e)c.deps&&y(a,f)||c.devDeps&&y(n,f)||c.peerDeps&&y(s,f)||i.push(f);if(i.length!==0){if(process.env.CI||ne&&!process.stdout.isTTY){const f=`Skipping package installation for [${e.join(", ")}] because the process is not interactive.`;if(t.throwOnWarn)throw new Error(f);t.logger?.warn?t.logger.warn(f):console.warn(f);return}if(typeof c.confirm?.message=="function"&&(c.confirm.message=c.confirm.message(i)),c.confirm?.message===void 0){const f=`${i.length===1?"Package is":"Packages are"} required for this config: ${i.join(", ")}. Do you want to install them?`;c.confirm===void 0?c.confirm={message:f}:c.confirm.message=f}await oe(c.confirm)&&await Y(i,{...c.installPackage,cwd:c.cwd?v(c.cwd):void 0,dev:o==="devDependencies"})}};export{je as clearPackageJsonCache,Ie as ensurePackages,be as findPackageJson,ke as findPackageJsonSync,Se as getPackageJsonProperty,Ne as hasPackageJsonAnyDependency,_e as hasPackageJsonProperty,Pe as parsePackageJson,xe as parsePackageJsonSync,Ee as writePackageJson,ve as writePackageJsonSync};
@@ -1,71 +1,73 @@
1
1
  /**
2
- * An asynchronous function that finds a lock file in the specified directory or any of its parent directories.
3
- * @param cwd Optional. The directory path to start the search from. The type of `cwd` is part of an `Options` type,
4
- * specifically `URL | string`. Defaults to the current working directory.
5
- * @returns A `Promise` that resolves with the path of the found lock file.
6
- * The type of the returned promise is `Promise&lt;string>`.
7
- * @throws An `Error` if no lock file is found.
8
- */
9
- export declare const findLockFile: (cwd?: URL | string) => Promise<string>;
10
- export declare const findLockFileSync: (cwd?: URL | string) => string;
11
- export type PackageManager = "bun" | "npm" | "pnpm" | "yarn";
12
- export type PackageManagerResult = {
13
- packageManager: PackageManager;
14
- path: string;
2
+ * An asynchronous function that finds a lock file in the specified directory or any of its parent directories.
3
+ * @param cwd Optional. The directory path to start the search from. The type of `cwd` is part of an `Options` type,
4
+ * specifically `URL | string`. Defaults to the current working directory.
5
+ * @returns A `Promise` that resolves with the path of the found lock file.
6
+ * The type of the returned promise is `Promise&lt;string>`.
7
+ * @throws An `Error` if no lock file is found.
8
+ */
9
+ declare const findLockFile: (cwd?: URL | string) => Promise<string>;
10
+ declare const findLockFileSync: (cwd?: URL | string) => string;
11
+ type PackageManager = "bun" | "npm" | "pnpm" | "yarn";
12
+ type PackageManagerResult = {
13
+ packageManager: PackageManager;
14
+ path: string;
15
15
  };
16
16
  /**
17
- * An asynchronous function that finds the package manager used in a project based on the presence of lock files
18
- * or package.json configuration. If found, it returns the package manager and the path to the lock file or package.json.
19
- * Throws an error if no lock file or package.json is found.
20
- * @param cwd Optional. The current working directory to start the search from. The type of `cwd` is part of an `Options`
21
- * type, specifically `URL | string`.
22
- * @returns A `Promise` that resolves to an object containing the package manager and path.
23
- * The return type of the function is `Promise&lt;PackageManagerResult>`.
24
- * @throws An `Error` if no lock file or package.json is found.
25
- */
26
- export declare const findPackageManager: (cwd?: URL | string) => Promise<PackageManagerResult>;
17
+ * An asynchronous function that finds the package manager used in a project based on the presence of lock files
18
+ * or package.json configuration. If found, it returns the package manager and the path to the lock file or package.json.
19
+ * Throws an error if no lock file or package.json is found.
20
+ * @param cwd Optional. The current working directory to start the search from. The type of `cwd` is part of an `Options`
21
+ * type, specifically `URL | string`.
22
+ * @returns A `Promise` that resolves to an object containing the package manager and path.
23
+ * The return type of the function is `Promise&lt;PackageManagerResult>`.
24
+ * @throws An `Error` if no lock file or package.json is found.
25
+ */
26
+ declare const findPackageManager: (cwd?: URL | string) => Promise<PackageManagerResult>;
27
27
  /**
28
- * An function that finds the package manager used in a project based on the presence of lock files
29
- * or package.json configuration. If found, it returns the package manager and the path to the lock file or package.json.
30
- * Throws an error if no lock file or package.json is found.
31
- * @param cwd Optional. The current working directory to start the search from. The type of `cwd` is part of an `Options`
32
- * type, specifically `URL | string`.
33
- * @returns A `Promise` that resolves to an object containing the package manager and path.
34
- * The return type of the function is `Promise&lt;PackageManagerResult>`.
35
- * @throws An `Error` if no lock file or package.json is found.
36
- */
37
- export declare const findPackageManagerSync: (cwd?: URL | string) => PackageManagerResult;
28
+ * An function that finds the package manager used in a project based on the presence of lock files
29
+ * or package.json configuration. If found, it returns the package manager and the path to the lock file or package.json.
30
+ * Throws an error if no lock file or package.json is found.
31
+ * @param cwd Optional. The current working directory to start the search from. The type of `cwd` is part of an `Options`
32
+ * type, specifically `URL | string`.
33
+ * @returns A `Promise` that resolves to an object containing the package manager and path.
34
+ * The return type of the function is `Promise&lt;PackageManagerResult>`.
35
+ * @throws An `Error` if no lock file or package.json is found.
36
+ */
37
+ declare const findPackageManagerSync: (cwd?: URL | string) => PackageManagerResult;
38
38
  /**
39
- * Function that retrieves the version of the specified package manager.
40
- * @param name The name of the package manager. The type of `name` is `string`.
41
- * @returns The version of the package manager. The return type of the function is `string`.
42
- */
43
- export declare const getPackageManagerVersion: (name: string) => string;
39
+ * Function that retrieves the version of the specified package manager.
40
+ * @param name The name of the package manager. Must be one of the known managers (`npm`, `pnpm`, `yarn`, `bun`).
41
+ * @returns The version of the package manager. The return type of the function is `string`.
42
+ * @throws An `Error` if `name` is not a recognized package manager. This guards against executing an
43
+ * arbitrary or relative-path binary derived from untrusted input.
44
+ */
45
+ declare const getPackageManagerVersion: (name: string) => string;
44
46
  /**
45
- * An asynchronous function that detects what package manager executes the process.
46
- *
47
- * Supports npm, pnpm, Yarn, cnpm, and bun. And also any other package manager that sets the npm_config_user_agent env variable.
48
- * @returns A `Promise` that resolves to an object containing the name and version of the package manager,
49
- * or undefined if the package manager information cannot be determined. The return type of the function
50
- * is `Promise&lt;{ name: PackageManager | "cnpm"; version: string } | undefined>`.
51
- */
52
- export declare const identifyInitiatingPackageManager: () => Promise<{
53
- name: PackageManager | "cnpm";
54
- version: string;
55
- } | undefined>;
47
+ * An asynchronous function that detects what package manager executes the process.
48
+ *
49
+ * Supports npm, pnpm, Yarn, cnpm, and bun. And also any other package manager that sets the npm_config_user_agent env variable.
50
+ * @returns An object containing the name and version of the package manager,
51
+ * or undefined if the package manager information cannot be determined.
52
+ */
53
+ declare const identifyInitiatingPackageManager: () => {
54
+ name: PackageManager | "cnpm" | (string & {});
55
+ version: string;
56
+ } | undefined;
56
57
  /**
57
- * Function that generates a message to install missing packages.
58
- * @param packageName The name of the package that requires the missing packages.
59
- * @param missingPackages An array of missing package names.
60
- * @param options An object containing optional parameters:
61
- * @param options.packageManagers An array of package managers to include in the message. Defaults to \["npm", "pnpm", "yarn"\].
62
- * @param options.postMessage A string to append to the end of the message.
63
- * @param options.preMessage A string to prepend to the beginning of the message.
64
- * @returns A string message with instructions to install the missing packages using the specified package managers.
65
- * @throws An `Error` if no package managers are provided in the options.
66
- */
67
- export declare const generateMissingPackagesInstallMessage: (packageName: string, missingPackages: string[], options: {
68
- packageManagers?: PackageManager[];
69
- postMessage?: string;
70
- preMessage?: string;
58
+ * Function that generates a message to install missing packages.
59
+ * @param packageName The name of the package that requires the missing packages.
60
+ * @param missingPackages An array of missing package names.
61
+ * @param options An object containing optional parameters:
62
+ * @param options.packageManagers An array of package managers to include in the message. Defaults to \["npm", "pnpm", "yarn"\].
63
+ * @param options.postMessage A string to append to the end of the message.
64
+ * @param options.preMessage A string to prepend to the beginning of the message.
65
+ * @returns A string message with instructions to install the missing packages using the specified package managers.
66
+ * @throws An `Error` if no package managers are provided in the options.
67
+ */
68
+ declare const generateMissingPackagesInstallMessage: (packageName: string, missingPackages: string[], options: {
69
+ packageManagers?: PackageManager[];
70
+ postMessage?: string;
71
+ preMessage?: string;
71
72
  }) => string;
73
+ export { PackageManager, PackageManagerResult, findLockFile, findLockFileSync, findPackageManager, findPackageManagerSync, generateMissingPackagesInstallMessage, getPackageManagerVersion, identifyInitiatingPackageManager };