@visulima/package 3.4.2 → 3.4.3

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 +1,413 @@
1
- var A=Object.defineProperty;var c=(e,n)=>A(e,"name",{value:n,configurable:!0});import{existsSync as N}from"node:fs";import{installPackage as $}from"@antfu/install-pkg";import O from"@inquirer/confirm";import{findUp as T,readJson as _,findUpSync as C,readJsonSync as J,writeJson as K,writeJsonSync as F}from"@visulima/fs";import{NotFoundError as E}from"@visulima/fs/error";import{toPath as m,parseJson as U}from"@visulima/fs/utils";import{join as j}from"@visulima/path";import P from"normalize-package-data";var q=Object.defineProperty,f=c((e,n)=>q(e,"name",{value:n,configurable:!0}),"s");const p=f(e=>{const n=typeof e;return e!==null&&(n==="object"||n==="function")},"isObject"),M=f(e=>p(e)&&Object.keys(e).length===0,"isEmptyObject"),k=new Set(["__proto__","prototype","constructor"]),Y=new Set("0123456789");function l(e){const n=[];let r="",t="start",o=!1;for(const a of e)switch(a){case"\\":{if(t==="index")throw new Error("Invalid character in an index");if(t==="indexEnd")throw new Error("Invalid character after an index");o&&(r+=a),t="property",o=!o;break}case".":{if(t==="index")throw new Error("Invalid character in an index");if(t==="indexEnd"){t="property";break}if(o){o=!1,r+=a;break}if(k.has(r))return[];n.push(r),r="",t="property";break}case"[":{if(t==="index")throw new Error("Invalid character in an index");if(t==="indexEnd"){t="index";break}if(o){o=!1,r+=a;break}if(t==="property"){if(k.has(r))return[];n.push(r),r=""}t="index";break}case"]":{if(t==="index"){n.push(Number.parseInt(r,10)),r="",t="indexEnd";break}if(t==="indexEnd")throw new Error("Invalid character after an index")}default:{if(t==="index"&&!Y.has(a))throw new Error("Invalid character in an index");if(t==="indexEnd")throw new Error("Invalid character after an index");t==="start"&&(t="property"),o&&(o=!1,r+="\\"),r+=a}}switch(o&&(r+="\\"),t){case"property":{if(k.has(r))return[];n.push(r);break}case"index":throw new Error("Index was not closed");case"start":{n.push("");break}}return n}c(l,"d");f(l,"getPathSegments");function w(e,n){if(typeof n!="number"&&Array.isArray(e)){const r=Number.parseInt(n,10);return Number.isInteger(r)&&e[r]===e[n]}return!1}c(w,"l");f(w,"isStringIndex");function b(e,n){if(w(e,n))throw new Error("Cannot use string index")}c(b,"p");f(b,"assertNotStringIndex");function u(e,n,r){if(!p(e)||typeof n!="string")return r===void 0?e:r;const t=l(n);if(t.length===0)return r;for(let o=0;o<t.length;o++){const a=t[o];if(w(e,a)?e=o===t.length-1?void 0:null:e=e[a],e==null){if(o!==t.length-1)return r;break}}return e===void 0?r:e}c(u,"getProperty");f(u,"getProperty");function z(e,n,r){if(!p(e)||typeof n!="string")return e;const t=e,o=l(n);for(let a=0;a<o.length;a++){const s=o[a];b(e,s),a===o.length-1?e[s]=r:p(e[s])||(e[s]=typeof o[a+1]=="number"?[]:{}),e=e[s]}return t}c(z,"setProperty");f(z,"setProperty");function B(e,n){if(!p(e)||typeof n!="string")return!1;const r=l(n);for(let t=0;t<r.length;t++){const o=r[t];if(b(e,o),t===r.length-1)return delete e[o],!0;if(e=e[o],!p(e))return!1}}c(B,"deleteProperty");f(B,"deleteProperty");function y(e,n){if(!p(e)||typeof n!="string")return!1;const r=l(n);if(r.length===0)return!1;for(const t of r){if(!p(e)||!(t in e)||w(e,t))return!1;e=e[t]}return!0}c(y,"hasProperty");f(y,"hasProperty");function I(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replaceAll(/[\\.[]/g,"\\$&")}c(I,"escapePath");f(I,"escapePath");function x(e){const n=Object.entries(e);return Array.isArray(e)?n.map(([r,t])=>[Number(r),t]):n}c(x,"h");f(x,"entries");function S(e){let n="";for(let[r,t]of x(e))typeof t=="number"?n+=`[${t}]`:(t=I(t),n+=r===0?t:`.${t}`);return n}c(S,"w");f(S,"stringifyPath");function*v(e,n=[]){if(!p(e)||M(e)){n.length>0&&(yield S(n));return}for(const[r,t]of x(e))yield*v(t,[...n,r])}c(v,"y$1");f(v,"deepKeysIterator");function G(e){return[...v(e)]}c(G,"deepKeys");f(G,"deepKeys");const H=typeof process.stdout<"u"&&!process.versions?.deno&&!globalThis.window;var L=Object.defineProperty,d=c((e,n)=>L(e,"name",{value:n,configurable:!0}),"r");const D=new Map,re=d(async(e,n={})=>{const r={type:"file"};e&&(r.cwd=e);const t=await T("package.json",r);if(!t)throw new E("No such file or directory, for package.json found.");const o=n.cache&&typeof n.cache!="boolean"?n.cache:D;if(n.cache&&o.has(t))return o.get(t);const a=await _(t);P(a);const s={packageJson:a,path:t};return o.set(t,s),s},"findPackageJson"),oe=d((e,n={})=>{const r={type:"file"};e&&(r.cwd=e);const t=C("package.json",r);if(!t)throw new E("No such file or directory, for package.json found.");const o=n.cache&&typeof n.cache!="boolean"?n.cache:D;if(n.cache&&o.has(t))return o.get(t);const a=J(t);P(a);const s={packageJson:a,path:t};return o.set(t,s),s},"findPackageJsonSync"),ae=d(async(e,n={})=>{const{cwd:r,...t}=n,o=m(n.cwd??process.cwd());await K(j(o,"package.json"),e,t)},"writePackageJson"),se=d((e,n={})=>{const{cwd:r,...t}=n,o=m(n.cwd??process.cwd());F(j(o,"package.json"),e,t)},"writePackageJsonSync"),ce=d(e=>{const n=e!==null&&typeof e=="object"&&!Array.isArray(e);if(!n&&typeof e!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");const r=n?structuredClone(e):N(e)?J(e):U(e);return P(r),r},"parsePackageJson"),ie=d((e,n,r)=>u(e,n,r),"getPackageJsonProperty"),fe=d((e,n)=>y(e,n),"hasPackageJsonProperty"),pe=d((e,n,r)=>{const t=u(e,"dependencies",{}),o=u(e,"devDependencies",{}),a=u(e,"peerDependencies",{}),s={...t,...o,...r?.peerDeps===!1?{}:a};for(const g of n)if(y(s,g))return!0;return!1},"hasPackageJsonAnyDependency"),de=d(async(e,n,r="dependencies",t={})=>{if(process.env.CI||H&&!process.stdout?.isTTY){console.warn("Skipping package installation because the process is not interactive.");return}const o=u(e,"dependencies",{}),a=u(e,"devDependencies",{}),s=u(e,"peerDependencies",{}),g=[],i={deps:!0,devDeps:!0,peerDeps:!1,...t};for(const h of n)i.deps&&y(o,h)||i.devDeps&&y(a,h)||i.peerDeps&&y(s,h)||g.push(h);if(typeof i.confirm?.message=="function"&&(i.confirm.message=i.confirm.message(g)),i.confirm?.message===void 0){const h=`${g.length===1?"Package is":"Packages are"} required for this config: ${g.join(", ")}. Do you want to install them?`;i.confirm===void 0?i.confirm={message:h}:i.confirm.message=h}await O(i.confirm)&&await $(g,{...i.installPackage,cwd:i.cwd?m(i.cwd):void 0,dev:r==="devDependencies"})},"ensurePackages");export{de as ensurePackages,re as findPackageJson,oe as findPackageJsonSync,ie as getPackageJsonProperty,pe as hasPackageJsonAnyDependency,fe as hasPackageJsonProperty,ce as parsePackageJson,ae as writePackageJson,se as writePackageJsonSync};
1
+ import { existsSync } from 'node:fs';
2
+ import { installPackage } from '@antfu/install-pkg';
3
+ import confirm from '@inquirer/confirm';
4
+ import { findUp, readJson, findUpSync, readJsonSync, writeJson, writeJsonSync } from '@visulima/fs';
5
+ import { NotFoundError } from '@visulima/fs/error';
6
+ import { toPath, parseJson } from '@visulima/fs/utils';
7
+ import { join } from '@visulima/path';
8
+ import normalizeData from 'normalize-package-data';
9
+
10
+ var __defProp$1 = Object.defineProperty;
11
+ var __name$1 = (target, value) => __defProp$1(target, "name", { value, configurable: true });
12
+ const isObject = /* @__PURE__ */ __name$1((value) => {
13
+ const type = typeof value;
14
+ return value !== null && (type === "object" || type === "function");
15
+ }, "isObject");
16
+ const isEmptyObject = /* @__PURE__ */ __name$1((value) => isObject(value) && Object.keys(value).length === 0, "isEmptyObject");
17
+ const disallowedKeys = /* @__PURE__ */ new Set([
18
+ "__proto__",
19
+ "prototype",
20
+ "constructor"
21
+ ]);
22
+ const digits = new Set("0123456789");
23
+ function getPathSegments(path) {
24
+ const parts = [];
25
+ let currentSegment = "";
26
+ let currentPart = "start";
27
+ let isIgnoring = false;
28
+ for (const character of path) {
29
+ switch (character) {
30
+ case "\\": {
31
+ if (currentPart === "index") {
32
+ throw new Error("Invalid character in an index");
33
+ }
34
+ if (currentPart === "indexEnd") {
35
+ throw new Error("Invalid character after an index");
36
+ }
37
+ if (isIgnoring) {
38
+ currentSegment += character;
39
+ }
40
+ currentPart = "property";
41
+ isIgnoring = !isIgnoring;
42
+ break;
43
+ }
44
+ case ".": {
45
+ if (currentPart === "index") {
46
+ throw new Error("Invalid character in an index");
47
+ }
48
+ if (currentPart === "indexEnd") {
49
+ currentPart = "property";
50
+ break;
51
+ }
52
+ if (isIgnoring) {
53
+ isIgnoring = false;
54
+ currentSegment += character;
55
+ break;
56
+ }
57
+ if (disallowedKeys.has(currentSegment)) {
58
+ return [];
59
+ }
60
+ parts.push(currentSegment);
61
+ currentSegment = "";
62
+ currentPart = "property";
63
+ break;
64
+ }
65
+ case "[": {
66
+ if (currentPart === "index") {
67
+ throw new Error("Invalid character in an index");
68
+ }
69
+ if (currentPart === "indexEnd") {
70
+ currentPart = "index";
71
+ break;
72
+ }
73
+ if (isIgnoring) {
74
+ isIgnoring = false;
75
+ currentSegment += character;
76
+ break;
77
+ }
78
+ if (currentPart === "property") {
79
+ if (disallowedKeys.has(currentSegment)) {
80
+ return [];
81
+ }
82
+ parts.push(currentSegment);
83
+ currentSegment = "";
84
+ }
85
+ currentPart = "index";
86
+ break;
87
+ }
88
+ case "]": {
89
+ if (currentPart === "index") {
90
+ parts.push(Number.parseInt(currentSegment, 10));
91
+ currentSegment = "";
92
+ currentPart = "indexEnd";
93
+ break;
94
+ }
95
+ if (currentPart === "indexEnd") {
96
+ throw new Error("Invalid character after an index");
97
+ }
98
+ }
99
+ default: {
100
+ if (currentPart === "index" && !digits.has(character)) {
101
+ throw new Error("Invalid character in an index");
102
+ }
103
+ if (currentPart === "indexEnd") {
104
+ throw new Error("Invalid character after an index");
105
+ }
106
+ if (currentPart === "start") {
107
+ currentPart = "property";
108
+ }
109
+ if (isIgnoring) {
110
+ isIgnoring = false;
111
+ currentSegment += "\\";
112
+ }
113
+ currentSegment += character;
114
+ }
115
+ }
116
+ }
117
+ if (isIgnoring) {
118
+ currentSegment += "\\";
119
+ }
120
+ switch (currentPart) {
121
+ case "property": {
122
+ if (disallowedKeys.has(currentSegment)) {
123
+ return [];
124
+ }
125
+ parts.push(currentSegment);
126
+ break;
127
+ }
128
+ case "index": {
129
+ throw new Error("Index was not closed");
130
+ }
131
+ case "start": {
132
+ parts.push("");
133
+ break;
134
+ }
135
+ }
136
+ return parts;
137
+ }
138
+ __name$1(getPathSegments, "getPathSegments");
139
+ function isStringIndex(object, key) {
140
+ if (typeof key !== "number" && Array.isArray(object)) {
141
+ const index = Number.parseInt(key, 10);
142
+ return Number.isInteger(index) && object[index] === object[key];
143
+ }
144
+ return false;
145
+ }
146
+ __name$1(isStringIndex, "isStringIndex");
147
+ function assertNotStringIndex(object, key) {
148
+ if (isStringIndex(object, key)) {
149
+ throw new Error("Cannot use string index");
150
+ }
151
+ }
152
+ __name$1(assertNotStringIndex, "assertNotStringIndex");
153
+ function getProperty(object, path, value) {
154
+ if (!isObject(object) || typeof path !== "string") {
155
+ return value === undefined ? object : value;
156
+ }
157
+ const pathArray = getPathSegments(path);
158
+ if (pathArray.length === 0) {
159
+ return value;
160
+ }
161
+ for (let index = 0; index < pathArray.length; index++) {
162
+ const key = pathArray[index];
163
+ if (isStringIndex(object, key)) {
164
+ object = index === pathArray.length - 1 ? undefined : null;
165
+ } else {
166
+ object = object[key];
167
+ }
168
+ if (object === undefined || object === null) {
169
+ if (index !== pathArray.length - 1) {
170
+ return value;
171
+ }
172
+ break;
173
+ }
174
+ }
175
+ return object === undefined ? value : object;
176
+ }
177
+ __name$1(getProperty, "getProperty");
178
+ function setProperty(object, path, value) {
179
+ if (!isObject(object) || typeof path !== "string") {
180
+ return object;
181
+ }
182
+ const root = object;
183
+ const pathArray = getPathSegments(path);
184
+ for (let index = 0; index < pathArray.length; index++) {
185
+ const key = pathArray[index];
186
+ assertNotStringIndex(object, key);
187
+ if (index === pathArray.length - 1) {
188
+ object[key] = value;
189
+ } else if (!isObject(object[key])) {
190
+ object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
191
+ }
192
+ object = object[key];
193
+ }
194
+ return root;
195
+ }
196
+ __name$1(setProperty, "setProperty");
197
+ function deleteProperty(object, path) {
198
+ if (!isObject(object) || typeof path !== "string") {
199
+ return false;
200
+ }
201
+ const pathArray = getPathSegments(path);
202
+ for (let index = 0; index < pathArray.length; index++) {
203
+ const key = pathArray[index];
204
+ assertNotStringIndex(object, key);
205
+ if (index === pathArray.length - 1) {
206
+ delete object[key];
207
+ return true;
208
+ }
209
+ object = object[key];
210
+ if (!isObject(object)) {
211
+ return false;
212
+ }
213
+ }
214
+ }
215
+ __name$1(deleteProperty, "deleteProperty");
216
+ function hasProperty(object, path) {
217
+ if (!isObject(object) || typeof path !== "string") {
218
+ return false;
219
+ }
220
+ const pathArray = getPathSegments(path);
221
+ if (pathArray.length === 0) {
222
+ return false;
223
+ }
224
+ for (const key of pathArray) {
225
+ if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
226
+ return false;
227
+ }
228
+ object = object[key];
229
+ }
230
+ return true;
231
+ }
232
+ __name$1(hasProperty, "hasProperty");
233
+ function escapePath(path) {
234
+ if (typeof path !== "string") {
235
+ throw new TypeError("Expected a string");
236
+ }
237
+ return path.replaceAll(/[\\.[]/g, "\\$&");
238
+ }
239
+ __name$1(escapePath, "escapePath");
240
+ function entries(value) {
241
+ const result = Object.entries(value);
242
+ if (Array.isArray(value)) {
243
+ return result.map(([key, value2]) => [Number(key), value2]);
244
+ }
245
+ return result;
246
+ }
247
+ __name$1(entries, "entries");
248
+ function stringifyPath(pathSegments) {
249
+ let result = "";
250
+ for (let [index, segment] of entries(pathSegments)) {
251
+ if (typeof segment === "number") {
252
+ result += `[${segment}]`;
253
+ } else {
254
+ segment = escapePath(segment);
255
+ result += index === 0 ? segment : `.${segment}`;
256
+ }
257
+ }
258
+ return result;
259
+ }
260
+ __name$1(stringifyPath, "stringifyPath");
261
+ function* deepKeysIterator(object, currentPath = []) {
262
+ if (!isObject(object) || isEmptyObject(object)) {
263
+ if (currentPath.length > 0) {
264
+ yield stringifyPath(currentPath);
265
+ }
266
+ return;
267
+ }
268
+ for (const [key, value] of entries(object)) {
269
+ yield* deepKeysIterator(value, [...currentPath, key]);
270
+ }
271
+ }
272
+ __name$1(deepKeysIterator, "deepKeysIterator");
273
+ function deepKeys(object) {
274
+ return [...deepKeysIterator(object)];
275
+ }
276
+ __name$1(deepKeys, "deepKeys");
277
+
278
+ const isNode = typeof process.stdout < "u" && !process.versions?.deno && !globalThis.window;
279
+
280
+ var __defProp = Object.defineProperty;
281
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
282
+ const PackageJsonFileCache = /* @__PURE__ */ new Map();
283
+ const findPackageJson = /* @__PURE__ */ __name(async (cwd, options = {}) => {
284
+ const findUpConfig = {
285
+ type: "file"
286
+ };
287
+ if (cwd) {
288
+ findUpConfig.cwd = cwd;
289
+ }
290
+ const filePath = await findUp("package.json", findUpConfig);
291
+ if (!filePath) {
292
+ throw new NotFoundError("No such file or directory, for package.json found.");
293
+ }
294
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
295
+ if (options.cache && cache.has(filePath)) {
296
+ return cache.get(filePath);
297
+ }
298
+ const packageJson = await readJson(filePath);
299
+ normalizeData(packageJson);
300
+ const output = {
301
+ packageJson,
302
+ path: filePath
303
+ };
304
+ cache.set(filePath, output);
305
+ return output;
306
+ }, "findPackageJson");
307
+ const findPackageJsonSync = /* @__PURE__ */ __name((cwd, options = {}) => {
308
+ const findUpConfig = {
309
+ type: "file"
310
+ };
311
+ if (cwd) {
312
+ findUpConfig.cwd = cwd;
313
+ }
314
+ const filePath = findUpSync("package.json", findUpConfig);
315
+ if (!filePath) {
316
+ throw new NotFoundError("No such file or directory, for package.json found.");
317
+ }
318
+ const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
319
+ if (options.cache && cache.has(filePath)) {
320
+ return cache.get(filePath);
321
+ }
322
+ const packageJson = readJsonSync(filePath);
323
+ normalizeData(packageJson);
324
+ const output = {
325
+ packageJson,
326
+ path: filePath
327
+ };
328
+ cache.set(filePath, output);
329
+ return output;
330
+ }, "findPackageJsonSync");
331
+ const writePackageJson = /* @__PURE__ */ __name(async (data, options = {}) => {
332
+ const { cwd, ...writeOptions } = options;
333
+ const directory = toPath(options.cwd ?? process.cwd());
334
+ await writeJson(join(directory, "package.json"), data, writeOptions);
335
+ }, "writePackageJson");
336
+ const writePackageJsonSync = /* @__PURE__ */ __name((data, options = {}) => {
337
+ const { cwd, ...writeOptions } = options;
338
+ const directory = toPath(options.cwd ?? process.cwd());
339
+ writeJsonSync(join(directory, "package.json"), data, writeOptions);
340
+ }, "writePackageJsonSync");
341
+ const parsePackageJson = /* @__PURE__ */ __name((packageFile) => {
342
+ const isObject = packageFile !== null && typeof packageFile === "object" && !Array.isArray(packageFile);
343
+ const isString = typeof packageFile === "string";
344
+ if (!isObject && !isString) {
345
+ throw new TypeError("`packageFile` should be either an `object` or a `string`.");
346
+ }
347
+ const json = isObject ? structuredClone(packageFile) : (
348
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
349
+ existsSync(packageFile) ? readJsonSync(packageFile) : parseJson(packageFile)
350
+ );
351
+ normalizeData(json);
352
+ return json;
353
+ }, "parsePackageJson");
354
+ const getPackageJsonProperty = /* @__PURE__ */ __name((packageJson, property, defaultValue) => getProperty(packageJson, property, defaultValue), "getPackageJsonProperty");
355
+ const hasPackageJsonProperty = /* @__PURE__ */ __name((packageJson, property) => hasProperty(packageJson, property), "hasPackageJsonProperty");
356
+ const hasPackageJsonAnyDependency = /* @__PURE__ */ __name((packageJson, arguments_, options) => {
357
+ const dependencies = getProperty(packageJson, "dependencies", {});
358
+ const devDependencies = getProperty(packageJson, "devDependencies", {});
359
+ const peerDependencies = getProperty(packageJson, "peerDependencies", {});
360
+ const allDependencies = { ...dependencies, ...devDependencies, ...options?.peerDeps === false ? {} : peerDependencies };
361
+ for (const argument of arguments_) {
362
+ if (hasProperty(allDependencies, argument)) {
363
+ return true;
364
+ }
365
+ }
366
+ return false;
367
+ }, "hasPackageJsonAnyDependency");
368
+ const ensurePackages = /* @__PURE__ */ __name(async (packageJson, packages, installKey = "dependencies", options = {}) => {
369
+ if (process.env.CI || isNode && !process.stdout?.isTTY) {
370
+ console.warn("Skipping package installation because the process is not interactive.");
371
+ return;
372
+ }
373
+ const dependencies = getProperty(packageJson, "dependencies", {});
374
+ const devDependencies = getProperty(packageJson, "devDependencies", {});
375
+ const peerDependencies = getProperty(packageJson, "peerDependencies", {});
376
+ const nonExistingPackages = [];
377
+ const config = {
378
+ deps: true,
379
+ devDeps: true,
380
+ peerDeps: false,
381
+ ...options
382
+ };
383
+ for (const packageName of packages) {
384
+ if (config.deps && hasProperty(dependencies, packageName) || config.devDeps && hasProperty(devDependencies, packageName) || config.peerDeps && hasProperty(peerDependencies, packageName)) {
385
+ continue;
386
+ }
387
+ nonExistingPackages.push(packageName);
388
+ }
389
+ if (typeof config.confirm?.message === "function") {
390
+ config.confirm.message = config.confirm.message(nonExistingPackages);
391
+ }
392
+ if (config.confirm?.message === undefined) {
393
+ const message = `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?`;
394
+ if (config.confirm === undefined) {
395
+ config.confirm = {
396
+ message
397
+ };
398
+ } else {
399
+ config.confirm.message = message;
400
+ }
401
+ }
402
+ const answer = await confirm(config.confirm);
403
+ if (!answer) {
404
+ return;
405
+ }
406
+ await installPackage(nonExistingPackages, {
407
+ ...config.installPackage,
408
+ cwd: config.cwd ? toPath(config.cwd) : undefined,
409
+ dev: installKey === "devDependencies"
410
+ });
411
+ }, "ensurePackages");
412
+
413
+ export { ensurePackages, findPackageJson, findPackageJsonSync, getPackageJsonProperty, hasPackageJsonAnyDependency, hasPackageJsonProperty, parsePackageJson, writePackageJson, writePackageJsonSync };
@@ -1,13 +1,180 @@
1
- "use strict";var w=Object.defineProperty;var l=(e,n)=>w(e,"name",{value:n,configurable:!0});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("node:child_process"),p=require("node:fs"),o=require("@visulima/fs"),k=require("@visulima/fs/error"),i=require("@visulima/path"),f=require("./package-json.cjs");var v=Object.defineProperty,r=l((e,n)=>v(e,"name",{value:n,configurable:!0}),"r");const d=["yarn.lock","package-lock.json","pnpm-lock.yaml","npm-shrinkwrap.json","bun.lockb"],u=r(e=>{let n;if(d.forEach(t=>{!n&&p.existsSync(i.join(e,t))&&(n=i.join(e,t))}),n)return n;const a=i.join(e,"package.json");if(p.existsSync(a)&&f.parsePackageJson(p.readFileSync(a,"utf8")).packageManager!==void 0)return a},"packageMangerFindUpMatcher"),m=r(e=>{if(!e)throw new k.NotFoundError("Could not find a package manager");if(e.endsWith("package.json")){const n=f.parsePackageJson(e);if(n.packageManager){const a=["npm","yarn","pnpm","bun"].find(t=>n.packageManager.startsWith(t));if(a)return{packageManager:a,path:i.dirname(e)}}}if(e.endsWith("yarn.lock"))return{packageManager:"yarn",path:i.dirname(e)};if(e.endsWith("package-lock.json")||e.endsWith("npm-shrinkwrap.json"))return{packageManager:"npm",path:i.dirname(e)};if(e.endsWith("pnpm-lock.yaml"))return{packageManager:"pnpm",path:i.dirname(e)};if(e.endsWith("bun.lockb"))return{packageManager:"bun",path:i.dirname(e)};throw new k.NotFoundError("Could not find a package manager")},"findPackageManagerOnFile"),S=r(async e=>{const n=await o.findUp(d,{type:"file",...e&&{cwd:e}});if(!n)throw new Error("Could not find lock file");return n},"findLockFile"),j=r(e=>{const n=o.findUpSync(d,{type:"file",...e&&{cwd:e}});if(!n)throw new Error("Could not find lock file");return n},"findLockFileSync"),b=r(async e=>{const n=await o.findUp(u,{...e&&{cwd:e}});return m(n)},"findPackageManager"),F=r(e=>{const n=o.findUpSync(u,{...e&&{cwd:e}});return m(n)},"findPackageManagerSync"),$=r(e=>P.execSync(`${e} --version`).toString("utf8").trim(),"getPackageManagerVersion"),_=r(async()=>{if(!process.env.npm_config_user_agent)return;const e=process.env.npm_config_user_agent.split(" ")[0],n=e.lastIndexOf("/"),a=e.slice(0,Math.max(0,n));return{name:a==="npminstall"?"cnpm":a,version:e.slice(Math.max(0,n+1))}},"identifyInitiatingPackageManager"),E=r((e,n,a)=>{const t=n.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(n.length===0)throw new Error("No missing packages provided, please provide at least one missing package");let g=`
2
- ${a.preMessage??""}
3
- ${e} could not find the following package${t}
1
+ 'use strict';
4
2
 
5
- ${n.join(`
6
- `)}
3
+ Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
7
4
 
8
- To install the missing package${t}, please run the following command:
9
- `;const M=r(s=>s.split("@").includes("@")?s:`${s}@latest`,"atLatest"),h=a.packageManagers.map(s=>{const c=n.map(y=>M(y)).join(" ");switch(s){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+=h.join(`
5
+ const node_child_process = require('node:child_process');
6
+ const node_fs = require('node:fs');
7
+ const fs = require('@visulima/fs');
8
+ const error = require('@visulima/fs/error');
9
+ const path = require('@visulima/path');
10
+ const packageJson = require('./package-json.cjs');
10
11
 
11
- or
12
+ var __defProp = Object.defineProperty;
13
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
+ const lockFileNames = ["yarn.lock", "package-lock.json", "pnpm-lock.yaml", "npm-shrinkwrap.json", "bun.lockb"];
15
+ const packageMangerFindUpMatcher = /* @__PURE__ */ __name((directory) => {
16
+ let lockFile;
17
+ lockFileNames.forEach((lockFileName) => {
18
+ if (!lockFile && node_fs.existsSync(path.join(directory, lockFileName))) {
19
+ lockFile = path.join(directory, lockFileName);
20
+ }
21
+ });
22
+ if (lockFile) {
23
+ return lockFile;
24
+ }
25
+ const packageJsonFilePath = path.join(directory, "package.json");
26
+ if (node_fs.existsSync(packageJsonFilePath)) {
27
+ const packageJson$1 = packageJson.parsePackageJson(node_fs.readFileSync(packageJsonFilePath, "utf8"));
28
+ if (packageJson$1.packageManager !== undefined) {
29
+ return packageJsonFilePath;
30
+ }
31
+ }
32
+ return undefined;
33
+ }, "packageMangerFindUpMatcher");
34
+ const findPackageManagerOnFile = /* @__PURE__ */ __name((foundFile) => {
35
+ if (!foundFile) {
36
+ throw new error.NotFoundError("Could not find a package manager");
37
+ }
38
+ if (foundFile.endsWith("package.json")) {
39
+ const packageJson$1 = packageJson.parsePackageJson(foundFile);
40
+ if (packageJson$1.packageManager) {
41
+ const packageManagerNames = ["npm", "yarn", "pnpm", "bun"];
42
+ const foundPackageManager = packageManagerNames.find((prefix) => packageJson$1.packageManager.startsWith(prefix));
43
+ if (foundPackageManager) {
44
+ return {
45
+ packageManager: foundPackageManager,
46
+ path: path.dirname(foundFile)
47
+ };
48
+ }
49
+ }
50
+ }
51
+ if (foundFile.endsWith("yarn.lock")) {
52
+ return {
53
+ packageManager: "yarn",
54
+ path: path.dirname(foundFile)
55
+ };
56
+ }
57
+ if (foundFile.endsWith("package-lock.json") || foundFile.endsWith("npm-shrinkwrap.json")) {
58
+ return {
59
+ packageManager: "npm",
60
+ path: path.dirname(foundFile)
61
+ };
62
+ }
63
+ if (foundFile.endsWith("pnpm-lock.yaml")) {
64
+ return {
65
+ packageManager: "pnpm",
66
+ path: path.dirname(foundFile)
67
+ };
68
+ }
69
+ if (foundFile.endsWith("bun.lockb")) {
70
+ return {
71
+ packageManager: "bun",
72
+ path: path.dirname(foundFile)
73
+ };
74
+ }
75
+ throw new error.NotFoundError("Could not find a package manager");
76
+ }, "findPackageManagerOnFile");
77
+ const findLockFile = /* @__PURE__ */ __name(async (cwd) => {
78
+ const filePath = await fs.findUp(lockFileNames, {
79
+ type: "file",
80
+ ...cwd && { cwd }
81
+ });
82
+ if (!filePath) {
83
+ throw new Error("Could not find lock file");
84
+ }
85
+ return filePath;
86
+ }, "findLockFile");
87
+ const findLockFileSync = /* @__PURE__ */ __name((cwd) => {
88
+ const filePath = fs.findUpSync(lockFileNames, {
89
+ type: "file",
90
+ ...cwd && { cwd }
91
+ });
92
+ if (!filePath) {
93
+ throw new Error("Could not find lock file");
94
+ }
95
+ return filePath;
96
+ }, "findLockFileSync");
97
+ const findPackageManager = /* @__PURE__ */ __name(async (cwd) => {
98
+ const foundFile = await fs.findUp(packageMangerFindUpMatcher, {
99
+ ...cwd && { cwd }
100
+ });
101
+ return findPackageManagerOnFile(foundFile);
102
+ }, "findPackageManager");
103
+ const findPackageManagerSync = /* @__PURE__ */ __name((cwd) => {
104
+ const foundFile = fs.findUpSync(packageMangerFindUpMatcher, {
105
+ ...cwd && { cwd }
106
+ });
107
+ return findPackageManagerOnFile(foundFile);
108
+ }, "findPackageManagerSync");
109
+ const getPackageManagerVersion = /* @__PURE__ */ __name((name) => node_child_process.execSync(`${name} --version`).toString("utf8").trim(), "getPackageManagerVersion");
110
+ const identifyInitiatingPackageManager = /* @__PURE__ */ __name(async () => {
111
+ if (!process.env.npm_config_user_agent) {
112
+ return undefined;
113
+ }
114
+ const pmSpec = process.env.npm_config_user_agent.split(" ")[0];
115
+ const separatorPos = pmSpec.lastIndexOf("/");
116
+ const name = pmSpec.slice(0, Math.max(0, separatorPos));
117
+ return {
118
+ name: name === "npminstall" ? "cnpm" : name,
119
+ version: pmSpec.slice(Math.max(0, separatorPos + 1))
120
+ };
121
+ }, "identifyInitiatingPackageManager");
122
+ const generateMissingPackagesInstallMessage = /* @__PURE__ */ __name((packageName, missingPackages, options) => {
123
+ const s = missingPackages.length === 1 ? "" : "s";
124
+ if (options.packageManagers === undefined) {
125
+ options.packageManagers = ["npm", "pnpm", "yarn"];
126
+ }
127
+ if (options.packageManagers.length === 0) {
128
+ throw new Error("No package managers provided, please provide at least one package manager");
129
+ }
130
+ if (missingPackages.length === 0) {
131
+ throw new Error("No missing packages provided, please provide at least one missing package");
132
+ }
133
+ let message = `
134
+ ${options.preMessage ?? ""}
135
+ ${packageName} could not find the following package${s}
12
136
 
13
- `),a.postMessage&&(g+=a.postMessage),g},"generateMissingPackagesInstallMessage");exports.findLockFile=S;exports.findLockFileSync=j;exports.findPackageManager=b;exports.findPackageManagerSync=F;exports.generateMissingPackagesInstallMessage=E;exports.getPackageManagerVersion=$;exports.identifyInitiatingPackageManager=_;
137
+ ${missingPackages.join("\n ")}
138
+
139
+ To install the missing package${s}, please run the following command:
140
+ `;
141
+ const atLatest = /* @__PURE__ */ __name((name) => {
142
+ if (!name.split("@").includes("@")) {
143
+ return `${name}@latest`;
144
+ }
145
+ return name;
146
+ }, "atLatest");
147
+ const packageManagerCommands = options.packageManagers.map((packageManager) => {
148
+ const missingPackagesString = missingPackages.map((element) => atLatest(element)).join(" ");
149
+ switch (packageManager) {
150
+ case "bun": {
151
+ return ` bun add ${missingPackagesString} -D`;
152
+ }
153
+ case "npm": {
154
+ return ` npm install ${missingPackagesString} --save-dev`;
155
+ }
156
+ case "pnpm": {
157
+ return ` pnpm add ${missingPackagesString} -D`;
158
+ }
159
+ case "yarn": {
160
+ return ` yarn add ${missingPackagesString} --dev`;
161
+ }
162
+ default: {
163
+ throw new Error("Unknown package manager");
164
+ }
165
+ }
166
+ });
167
+ message += packageManagerCommands.join("\n\nor\n\n");
168
+ if (options.postMessage) {
169
+ message += options.postMessage;
170
+ }
171
+ return message;
172
+ }, "generateMissingPackagesInstallMessage");
173
+
174
+ exports.findLockFile = findLockFile;
175
+ exports.findLockFileSync = findLockFileSync;
176
+ exports.findPackageManager = findPackageManager;
177
+ exports.findPackageManagerSync = findPackageManagerSync;
178
+ exports.generateMissingPackagesInstallMessage = generateMissingPackagesInstallMessage;
179
+ exports.getPackageManagerVersion = getPackageManagerVersion;
180
+ exports.identifyInitiatingPackageManager = identifyInitiatingPackageManager;