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

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.
@@ -1,13 +1,235 @@
1
- var v=Object.defineProperty;var d=(n,e)=>v(n,"name",{value:e,configurable:!0});import{createRequire as _}from"node:module";import{findUpSync as m,findUp as h}from"@visulima/fs";import{NotFoundError as p}from"@visulima/fs/error";import{join as l,dirname as t}from"@visulima/path";import{parsePackageJsonSync as M,parsePackageJson as $}from"./package-json.js";const P=_(import.meta.url),s=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,u=d(n=>{if(typeof s<"u"&&s.versions&&s.versions.node){const[e,a]=s.versions.node.split(".").map(Number);if(e>22||e===22&&a>=3||e===20&&a>=16)return s.getBuiltinModule(n)}return P(n)},"__cjs_getBuiltinModule"),{execSync:W}=u("node:child_process"),{existsSync:k,readFileSync:S}=u("node:fs");var F=Object.defineProperty,r=d((n,e)=>F(n,"name",{value:e,configurable:!0}),"t");const f=["yarn.lock","package-lock.json","pnpm-lock.yaml","npm-shrinkwrap.json","bun.lockb"],y=r(n=>{let e;if(f.forEach(i=>{!e&&k(l(n,i))&&(e=l(n,i))}),e)return e;const a=l(n,"package.json");if(k(a)&&M(S(a,"utf8")).packageManager!==void 0)return a},"packageMangerFindUpMatcher"),E=r(async n=>{if(!n)throw new p("Could not find a package manager");if(n.endsWith("package.json")){const e=await $(n);if(e.packageManager){const a=["npm","yarn","pnpm","bun"].find(i=>e.packageManager.startsWith(i));if(a)return{packageManager:a,path:t(n)}}}if(n.endsWith("yarn.lock"))return{packageManager:"yarn",path:t(n)};if(n.endsWith("package-lock.json")||n.endsWith("npm-shrinkwrap.json"))return{packageManager:"npm",path:t(n)};if(n.endsWith("pnpm-lock.yaml"))return{packageManager:"pnpm",path:t(n)};if(n.endsWith("bun.lockb"))return{packageManager:"bun",path:t(n)};throw new p("Could not find a package manager")},"findPackageManagerOnFile"),x=r(n=>{if(!n)throw new p("Could not find a package manager");if(n.endsWith("package.json")){const e=M(n);if(e.packageManager){const a=["npm","yarn","pnpm","bun"].find(i=>e.packageManager.startsWith(i));if(a)return{packageManager:a,path:t(n)}}}if(n.endsWith("yarn.lock"))return{packageManager:"yarn",path:t(n)};if(n.endsWith("package-lock.json")||n.endsWith("npm-shrinkwrap.json"))return{packageManager:"npm",path:t(n)};if(n.endsWith("pnpm-lock.yaml"))return{packageManager:"pnpm",path:t(n)};if(n.endsWith("bun.lockb"))return{packageManager:"bun",path:t(n)};throw new p("Could not find a package manager")},"findPackageManagerOnFileSync"),U=r(async n=>{const e=await h(f,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find lock file");return e},"findLockFile"),q=r(n=>{const e=m(f,{type:"file",...n&&{cwd:n}});if(!e)throw new Error("Could not find lock file");return e},"findLockFileSync"),B=r(async n=>{const e=await h(y,{...n&&{cwd:n}});return E(e)},"findPackageManager"),D=r(n=>{const e=m(y,{...n&&{cwd:n}});return x(e)},"findPackageManagerSync"),J=r(n=>W(`${n} --version`).toString("utf8").trim(),"getPackageManagerVersion"),R=r(async()=>{if(!process.env.npm_config_user_agent)return;const n=process.env.npm_config_user_agent.split(" ")[0],e=n.lastIndexOf("/"),a=n.slice(0,Math.max(0,e));return{name:a==="npminstall"?"cnpm":a,version:n.slice(Math.max(0,e+1))}},"identifyInitiatingPackageManager"),V=r((n,e,a)=>{const i=e.length===1?"":"s";if(a.packageManagers===void 0&&(a.packageManagers=["npm","pnpm","yarn"]),a.packageManagers.length===0)throw new Error("No package managers provided, please provide at least one package manager");if(e.length===0)throw new Error("No missing packages provided, please provide at least one missing package");let g=`
2
- ${a.preMessage??""}
3
- ${n} could not find the following package${i}
1
+ import { createRequire as __cjs_createRequire } from "node:module";
4
2
 
5
- ${e.join(`
6
- `)}
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
7
4
 
8
- To install the missing package${i}, please run the following command:
9
- `;const w=r(o=>o.split("@").includes("@")?o:`${o}@latest`,"atLatest"),j=a.packageManagers.map(o=>{const c=e.map(b=>w(b)).join(" ");switch(o){case"bun":return` bun add ${c} -D`;case"npm":return` npm install ${c} --save-dev`;case"pnpm":return` pnpm add ${c} -D`;case"yarn":return` yarn add ${c} --dev`;default:throw new Error("Unknown package manager")}});return g+=j.join(`
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
10
6
 
11
- or
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
12
19
 
13
- `),a.postMessage&&(g+=a.postMessage),g},"generateMissingPackagesInstallMessage");export{U as findLockFile,q as findLockFileSync,B as findPackageManager,D as findPackageManagerSync,V as generateMissingPackagesInstallMessage,J as getPackageManagerVersion,R as identifyInitiatingPackageManager};
20
+ const {
21
+ execSync
22
+ } = __cjs_getBuiltinModule("node:child_process");
23
+ const {
24
+ existsSync,
25
+ readFileSync
26
+ } = __cjs_getBuiltinModule("node:fs");
27
+ import { findUp, findUpSync } from '@visulima/fs';
28
+ import { NotFoundError } from '@visulima/fs/error';
29
+ import { join, dirname } from '@visulima/path';
30
+ import { parsePackageJsonSync, parsePackageJson } from './package-json.js';
31
+
32
+ const lockFileNames = ["yarn.lock", "package-lock.json", "pnpm-lock.yaml", "npm-shrinkwrap.json", "bun.lockb"];
33
+ const packageMangerFindUpMatcher = (directory) => {
34
+ let lockFile;
35
+ lockFileNames.forEach((lockFileName) => {
36
+ if (!lockFile && existsSync(join(directory, lockFileName))) {
37
+ lockFile = join(directory, lockFileName);
38
+ }
39
+ });
40
+ if (lockFile) {
41
+ return lockFile;
42
+ }
43
+ const packageJsonFilePath = join(directory, "package.json");
44
+ if (existsSync(packageJsonFilePath)) {
45
+ const packageJson = parsePackageJsonSync(readFileSync(packageJsonFilePath, "utf8"));
46
+ if (packageJson.packageManager !== void 0) {
47
+ return packageJsonFilePath;
48
+ }
49
+ }
50
+ return void 0;
51
+ };
52
+ const findPackageManagerOnFile = async (foundFile) => {
53
+ if (!foundFile) {
54
+ throw new NotFoundError("Could not find a package manager");
55
+ }
56
+ if (foundFile.endsWith("package.json")) {
57
+ const packageJson = await parsePackageJson(foundFile);
58
+ if (packageJson.packageManager) {
59
+ const packageManagerNames = ["npm", "yarn", "pnpm", "bun"];
60
+ const foundPackageManager = packageManagerNames.find((prefix) => packageJson.packageManager.startsWith(prefix));
61
+ if (foundPackageManager) {
62
+ return {
63
+ packageManager: foundPackageManager,
64
+ path: dirname(foundFile)
65
+ };
66
+ }
67
+ }
68
+ }
69
+ if (foundFile.endsWith("yarn.lock")) {
70
+ return {
71
+ packageManager: "yarn",
72
+ path: dirname(foundFile)
73
+ };
74
+ }
75
+ if (foundFile.endsWith("package-lock.json") || foundFile.endsWith("npm-shrinkwrap.json")) {
76
+ return {
77
+ packageManager: "npm",
78
+ path: dirname(foundFile)
79
+ };
80
+ }
81
+ if (foundFile.endsWith("pnpm-lock.yaml")) {
82
+ return {
83
+ packageManager: "pnpm",
84
+ path: dirname(foundFile)
85
+ };
86
+ }
87
+ if (foundFile.endsWith("bun.lockb")) {
88
+ return {
89
+ packageManager: "bun",
90
+ path: dirname(foundFile)
91
+ };
92
+ }
93
+ throw new NotFoundError("Could not find a package manager");
94
+ };
95
+ const findPackageManagerOnFileSync = (foundFile) => {
96
+ if (!foundFile) {
97
+ throw new NotFoundError("Could not find a package manager");
98
+ }
99
+ if (foundFile.endsWith("package.json")) {
100
+ const packageJson = parsePackageJsonSync(foundFile);
101
+ if (packageJson.packageManager) {
102
+ const packageManagerNames = ["npm", "yarn", "pnpm", "bun"];
103
+ const foundPackageManager = packageManagerNames.find((prefix) => packageJson.packageManager.startsWith(prefix));
104
+ if (foundPackageManager) {
105
+ return {
106
+ packageManager: foundPackageManager,
107
+ path: dirname(foundFile)
108
+ };
109
+ }
110
+ }
111
+ }
112
+ if (foundFile.endsWith("yarn.lock")) {
113
+ return {
114
+ packageManager: "yarn",
115
+ path: dirname(foundFile)
116
+ };
117
+ }
118
+ if (foundFile.endsWith("package-lock.json") || foundFile.endsWith("npm-shrinkwrap.json")) {
119
+ return {
120
+ packageManager: "npm",
121
+ path: dirname(foundFile)
122
+ };
123
+ }
124
+ if (foundFile.endsWith("pnpm-lock.yaml")) {
125
+ return {
126
+ packageManager: "pnpm",
127
+ path: dirname(foundFile)
128
+ };
129
+ }
130
+ if (foundFile.endsWith("bun.lockb")) {
131
+ return {
132
+ packageManager: "bun",
133
+ path: dirname(foundFile)
134
+ };
135
+ }
136
+ throw new NotFoundError("Could not find a package manager");
137
+ };
138
+ const findLockFile = async (cwd) => {
139
+ const filePath = await findUp(lockFileNames, {
140
+ type: "file",
141
+ ...cwd && { cwd }
142
+ });
143
+ if (!filePath) {
144
+ throw new Error("Could not find lock file");
145
+ }
146
+ return filePath;
147
+ };
148
+ const findLockFileSync = (cwd) => {
149
+ const filePath = findUpSync(lockFileNames, {
150
+ type: "file",
151
+ ...cwd && { cwd }
152
+ });
153
+ if (!filePath) {
154
+ throw new Error("Could not find lock file");
155
+ }
156
+ return filePath;
157
+ };
158
+ const findPackageManager = async (cwd) => {
159
+ const foundFile = await findUp(packageMangerFindUpMatcher, {
160
+ ...cwd && { cwd }
161
+ });
162
+ return findPackageManagerOnFile(foundFile);
163
+ };
164
+ const findPackageManagerSync = (cwd) => {
165
+ const foundFile = findUpSync(packageMangerFindUpMatcher, {
166
+ ...cwd && { cwd }
167
+ });
168
+ return findPackageManagerOnFileSync(foundFile);
169
+ };
170
+ const getPackageManagerVersion = (name) => execSync(`${name} --version`).toString("utf8").trim();
171
+ const identifyInitiatingPackageManager = async () => {
172
+ if (!process.env.npm_config_user_agent) {
173
+ return void 0;
174
+ }
175
+ const pmSpec = process.env.npm_config_user_agent.split(" ")[0];
176
+ const separatorPos = pmSpec.lastIndexOf("/");
177
+ const name = pmSpec.slice(0, Math.max(0, separatorPos));
178
+ return {
179
+ name: name === "npminstall" ? "cnpm" : name,
180
+ version: pmSpec.slice(Math.max(0, separatorPos + 1))
181
+ };
182
+ };
183
+ const generateMissingPackagesInstallMessage = (packageName, missingPackages, options) => {
184
+ const s = missingPackages.length === 1 ? "" : "s";
185
+ if (options.packageManagers === void 0) {
186
+ options.packageManagers = ["npm", "pnpm", "yarn"];
187
+ }
188
+ if (options.packageManagers.length === 0) {
189
+ throw new Error("No package managers provided, please provide at least one package manager");
190
+ }
191
+ if (missingPackages.length === 0) {
192
+ throw new Error("No missing packages provided, please provide at least one missing package");
193
+ }
194
+ let message = `
195
+ ${options.preMessage ?? ""}
196
+ ${packageName} could not find the following package${s}
197
+
198
+ ${missingPackages.join("\n ")}
199
+
200
+ To install the missing package${s}, please run the following command:
201
+ `;
202
+ const atLatest = (name) => {
203
+ if (!name.split("@").includes("@")) {
204
+ return `${name}@latest`;
205
+ }
206
+ return name;
207
+ };
208
+ const packageManagerCommands = options.packageManagers.map((packageManager) => {
209
+ const missingPackagesString = missingPackages.map((element) => atLatest(element)).join(" ");
210
+ switch (packageManager) {
211
+ case "bun": {
212
+ return ` bun add ${missingPackagesString} -D`;
213
+ }
214
+ case "npm": {
215
+ return ` npm install ${missingPackagesString} --save-dev`;
216
+ }
217
+ case "pnpm": {
218
+ return ` pnpm add ${missingPackagesString} -D`;
219
+ }
220
+ case "yarn": {
221
+ return ` yarn add ${missingPackagesString} --dev`;
222
+ }
223
+ default: {
224
+ throw new Error("Unknown package manager");
225
+ }
226
+ }
227
+ });
228
+ message += packageManagerCommands.join("\n\nor\n\n");
229
+ if (options.postMessage) {
230
+ message += options.postMessage;
231
+ }
232
+ return message;
233
+ };
234
+
235
+ export { findLockFile, findLockFileSync, findPackageManager, findPackageManagerSync, generateMissingPackagesInstallMessage, getPackageManagerVersion, identifyInitiatingPackageManager };
package/dist/package.js CHANGED
@@ -1 +1,81 @@
1
- var u=Object.defineProperty;var c=(e,o)=>u(e,"name",{value:o,configurable:!0});import{createRequire as l}from"node:module";import{findUp as a,findUpSync as f,readJsonSync as _}from"@visulima/fs";import{dirname as r,join as d}from"@visulima/path";import{findLockFile as w,findLockFileSync as j}from"./package-manager.js";const g=l(import.meta.url),i=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,y=c(e=>{if(typeof i<"u"&&i.versions&&i.versions.node){const[o,n]=i.versions.node.split(".").map(Number);if(o>22||o===22&&n>=3||o===20&&n>=16)return i.getBuiltinModule(e)}return g(e)},"__cjs_getBuiltinModule"),{existsSync:m}=y("node:fs");var k=Object.defineProperty,s=c((e,o)=>k(e,"name",{value:o,configurable:!0}),"r");const p=s(e=>{if(m(d(e,"package.json"))){const o=_(d(e,"package.json"));if(o.name&&o.private!==!0)return"package.json"}},"packageJsonMatcher"),S=s(async e=>{try{const t=await w(e);return r(t)}catch{}const o=await a(".git/config",{...e&&{cwd:e},type:"file"});if(o)return r(r(o));const n=await a(p,{...e&&{cwd:e},type:"file"});if(n)return r(n);throw new Error("Could not find root directory")},"findPackageRoot"),q=s(e=>{try{const t=j(e);return r(t)}catch{}const o=f(".git/config",{...e&&{cwd:e},type:"file"});if(o)return r(r(o));const n=f(p,{...e&&{cwd:e},type:"file"});if(n)return r(n);throw new Error("Could not find root directory")},"findPackageRootSync");export{S as findPackageRoot,q as findPackageRootSync};
1
+ import { createRequire as __cjs_createRequire } from "node:module";
2
+
3
+ const __cjs_require = __cjs_createRequire(import.meta.url);
4
+
5
+ const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
6
+
7
+ const __cjs_getBuiltinModule = (module) => {
8
+ // Check if we're in Node.js and version supports getBuiltinModule
9
+ if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
10
+ const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
11
+ // Node.js 20.16.0+ and 22.3.0+
12
+ if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
13
+ return __cjs_getProcess.getBuiltinModule(module);
14
+ }
15
+ }
16
+ // Fallback to createRequire
17
+ return __cjs_require(module);
18
+ };
19
+
20
+ const {
21
+ existsSync
22
+ } = __cjs_getBuiltinModule("node:fs");
23
+ import { findUp, findUpSync, readJsonSync } from '@visulima/fs';
24
+ import { dirname, join } from '@visulima/path';
25
+ import { findLockFile, findLockFileSync } from './package-manager.js';
26
+
27
+ const packageJsonMatcher = (directory) => {
28
+ if (existsSync(join(directory, "package.json"))) {
29
+ const packageJson = readJsonSync(join(directory, "package.json"));
30
+ if (packageJson.name && packageJson.private !== true) {
31
+ return "package.json";
32
+ }
33
+ }
34
+ return void 0;
35
+ };
36
+ const findPackageRoot = async (cwd) => {
37
+ try {
38
+ const lockFile = await findLockFile(cwd);
39
+ return dirname(lockFile);
40
+ } catch {
41
+ }
42
+ const gitConfig = await findUp(".git/config", {
43
+ ...cwd && { cwd },
44
+ type: "file"
45
+ });
46
+ if (gitConfig) {
47
+ return dirname(dirname(gitConfig));
48
+ }
49
+ const filePath = await findUp(packageJsonMatcher, {
50
+ ...cwd && { cwd },
51
+ type: "file"
52
+ });
53
+ if (filePath) {
54
+ return dirname(filePath);
55
+ }
56
+ throw new Error("Could not find root directory");
57
+ };
58
+ const findPackageRootSync = (cwd) => {
59
+ try {
60
+ const lockFile = findLockFileSync(cwd);
61
+ return dirname(lockFile);
62
+ } catch {
63
+ }
64
+ const gitConfig = findUpSync(".git/config", {
65
+ ...cwd && { cwd },
66
+ type: "file"
67
+ });
68
+ if (gitConfig) {
69
+ return dirname(dirname(gitConfig));
70
+ }
71
+ const filePath = findUpSync(packageJsonMatcher, {
72
+ ...cwd && { cwd },
73
+ type: "file"
74
+ });
75
+ if (filePath) {
76
+ return dirname(filePath);
77
+ }
78
+ throw new Error("Could not find root directory");
79
+ };
80
+
81
+ export { findPackageRoot, findPackageRootSync };
@@ -0,0 +1,46 @@
1
+ import { findPackageManagerSync } from '../package-manager.js';
2
+
3
+ class PackageNotFoundError extends Error {
4
+ /**
5
+ * @param packageName The name of the package that was not found.
6
+ * @param packageManager The package manager used to install the package.
7
+ */
8
+ constructor(packageName, packageManager) {
9
+ if (typeof packageName === "string") {
10
+ packageName = [packageName];
11
+ }
12
+ if (packageName.length === 0) {
13
+ super("Package was not found.");
14
+ return;
15
+ }
16
+ if (packageManager === void 0) {
17
+ try {
18
+ const foundManager = findPackageManagerSync();
19
+ packageManager = foundManager.packageManager;
20
+ } catch {
21
+ }
22
+ }
23
+ if (packageManager === void 0) {
24
+ packageManager = "npm";
25
+ }
26
+ super(`Package '${packageName.join(" ")}' was not found. Please install it using '${packageManager} install ${packageName.join(" ")}'`);
27
+ }
28
+ // eslint-disable-next-line class-methods-use-this
29
+ get code() {
30
+ return "PACKAGE_NOT_FOUND";
31
+ }
32
+ // eslint-disable-next-line class-methods-use-this,@typescript-eslint/explicit-module-boundary-types
33
+ set code(_name) {
34
+ throw new Error("Cannot overwrite code PACKAGE_NOT_FOUND");
35
+ }
36
+ // eslint-disable-next-line class-methods-use-this
37
+ get name() {
38
+ return "PackageNotFoundError";
39
+ }
40
+ // eslint-disable-next-line class-methods-use-this,@typescript-eslint/explicit-module-boundary-types
41
+ set name(_name) {
42
+ throw new Error("Cannot overwrite name of PackageNotFoundError");
43
+ }
44
+ }
45
+
46
+ export { PackageNotFoundError as default };
package/dist/pnpm.js CHANGED
@@ -1 +1,105 @@
1
- var y=Object.defineProperty;var f=(t,a)=>y(t,"name",{value:a,configurable:!0});import{findUpSync as u,findUp as m}from"@visulima/fs";import{readYamlSync as v,readYaml as k}from"@visulima/fs/yaml";import{dirname as l,relative as b}from"@visulima/path";var h=Object.defineProperty,i=f((t,a)=>h(t,"name",{value:a,configurable:!0}),"c");const d=i((t,a,e)=>{const c=l(t),o=l(a),g=o===c?".":b(c,o);return e.some(p=>{const n=p.startsWith("./")?p.slice(2):p,s=g.startsWith("./")?g.slice(2):g;if(n==="."&&s===".")return!0;if(n.endsWith("/**")){const r=n.slice(0,-3);return s===r||s.startsWith(`${r}/`)}if(n.endsWith("/*")){const r=n.slice(0,-2);return r===""?s!=="."&&!s.includes("/"):s.startsWith(`${r}/`)||s===r}return s===n||s.startsWith(`${n}/`)})},"isPackageInWorkspace"),D=i(async t=>{const a=await m("pnpm-workspace.yaml",{cwd:l(t),type:"file"});if(!a)return;const e=await k(a),c=Array.isArray(e.packages)?e.packages:[];if(!d(a,t,c))return;const o={};return e.catalog&&typeof e.catalog=="object"&&(o.catalog=e.catalog),e.catalogs&&typeof e.catalogs=="object"&&(o.catalogs=e.catalogs),Object.keys(o).length>0?o:void 0},"readPnpmCatalogs"),A=i(t=>{const a=u("pnpm-workspace.yaml",{cwd:l(t),type:"file"});if(!a)return;const e=v(a),c=Array.isArray(e.packages)?e.packages:[];if(!d(a,t,c))return;const o={};return e.catalog&&typeof e.catalog=="object"&&(o.catalog=e.catalog),e.catalogs&&typeof e.catalogs=="object"&&(o.catalogs=e.catalogs),Object.keys(o).length>0?o:void 0},"readPnpmCatalogsSync"),C=i((t,a,e)=>{if(a==="catalog:")return e.catalog?.[t];if(a.startsWith("catalog:")){const c=a.slice(8);return e.catalogs?.[c]?.[t]}},"resolveCatalogReference"),W=i((t,a)=>{for(const[e,c]of Object.entries(t)){if(typeof c!="string")continue;const o=C(e,c,a);o&&(t[e]=o)}},"resolveDependenciesCatalogReferences"),O=i((t,a)=>{const e=["dependencies","devDependencies","peerDependencies","optionalDependencies"];for(const c of e){if(!t[c]||typeof t[c]!="object")continue;const o=t[c];W(o,a)}},"resolveCatalogReferences");export{d as isPackageInWorkspace,D as readPnpmCatalogs,A as readPnpmCatalogsSync,C as resolveCatalogReference,O as resolveCatalogReferences,W as resolveDependenciesCatalogReferences};
1
+ import { findUp, findUpSync } from '@visulima/fs';
2
+ import { readYaml, readYamlSync } from '@visulima/fs/yaml';
3
+ import { dirname, relative } from '@visulima/path';
4
+
5
+ const isPackageInWorkspace = (workspacePath, packagePath, workspacePackages) => {
6
+ const workspaceDirectory = dirname(workspacePath);
7
+ const packageDirectory = dirname(packagePath);
8
+ const relativePath = packageDirectory === workspaceDirectory ? "." : relative(workspaceDirectory, packageDirectory);
9
+ return workspacePackages.some((pattern) => {
10
+ const normalizedPattern = pattern.startsWith("./") ? pattern.slice(2) : pattern;
11
+ const normalizedRelativePath = relativePath.startsWith("./") ? relativePath.slice(2) : relativePath;
12
+ if (normalizedPattern === "." && normalizedRelativePath === ".") {
13
+ return true;
14
+ }
15
+ if (normalizedPattern.endsWith("/**")) {
16
+ const prefix = normalizedPattern.slice(0, -3);
17
+ return normalizedRelativePath === prefix || normalizedRelativePath.startsWith(`${prefix}/`);
18
+ }
19
+ if (normalizedPattern.endsWith("/*")) {
20
+ const prefix = normalizedPattern.slice(0, -2);
21
+ if (prefix === "") {
22
+ return normalizedRelativePath !== "." && !normalizedRelativePath.includes("/");
23
+ }
24
+ return normalizedRelativePath.startsWith(`${prefix}/`) || normalizedRelativePath === prefix;
25
+ }
26
+ return normalizedRelativePath === normalizedPattern || normalizedRelativePath.startsWith(`${normalizedPattern}/`);
27
+ });
28
+ };
29
+ const readPnpmCatalogs = async (packagePath) => {
30
+ const workspacePath = await findUp("pnpm-workspace.yaml", {
31
+ cwd: dirname(packagePath),
32
+ type: "file"
33
+ });
34
+ if (!workspacePath) {
35
+ return void 0;
36
+ }
37
+ const workspaceData = await readYaml(workspacePath);
38
+ const workspacePackages = Array.isArray(workspaceData.packages) ? workspaceData.packages : [];
39
+ if (!isPackageInWorkspace(workspacePath, packagePath, workspacePackages)) {
40
+ return void 0;
41
+ }
42
+ const catalogs = {};
43
+ if (workspaceData.catalog && typeof workspaceData.catalog === "object") {
44
+ catalogs.catalog = workspaceData.catalog;
45
+ }
46
+ if (workspaceData.catalogs && typeof workspaceData.catalogs === "object") {
47
+ catalogs.catalogs = workspaceData.catalogs;
48
+ }
49
+ return Object.keys(catalogs).length > 0 ? catalogs : void 0;
50
+ };
51
+ const readPnpmCatalogsSync = (packagePath) => {
52
+ const workspacePath = findUpSync("pnpm-workspace.yaml", {
53
+ cwd: dirname(packagePath),
54
+ type: "file"
55
+ });
56
+ if (!workspacePath) {
57
+ return void 0;
58
+ }
59
+ const workspaceData = readYamlSync(workspacePath);
60
+ const workspacePackages = Array.isArray(workspaceData.packages) ? workspaceData.packages : [];
61
+ if (!isPackageInWorkspace(workspacePath, packagePath, workspacePackages)) {
62
+ return void 0;
63
+ }
64
+ const catalogs = {};
65
+ if (workspaceData.catalog && typeof workspaceData.catalog === "object") {
66
+ catalogs.catalog = workspaceData.catalog;
67
+ }
68
+ if (workspaceData.catalogs && typeof workspaceData.catalogs === "object") {
69
+ catalogs.catalogs = workspaceData.catalogs;
70
+ }
71
+ return Object.keys(catalogs).length > 0 ? catalogs : void 0;
72
+ };
73
+ const resolveCatalogReference = (packageName, versionSpec, catalogs) => {
74
+ if (versionSpec === "catalog:") {
75
+ return catalogs.catalog?.[packageName];
76
+ }
77
+ if (versionSpec.startsWith("catalog:")) {
78
+ const catalogName = versionSpec.slice(8);
79
+ return catalogs.catalogs?.[catalogName]?.[packageName];
80
+ }
81
+ return void 0;
82
+ };
83
+ const resolveDependenciesCatalogReferences = (dependencies, catalogs) => {
84
+ for (const [packageName, versionSpec] of Object.entries(dependencies)) {
85
+ if (typeof versionSpec !== "string") {
86
+ continue;
87
+ }
88
+ const resolvedVersion = resolveCatalogReference(packageName, versionSpec, catalogs);
89
+ if (resolvedVersion) {
90
+ dependencies[packageName] = resolvedVersion;
91
+ }
92
+ }
93
+ };
94
+ const resolveCatalogReferences = (packageJson, catalogs) => {
95
+ const dependencyFields = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"];
96
+ for (const field of dependencyFields) {
97
+ if (!packageJson[field] || typeof packageJson[field] !== "object") {
98
+ continue;
99
+ }
100
+ const dependencies = packageJson[field];
101
+ resolveDependenciesCatalogReferences(dependencies, catalogs);
102
+ }
103
+ };
104
+
105
+ export { isPackageInWorkspace, readPnpmCatalogs, readPnpmCatalogsSync, resolveCatalogReference, resolveCatalogReferences, resolveDependenciesCatalogReferences };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@visulima/package",
3
- "version": "5.0.0-alpha.3",
3
+ "version": "5.0.0-alpha.5",
4
4
  "description": "A comprehensive package management utility that helps you find root directories, monorepos, package managers, and parse package.json, package.yaml, and package.json5 files with advanced features like catalog resolution.",
5
5
  "keywords": [
6
6
  "anolilab",
@@ -97,13 +97,15 @@
97
97
  ],
98
98
  "dependencies": {
99
99
  "@antfu/install-pkg": "^1.1.0",
100
- "@visulima/fs": "5.0.0-alpha.3",
101
- "@visulima/path": "3.0.0-alpha.4",
100
+ "@visulima/fs": "5.0.0-alpha.5",
101
+ "@visulima/path": "3.0.0-alpha.6",
102
102
  "json5": "^2.2.3",
103
103
  "normalize-package-data": "^8.0.0",
104
- "type-fest": "^5.3.1",
105
- "yaml": "^2.8.2"
104
+ "type-fest": "5.5.0",
105
+ "yaml": "2.8.3"
106
106
  },
107
+ "peerDependencies": {},
108
+ "optionalDependencies": {},
107
109
  "engines": {
108
110
  "node": ">=22.13 <=25.x"
109
111
  },
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var a=(t,e)=>o(t,"name",{value:e,configurable:!0});import{findPackageManagerSync as n}from"../package-manager.js";var c=Object.defineProperty,i=a((t,e)=>c(t,"name",{value:e,configurable:!0}),"t");class g extends Error{static{a(this,"u")}static{i(this,"PackageNotFoundError")}constructor(e,r){if(typeof e=="string"&&(e=[e]),e.length===0){super("Package was not found.");return}if(r===void 0)try{r=n().packageManager}catch{}r===void 0&&(r="npm"),super(`Package '${e.join(" ")}' was not found. Please install it using '${r} install ${e.join(" ")}'`)}get code(){return"PACKAGE_NOT_FOUND"}set code(e){throw new Error("Cannot overwrite code PACKAGE_NOT_FOUND")}get name(){return"PackageNotFoundError"}set name(e){throw new Error("Cannot overwrite name of PackageNotFoundError")}}export{g as default};