@visulima/package 3.5.9 → 3.5.11

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,1265 +1,3 @@
1
- import { existsSync } from 'node:fs';
2
- import process$1 from 'node:process';
3
- import fs from 'node:fs/promises';
4
- import path, { resolve as resolve$1 } from 'node:path';
5
- import { createRequire } from 'node:module';
6
- import { spawn } from 'child_process';
7
- import { delimiter, resolve, dirname, normalize } from 'path';
8
- import { cwd } from 'process';
9
- import { PassThrough } from 'stream';
10
- import me from 'readline';
11
- import confirm from '@inquirer/confirm';
12
- import { findUp, readJson, findUpSync, readJsonSync, writeJson, writeJsonSync } from '@visulima/fs';
13
- import { NotFoundError } from '@visulima/fs/error';
14
- import { toPath, parseJson } from '@visulima/fs/utils';
15
- import { join } from '@visulima/path';
16
- import normalizeData from 'normalize-package-data';
17
-
18
- const AGENTS = [
19
- "npm",
20
- "yarn",
21
- "yarn@berry",
22
- "pnpm",
23
- "pnpm@6",
24
- "bun",
25
- "deno"
26
- ];
27
- const LOCKS = {
28
- "bun.lock": "bun",
29
- "bun.lockb": "bun",
30
- "deno.lock": "deno",
31
- "pnpm-lock.yaml": "pnpm",
32
- "pnpm-workspace.yaml": "pnpm",
33
- "yarn.lock": "yarn",
34
- "package-lock.json": "npm",
35
- "npm-shrinkwrap.json": "npm"
36
- };
37
- const INSTALL_METADATA = {
38
- "node_modules/.deno/": "deno",
39
- "node_modules/.pnpm/": "pnpm",
40
- "node_modules/.yarn-state.yml": "yarn",
41
- // yarn v2+ (node-modules)
42
- "node_modules/.yarn_integrity": "yarn",
43
- // yarn v1
44
- "node_modules/.package-lock.json": "npm",
45
- ".pnp.cjs": "yarn",
46
- // yarn v3+ (pnp)
47
- ".pnp.js": "yarn",
48
- // yarn v2 (pnp)
49
- "bun.lock": "bun",
50
- "bun.lockb": "bun"
51
- };
52
-
53
- var __defProp$4 = Object.defineProperty;
54
- var __name$4 = (target, value) => __defProp$4(target, "name", { value, configurable: true });
55
- async function pathExists(path2, type) {
56
- try {
57
- const stat = await fs.stat(path2);
58
- return type === "file" ? stat.isFile() : stat.isDirectory();
59
- } catch {
60
- return false;
61
- }
62
- }
63
- __name$4(pathExists, "pathExists");
64
- function getUserAgent() {
65
- const userAgent = process$1.env.npm_config_user_agent;
66
- if (!userAgent) {
67
- return null;
68
- }
69
- const name = userAgent.split("/")[0];
70
- return AGENTS.includes(name) ? name : null;
71
- }
72
- __name$4(getUserAgent, "getUserAgent");
73
- function* lookup(cwd = process$1.cwd()) {
74
- let directory = path.resolve(cwd);
75
- const { root } = path.parse(directory);
76
- while (directory && directory !== root) {
77
- yield directory;
78
- directory = path.dirname(directory);
79
- }
80
- }
81
- __name$4(lookup, "lookup");
82
- async function parsePackageJson$1(filepath, onUnknown) {
83
- return !filepath || !pathExists(filepath, "file") ? null : await handlePackageManager(filepath, onUnknown);
84
- }
85
- __name$4(parsePackageJson$1, "parsePackageJson");
86
- async function detect(options = {}) {
87
- const {
88
- cwd,
89
- strategies = ["lockfile", "packageManager-field", "devEngines-field"],
90
- onUnknown
91
- } = options;
92
- let stopDir;
93
- if (typeof options.stopDir === "string") {
94
- const resolved = path.resolve(options.stopDir);
95
- stopDir = /* @__PURE__ */ __name$4((dir) => dir === resolved, "stopDir");
96
- } else {
97
- stopDir = options.stopDir;
98
- }
99
- for (const directory of lookup(cwd)) {
100
- for (const strategy of strategies) {
101
- switch (strategy) {
102
- case "lockfile": {
103
- for (const lock of Object.keys(LOCKS)) {
104
- if (await pathExists(path.join(directory, lock), "file")) {
105
- const name = LOCKS[lock];
106
- const result = await parsePackageJson$1(path.join(directory, "package.json"), onUnknown);
107
- if (result)
108
- return result;
109
- else
110
- return { name, agent: name };
111
- }
112
- }
113
- break;
114
- }
115
- case "packageManager-field":
116
- case "devEngines-field": {
117
- const result = await parsePackageJson$1(path.join(directory, "package.json"), onUnknown);
118
- if (result)
119
- return result;
120
- break;
121
- }
122
- case "install-metadata": {
123
- for (const metadata of Object.keys(INSTALL_METADATA)) {
124
- const fileOrDir = metadata.endsWith("/") ? "dir" : "file";
125
- if (await pathExists(path.join(directory, metadata), fileOrDir)) {
126
- const name = INSTALL_METADATA[metadata];
127
- const agent = name === "yarn" ? isMetadataYarnClassic(metadata) ? "yarn" : "yarn@berry" : name;
128
- return { name, agent };
129
- }
130
- }
131
- break;
132
- }
133
- }
134
- }
135
- if (stopDir?.(directory))
136
- break;
137
- }
138
- return null;
139
- }
140
- __name$4(detect, "detect");
141
- function getNameAndVer(pkg) {
142
- const handelVer = /* @__PURE__ */ __name$4((version) => version?.match(/\d+(\.\d+){0,2}/)?.[0] ?? version, "handelVer");
143
- if (typeof pkg.packageManager === "string") {
144
- const [name, ver] = pkg.packageManager.replace(/^\^/, "").split("@");
145
- return { name, ver: handelVer(ver) };
146
- }
147
- if (typeof pkg.devEngines?.packageManager?.name === "string") {
148
- return {
149
- name: pkg.devEngines.packageManager.name,
150
- ver: handelVer(pkg.devEngines.packageManager.version)
151
- };
152
- }
153
- return void 0;
154
- }
155
- __name$4(getNameAndVer, "getNameAndVer");
156
- async function handlePackageManager(filepath, onUnknown) {
157
- try {
158
- const pkg = JSON.parse(await fs.readFile(filepath, "utf8"));
159
- let agent;
160
- const nameAndVer = getNameAndVer(pkg);
161
- if (nameAndVer) {
162
- const name = nameAndVer.name;
163
- const ver = nameAndVer.ver;
164
- let version = ver;
165
- if (name === "yarn" && ver && Number.parseInt(ver) > 1) {
166
- agent = "yarn@berry";
167
- version = "berry";
168
- return { name, agent, version };
169
- } else if (name === "pnpm" && ver && Number.parseInt(ver) < 7) {
170
- agent = "pnpm@6";
171
- return { name, agent, version };
172
- } else if (AGENTS.includes(name)) {
173
- agent = name;
174
- return { name, agent, version };
175
- } else {
176
- return onUnknown?.(pkg.packageManager) ?? null;
177
- }
178
- }
179
- } catch {
180
- }
181
- return null;
182
- }
183
- __name$4(handlePackageManager, "handlePackageManager");
184
- function isMetadataYarnClassic(metadataPath) {
185
- return metadataPath.endsWith(".yarn_integrity");
186
- }
187
- __name$4(isMetadataYarnClassic, "isMetadataYarnClassic");
188
-
189
- var __defProp$3 = Object.defineProperty;
190
- var __name$3 = (target, value) => __defProp$3(target, "name", { value, configurable: true });
191
- const require2 = createRequire(import.meta.url);
192
- var St = Object.create;
193
- var $ = Object.defineProperty;
194
- var kt = Object.getOwnPropertyDescriptor;
195
- var Tt = Object.getOwnPropertyNames;
196
- var At = Object.getPrototypeOf;
197
- var Rt = Object.prototype.hasOwnProperty;
198
- var h = /* @__PURE__ */ ((t) => typeof require2 < "u" ? require2 : typeof Proxy < "u" ? new Proxy(t, {
199
- get: /* @__PURE__ */ __name$3((e, n) => (typeof require2 < "u" ? require2 : e)[n], "get")
200
- }) : t)(function(t) {
201
- if (typeof require2 < "u") return require2.apply(this, arguments);
202
- throw Error('Dynamic require of "' + t + '" is not supported');
203
- });
204
- var l = /* @__PURE__ */ __name$3((t, e) => () => (e || t((e = { exports: {} }).exports, e), e.exports), "l");
205
- var $t = /* @__PURE__ */ __name$3((t, e, n, r) => {
206
- if (e && typeof e == "object" || typeof e == "function")
207
- for (let s of Tt(e))
208
- !Rt.call(t, s) && s !== n && $(t, s, { get: /* @__PURE__ */ __name$3(() => e[s], "get"), enumerable: !(r = kt(e, s)) || r.enumerable });
209
- return t;
210
- }, "$t");
211
- var Nt = /* @__PURE__ */ __name$3((t, e, n) => (n = t != null ? St(At(t)) : {}, $t(
212
- // If the importer is in node compatibility mode or this is not an ESM
213
- // file that has been converted to a CommonJS file using a Babel-
214
- // compatible transform (i.e. "__esModule" has not been set), then set
215
- // "default" to the CommonJS "module.exports" for node compatibility.
216
- e || !t || !t.__esModule ? $(n, "default", { value: t, enumerable: true }) : n,
217
- t
218
- )), "Nt");
219
- var W = l((Se, H) => {
220
- H.exports = z;
221
- z.sync = Wt;
222
- var j = h("fs");
223
- function Ht(t, e) {
224
- var n = e.pathExt !== void 0 ? e.pathExt : process.env.PATHEXT;
225
- if (!n || (n = n.split(";"), n.indexOf("") !== -1))
226
- return true;
227
- for (var r = 0; r < n.length; r++) {
228
- var s = n[r].toLowerCase();
229
- if (s && t.substr(-s.length).toLowerCase() === s)
230
- return true;
231
- }
232
- return false;
233
- }
234
- __name$3(Ht, "Ht");
235
- function F(t, e, n) {
236
- return !t.isSymbolicLink() && !t.isFile() ? false : Ht(e, n);
237
- }
238
- __name$3(F, "F");
239
- function z(t, e, n) {
240
- j.stat(t, function(r, s) {
241
- n(r, r ? false : F(s, t, e));
242
- });
243
- }
244
- __name$3(z, "z");
245
- function Wt(t, e) {
246
- return F(j.statSync(t), t, e);
247
- }
248
- __name$3(Wt, "Wt");
249
- });
250
- var X = l((ke, B) => {
251
- B.exports = K;
252
- K.sync = Dt;
253
- var D = h("fs");
254
- function K(t, e, n) {
255
- D.stat(t, function(r, s) {
256
- n(r, r ? false : M(s, e));
257
- });
258
- }
259
- __name$3(K, "K");
260
- function Dt(t, e) {
261
- return M(D.statSync(t), e);
262
- }
263
- __name$3(Dt, "Dt");
264
- function M(t, e) {
265
- return t.isFile() && Kt(t, e);
266
- }
267
- __name$3(M, "M");
268
- function Kt(t, e) {
269
- var n = t.mode, r = t.uid, s = t.gid, o = e.uid !== void 0 ? e.uid : process.getuid && process.getuid(), i = e.gid !== void 0 ? e.gid : process.getgid && process.getgid(), a = parseInt("100", 8), c = parseInt("010", 8), u = parseInt("001", 8), f = a | c, p = n & u || n & c && s === i || n & a && r === o || n & f && o === 0;
270
- return p;
271
- }
272
- __name$3(Kt, "Kt");
273
- });
274
- var U = l((Ae, G) => {
275
- h("fs"); var v;
276
- process.platform === "win32" || global.TESTING_WINDOWS ? v = W() : v = X();
277
- G.exports = y;
278
- y.sync = Mt;
279
- function y(t, e, n) {
280
- if (typeof e == "function" && (n = e, e = {}), !n) {
281
- if (typeof Promise != "function")
282
- throw new TypeError("callback not provided");
283
- return new Promise(function(r, s) {
284
- y(t, e || {}, function(o, i) {
285
- o ? s(o) : r(i);
286
- });
287
- });
288
- }
289
- v(t, e || {}, function(r, s) {
290
- r && (r.code === "EACCES" || e && e.ignoreErrors) && (r = null, s = false), n(r, s);
291
- });
292
- }
293
- __name$3(y, "y");
294
- function Mt(t, e) {
295
- try {
296
- return v.sync(t, e || {});
297
- } catch (n) {
298
- if (e && e.ignoreErrors || n.code === "EACCES")
299
- return false;
300
- throw n;
301
- }
302
- }
303
- __name$3(Mt, "Mt");
304
- });
305
- var et = l((Re, tt) => {
306
- var g = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys", Y = h("path"), Bt = g ? ";" : ":", V = U(), J = /* @__PURE__ */ __name$3((t) => Object.assign(new Error(`not found: ${t}`), { code: "ENOENT" }), "J"), Q = /* @__PURE__ */ __name$3((t, e) => {
307
- let n = e.colon || Bt, r = t.match(/\//) || g && t.match(/\\/) ? [""] : [
308
- // windows always checks the cwd first
309
- ...g ? [process.cwd()] : [],
310
- ...(e.path || process.env.PATH || /* istanbul ignore next: very unusual */
311
- "").split(n)
312
- ], s = g ? e.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "", o = g ? s.split(n) : [""];
313
- return g && t.indexOf(".") !== -1 && o[0] !== "" && o.unshift(""), {
314
- pathEnv: r,
315
- pathExt: o,
316
- pathExtExe: s
317
- };
318
- }, "Q"), Z = /* @__PURE__ */ __name$3((t, e, n) => {
319
- typeof e == "function" && (n = e, e = {}), e || (e = {});
320
- let { pathEnv: r, pathExt: s, pathExtExe: o } = Q(t, e), i = [], a = /* @__PURE__ */ __name$3((u) => new Promise((f, p) => {
321
- if (u === r.length)
322
- return e.all && i.length ? f(i) : p(J(t));
323
- let d = r[u], w = /^".*"$/.test(d) ? d.slice(1, -1) : d, m = Y.join(w, t), b = !w && /^\.[\\\/]/.test(t) ? t.slice(0, 2) + m : m;
324
- f(c(b, u, 0));
325
- }), "a"), c = /* @__PURE__ */ __name$3((u, f, p) => new Promise((d, w) => {
326
- if (p === s.length)
327
- return d(a(f + 1));
328
- let m = s[p];
329
- V(u + m, { pathExt: o }, (b, Ot) => {
330
- if (!b && Ot)
331
- if (e.all)
332
- i.push(u + m);
333
- else
334
- return d(u + m);
335
- return d(c(u, f, p + 1));
336
- });
337
- }), "c");
338
- return n ? a(0).then((u) => n(null, u), n) : a(0);
339
- }, "Z"), Xt = /* @__PURE__ */ __name$3((t, e) => {
340
- e = e || {};
341
- let { pathEnv: n, pathExt: r, pathExtExe: s } = Q(t, e), o = [];
342
- for (let i = 0; i < n.length; i++) {
343
- let a = n[i], c = /^".*"$/.test(a) ? a.slice(1, -1) : a, u = Y.join(c, t), f = !c && /^\.[\\\/]/.test(t) ? t.slice(0, 2) + u : u;
344
- for (let p = 0; p < r.length; p++) {
345
- let d = f + r[p];
346
- try {
347
- if (V.sync(d, { pathExt: s }))
348
- if (e.all)
349
- o.push(d);
350
- else
351
- return d;
352
- } catch {
353
- }
354
- }
355
- }
356
- if (e.all && o.length)
357
- return o;
358
- if (e.nothrow)
359
- return null;
360
- throw J(t);
361
- }, "Xt");
362
- tt.exports = Z;
363
- Z.sync = Xt;
364
- });
365
- var rt = l(($e, _) => {
366
- var nt = /* @__PURE__ */ __name$3((t = {}) => {
367
- let e = t.env || process.env;
368
- return (t.platform || process.platform) !== "win32" ? "PATH" : Object.keys(e).reverse().find((r) => r.toUpperCase() === "PATH") || "Path";
369
- }, "nt");
370
- _.exports = nt;
371
- _.exports.default = nt;
372
- });
373
- var ct = l((Ne, it) => {
374
- var st = h("path"), Gt = et(), Ut = rt();
375
- function ot(t, e) {
376
- let n = t.options.env || process.env, r = process.cwd(), s = t.options.cwd != null, o = s && process.chdir !== void 0 && !process.chdir.disabled;
377
- if (o)
378
- try {
379
- process.chdir(t.options.cwd);
380
- } catch {
381
- }
382
- let i;
383
- try {
384
- i = Gt.sync(t.command, {
385
- path: n[Ut({ env: n })],
386
- pathExt: e ? st.delimiter : void 0
387
- });
388
- } catch {
389
- } finally {
390
- o && process.chdir(r);
391
- }
392
- return i && (i = st.resolve(s ? t.options.cwd : "", i)), i;
393
- }
394
- __name$3(ot, "ot");
395
- function Yt(t) {
396
- return ot(t) || ot(t, true);
397
- }
398
- __name$3(Yt, "Yt");
399
- it.exports = Yt;
400
- });
401
- var ut = l((qe, P) => {
402
- var C = /([()\][%!^"`<>&|;, *?])/g;
403
- function Vt(t) {
404
- return t = t.replace(C, "^$1"), t;
405
- }
406
- __name$3(Vt, "Vt");
407
- function Jt(t, e) {
408
- return t = `${t}`, t = t.replace(/(\\*)"/g, '$1$1\\"'), t = t.replace(/(\\*)$/, "$1$1"), t = `"${t}"`, t = t.replace(C, "^$1"), e && (t = t.replace(C, "^$1")), t;
409
- }
410
- __name$3(Jt, "Jt");
411
- P.exports.command = Vt;
412
- P.exports.argument = Jt;
413
- });
414
- var lt = l((Ie, at) => {
415
- at.exports = /^#!(.*)/;
416
- });
417
- var dt = l((Le, pt) => {
418
- var Qt = lt();
419
- pt.exports = (t = "") => {
420
- let e = t.match(Qt);
421
- if (!e)
422
- return null;
423
- let [n, r] = e[0].replace(/#! ?/, "").split(" "), s = n.split("/").pop();
424
- return s === "env" ? r : r ? `${s} ${r}` : s;
425
- };
426
- });
427
- var ht = l((je, ft) => {
428
- var O = h("fs"), Zt = dt();
429
- function te(t) {
430
- let n = Buffer.alloc(150), r;
431
- try {
432
- r = O.openSync(t, "r"), O.readSync(r, n, 0, 150, 0), O.closeSync(r);
433
- } catch {
434
- }
435
- return Zt(n.toString());
436
- }
437
- __name$3(te, "te");
438
- ft.exports = te;
439
- });
440
- var wt = l((Fe, Et) => {
441
- var ee = h("path"), mt = ct(), gt = ut(), ne = ht(), re = process.platform === "win32", se = /\.(?:com|exe)$/i, oe = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
442
- function ie(t) {
443
- t.file = mt(t);
444
- let e = t.file && ne(t.file);
445
- return e ? (t.args.unshift(t.file), t.command = e, mt(t)) : t.file;
446
- }
447
- __name$3(ie, "ie");
448
- function ce(t) {
449
- if (!re)
450
- return t;
451
- let e = ie(t), n = !se.test(e);
452
- if (t.options.forceShell || n) {
453
- let r = oe.test(e);
454
- t.command = ee.normalize(t.command), t.command = gt.command(t.command), t.args = t.args.map((o) => gt.argument(o, r));
455
- let s = [t.command].concat(t.args).join(" ");
456
- t.args = ["/d", "/s", "/c", `"${s}"`], t.command = process.env.comspec || "cmd.exe", t.options.windowsVerbatimArguments = true;
457
- }
458
- return t;
459
- }
460
- __name$3(ce, "ce");
461
- function ue(t, e, n) {
462
- e && !Array.isArray(e) && (n = e, e = null), e = e ? e.slice(0) : [], n = Object.assign({}, n);
463
- let r = {
464
- command: t,
465
- args: e,
466
- options: n,
467
- file: void 0,
468
- original: {
469
- command: t,
470
- args: e
471
- }
472
- };
473
- return n.shell ? r : ce(r);
474
- }
475
- __name$3(ue, "ue");
476
- Et.exports = ue;
477
- });
478
- var bt = l((ze, vt) => {
479
- var S = process.platform === "win32";
480
- function k(t, e) {
481
- return Object.assign(new Error(`${e} ${t.command} ENOENT`), {
482
- code: "ENOENT",
483
- errno: "ENOENT",
484
- syscall: `${e} ${t.command}`,
485
- path: t.command,
486
- spawnargs: t.args
487
- });
488
- }
489
- __name$3(k, "k");
490
- function ae(t, e) {
491
- if (!S)
492
- return;
493
- let n = t.emit;
494
- t.emit = function(r, s) {
495
- if (r === "exit") {
496
- let o = xt(s, e);
497
- if (o)
498
- return n.call(t, "error", o);
499
- }
500
- return n.apply(t, arguments);
501
- };
502
- }
503
- __name$3(ae, "ae");
504
- function xt(t, e) {
505
- return S && t === 1 && !e.file ? k(e.original, "spawn") : null;
506
- }
507
- __name$3(xt, "xt");
508
- function le(t, e) {
509
- return S && t === 1 && !e.file ? k(e.original, "spawnSync") : null;
510
- }
511
- __name$3(le, "le");
512
- vt.exports = {
513
- hookChildProcess: ae,
514
- verifyENOENT: xt,
515
- verifyENOENTSync: le,
516
- notFoundError: k
517
- };
518
- });
519
- var Ct = l((He, E) => {
520
- var yt = h("child_process"), T = wt(), A = bt();
521
- function _t(t, e, n) {
522
- let r = T(t, e, n), s = yt.spawn(r.command, r.args, r.options);
523
- return A.hookChildProcess(s, r), s;
524
- }
525
- __name$3(_t, "_t");
526
- function pe(t, e, n) {
527
- let r = T(t, e, n), s = yt.spawnSync(r.command, r.args, r.options);
528
- return s.error = s.error || A.verifyENOENTSync(s.status, r), s;
529
- }
530
- __name$3(pe, "pe");
531
- E.exports = _t;
532
- E.exports.spawn = _t;
533
- E.exports.sync = pe;
534
- E.exports._parse = T;
535
- E.exports._enoent = A;
536
- });
537
- var Lt = /^path$/i;
538
- var q = { key: "PATH", value: "" };
539
- function jt(t) {
540
- for (let e in t) {
541
- if (!Object.prototype.hasOwnProperty.call(t, e) || !Lt.test(e))
542
- continue;
543
- let n = t[e];
544
- return n ? { key: e, value: n } : q;
545
- }
546
- return q;
547
- }
548
- __name$3(jt, "jt");
549
- function Ft(t, e) {
550
- let n = e.value.split(delimiter), r = t, s;
551
- do
552
- n.push(resolve(r, "node_modules", ".bin")), s = r, r = dirname(r);
553
- while (r !== s);
554
- return { key: e.key, value: n.join(delimiter) };
555
- }
556
- __name$3(Ft, "Ft");
557
- function I(t, e) {
558
- let n = {
559
- ...process.env,
560
- ...e
561
- }, r = Ft(t, jt(n));
562
- return n[r.key] = r.value, n;
563
- }
564
- __name$3(I, "I");
565
- var L = /* @__PURE__ */ __name$3((t) => {
566
- let e = t.length, n = new PassThrough(), r = /* @__PURE__ */ __name$3(() => {
567
- --e === 0 && n.emit("end");
568
- }, "r");
569
- for (let s of t)
570
- s.pipe(n, { end: false }), s.on("end", r);
571
- return n;
572
- }, "L");
573
- var Pt = Nt(Ct(), 1);
574
- var x = class extends Error {
575
- static {
576
- __name$3(this, "x");
577
- }
578
- result;
579
- output;
580
- get exitCode() {
581
- if (this.result.exitCode !== null)
582
- return this.result.exitCode;
583
- }
584
- constructor(e, n) {
585
- super(`Process exited with non-zero status (${e.exitCode})`), this.result = e, this.output = n;
586
- }
587
- };
588
- var ge = {
589
- timeout: void 0,
590
- persist: false
591
- };
592
- var Ee = {
593
- windowsHide: true
594
- };
595
- function we(t, e) {
596
- return {
597
- command: normalize(t),
598
- args: e ?? []
599
- };
600
- }
601
- __name$3(we, "we");
602
- function xe(t) {
603
- let e = new AbortController();
604
- for (let n of t) {
605
- if (n.aborted)
606
- return e.abort(), n;
607
- let r = /* @__PURE__ */ __name$3(() => {
608
- e.abort(n.reason);
609
- }, "r");
610
- n.addEventListener("abort", r, {
611
- signal: e.signal
612
- });
613
- }
614
- return e.signal;
615
- }
616
- __name$3(xe, "xe");
617
- var R = class {
618
- static {
619
- __name$3(this, "R");
620
- }
621
- _process;
622
- _aborted = false;
623
- _options;
624
- _command;
625
- _args;
626
- _resolveClose;
627
- _processClosed;
628
- _thrownError;
629
- get process() {
630
- return this._process;
631
- }
632
- get pid() {
633
- return this._process?.pid;
634
- }
635
- get exitCode() {
636
- if (this._process && this._process.exitCode !== null)
637
- return this._process.exitCode;
638
- }
639
- constructor(e, n, r) {
640
- this._options = {
641
- ...ge,
642
- ...r
643
- }, this._command = e, this._args = n ?? [], this._processClosed = new Promise((s) => {
644
- this._resolveClose = s;
645
- });
646
- }
647
- kill(e) {
648
- return this._process?.kill(e) === true;
649
- }
650
- get aborted() {
651
- return this._aborted;
652
- }
653
- get killed() {
654
- return this._process?.killed === true;
655
- }
656
- pipe(e, n, r) {
657
- return be(e, n, {
658
- ...r,
659
- stdin: this
660
- });
661
- }
662
- async *[Symbol.asyncIterator]() {
663
- let e = this._process;
664
- if (!e)
665
- return;
666
- let n = [];
667
- this._streamErr && n.push(this._streamErr), this._streamOut && n.push(this._streamOut);
668
- let r = L(n), s = me.createInterface({
669
- input: r
670
- });
671
- for await (let o of s)
672
- yield o.toString();
673
- if (await this._processClosed, e.removeAllListeners(), this._thrownError)
674
- throw this._thrownError;
675
- if (this._options?.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0)
676
- throw new x(this);
677
- }
678
- async _waitForOutput() {
679
- let e = this._process;
680
- if (!e)
681
- throw new Error("No process was started");
682
- let n = "", r = "";
683
- if (this._streamOut)
684
- for await (let o of this._streamOut)
685
- r += o.toString();
686
- if (this._streamErr)
687
- for await (let o of this._streamErr)
688
- n += o.toString();
689
- if (await this._processClosed, this._options?.stdin && await this._options.stdin, e.removeAllListeners(), this._thrownError)
690
- throw this._thrownError;
691
- let s = {
692
- stderr: n,
693
- stdout: r,
694
- exitCode: this.exitCode
695
- };
696
- if (this._options.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0)
697
- throw new x(this, s);
698
- return s;
699
- }
700
- then(e, n) {
701
- return this._waitForOutput().then(e, n);
702
- }
703
- _streamOut;
704
- _streamErr;
705
- spawn() {
706
- let e = cwd(), n = this._options, r = {
707
- ...Ee,
708
- ...n.nodeOptions
709
- }, s = [];
710
- this._resetState(), n.timeout !== void 0 && s.push(AbortSignal.timeout(n.timeout)), n.signal !== void 0 && s.push(n.signal), n.persist === true && (r.detached = true), s.length > 0 && (r.signal = xe(s)), r.env = I(e, r.env);
711
- let { command: o, args: i } = we(this._command, this._args), a = (0, Pt._parse)(o, i, r), c = spawn(
712
- a.command,
713
- a.args,
714
- a.options
715
- );
716
- if (c.stderr && (this._streamErr = c.stderr), c.stdout && (this._streamOut = c.stdout), this._process = c, c.once("error", this._onError), c.once("close", this._onClose), n.stdin !== void 0 && c.stdin && n.stdin.process) {
717
- let { stdout: u } = n.stdin.process;
718
- u && u.pipe(c.stdin);
719
- }
720
- }
721
- _resetState() {
722
- this._aborted = false, this._processClosed = new Promise((e) => {
723
- this._resolveClose = e;
724
- }), this._thrownError = void 0;
725
- }
726
- _onError = /* @__PURE__ */ __name$3((e) => {
727
- if (e.name === "AbortError" && (!(e.cause instanceof Error) || e.cause.name !== "TimeoutError")) {
728
- this._aborted = true;
729
- return;
730
- }
731
- this._thrownError = e;
732
- }, "_onError");
733
- _onClose = /* @__PURE__ */ __name$3(() => {
734
- this._resolveClose && this._resolveClose();
735
- }, "_onClose");
736
- };
737
- var ve = /* @__PURE__ */ __name$3((t, e, n) => {
738
- let r = new R(t, e, n);
739
- return r.spawn(), r;
740
- }, "ve");
741
- var be = ve;
742
-
743
- var __defProp$2 = Object.defineProperty;
744
- var __name$2 = (target, value) => __defProp$2(target, "name", { value, configurable: true });
745
- async function detectPackageManager(cwd = process$1.cwd()) {
746
- const result = await detect({
747
- cwd,
748
- onUnknown(packageManager) {
749
- console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
750
- return void 0;
751
- }
752
- });
753
- return result?.agent || null;
754
- }
755
- __name$2(detectPackageManager, "detectPackageManager");
756
- async function installPackage(names, options = {}) {
757
- const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
758
- const [agent] = detectedAgent.split("@");
759
- if (!Array.isArray(names))
760
- names = [names];
761
- const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
762
- if (options.preferOffline) {
763
- if (detectedAgent === "yarn@berry")
764
- args.unshift("--cached");
765
- else
766
- args.unshift("--prefer-offline");
767
- }
768
- if (agent === "pnpm") {
769
- args.unshift(
770
- /**
771
- * Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
772
- * @see https://pnpm.io/cli/install#--prod--p
773
- */
774
- "--prod=false"
775
- );
776
- if (existsSync(resolve$1(options.cwd ?? process$1.cwd(), "pnpm-workspace.yaml"))) {
777
- args.unshift("-w");
778
- }
779
- }
780
- return ve(
781
- agent,
782
- [
783
- agent === "yarn" ? "add" : "install",
784
- options.dev ? "-D" : "",
785
- ...args,
786
- ...names
787
- ].filter(Boolean),
788
- {
789
- nodeOptions: {
790
- stdio: options.silent ? "ignore" : "inherit",
791
- cwd: options.cwd
792
- },
793
- throwOnError: true
794
- }
795
- );
796
- }
797
- __name$2(installPackage, "installPackage");
798
- async function uninstallPackage(names, options = {}) {
799
- const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
800
- const [agent] = detectedAgent.split("@");
801
- if (!Array.isArray(names))
802
- names = [names];
803
- const args = options.additionalArgs || [];
804
- if (agent === "pnpm" && existsSync(resolve$1(options.cwd ?? process$1.cwd(), "pnpm-workspace.yaml")))
805
- args.unshift("-w");
806
- return ve(
807
- agent,
808
- [
809
- agent === "yarn" ? "remove" : "uninstall",
810
- options.dev ? "-D" : "",
811
- ...args,
812
- ...names
813
- ].filter(Boolean),
814
- {
815
- nodeOptions: {
816
- stdio: options.silent ? "ignore" : "inherit",
817
- cwd: options.cwd
818
- },
819
- throwOnError: true
820
- }
821
- );
822
- }
823
- __name$2(uninstallPackage, "uninstallPackage");
824
-
825
- var __defProp$1 = Object.defineProperty;
826
- var __name$1 = (target, value) => __defProp$1(target, "name", { value, configurable: true });
827
- const isObject = /* @__PURE__ */ __name$1((value) => {
828
- const type = typeof value;
829
- return value !== null && (type === "object" || type === "function");
830
- }, "isObject");
831
- const isEmptyObject = /* @__PURE__ */ __name$1((value) => isObject(value) && Object.keys(value).length === 0, "isEmptyObject");
832
- const disallowedKeys = /* @__PURE__ */ new Set([
833
- "__proto__",
834
- "prototype",
835
- "constructor"
836
- ]);
837
- const digits = new Set("0123456789");
838
- function getPathSegments(path) {
839
- const parts = [];
840
- let currentSegment = "";
841
- let currentPart = "start";
842
- let isIgnoring = false;
843
- for (const character of path) {
844
- switch (character) {
845
- case "\\": {
846
- if (currentPart === "index") {
847
- throw new Error("Invalid character in an index");
848
- }
849
- if (currentPart === "indexEnd") {
850
- throw new Error("Invalid character after an index");
851
- }
852
- if (isIgnoring) {
853
- currentSegment += character;
854
- }
855
- currentPart = "property";
856
- isIgnoring = !isIgnoring;
857
- break;
858
- }
859
- case ".": {
860
- if (currentPart === "index") {
861
- throw new Error("Invalid character in an index");
862
- }
863
- if (currentPart === "indexEnd") {
864
- currentPart = "property";
865
- break;
866
- }
867
- if (isIgnoring) {
868
- isIgnoring = false;
869
- currentSegment += character;
870
- break;
871
- }
872
- if (disallowedKeys.has(currentSegment)) {
873
- return [];
874
- }
875
- parts.push(currentSegment);
876
- currentSegment = "";
877
- currentPart = "property";
878
- break;
879
- }
880
- case "[": {
881
- if (currentPart === "index") {
882
- throw new Error("Invalid character in an index");
883
- }
884
- if (currentPart === "indexEnd") {
885
- currentPart = "index";
886
- break;
887
- }
888
- if (isIgnoring) {
889
- isIgnoring = false;
890
- currentSegment += character;
891
- break;
892
- }
893
- if (currentPart === "property") {
894
- if (disallowedKeys.has(currentSegment)) {
895
- return [];
896
- }
897
- parts.push(currentSegment);
898
- currentSegment = "";
899
- }
900
- currentPart = "index";
901
- break;
902
- }
903
- case "]": {
904
- if (currentPart === "index") {
905
- parts.push(Number.parseInt(currentSegment, 10));
906
- currentSegment = "";
907
- currentPart = "indexEnd";
908
- break;
909
- }
910
- if (currentPart === "indexEnd") {
911
- throw new Error("Invalid character after an index");
912
- }
913
- }
914
- default: {
915
- if (currentPart === "index" && !digits.has(character)) {
916
- throw new Error("Invalid character in an index");
917
- }
918
- if (currentPart === "indexEnd") {
919
- throw new Error("Invalid character after an index");
920
- }
921
- if (currentPart === "start") {
922
- currentPart = "property";
923
- }
924
- if (isIgnoring) {
925
- isIgnoring = false;
926
- currentSegment += "\\";
927
- }
928
- currentSegment += character;
929
- }
930
- }
931
- }
932
- if (isIgnoring) {
933
- currentSegment += "\\";
934
- }
935
- switch (currentPart) {
936
- case "property": {
937
- if (disallowedKeys.has(currentSegment)) {
938
- return [];
939
- }
940
- parts.push(currentSegment);
941
- break;
942
- }
943
- case "index": {
944
- throw new Error("Index was not closed");
945
- }
946
- case "start": {
947
- parts.push("");
948
- break;
949
- }
950
- }
951
- return parts;
952
- }
953
- __name$1(getPathSegments, "getPathSegments");
954
- function isStringIndex(object, key) {
955
- if (typeof key !== "number" && Array.isArray(object)) {
956
- const index = Number.parseInt(key, 10);
957
- return Number.isInteger(index) && object[index] === object[key];
958
- }
959
- return false;
960
- }
961
- __name$1(isStringIndex, "isStringIndex");
962
- function assertNotStringIndex(object, key) {
963
- if (isStringIndex(object, key)) {
964
- throw new Error("Cannot use string index");
965
- }
966
- }
967
- __name$1(assertNotStringIndex, "assertNotStringIndex");
968
- function getProperty(object, path, value) {
969
- if (!isObject(object) || typeof path !== "string") {
970
- return value === void 0 ? object : value;
971
- }
972
- const pathArray = getPathSegments(path);
973
- if (pathArray.length === 0) {
974
- return value;
975
- }
976
- for (let index = 0; index < pathArray.length; index++) {
977
- const key = pathArray[index];
978
- if (isStringIndex(object, key)) {
979
- object = index === pathArray.length - 1 ? void 0 : null;
980
- } else {
981
- object = object[key];
982
- }
983
- if (object === void 0 || object === null) {
984
- if (index !== pathArray.length - 1) {
985
- return value;
986
- }
987
- break;
988
- }
989
- }
990
- return object === void 0 ? value : object;
991
- }
992
- __name$1(getProperty, "getProperty");
993
- function setProperty(object, path, value) {
994
- if (!isObject(object) || typeof path !== "string") {
995
- return object;
996
- }
997
- const root = object;
998
- const pathArray = getPathSegments(path);
999
- for (let index = 0; index < pathArray.length; index++) {
1000
- const key = pathArray[index];
1001
- assertNotStringIndex(object, key);
1002
- if (index === pathArray.length - 1) {
1003
- object[key] = value;
1004
- } else if (!isObject(object[key])) {
1005
- object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
1006
- }
1007
- object = object[key];
1008
- }
1009
- return root;
1010
- }
1011
- __name$1(setProperty, "setProperty");
1012
- function deleteProperty(object, path) {
1013
- if (!isObject(object) || typeof path !== "string") {
1014
- return false;
1015
- }
1016
- const pathArray = getPathSegments(path);
1017
- for (let index = 0; index < pathArray.length; index++) {
1018
- const key = pathArray[index];
1019
- assertNotStringIndex(object, key);
1020
- if (index === pathArray.length - 1) {
1021
- delete object[key];
1022
- return true;
1023
- }
1024
- object = object[key];
1025
- if (!isObject(object)) {
1026
- return false;
1027
- }
1028
- }
1029
- }
1030
- __name$1(deleteProperty, "deleteProperty");
1031
- function hasProperty(object, path) {
1032
- if (!isObject(object) || typeof path !== "string") {
1033
- return false;
1034
- }
1035
- const pathArray = getPathSegments(path);
1036
- if (pathArray.length === 0) {
1037
- return false;
1038
- }
1039
- for (const key of pathArray) {
1040
- if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
1041
- return false;
1042
- }
1043
- object = object[key];
1044
- }
1045
- return true;
1046
- }
1047
- __name$1(hasProperty, "hasProperty");
1048
- function escapePath(path) {
1049
- if (typeof path !== "string") {
1050
- throw new TypeError("Expected a string");
1051
- }
1052
- return path.replaceAll(/[\\.[]/g, "\\$&");
1053
- }
1054
- __name$1(escapePath, "escapePath");
1055
- function entries(value) {
1056
- const result = Object.entries(value);
1057
- if (Array.isArray(value)) {
1058
- return result.map(([key, value2]) => [Number(key), value2]);
1059
- }
1060
- return result;
1061
- }
1062
- __name$1(entries, "entries");
1063
- function stringifyPath(pathSegments) {
1064
- let result = "";
1065
- for (let [index, segment] of entries(pathSegments)) {
1066
- if (typeof segment === "number") {
1067
- result += `[${segment}]`;
1068
- } else {
1069
- segment = escapePath(segment);
1070
- result += index === 0 ? segment : `.${segment}`;
1071
- }
1072
- }
1073
- return result;
1074
- }
1075
- __name$1(stringifyPath, "stringifyPath");
1076
- function* deepKeysIterator(object, currentPath = []) {
1077
- if (!isObject(object) || isEmptyObject(object)) {
1078
- if (currentPath.length > 0) {
1079
- yield stringifyPath(currentPath);
1080
- }
1081
- return;
1082
- }
1083
- for (const [key, value] of entries(object)) {
1084
- yield* deepKeysIterator(value, [...currentPath, key]);
1085
- }
1086
- }
1087
- __name$1(deepKeysIterator, "deepKeysIterator");
1088
- function deepKeys(object) {
1089
- return [...deepKeysIterator(object)];
1090
- }
1091
- __name$1(deepKeys, "deepKeys");
1092
-
1093
- const isNode = typeof process.stdout < "u" && !process.versions.deno && !globalThis.window;
1094
-
1095
- var __defProp = Object.defineProperty;
1096
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
1097
- const PackageJsonFileCache = /* @__PURE__ */ new Map();
1098
- class PackageJsonValidationError extends Error {
1099
- static {
1100
- __name(this, "PackageJsonValidationError");
1101
- }
1102
- constructor(warnings) {
1103
- super(`The following warnings were encountered while normalizing package data:
1104
- - ${warnings.join("\n- ")}`);
1105
- this.name = "PackageJsonValidationError";
1106
- }
1107
- }
1108
- const normalizeInput = /* @__PURE__ */ __name((input, strict, ignoreWarnings = []) => {
1109
- const warnings = [];
1110
- normalizeData(
1111
- input,
1112
- (message) => {
1113
- warnings.push(message);
1114
- },
1115
- strict
1116
- );
1117
- if (strict && warnings.length > 0) {
1118
- const filteredWarnings = warnings.filter(
1119
- (warning) => !ignoreWarnings.some((pattern) => {
1120
- if (pattern instanceof RegExp) {
1121
- return pattern.test(warning);
1122
- }
1123
- return pattern === warning;
1124
- })
1125
- );
1126
- if (filteredWarnings.length > 0) {
1127
- throw new PackageJsonValidationError(filteredWarnings);
1128
- }
1129
- }
1130
- return input;
1131
- }, "normalizeInput");
1132
- const findPackageJson = /* @__PURE__ */ __name(async (cwd, options = {}) => {
1133
- const findUpConfig = {
1134
- type: "file"
1135
- };
1136
- if (cwd) {
1137
- findUpConfig.cwd = cwd;
1138
- }
1139
- const filePath = await findUp("package.json", findUpConfig);
1140
- if (!filePath) {
1141
- throw new NotFoundError("No such file or directory, for package.json found.");
1142
- }
1143
- const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
1144
- if (options.cache && cache.has(filePath)) {
1145
- return cache.get(filePath);
1146
- }
1147
- const packageJson = await readJson(filePath);
1148
- normalizeInput(packageJson, options.strict ?? false, options.ignoreWarnings);
1149
- const output = {
1150
- packageJson,
1151
- path: filePath
1152
- };
1153
- cache.set(filePath, output);
1154
- return output;
1155
- }, "findPackageJson");
1156
- const findPackageJsonSync = /* @__PURE__ */ __name((cwd, options = {}) => {
1157
- const findUpConfig = {
1158
- type: "file"
1159
- };
1160
- if (cwd) {
1161
- findUpConfig.cwd = cwd;
1162
- }
1163
- const filePath = findUpSync("package.json", findUpConfig);
1164
- if (!filePath) {
1165
- throw new NotFoundError("No such file or directory, for package.json found.");
1166
- }
1167
- const cache = options.cache && typeof options.cache !== "boolean" ? options.cache : PackageJsonFileCache;
1168
- if (options.cache && cache.has(filePath)) {
1169
- return cache.get(filePath);
1170
- }
1171
- const packageJson = readJsonSync(filePath);
1172
- normalizeInput(packageJson, options.strict ?? false, options.ignoreWarnings);
1173
- const output = {
1174
- packageJson,
1175
- path: filePath
1176
- };
1177
- cache.set(filePath, output);
1178
- return output;
1179
- }, "findPackageJsonSync");
1180
- const writePackageJson = /* @__PURE__ */ __name(async (data, options = {}) => {
1181
- const { cwd, ...writeOptions } = options;
1182
- const directory = toPath(options.cwd ?? process.cwd());
1183
- await writeJson(join(directory, "package.json"), data, writeOptions);
1184
- }, "writePackageJson");
1185
- const writePackageJsonSync = /* @__PURE__ */ __name((data, options = {}) => {
1186
- const { cwd, ...writeOptions } = options;
1187
- const directory = toPath(options.cwd ?? process.cwd());
1188
- writeJsonSync(join(directory, "package.json"), data, writeOptions);
1189
- }, "writePackageJsonSync");
1190
- const parsePackageJson = /* @__PURE__ */ __name((packageFile, options) => {
1191
- const isObject = packageFile !== null && typeof packageFile === "object" && !Array.isArray(packageFile);
1192
- const isString = typeof packageFile === "string";
1193
- if (!isObject && !isString) {
1194
- throw new TypeError("`packageFile` should be either an `object` or a `string`.");
1195
- }
1196
- const json = isObject ? structuredClone(packageFile) : (
1197
- // eslint-disable-next-line security/detect-non-literal-fs-filename
1198
- existsSync(packageFile) ? readJsonSync(packageFile) : parseJson(packageFile)
1199
- );
1200
- normalizeInput(json, options?.strict ?? false, options?.ignoreWarnings);
1201
- return json;
1202
- }, "parsePackageJson");
1203
- const getPackageJsonProperty = /* @__PURE__ */ __name((packageJson, property, defaultValue) => getProperty(packageJson, property, defaultValue), "getPackageJsonProperty");
1204
- const hasPackageJsonProperty = /* @__PURE__ */ __name((packageJson, property) => hasProperty(packageJson, property), "hasPackageJsonProperty");
1205
- const hasPackageJsonAnyDependency = /* @__PURE__ */ __name((packageJson, arguments_, options) => {
1206
- const dependencies = getProperty(packageJson, "dependencies", {});
1207
- const devDependencies = getProperty(packageJson, "devDependencies", {});
1208
- const peerDependencies = getProperty(packageJson, "peerDependencies", {});
1209
- const allDependencies = { ...dependencies, ...devDependencies, ...options?.peerDeps === false ? {} : peerDependencies };
1210
- for (const argument of arguments_) {
1211
- if (hasProperty(allDependencies, argument)) {
1212
- return true;
1213
- }
1214
- }
1215
- return false;
1216
- }, "hasPackageJsonAnyDependency");
1217
- const ensurePackages = /* @__PURE__ */ __name(async (packageJson, packages, installKey = "dependencies", options = {}) => {
1218
- if (process.env.CI || isNode && !process.stdout?.isTTY) {
1219
- console.warn("Skipping package installation because the process is not interactive.");
1220
- return;
1221
- }
1222
- const dependencies = getProperty(packageJson, "dependencies", {});
1223
- const devDependencies = getProperty(packageJson, "devDependencies", {});
1224
- const peerDependencies = getProperty(packageJson, "peerDependencies", {});
1225
- const nonExistingPackages = [];
1226
- const config = {
1227
- deps: true,
1228
- devDeps: true,
1229
- peerDeps: false,
1230
- ...options
1231
- };
1232
- for (const packageName of packages) {
1233
- if (config.deps && hasProperty(dependencies, packageName) || config.devDeps && hasProperty(devDependencies, packageName) || config.peerDeps && hasProperty(peerDependencies, packageName)) {
1234
- continue;
1235
- }
1236
- nonExistingPackages.push(packageName);
1237
- }
1238
- if (nonExistingPackages.length === 0) {
1239
- return;
1240
- }
1241
- if (typeof config.confirm?.message === "function") {
1242
- config.confirm.message = config.confirm.message(nonExistingPackages);
1243
- }
1244
- if (config.confirm?.message === void 0) {
1245
- const message = `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?`;
1246
- if (config.confirm === void 0) {
1247
- config.confirm = {
1248
- message
1249
- };
1250
- } else {
1251
- config.confirm.message = message;
1252
- }
1253
- }
1254
- const answer = await confirm(config.confirm);
1255
- if (!answer) {
1256
- return;
1257
- }
1258
- await installPackage(nonExistingPackages, {
1259
- ...config.installPackage,
1260
- cwd: config.cwd ? toPath(config.cwd) : void 0,
1261
- dev: installKey === "devDependencies"
1262
- });
1263
- }, "ensurePackages");
1264
-
1265
- export { ensurePackages, findPackageJson, findPackageJsonSync, getPackageJsonProperty, hasPackageJsonAnyDependency, hasPackageJsonProperty, parsePackageJson, writePackageJson, writePackageJsonSync };
1
+ var $e=Object.defineProperty;var l=(t,e)=>$e(t,"name",{value:e,configurable:!0});import{existsSync as z}from"node:fs";import I from"node:process";import oe from"node:fs/promises";import j,{resolve as se}from"node:path";import{createRequire as Oe}from"node:module";import{spawn as je}from"child_process";import{delimiter as Z,resolve as Ce,dirname as Se,normalize as Ae}from"path";import{cwd as Ne}from"process";import{PassThrough as Je}from"stream";import Te from"readline";import De from"@inquirer/confirm";import{readJsonSync as ie,findUp as Ie,readJson as Me,findUpSync as Fe,writeJson as He,writeJsonSync as We}from"@visulima/fs";import{NotFoundError as ae}from"@visulima/fs/error";import{parseJson as Le,toPath as K}from"@visulima/fs/utils";import{join as ce}from"@visulima/path";import Ue from"normalize-package-data";const le=["npm","yarn","yarn@berry","pnpm","pnpm@6","bun","deno"],ee={"bun.lock":"bun","bun.lockb":"bun","deno.lock":"deno","pnpm-lock.yaml":"pnpm","pnpm-workspace.yaml":"pnpm","yarn.lock":"yarn","package-lock.json":"npm","npm-shrinkwrap.json":"npm"},te={"node_modules/.deno/":"deno","node_modules/.pnpm/":"pnpm","node_modules/.yarn-state.yml":"yarn","node_modules/.yarn_integrity":"yarn","node_modules/.package-lock.json":"npm",".pnp.cjs":"yarn",".pnp.js":"yarn","bun.lock":"bun","bun.lockb":"bun"};var Ve=Object.defineProperty,P=l((t,e)=>Ve(t,"name",{value:e,configurable:!0}),"i$1");async function F(t,e){try{const n=await oe.stat(t);return e==="file"?n.isFile():n.isDirectory()}catch{return!1}}l(F,"g$2");P(F,"pathExists");function ze(){const t=I.env.npm_config_user_agent;if(!t)return null;const e=t.split("/")[0];return le.includes(e)?e:null}l(ze,"M$1");P(ze,"getUserAgent");function*pe(t=I.cwd()){let e=j.resolve(t);const{root:n}=j.parse(e);for(;e&&e!==n;)yield e,e=j.dirname(e)}l(pe,"h$2");P(pe,"lookup");async function V(t,e){return!t||!F(t,"file")?null:await de(t,e)}l(V,"m");P(V,"parsePackageJson");async function ue(t={}){const{cwd:e,strategies:n=["lockfile","packageManager-field","devEngines-field"],onUnknown:r}=t;let o;if(typeof t.stopDir=="string"){const i=j.resolve(t.stopDir);o=P(a=>a===i,"stopDir")}else o=t.stopDir;for(const i of pe(e)){for(const a of n)switch(a){case"lockfile":{for(const s of Object.keys(ee))if(await F(j.join(i,s),"file")){const c=ee[s];return await V(j.join(i,"package.json"),r)||{name:c,agent:c}}break}case"packageManager-field":case"devEngines-field":{const s=await V(j.join(i,"package.json"),r);if(s)return s;break}case"install-metadata":{for(const s of Object.keys(te)){const c=s.endsWith("/")?"dir":"file";if(await F(j.join(i,s),c)){const u=te[s],p=u==="yarn"?he(s)?"yarn":"yarn@berry":u;return{name:u,agent:p}}}break}}if(o?.(i))break}return null}l(ue,"A");P(ue,"detect");function fe(t){const e=P(n=>n?.match(/\d+(\.\d+){0,2}/)?.[0]??n,"handelVer");if(typeof t.packageManager=="string"){const[n,r]=t.packageManager.replace(/^\^/,"").split("@");return{name:n,ver:e(r)}}if(typeof t.devEngines?.packageManager?.name=="string")return{name:t.devEngines.packageManager.name,ver:e(t.devEngines.packageManager.version)}}l(fe,"j$1");P(fe,"getNameAndVer");async function de(t,e){try{const n=JSON.parse(await oe.readFile(t,"utf8"));let r;const o=fe(n);if(o){const i=o.name,a=o.ver;let s=a;return i==="yarn"&&a&&Number.parseInt(a)>1?(r="yarn@berry",s="berry",{name:i,agent:r,version:s}):i==="pnpm"&&a&&Number.parseInt(a)<7?(r="pnpm@6",{name:i,agent:r,version:s}):le.includes(i)?(r=i,{name:i,agent:r,version:s}):e?.(n.packageManager)??null}}catch{}return null}l(de,"E$1");P(de,"handlePackageManager");function he(t){return t.endsWith(".yarn_integrity")}l(he,"D$1");P(he,"isMetadataYarnClassic");var Ke=Object.defineProperty,f=l((t,e)=>Ke(t,"name",{value:e,configurable:!0}),"l$2");const T=Oe(import.meta.url);var Ye=Object.create,ge=Object.defineProperty,Be=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyNames,qe=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty,S=(t=>typeof T<"u"?T:typeof Proxy<"u"?new Proxy(t,{get:f((e,n)=>(typeof T<"u"?T:e)[n],"get")}):t)(function(t){if(typeof T<"u")return T.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),E=f((t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),"l"),Ge=f((t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xe(e))!Re.call(t,o)&&o!==n&&ge(t,o,{get:f(()=>e[o],"get"),enumerable:!(r=Be(e,o))||r.enumerable});return t},"$t"),Qe=f((t,e,n)=>(n=t!=null?Ye(qe(t)):{},Ge(e||!t||!t.__esModule?ge(n,"default",{value:t,enumerable:!0}):n,t)),"Nt"),Ze=E((t,e)=>{e.exports=i,i.sync=a;var n=S("fs");function r(s,c){var u=c.pathExt!==void 0?c.pathExt:process.env.PATHEXT;if(!u||(u=u.split(";"),u.indexOf("")!==-1))return!0;for(var p=0;p<u.length;p++){var h=u[p].toLowerCase();if(h&&s.substr(-h.length).toLowerCase()===h)return!0}return!1}l(r,"o"),f(r,"Ht");function o(s,c,u){return!s.isSymbolicLink()&&!s.isFile()?!1:r(c,u)}l(o,"i"),f(o,"F");function i(s,c,u){n.stat(s,function(p,h){u(p,p?!1:o(h,s,c))})}l(i,"u"),f(i,"z");function a(s,c){return o(n.statSync(s),s,c)}l(a,"d"),f(a,"Wt")}),et=E((t,e)=>{e.exports=r,r.sync=o;var n=S("fs");function r(s,c,u){n.stat(s,function(p,h){u(p,p?!1:i(h,c))})}l(r,"o"),f(r,"K");function o(s,c){return i(n.statSync(s),c)}l(o,"i"),f(o,"Dt");function i(s,c){return s.isFile()&&a(s,c)}l(i,"u"),f(i,"M");function a(s,c){var u=s.mode,p=s.uid,h=s.gid,d=c.uid!==void 0?c.uid:process.getuid&&process.getuid(),g=c.gid!==void 0?c.gid:process.getgid&&process.getgid(),m=parseInt("100",8),y=parseInt("010",8),k=parseInt("001",8),b=m|y,A=u&k||u&y&&h===g||u&m&&p===d||u&b&&d===0;return A}l(a,"d"),f(a,"Kt")}),tt=E((t,e)=>{S("fs");var n;process.platform==="win32"||global.TESTING_WINDOWS?n=Ze():n=et(),e.exports=r,r.sync=o;function r(i,a,s){if(typeof a=="function"&&(s=a,a={}),!s){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(c,u){r(i,a||{},function(p,h){p?u(p):c(h)})})}n(i,a||{},function(c,u){c&&(c.code==="EACCES"||a&&a.ignoreErrors)&&(c=null,u=!1),s(c,u)})}l(r,"i"),f(r,"y");function o(i,a){try{return n.sync(i,a||{})}catch(s){if(a&&a.ignoreErrors||s.code==="EACCES")return!1;throw s}}l(o,"u"),f(o,"Mt")}),rt=E((t,e)=>{var n=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",r=S("path"),o=n?";":":",i=tt(),a=f(p=>Object.assign(new Error(`not found: ${p}`),{code:"ENOENT"}),"J"),s=f((p,h)=>{let d=h.colon||o,g=p.match(/\//)||n&&p.match(/\\/)?[""]:[...n?[process.cwd()]:[],...(h.path||process.env.PATH||"").split(d)],m=n?h.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",y=n?m.split(d):[""];return n&&p.indexOf(".")!==-1&&y[0]!==""&&y.unshift(""),{pathEnv:g,pathExt:y,pathExtExe:m}},"Q"),c=f((p,h,d)=>{typeof h=="function"&&(d=h,h={}),h||(h={});let{pathEnv:g,pathExt:m,pathExtExe:y}=s(p,h),k=[],b=f(v=>new Promise((N,$)=>{if(v===g.length)return h.all&&k.length?N(k):$(a(p));let _=g[v],W=/^".*"$/.test(_)?_.slice(1,-1):_,J=r.join(W,p),L=!W&&/^\.[\\\/]/.test(p)?p.slice(0,2)+J:J;N(A(L,v,0))}),"a"),A=f((v,N,$)=>new Promise((_,W)=>{if($===m.length)return _(b(N+1));let J=m[$];i(v+J,{pathExt:y},(L,Pe)=>{if(!L&&Pe)if(h.all)k.push(v+J);else return _(v+J);return _(A(v,N,$+1))})}),"c");return d?b(0).then(v=>d(null,v),d):b(0)},"Z"),u=f((p,h)=>{h=h||{};let{pathEnv:d,pathExt:g,pathExtExe:m}=s(p,h),y=[];for(let k=0;k<d.length;k++){let b=d[k],A=/^".*"$/.test(b)?b.slice(1,-1):b,v=r.join(A,p),N=!A&&/^\.[\\\/]/.test(p)?p.slice(0,2)+v:v;for(let $=0;$<g.length;$++){let _=N+g[$];try{if(i.sync(_,{pathExt:m}))if(h.all)y.push(_);else return _}catch{}}}if(h.all&&y.length)return y;if(h.nothrow)return null;throw a(p)},"Xt");e.exports=c,c.sync=u}),nt=E((t,e)=>{var n=f((r={})=>{let o=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(o).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"},"nt");e.exports=n,e.exports.default=n}),ot=E((t,e)=>{var n=S("path"),r=rt(),o=nt();function i(s,c){let u=s.options.env||process.env,p=process.cwd(),h=s.options.cwd!=null,d=h&&process.chdir!==void 0&&!process.chdir.disabled;if(d)try{process.chdir(s.options.cwd)}catch{}let g;try{g=r.sync(s.command,{path:u[o({env:u})],pathExt:c?n.delimiter:void 0})}catch{}finally{d&&process.chdir(p)}return g&&(g=n.resolve(h?s.options.cwd:"",g)),g}l(i,"u"),f(i,"ot");function a(s){return i(s)||i(s,!0)}l(a,"d"),f(a,"Yt"),e.exports=a}),st=E((t,e)=>{var n=/([()\][%!^"`<>&|;, *?])/g;function r(i){return i=i.replace(n,"^$1"),i}l(r,"o"),f(r,"Vt");function o(i,a){return i=`${i}`,i=i.replace(/(\\*)"/g,'$1$1\\"'),i=i.replace(/(\\*)$/,"$1$1"),i=`"${i}"`,i=i.replace(n,"^$1"),a&&(i=i.replace(n,"^$1")),i}l(o,"i"),f(o,"Jt"),e.exports.command=r,e.exports.argument=o}),it=E((t,e)=>{e.exports=/^#!(.*)/}),at=E((t,e)=>{var n=it();e.exports=(r="")=>{let o=r.match(n);if(!o)return null;let[i,a]=o[0].replace(/#! ?/,"").split(" "),s=i.split("/").pop();return s==="env"?a:a?`${s} ${a}`:s}}),ct=E((t,e)=>{var n=S("fs"),r=at();function o(i){let a=Buffer.alloc(150),s;try{s=n.openSync(i,"r"),n.readSync(s,a,0,150,0),n.closeSync(s)}catch{}return r(a.toString())}l(o,"i"),f(o,"te"),e.exports=o}),lt=E((t,e)=>{var n=S("path"),r=ot(),o=st(),i=ct(),a=process.platform==="win32",s=/\.(?:com|exe)$/i,c=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u(d){d.file=r(d);let g=d.file&&i(d.file);return g?(d.args.unshift(d.file),d.command=g,r(d)):d.file}l(u,"h"),f(u,"ie");function p(d){if(!a)return d;let g=u(d),m=!s.test(g);if(d.options.forceShell||m){let y=c.test(g);d.command=n.normalize(d.command),d.command=o.command(d.command),d.args=d.args.map(b=>o.argument(b,y));let k=[d.command].concat(d.args).join(" ");d.args=["/d","/s","/c",`"${k}"`],d.command=process.env.comspec||"cmd.exe",d.options.windowsVerbatimArguments=!0}return d}l(p,"a"),f(p,"ce");function h(d,g,m){g&&!Array.isArray(g)&&(m=g,g=null),g=g?g.slice(0):[],m=Object.assign({},m);let y={command:d,args:g,options:m,file:void 0,original:{command:d,args:g}};return m.shell?y:p(y)}l(h,"p"),f(h,"ue"),e.exports=h}),pt=E((t,e)=>{var n=process.platform==="win32";function r(s,c){return Object.assign(new Error(`${c} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${c} ${s.command}`,path:s.command,spawnargs:s.args})}l(r,"o"),f(r,"k");function o(s,c){if(!n)return;let u=s.emit;s.emit=function(p,h){if(p==="exit"){let d=i(h,c);if(d)return u.call(s,"error",d)}return u.apply(s,arguments)}}l(o,"i"),f(o,"ae");function i(s,c){return n&&s===1&&!c.file?r(c.original,"spawn"):null}l(i,"u"),f(i,"xt");function a(s,c){return n&&s===1&&!c.file?r(c.original,"spawnSync"):null}l(a,"d"),f(a,"le"),e.exports={hookChildProcess:o,verifyENOENT:i,verifyENOENTSync:a,notFoundError:r}}),ut=E((t,e)=>{var n=S("child_process"),r=lt(),o=pt();function i(s,c,u){let p=r(s,c,u),h=n.spawn(p.command,p.args,p.options);return o.hookChildProcess(h,p),h}l(i,"u"),f(i,"_t");function a(s,c,u){let p=r(s,c,u),h=n.spawnSync(p.command,p.args,p.options);return h.error=h.error||o.verifyENOENTSync(h.status,p),h}l(a,"d"),f(a,"pe"),e.exports=i,e.exports.spawn=i,e.exports.sync=a,e.exports._parse=r,e.exports._enoent=o}),ft=/^path$/i,re={key:"PATH",value:""};function me(t){for(let e in t){if(!Object.prototype.hasOwnProperty.call(t,e)||!ft.test(e))continue;let n=t[e];return n?{key:e,value:n}:re}return re}l(me,"hr");f(me,"jt");function ye(t,e){let n=e.value.split(Z),r=t,o;do n.push(Ce(r,"node_modules",".bin")),o=r,r=Se(r);while(r!==o);return{key:e.key,value:n.join(Z)}}l(ye,"dr");f(ye,"Ft");function we(t,e){let n={...process.env,...e},r=ye(t,me(n));return n[r.key]=r.value,n}l(we,"fr");f(we,"I");var dt=f(t=>{let e=t.length,n=new Je,r=f(()=>{--e===0&&n.emit("end")},"r");for(let o of t)o.pipe(n,{end:!1}),o.on("end",r);return n},"L"),ht=Qe(ut(),1),ne=class extends Error{static{l(this,"N")}static{f(this,"x")}result;output;get exitCode(){if(this.result.exitCode!==null)return this.result.exitCode}constructor(t,e){super(`Process exited with non-zero status (${t.exitCode})`),this.result=t,this.output=e}},gt={timeout:void 0,persist:!1},mt={windowsHide:!0};function ve(t,e){return{command:Ae(t),args:e??[]}}l(ve,"yr");f(ve,"we");function Ee(t){let e=new AbortController;for(let n of t){if(n.aborted)return e.abort(),n;let r=f(()=>{e.abort(n.reason)},"r");n.addEventListener("abort",r,{signal:e.signal})}return e.signal}l(Ee,"xr");f(Ee,"xe");var yt=class{static{l(this,"I")}static{f(this,"R")}_process;_aborted=!1;_options;_command;_args;_resolveClose;_processClosed;_thrownError;get process(){return this._process}get pid(){return this._process?.pid}get exitCode(){if(this._process&&this._process.exitCode!==null)return this._process.exitCode}constructor(t,e,n){this._options={...gt,...n},this._command=t,this._args=e??[],this._processClosed=new Promise(r=>{this._resolveClose=r})}kill(t){return this._process?.kill(t)===!0}get aborted(){return this._aborted}get killed(){return this._process?.killed===!0}pipe(t,e,n){return wt(t,e,{...n,stdin:this})}async*[Symbol.asyncIterator](){let t=this._process;if(!t)return;let e=[];this._streamErr&&e.push(this._streamErr),this._streamOut&&e.push(this._streamOut);let n=dt(e),r=Te.createInterface({input:n});for await(let o of r)yield o.toString();if(await this._processClosed,t.removeAllListeners(),this._thrownError)throw this._thrownError;if(this._options?.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new ne(this)}async _waitForOutput(){let t=this._process;if(!t)throw new Error("No process was started");let e="",n="";if(this._streamOut)for await(let o of this._streamOut)n+=o.toString();if(this._streamErr)for await(let o of this._streamErr)e+=o.toString();if(await this._processClosed,this._options?.stdin&&await this._options.stdin,t.removeAllListeners(),this._thrownError)throw this._thrownError;let r={stderr:e,stdout:n,exitCode:this.exitCode};if(this._options.throwOnError&&this.exitCode!==0&&this.exitCode!==void 0)throw new ne(this,r);return r}then(t,e){return this._waitForOutput().then(t,e)}_streamOut;_streamErr;spawn(){let t=Ne(),e=this._options,n={...mt,...e.nodeOptions},r=[];this._resetState(),e.timeout!==void 0&&r.push(AbortSignal.timeout(e.timeout)),e.signal!==void 0&&r.push(e.signal),e.persist===!0&&(n.detached=!0),r.length>0&&(n.signal=Ee(r)),n.env=we(t,n.env);let{command:o,args:i}=ve(this._command,this._args),a=(0,ht._parse)(o,i,n),s=je(a.command,a.args,a.options);if(s.stderr&&(this._streamErr=s.stderr),s.stdout&&(this._streamOut=s.stdout),this._process=s,s.once("error",this._onError),s.once("close",this._onClose),e.stdin!==void 0&&s.stdin&&e.stdin.process){let{stdout:c}=e.stdin.process;c&&c.pipe(s.stdin)}}_resetState(){this._aborted=!1,this._processClosed=new Promise(t=>{this._resolveClose=t}),this._thrownError=void 0}_onError=f(t=>{if(t.name==="AbortError"&&(!(t.cause instanceof Error)||t.cause.name!=="TimeoutError")){this._aborted=!0;return}this._thrownError=t},"_onError");_onClose=f(()=>{this._resolveClose&&this._resolveClose()},"_onClose")},Y=f((t,e,n)=>{let r=new yt(t,e,n);return r.spawn(),r},"ve"),wt=Y,vt=Object.defineProperty,B=l((t,e)=>vt(t,"name",{value:e,configurable:!0}),"i");async function X(t=I.cwd()){return(await ue({cwd:t,onUnknown(e){console.warn("[@antfu/install-pkg] Unknown packageManager:",e)}}))?.agent||null}l(X,"c$2");B(X,"detectPackageManager");async function ke(t,e={}){const n=e.packageManager||await X(e.cwd)||"npm",[r]=n.split("@");Array.isArray(t)||(t=[t]);const o=(typeof e.additionalArgs=="function"?e.additionalArgs(r,n):e.additionalArgs)||[];return e.preferOffline&&(n==="yarn@berry"?o.unshift("--cached"):o.unshift("--prefer-offline")),r==="pnpm"&&(o.unshift("--prod=false"),z(se(e.cwd??I.cwd(),"pnpm-workspace.yaml"))&&o.unshift("-w")),Y(r,[r==="yarn"?"add":"install",e.dev?"-D":"",...o,...t].filter(Boolean),{nodeOptions:{stdio:e.silent?"ignore":"inherit",cwd:e.cwd},throwOnError:!0})}l(ke,"p$1");B(ke,"installPackage");async function Et(t,e={}){const n=e.packageManager||await X(e.cwd)||"npm",[r]=n.split("@");Array.isArray(t)||(t=[t]);const o=e.additionalArgs||[];return r==="pnpm"&&z(se(e.cwd??I.cwd(),"pnpm-workspace.yaml"))&&o.unshift("-w"),Y(r,[r==="yarn"?"remove":"uninstall",e.dev?"-D":"",...o,...t].filter(Boolean),{nodeOptions:{stdio:e.silent?"ignore":"inherit",cwd:e.cwd},throwOnError:!0})}l(Et,"h$1");B(Et,"uninstallPackage");var kt=Object.defineProperty,w=l((t,e)=>kt(t,"name",{value:e,configurable:!0}),"s");const O=w(t=>{const e=typeof t;return t!==null&&(e==="object"||e==="function")},"isObject"),bt=w(t=>O(t)&&Object.keys(t).length===0,"isEmptyObject"),U=new Set(["__proto__","prototype","constructor"]),_t=new Set("0123456789");function M(t){const e=[];let n="",r="start",o=!1;for(const i of t)switch(i){case"\\":{if(r==="index")throw new Error("Invalid character in an index");if(r==="indexEnd")throw new Error("Invalid character after an index");o&&(n+=i),r="property",o=!o;break}case".":{if(r==="index")throw new Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(o){o=!1,n+=i;break}if(U.has(n))return[];e.push(n),n="",r="property";break}case"[":{if(r==="index")throw new Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(o){o=!1,n+=i;break}if(r==="property"){if(U.has(n))return[];e.push(n),n=""}r="index";break}case"]":{if(r==="index"){e.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw new Error("Invalid character after an index")}default:{if(r==="index"&&!_t.has(i))throw new Error("Invalid character in an index");if(r==="indexEnd")throw new Error("Invalid character after an index");r==="start"&&(r="property"),o&&(o=!1,n+="\\"),n+=i}}switch(o&&(n+="\\"),r){case"property":{if(U.has(n))return[];e.push(n);break}case"index":throw new Error("Index was not closed");case"start":{e.push("");break}}return e}l(M,"d");w(M,"getPathSegments");function H(t,e){if(typeof e!="number"&&Array.isArray(t)){const n=Number.parseInt(e,10);return Number.isInteger(n)&&t[n]===t[e]}return!1}l(H,"l$1");w(H,"isStringIndex");function q(t,e){if(H(t,e))throw new Error("Cannot use string index")}l(q,"p");w(q,"assertNotStringIndex");function C(t,e,n){if(!O(t)||typeof e!="string")return n===void 0?t:n;const r=M(e);if(r.length===0)return n;for(let o=0;o<r.length;o++){const i=r[o];if(H(t,i)?t=o===r.length-1?void 0:null:t=t[i],t==null){if(o!==r.length-1)return n;break}}return t===void 0?n:t}l(C,"getProperty");w(C,"getProperty");function xt(t,e,n){if(!O(t)||typeof e!="string")return t;const r=t,o=M(e);for(let i=0;i<o.length;i++){const a=o[i];q(t,a),i===o.length-1?t[a]=n:O(t[a])||(t[a]=typeof o[i+1]=="number"?[]:{}),t=t[a]}return r}l(xt,"setProperty");w(xt,"setProperty");function Pt(t,e){if(!O(t)||typeof e!="string")return!1;const n=M(e);for(let r=0;r<n.length;r++){const o=n[r];if(q(t,o),r===n.length-1)return delete t[o],!0;if(t=t[o],!O(t))return!1}}l(Pt,"deleteProperty");w(Pt,"deleteProperty");function D(t,e){if(!O(t)||typeof e!="string")return!1;const n=M(e);if(n.length===0)return!1;for(const r of n){if(!O(t)||!(r in t)||H(t,r))return!1;t=t[r]}return!0}l(D,"hasProperty");w(D,"hasProperty");function be(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replaceAll(/[\\.[]/g,"\\$&")}l(be,"escapePath");w(be,"escapePath");function R(t){const e=Object.entries(t);return Array.isArray(t)?e.map(([n,r])=>[Number(n),r]):e}l(R,"h");w(R,"entries");function _e(t){let e="";for(let[n,r]of R(t))typeof r=="number"?e+=`[${r}]`:(r=be(r),e+=n===0?r:`.${r}`);return e}l(_e,"w");w(_e,"stringifyPath");function*G(t,e=[]){if(!O(t)||bt(t)){e.length>0&&(yield _e(e));return}for(const[n,r]of R(t))yield*G(r,[...e,n])}l(G,"y");w(G,"deepKeysIterator");function $t(t){return[...G(t)]}l($t,"deepKeys");w($t,"deepKeys");const Ot=typeof process.stdout<"u"&&!process.versions.deno&&!globalThis.window;var jt=Object.defineProperty,x=l((t,e)=>jt(t,"name",{value:e,configurable:!0}),"c");const xe=new Map;class Ct extends Error{static{l(this,"E")}static{x(this,"PackageJsonValidationError")}constructor(e){super(`The following warnings were encountered while normalizing package data:
2
+ - ${e.join(`
3
+ - `)}`),this.name="PackageJsonValidationError"}}const Q=x((t,e,n=[])=>{const r=[];if(Ue(t,o=>{r.push(o)},e),e&&r.length>0){const o=r.filter(i=>!n.some(a=>a instanceof RegExp?a.test(i):a===i));if(o.length>0)throw new Ct(o)}return t},"normalizeInput"),Bt=x(async(t,e={})=>{const n={type:"file"};t&&(n.cwd=t);const r=await Ie("package.json",n);if(!r)throw new ae("No such file or directory, for package.json found.");const o=e.cache&&typeof e.cache!="boolean"?e.cache:xe;if(e.cache&&o.has(r))return o.get(r);const i=await Me(r);Q(i,e.strict??!1,e.ignoreWarnings);const a={packageJson:i,path:r};return o.set(r,a),a},"findPackageJson"),Xt=x((t,e={})=>{const n={type:"file"};t&&(n.cwd=t);const r=Fe("package.json",n);if(!r)throw new ae("No such file or directory, for package.json found.");const o=e.cache&&typeof e.cache!="boolean"?e.cache:xe;if(e.cache&&o.has(r))return o.get(r);const i=ie(r);Q(i,e.strict??!1,e.ignoreWarnings);const a={packageJson:i,path:r};return o.set(r,a),a},"findPackageJsonSync"),qt=x(async(t,e={})=>{const{cwd:n,...r}=e,o=K(e.cwd??process.cwd());await He(ce(o,"package.json"),t,r)},"writePackageJson"),Rt=x((t,e={})=>{const{cwd:n,...r}=e,o=K(e.cwd??process.cwd());We(ce(o,"package.json"),t,r)},"writePackageJsonSync"),Gt=x((t,e)=>{const n=t!==null&&typeof t=="object"&&!Array.isArray(t);if(!n&&typeof t!="string")throw new TypeError("`packageFile` should be either an `object` or a `string`.");const r=n?structuredClone(t):z(t)?ie(t):Le(t);return Q(r,e?.strict??!1,e?.ignoreWarnings),r},"parsePackageJson"),Qt=x((t,e,n)=>C(t,e,n),"getPackageJsonProperty"),Zt=x((t,e)=>D(t,e),"hasPackageJsonProperty"),er=x((t,e,n)=>{const r=C(t,"dependencies",{}),o=C(t,"devDependencies",{}),i=C(t,"peerDependencies",{}),a={...r,...o,...n?.peerDeps===!1?{}:i};for(const s of e)if(D(a,s))return!0;return!1},"hasPackageJsonAnyDependency"),tr=x(async(t,e,n="dependencies",r={})=>{if(process.env.CI||Ot&&!process.stdout?.isTTY){console.warn("Skipping package installation because the process is not interactive.");return}const o=C(t,"dependencies",{}),i=C(t,"devDependencies",{}),a=C(t,"peerDependencies",{}),s=[],c={deps:!0,devDeps:!0,peerDeps:!1,...r};for(const u of e)c.deps&&D(o,u)||c.devDeps&&D(i,u)||c.peerDeps&&D(a,u)||s.push(u);if(s.length!==0){if(typeof c.confirm?.message=="function"&&(c.confirm.message=c.confirm.message(s)),c.confirm?.message===void 0){const u=`${s.length===1?"Package is":"Packages are"} required for this config: ${s.join(", ")}. Do you want to install them?`;c.confirm===void 0?c.confirm={message:u}:c.confirm.message=u}await De(c.confirm)&&await ke(s,{...c.installPackage,cwd:c.cwd?K(c.cwd):void 0,dev:n==="devDependencies"})}},"ensurePackages");export{tr as ensurePackages,Bt as findPackageJson,Xt as findPackageJsonSync,Qt as getPackageJsonProperty,er as hasPackageJsonAnyDependency,Zt as hasPackageJsonProperty,Gt as parsePackageJson,qt as writePackageJson,Rt as writePackageJsonSync};