package-management 0.0.10 → 0.0.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1293 @@
1
+ 'use strict';
2
+
3
+ const ErrorStackParser = require('error-stack-parser');
4
+ const path = require('pathe');
5
+ const process = require('node:process');
6
+ const path$1 = require('node:path');
7
+ const node_url = require('node:url');
8
+ const node_fs = require('node:fs');
9
+ const asyncCacheFn = require('async-cache-fn');
10
+ const execa = require('execa');
11
+ const findUp = require('find-up');
12
+ const promises = require('node:fs/promises');
13
+ const mlly = require('mlly');
14
+ const globby = require('globby');
15
+ const gitignoreParser = require('parse-gitignore');
16
+ const WST = require('workspace-tools');
17
+ const utils = require('pathe/utils');
18
+ const os = require('node:os');
19
+ const jsoncParser = require('jsonc-parser');
20
+ const util = require('@arktype/util');
21
+ const unstorage = require('unstorage');
22
+ const defineMemoryDriver = require('unstorage/drivers/memory');
23
+ const defineFsLiteDriver = require('unstorage/drivers/fs-lite');
24
+
25
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
26
+
27
+ function _interopNamespaceCompat(e) {
28
+ if (e && typeof e === 'object' && 'default' in e) return e;
29
+ const n = Object.create(null);
30
+ if (e) {
31
+ for (const k in e) {
32
+ n[k] = e[k];
33
+ }
34
+ }
35
+ n.default = e;
36
+ return n;
37
+ }
38
+
39
+ const ErrorStackParser__default = /*#__PURE__*/_interopDefaultCompat(ErrorStackParser);
40
+ const path__default$1 = /*#__PURE__*/_interopDefaultCompat(path);
41
+ const process__default = /*#__PURE__*/_interopDefaultCompat(process);
42
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path$1);
43
+ const gitignoreParser__default = /*#__PURE__*/_interopDefaultCompat(gitignoreParser);
44
+ const WST__namespace = /*#__PURE__*/_interopNamespaceCompat(WST);
45
+ const os__default = /*#__PURE__*/_interopDefaultCompat(os);
46
+ const defineMemoryDriver__default = /*#__PURE__*/_interopDefaultCompat(defineMemoryDriver);
47
+ const defineFsLiteDriver__default = /*#__PURE__*/_interopDefaultCompat(defineFsLiteDriver);
48
+
49
+ const toArray = (data) => Array.isArray(data) ? data : [data];
50
+ const entriesOf = (o) => Object.entries(o);
51
+ const fromEntries = (entries) => Object.fromEntries(entries);
52
+ const notFalsy = (value) => [false, null, void 0].every((v) => v !== value);
53
+ const select = (obj, selection, mode) => {
54
+ if (!selection) return obj;
55
+ const filtered = entriesOf(obj).filter(([key]) => {
56
+ return selection[key];
57
+ });
58
+ return fromEntries(filtered);
59
+ };
60
+ function normalizePath(path$1, option) {
61
+ if (typeof option === "function") {
62
+ return normalizePath(path$1);
63
+ }
64
+ if (option === false) {
65
+ return path$1;
66
+ }
67
+ return path.normalize(path$1);
68
+ }
69
+ const invariant = (predicate, message) => {
70
+ if (!predicate) {
71
+ throw new Error(message);
72
+ }
73
+ };
74
+ function getArrayItemAtOffset(arr, index, offset = 0) {
75
+ if (arr === void 0 || index === void 0) return void 0;
76
+ return arr[index + offset];
77
+ }
78
+ function isMatching(a, b) {
79
+ if (!a || !b) return false;
80
+ return a === b;
81
+ }
82
+ function checkResult(cb, options) {
83
+ try {
84
+ return buildSingleProp({
85
+ key: options?.keys?.data ?? "data",
86
+ value: cb()
87
+ });
88
+ } catch (error) {
89
+ return buildSingleProp({
90
+ key: "error",
91
+ value: error
92
+ });
93
+ }
94
+ }
95
+ function isPropertyKey(input) {
96
+ return typeof input === "string" || typeof input === "number" || typeof input === "symbol";
97
+ }
98
+ function buildSingleProp(entry) {
99
+ const [key, value] = Array.isArray(entry) ? entry : [entry.key, entry.value];
100
+ if (!isPropertyKey(key)) {
101
+ return {};
102
+ }
103
+ return { [key]: value };
104
+ }
105
+
106
+ function findCallerStackFrame(options) {
107
+ return findErrorStackFrame(options, (frame) => frame.isParentOfRootFunction);
108
+ }
109
+ function findErrorStackFrame(options, find) {
110
+ return getErrorStackFrames(options, find)[0];
111
+ }
112
+ function getErrorStackFrames(options, filter) {
113
+ const { error, rootFunctionName, startFrom = "top" } = options;
114
+ const frames = startFrom === "bottom" ? ErrorStackParser__default.parse(error).reverse() : ErrorStackParser__default.parse(error);
115
+ const { parsedFrames } = frames.reduce(
116
+ (acc, frame, index) => {
117
+ const parsed = parseFrame({
118
+ frame,
119
+ index,
120
+ rootFunctionName,
121
+ frames
122
+ });
123
+ const isValid = filter ? filter(parsed) : true;
124
+ if (isValid) {
125
+ acc.parsedFrames.push(parsed);
126
+ }
127
+ return acc;
128
+ },
129
+ { parsedFrames: [] }
130
+ );
131
+ return parsedFrames ?? [];
132
+ }
133
+ function parseFrame(options) {
134
+ const { frame, frames, index, rootFunctionName, cwd, debug } = options ?? {};
135
+ const functionName = parseFunctionName(frame.functionName);
136
+ const isRootFunction = isMatching(functionName, rootFunctionName);
137
+ const beforeFrameFunctionName = parseFunctionName(
138
+ getArrayItemAtOffset(frames, index, -1)?.functionName
139
+ );
140
+ const isParentOfRootFunction = isMatching(
141
+ beforeFrameFunctionName,
142
+ rootFunctionName
143
+ );
144
+ const fileData = frame.fileName ? getFilePathData({ filepath: frame.fileName, cwd }) : void 0;
145
+ const { isFileInCwd: isFrameInScope, ...restFileData } = fileData ?? {};
146
+ const data = {
147
+ ...restFileData,
148
+ functionName,
149
+ source: frame.source,
150
+ sourceFunctionName: frame.functionName,
151
+ isFrameInScope,
152
+ place: placeFormatter(index, frames?.length),
153
+ isRootFunction,
154
+ isParentOfRootFunction,
155
+ rootFunctionName
156
+ };
157
+ debug && console.log(data);
158
+ return data;
159
+ }
160
+ function getFilePathData({
161
+ filepath,
162
+ cwd
163
+ }) {
164
+ const workingDir = cwd ?? process__default.cwd();
165
+ const filePath = path.normalize(toFilePath(filepath));
166
+ const fileBasename = path.basename(filePath);
167
+ const dirPath = path.dirname(filePath);
168
+ const dirBasename = path.basename(dirPath);
169
+ const relativeFilePath = path.relative(workingDir, filePath);
170
+ const relativeDirPath = path.dirname(relativeFilePath);
171
+ const isFileInCwd = filePath.startsWith(workingDir);
172
+ return {
173
+ filePath,
174
+ dirPath,
175
+ relativeFilePath,
176
+ relativeDirPath,
177
+ fileBasename,
178
+ dirBasename,
179
+ isFileInCwd
180
+ };
181
+ }
182
+ function toFilePath(fileName) {
183
+ return fileName.startsWith("file:") ? node_url.fileURLToPath(fileName) : fileName;
184
+ }
185
+ function parseFunctionName(functionName) {
186
+ if (!functionName) return void 0;
187
+ return removeStart(functionName, "Module.");
188
+ }
189
+ function removeStart(input, value) {
190
+ return input.startsWith(value) ? input.slice(value.length) : input;
191
+ }
192
+ function placeFormatter(index, total) {
193
+ if (index === void 0 || !total) return void 0;
194
+ return [index, total].join("/");
195
+ }
196
+
197
+ const _filename = (options) => {
198
+ const { filePath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
199
+ return filePath;
200
+ };
201
+ const _dirname = (options) => {
202
+ const { dirPath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
203
+ return dirPath;
204
+ };
205
+
206
+ async function resolveModule(module) {
207
+ const resolved = await module;
208
+ return resolved.default || resolved;
209
+ }
210
+ function isPackageModuleFound(name, options) {
211
+ return Boolean(resolvePackageModulePath(name, options));
212
+ }
213
+ function resolvePackageModulePath(name, options) {
214
+ const resolvedPath = findResolvedModulePath(
215
+ [`${name}/package.json`, name],
216
+ options
217
+ );
218
+ if (resolvedPath === void 0) {
219
+ console.error(`Could not resolve package ${name}`);
220
+ return void 0;
221
+ }
222
+ return resolvedPath;
223
+ }
224
+ function findResolvedModulePath(paths, options) {
225
+ for (const path of paths) {
226
+ const resolvedPath = resolveModulePath(path, options);
227
+ if (resolvedPath === void 0) continue;
228
+ return resolvedPath;
229
+ }
230
+ }
231
+ function resolveModulePath(modulePath, options) {
232
+ const { normalize = true, paths, ...rest } = options ?? {};
233
+ try {
234
+ const path = normalizePath(modulePath, normalize);
235
+ return mlly.resolvePathSync(path, {
236
+ url: paths,
237
+ ...rest
238
+ });
239
+ } catch (e) {
240
+ return void 0;
241
+ }
242
+ }
243
+
244
+ const tsconfig = (tsconfigDir) => ({
245
+ get paths() {
246
+ return globby.globbySync(["tsconfig.json", "tsconfig.*.json"], {
247
+ cwd: tsconfigDir
248
+ }) ?? [];
249
+ }
250
+ });
251
+
252
+ function parseGitignoreFile(gitignorePath, options) {
253
+ return gitignoreParser__default(gitignorePath, options);
254
+ }
255
+ function getGitignoreData(gitignorePath) {
256
+ const gitignoreFileContent = node_fs.readFileSync(gitignorePath, "utf-8");
257
+ const gitignores = parseGitignoreFile(gitignoreFileContent);
258
+ return gitignores;
259
+ }
260
+ const gitignore = (gitignorePath) => ({
261
+ get data() {
262
+ return getGitignoreData(gitignorePath);
263
+ },
264
+ get patterns() {
265
+ return getGitignoreData(gitignorePath).patterns;
266
+ }
267
+ });
268
+
269
+ const dependencyTypeMap = {
270
+ dependency: "dependencies",
271
+ devDependency: "devDependencies",
272
+ peerDependency: "peerDependencies",
273
+ optionalDependency: "optionalDependencies"
274
+ };
275
+
276
+ function isDependencyInPackageJson(options, packageJson) {
277
+ return Boolean(findDependencyInPackageJson(options, packageJson));
278
+ }
279
+ function findDependencyInPackageJson(option, packageJson) {
280
+ const { name, type } = typeof option === "string" ? { name: option, type: void 0 } : option;
281
+ if (!packageJson) return void 0;
282
+ const allowedTypes = typeof type === "string" ? {
283
+ [type]: true
284
+ } : type ?? {
285
+ dependency: true,
286
+ devDependency: true
287
+ };
288
+ const allowedDependencyTypes = getAllowedDependencyTypeList(allowedTypes);
289
+ const matches = allowedDependencyTypes.map((type2) => {
290
+ return getPackageJsonDependencyItem({ name, type: type2 }, packageJson);
291
+ }).filter(notFalsy);
292
+ if (matches.length === 0) return void 0;
293
+ return {
294
+ firstMatch: matches[0],
295
+ matches
296
+ };
297
+ }
298
+ function getPackageJsonDependencyItem({
299
+ name,
300
+ type
301
+ }, packageJson) {
302
+ if (!packageJson) return void 0;
303
+ const dependencyMap = getPackageJsonDependencyMap(type, packageJson);
304
+ const version = dependencyMap?.[name];
305
+ if (version === void 0) return void 0;
306
+ return {
307
+ name,
308
+ version,
309
+ type
310
+ };
311
+ }
312
+ function getAllowedDependencyTypeList(selected) {
313
+ return Object.keys(dependencyTypeMap).filter(
314
+ (key) => selected[key]
315
+ );
316
+ }
317
+ function getPackageJsonDependencyMap(type, packageJson) {
318
+ return packageJson[dependencyTypeMap[type]];
319
+ }
320
+
321
+ function getWorkspaceFolder(options) {
322
+ const {
323
+ cwd = process__default.cwd(),
324
+ fallbackToGitRoot = true,
325
+ throwIfNotFound = true
326
+ } = options ?? {};
327
+ const getFolder = fallbackToGitRoot ? WST__namespace.findProjectRoot : WST__namespace.getWorkspaceManagerRoot;
328
+ const folder = getFolder(cwd);
329
+ if (folder === void 0 && throwIfNotFound) {
330
+ throw new Error(`Could not find workspace folder`);
331
+ }
332
+ return folder;
333
+ }
334
+
335
+ function getPackageFolder(options) {
336
+ return WST__namespace.findPackageRoot(options?.cwd ?? process__default.cwd());
337
+ }
338
+
339
+ function getPackageInfo(options) {
340
+ const packageDir = getPackageFolder(options);
341
+ return readPackageInfo({ packageDir });
342
+ }
343
+ function readPackageInfo({
344
+ packageDir
345
+ }) {
346
+ const packageJsonPath = path__default.join(packageDir, "package.json");
347
+ const packageJson = JSON.parse(
348
+ node_fs.readFileSync(packageJsonPath, "utf-8")
349
+ );
350
+ return {
351
+ name: packageJson.name,
352
+ path: packageJsonPath,
353
+ dirpath: packageDir,
354
+ packageJson
355
+ };
356
+ }
357
+
358
+ function getWorkspaceProjectInfo(options) {
359
+ try {
360
+ const workspaceDir = getWorkspaceFolder(options);
361
+ return readPackageInfo({ packageDir: workspaceDir });
362
+ } catch (e) {
363
+ console.error(e);
364
+ throw new Error("Root workspace not found");
365
+ }
366
+ }
367
+
368
+ function getWorkspacePackageInfoList(options) {
369
+ const { workspaceDir, resolveWstList } = common(options);
370
+ const wstList = WST__namespace.getWorkspaceInfos(workspaceDir);
371
+ return resolveWstList(wstList);
372
+ }
373
+ function common(options) {
374
+ const { cwd, includeRoot: includeWorkspace } = options ?? {};
375
+ const workspaceDir = getWorkspaceFolder({ cwd });
376
+ function resolveWstList(list) {
377
+ if (!workspaceDir || !list) return [];
378
+ if (includeWorkspace) return [getWorkspaceProjectInfo(), ...list];
379
+ return list;
380
+ }
381
+ return {
382
+ workspaceDir,
383
+ includeWorkspace,
384
+ resolveWstList
385
+ };
386
+ }
387
+
388
+ function getWorkspacePackageInfoMap(options) {
389
+ const workspaceInfo = getWorkspacePackageInfoList(options);
390
+ const entries = workspaceInfo.map((info) => [info.name, info]);
391
+ return Object.fromEntries(entries);
392
+ }
393
+
394
+ function getProjectInfoByName(name, options) {
395
+ const { cwd } = options ?? {};
396
+ return getWorkspacePackageInfoMap({ cwd })[name];
397
+ }
398
+
399
+ function getGitRootFolder(options) {
400
+ const { cwd = process__default.cwd(), throwIfNotFound = true } = options ?? {};
401
+ const { stdout } = execa.execaSync("git", ["rev-parse", "--show-toplevel"], {
402
+ cwd,
403
+ reject: false
404
+ });
405
+ if (!stdout) {
406
+ if (throwIfNotFound) {
407
+ throw new Error(`Directory "${cwd}" is not in a git repository`);
408
+ }
409
+ return void 0;
410
+ }
411
+ return path__default$1.normalize(stdout);
412
+ }
413
+
414
+ function getProjectInfo(folder, options) {
415
+ if (isWorkspaceFolderTypeOption(folder)) {
416
+ return getWorkspaceProjectInfo(
417
+ parseWorkspaceFolderTypeOptions(folder, options)
418
+ );
419
+ }
420
+ if (folder === "<package_folder>") {
421
+ return getPackageInfo(options);
422
+ }
423
+ if (folder === "<gitroot_folder>") {
424
+ return readPackageInfo({ packageDir: getGitRootFolder(options) });
425
+ }
426
+ return getProjectInfoByName(folder.packageName, options);
427
+ }
428
+ function isWorkspaceFolderTypeOption(option) {
429
+ return Boolean(
430
+ option === "<workspace_folder>" || typeof option === "object" && "<workspace_folder>" in option
431
+ );
432
+ }
433
+ function parseWorkspaceFolderTypeOptions(option, defaultOptions) {
434
+ if (typeof option === "string") {
435
+ return defaultOptions ?? {};
436
+ }
437
+ return { ...defaultOptions, ...option["<workspace_folder>"] };
438
+ }
439
+
440
+ const project = (...args) => {
441
+ const [source, projectOptions] = args;
442
+ const { packageJson, packageJsonPath, packageName, projectDir } = info();
443
+ const {
444
+ findPackageManager: findPackageManager2,
445
+ detectPackageManagers,
446
+ detectLockfilePackageManagers,
447
+ detectGlobalPackageManagers,
448
+ globalVersions,
449
+ filterPackageManagers,
450
+ mapPackageManagers
451
+ } = definePackageManagerClient({ cwd: projectDir });
452
+ return {
453
+ packageJson,
454
+ packageJsonPath,
455
+ packageName,
456
+ projectDir,
457
+ findPackageManager: findPackageManager2,
458
+ detectPackageManagers,
459
+ detectGlobalPackageManagers,
460
+ detectLockfilePackageManagers,
461
+ globalVersions,
462
+ mapPackageManagers,
463
+ tsconfig: tsconfig(projectDir ?? ""),
464
+ gitignore: gitignore(path__default$1.join(projectDir ?? "", ".gitignore")),
465
+ filterPackageManagers,
466
+ getPackageJson: () => get("packageJson"),
467
+ findDependencyInPackageJson: (options) => findDependencyInPackageJson(options, get("packageJson")),
468
+ isDependencyInPackageJson: (options) => isDependencyInPackageJson(options, get("packageJson"))
469
+ };
470
+ function info() {
471
+ const {
472
+ packageJson: packageJson2,
473
+ name: packageName2,
474
+ dirpath: projectDir2,
475
+ path: packageJsonPath2
476
+ } = getProjectInfo(source, projectOptions) ?? {};
477
+ return {
478
+ packageJson: packageJson2,
479
+ packageJsonPath: packageJsonPath2,
480
+ packageName: packageName2,
481
+ projectDir: projectDir2
482
+ };
483
+ }
484
+ function get(key) {
485
+ return info()[key];
486
+ }
487
+ };
488
+
489
+ function getWorkspacePackageNames(options) {
490
+ return getWorkspacePackageInfoList(options).map((e) => e.name);
491
+ }
492
+
493
+ const workspace = {
494
+ packageNames: getWorkspacePackageNames,
495
+ packageGraph: getWorkspacePackageInfoMap,
496
+ packageList: getWorkspacePackageInfoList,
497
+ workspaceRootDir: getWorkspaceFolder,
498
+ getProject: project
499
+ };
500
+
501
+ function importer(imports, options) {
502
+ const { install: defaultInstall = true, installer } = options ?? {};
503
+ return Promise.all(
504
+ imports.map(async (e) => {
505
+ const importOpt = resolveImportOption(e);
506
+ const shouldInstall = importOpt.install ?? defaultInstall;
507
+ if (shouldInstall && importOpt.name) {
508
+ await installImport(importOpt.name, importOpt, installer);
509
+ }
510
+ const m = await importOpt.import();
511
+ return resolveModule(m);
512
+ })
513
+ );
514
+ }
515
+ const definePackage = (option) => {
516
+ const { name, ...rest } = typeof option === "string" ? { name: option } : option;
517
+ return {
518
+ name,
519
+ import: () => import(name),
520
+ ...rest
521
+ };
522
+ };
523
+ function resolveImportOption(option) {
524
+ if (typeof option === "function") {
525
+ return {
526
+ import: option
527
+ };
528
+ }
529
+ if (option instanceof Promise) {
530
+ return {
531
+ import: () => option
532
+ };
533
+ }
534
+ return option;
535
+ }
536
+ async function installImport(packageName, options, installer) {
537
+ if (!packageName) return;
538
+ const { checkExists } = options ?? {};
539
+ if (checkExists && isPackageDependency(packageName)) return;
540
+ const installerFn = installer ?? (await workspace.getProject("<package_folder>").findPackageManager()).installPackage;
541
+ await installerFn(packageName, options);
542
+ }
543
+
544
+ const importMap = async (importMap2, options) => {
545
+ const keys = Object.keys(importMap2);
546
+ const imported = await importer(
547
+ keys.map((key) => importMap2[key]),
548
+ options
549
+ );
550
+ return Object.fromEntries(
551
+ keys.map((key, index) => [key, imported[index]])
552
+ );
553
+ };
554
+
555
+ function definePackageManager(config, options) {
556
+ const { cwd: defaultCwd } = options ?? {};
557
+ const { command, args: agentArgs, options: agentOptions } = config;
558
+ const findLockfilePath = asyncCacheFn.asyncCacheFn(async (options2) => {
559
+ const { cwd = defaultCwd } = options2 ?? {};
560
+ const lockfiles = toArray(config.meta.lockfile);
561
+ return await findUp.findUp(lockfiles, { cwd });
562
+ });
563
+ const installPackage = async (packageName, options2) => {
564
+ const install = agentArgs.install;
565
+ const { dev, preferOffline } = select(
566
+ install.options,
567
+ {
568
+ preferOffline: true,
569
+ cwd: defaultCwd,
570
+ ...options2
571
+ });
572
+ const packageNames = toArray(packageName);
573
+ try {
574
+ await $$({
575
+ command,
576
+ args: [install.command, dev, preferOffline, ...packageNames],
577
+ cwd: defaultCwd,
578
+ ...options2
579
+ });
580
+ } catch (error) {
581
+ throw new Error(`Failed to install: ${packageNames.join(", ")}`, {
582
+ cause: error
583
+ });
584
+ }
585
+ };
586
+ const uninstallPackage = async (packageName, options2) => {
587
+ const uninstall = agentArgs.uninstall;
588
+ const cwd = options2?.cwd ?? defaultCwd;
589
+ const { packageJson } = getPackageInfo({ cwd });
590
+ const installed = toArray(packageName).filter(
591
+ (name) => isDependencyInPackageJson(name, packageJson)
592
+ );
593
+ if (installed.length === 0) return;
594
+ try {
595
+ await $$({
596
+ command,
597
+ args: [uninstall.command, ...installed],
598
+ cwd,
599
+ ...options2
600
+ });
601
+ } catch (error) {
602
+ throw new Error(`Failed to uninstall: ${installed.join(", ")}`, {
603
+ cause: error
604
+ });
605
+ }
606
+ };
607
+ return {
608
+ id: config.id,
609
+ config,
610
+ findLockfilePath,
611
+ hasLockfile: asyncCacheFn.asyncCacheFn(async (...args) => {
612
+ const lockfilePath = await findLockfilePath.noCache(...args);
613
+ return Boolean(lockfilePath);
614
+ }),
615
+ readLockfile: asyncCacheFn.asyncCacheFn(async (...args) => {
616
+ const lockfilePath = await findLockfilePath.noCache(...args);
617
+ if (!lockfilePath) return void 0;
618
+ return promises.readFile(lockfilePath, "utf8");
619
+ }),
620
+ globalVersion: asyncCacheFn.asyncCacheFn(async (...args) => {
621
+ const [options2] = args;
622
+ try {
623
+ const { stdout } = await $$({
624
+ command,
625
+ args: [agentOptions.version],
626
+ cwd: defaultCwd,
627
+ ...options2
628
+ });
629
+ return `${stdout}`;
630
+ } catch (e) {
631
+ return void 0;
632
+ }
633
+ }),
634
+ definePackage,
635
+ installPackage,
636
+ uninstallPackage,
637
+ defineImportMap(imports, options2) {
638
+ const { install = true } = options2 ?? {};
639
+ return importMap(imports, {
640
+ install,
641
+ installer: installPackage
642
+ });
643
+ }
644
+ };
645
+ }
646
+ async function $$(options) {
647
+ const { command, args = [], silent = true, cwd, shellOptions } = options;
648
+ return execa.execa(command, args.filter(notFalsy), {
649
+ cwd,
650
+ ...shellOptions,
651
+ // `pipe` keeps output off the console while still capturing it: a failed
652
+ // command can report why it failed, and `globalVersion` can read stdout.
653
+ // `ignore` discards the reason along with the output.
654
+ stdio: silent ? "pipe" : "inherit"
655
+ });
656
+ }
657
+
658
+ function definePackageManagerConfig(config) {
659
+ return config;
660
+ }
661
+
662
+ const bun = definePackageManagerConfig({
663
+ id: "bun",
664
+ name: "Bun",
665
+ command: "bun",
666
+ runner: "bunx",
667
+ meta: {
668
+ lockfile: "bun.lockb"
669
+ },
670
+ args: {
671
+ install: {
672
+ command: "install",
673
+ options: {
674
+ dev: "-D",
675
+ preferOffline: "--prefer-offline"
676
+ }
677
+ },
678
+ uninstall: {
679
+ command: "uninstall"
680
+ }
681
+ },
682
+ options: {
683
+ version: "--version"
684
+ }
685
+ });
686
+
687
+ const npm = definePackageManagerConfig({
688
+ id: "npm",
689
+ name: "NPM",
690
+ command: "npm",
691
+ runner: "npx",
692
+ meta: {
693
+ lockfile: ["package-lock.json", "npm-shrinkwrap.json"]
694
+ },
695
+ args: {
696
+ install: {
697
+ command: "install",
698
+ options: {
699
+ dev: "-D",
700
+ preferOffline: "--prefer-offline"
701
+ }
702
+ },
703
+ uninstall: {
704
+ command: "uninstall"
705
+ }
706
+ },
707
+ options: {
708
+ version: "--version"
709
+ }
710
+ });
711
+
712
+ const pnpm = definePackageManagerConfig({
713
+ id: "pnpm",
714
+ name: "PNPM",
715
+ command: "pnpm",
716
+ runner: "pnpx",
717
+ meta: {
718
+ lockfile: "pnpm-lock.yaml"
719
+ },
720
+ args: {
721
+ install: {
722
+ command: "install",
723
+ options: {
724
+ dev: "-D",
725
+ preferOffline: "--prefer-offline"
726
+ }
727
+ },
728
+ uninstall: {
729
+ command: "remove"
730
+ }
731
+ },
732
+ options: {
733
+ version: "--version"
734
+ }
735
+ });
736
+
737
+ const yarn = definePackageManagerConfig({
738
+ id: "yarn",
739
+ name: "Yarn",
740
+ command: "yarn",
741
+ runner: "yarn dlx",
742
+ meta: {
743
+ lockfile: "yarn.lock"
744
+ },
745
+ args: {
746
+ install: {
747
+ command: "add",
748
+ options: {
749
+ dev: "-D",
750
+ preferOffline: "--prefer-offline"
751
+ }
752
+ },
753
+ uninstall: {
754
+ command: "remove"
755
+ }
756
+ },
757
+ options: {
758
+ version: "--version"
759
+ }
760
+ });
761
+
762
+ async function findPackageManager(packageManagers, options) {
763
+ const packageManager = await findPackageManagerSafely(
764
+ packageManagers,
765
+ options
766
+ );
767
+ invariant(packageManager, "No package manager found");
768
+ return packageManager;
769
+ }
770
+ async function findPackageManagerSafely(packageManagers, options) {
771
+ const [fromLockfile] = await detectLockfilePackageManagers(
772
+ packageManagers,
773
+ options
774
+ );
775
+ if (fromLockfile) return fromLockfile;
776
+ const [fromGlobal] = await detectGlobalPackageManagers(
777
+ packageManagers,
778
+ options
779
+ );
780
+ return fromGlobal;
781
+ }
782
+ async function detectPackageManagers(packageManagers, options) {
783
+ return [
784
+ ...await detectLockfilePackageManagers(packageManagers, options),
785
+ ...await detectGlobalPackageManagers(packageManagers, options)
786
+ ];
787
+ }
788
+ async function detectLockfilePackageManagers(packageManagers, options) {
789
+ return filterPackageManagers(
790
+ packageManagers,
791
+ (packageManager) => packageManager.hasLockfile(options),
792
+ options
793
+ );
794
+ }
795
+ async function detectGlobalPackageManagers(packageManagers, options) {
796
+ return filterPackageManagers(
797
+ packageManagers,
798
+ // Without the `await`, `Boolean` receives a pending promise and is always
799
+ // `true`, so every package manager passes the filter regardless of whether
800
+ // it is actually installed.
801
+ async (packageManager) => Boolean(await packageManager.globalVersion(options)),
802
+ options
803
+ );
804
+ }
805
+ async function getGlobalVersions(packageManagers, options) {
806
+ const entries = await mapPackageManagers(
807
+ packageManagers,
808
+ async (packageManager) => [packageManager.id, await packageManager.globalVersion(options)],
809
+ options
810
+ );
811
+ return Object.fromEntries(entries);
812
+ }
813
+ async function mapPackageManagers(packageManagers, mapFn, options) {
814
+ return Promise.all(
815
+ selectAllowedPackageManagers(packageManagers, options).map(
816
+ (packageManager) => mapFn(packageManager)
817
+ )
818
+ );
819
+ }
820
+ async function filterPackageManagers(packageManagers, filterFn, options) {
821
+ const matches = await mapPackageManagers(
822
+ packageManagers,
823
+ async (packageManager) => await filterFn(packageManager) ? packageManager : void 0,
824
+ options
825
+ );
826
+ return matches.filter(notFalsy);
827
+ }
828
+ function selectAllowedPackageManagers(packageManagers, options) {
829
+ return packageManagers.filter(
830
+ ({ id }) => options?.allowed ? id in options.allowed : true
831
+ );
832
+ }
833
+
834
+ const packageManagerConfigs = [pnpm, yarn, bun, npm];
835
+ function definePackageManagerClient(options) {
836
+ const configs = packageManagerConfigs.map(
837
+ (config) => definePackageManager(config, options)
838
+ );
839
+ return {
840
+ configs,
841
+ findPackageManager: asyncCacheFn.asyncCacheFn(
842
+ async (options2) => await findPackageManager(configs, options2)
843
+ ),
844
+ findPackageManagerSafely: asyncCacheFn.asyncCacheFn(
845
+ async (options2) => await findPackageManagerSafely(configs, options2)
846
+ ),
847
+ detectPackageManagers: asyncCacheFn.asyncCacheFn(
848
+ async (options2) => await detectPackageManagers(configs, options2)
849
+ ),
850
+ detectLockfilePackageManagers: asyncCacheFn.asyncCacheFn(
851
+ async (options2) => detectLockfilePackageManagers(configs, options2)
852
+ ),
853
+ detectGlobalPackageManagers: asyncCacheFn.asyncCacheFn(
854
+ async (options2) => detectGlobalPackageManagers(configs, options2)
855
+ ),
856
+ globalVersions: asyncCacheFn.asyncCacheFn(
857
+ async (options2) => getGlobalVersions(configs, options2)
858
+ ),
859
+ filterPackageManagers: async (filterFn, options2) => filterPackageManagers(configs, filterFn, options2),
860
+ mapPackageManagers: async (mapFn, options2) => mapPackageManagers(configs, mapFn, options2)
861
+ };
862
+ }
863
+
864
+ function isPackageDependency(packageName) {
865
+ return toArray(packageName).every((name) => isDependencyInPackageJson(name));
866
+ }
867
+
868
+ function definePathAliases(aliasDefinitions) {
869
+ const aliasMap = getAliasMap(aliasDefinitions);
870
+ function getFilePath(options, aliases) {
871
+ return getAliasedFilePath(
872
+ { ...aliasMap, ...aliases },
873
+ options
874
+ );
875
+ }
876
+ return {
877
+ aliasDefinitions,
878
+ aliasMap,
879
+ getFilePath
880
+ };
881
+ }
882
+ function getAliasedFilePath(aliasMap, options) {
883
+ const { to, startingFrom, cwd, checkExistence, glob } = typeof options === "string" || Array.isArray(options) ? { to: options } : options;
884
+ const resolveOptions = { cwd, checkExistence, glob, aliasMap };
885
+ try {
886
+ return startingFrom ? resolveRelativePathTo(to, startingFrom, resolveOptions) : resolvePathTo(to, resolveOptions);
887
+ } catch (error) {
888
+ if (checkExistence || glob) return void 0;
889
+ throw error;
890
+ }
891
+ }
892
+ function resolveRelativePathTo(to, from, options) {
893
+ const pathFrom = resolvePathTo(from, options);
894
+ const pathTo = resolvePathTo(to, options);
895
+ return path__default$1.relative(pathFrom, pathTo);
896
+ }
897
+ function resolvePathTo(pathTo, { cwd, checkExistence, glob, aliasMap }) {
898
+ const normalized = normalizePathTo(pathTo, { cwd, aliasMap });
899
+ if (glob) {
900
+ const globPaths = globby.globbySync(normalized, { cwd });
901
+ if (!globPaths[0])
902
+ throw new Error(`No paths found for glob: ${normalized}`);
903
+ return globPaths[0];
904
+ }
905
+ if (!glob && checkExistence && !node_fs.existsSync(normalized))
906
+ throw new Error(`Path does not exist: ${normalized}`);
907
+ return normalized;
908
+ }
909
+ function normalizePathTo(pathTo, options) {
910
+ const { cwd, aliasMap } = options ?? {};
911
+ const aliasedPath = Array.isArray(pathTo) ? path__default$1.join(...pathTo.filter(isNotNull)) : pathTo;
912
+ const baseDir = Array.isArray(pathTo) ? pathTo[0] : findAliasToken(aliasedPath, aliasMap);
913
+ if (baseDir === void 0) return aliasedPath;
914
+ const baseDirPath = executeMapFn(aliasMap, baseDir, [{ cwd }]);
915
+ if (typeof baseDirPath !== "string" || baseDirPath.length === 0) {
916
+ throw new Error(`Path alias resolved to no location: ${baseDir}`);
917
+ }
918
+ return utils.resolveAlias(aliasedPath, { [baseDir]: baseDirPath });
919
+ }
920
+ function findAliasToken(pathTo, aliasMap) {
921
+ return Object.keys(aliasMap ?? {}).filter((alias) => pathTo === alias || pathTo.startsWith(`${alias}/`)).sort((a, b) => b.length - a.length)[0];
922
+ }
923
+ function executeMapFn(map, key, args) {
924
+ if (!map || !key || !(key in map)) return void 0;
925
+ const fnArgs = Array.isArray(args) ? args : [args];
926
+ const resolver = map?.[key];
927
+ return typeof resolver === "function" ? resolver?.(...fnArgs) : resolver;
928
+ }
929
+ function getAliasMap(aliasDefs) {
930
+ return Object.fromEntries(
931
+ Object.entries(aliasDefs).flatMap(([alias, v]) => {
932
+ const { resolve, subpaths = [] } = v;
933
+ return [
934
+ [alias, resolve],
935
+ ...subpaths.map(({ to }) => {
936
+ const subpathAlias = path__default$1.join(alias, to);
937
+ return [
938
+ subpathAlias,
939
+ (opts) => utils.resolveAlias(subpathAlias, { [alias]: resolve(opts) })
940
+ ];
941
+ })
942
+ ];
943
+ })
944
+ );
945
+ }
946
+ function isNotNull(value) {
947
+ return value !== null && value !== void 0;
948
+ }
949
+
950
+ const predefinedPathAliases = {
951
+ "<workspace_folder>": {
952
+ resolve: (opts) => getWorkspaceFolder(opts),
953
+ subpaths: [
954
+ {
955
+ to: "node_modules"
956
+ },
957
+ {
958
+ to: "node_modules/.bin"
959
+ }
960
+ ]
961
+ },
962
+ "<workspace_folder?>": {
963
+ resolve: (opts) => getWorkspaceFolder({ ...opts, fallbackToGitRoot: false }),
964
+ subpaths: [
965
+ {
966
+ to: "node_modules"
967
+ },
968
+ {
969
+ to: "node_modules/.bin"
970
+ }
971
+ ]
972
+ },
973
+ "<package_folder>": {
974
+ resolve: (opts) => getPackageFolder(opts),
975
+ subpaths: [
976
+ {
977
+ to: "node_modules"
978
+ },
979
+ {
980
+ to: "node_modules/.bin"
981
+ },
982
+ {
983
+ to: "src"
984
+ }
985
+ ]
986
+ },
987
+ "<gitroot_folder>": {
988
+ resolve: (opts) => getGitRootFolder(opts),
989
+ subpaths: [
990
+ {
991
+ to: "node_modules"
992
+ },
993
+ {
994
+ to: "node_modules/.bin"
995
+ },
996
+ {
997
+ to: ".vscode"
998
+ }
999
+ ]
1000
+ },
1001
+ "<user_home>": {
1002
+ resolve: () => os__default.homedir(),
1003
+ subpaths: []
1004
+ },
1005
+ "<user_tmpdir>": {
1006
+ resolve: () => os__default.tmpdir(),
1007
+ subpaths: []
1008
+ },
1009
+ "<cwd>": {
1010
+ resolve: () => process__default.cwd(),
1011
+ subpaths: []
1012
+ },
1013
+ "<current_file>": {
1014
+ // resolve: () => fileURLToPath(import.meta.url),
1015
+ resolve: () => _filename({ rootFunctionName: "getFilePath" }) ?? "",
1016
+ subpaths: []
1017
+ },
1018
+ "<current_folder>": {
1019
+ // resolve: () => fileURLToPath(import.meta.url),
1020
+ resolve: () => _dirname({ rootFunctionName: "getFilePath" }) ?? "",
1021
+ subpaths: []
1022
+ }
1023
+ };
1024
+
1025
+ const getPath = definePathAliases(predefinedPathAliases).getFilePath;
1026
+
1027
+ function getFolderByPackageName(name, options) {
1028
+ const infoMap = getWorkspacePackageInfoMap({ ...options, includeRoot: true });
1029
+ const info = infoMap?.[name];
1030
+ return info?.dirpath;
1031
+ }
1032
+
1033
+ const jsonSourceResolvers = {
1034
+ data: (json) => {
1035
+ return {
1036
+ text: () => JSON.stringify(json),
1037
+ data: () => json
1038
+ };
1039
+ },
1040
+ text: (text) => {
1041
+ return {
1042
+ text: () => text,
1043
+ data: () => JSON.parse(text)
1044
+ };
1045
+ },
1046
+ filepath: (filepath) => {
1047
+ const text = node_fs.readFileSync(filepath, "utf-8");
1048
+ return {
1049
+ text: () => text,
1050
+ data: () => JSON.parse(text)
1051
+ };
1052
+ }
1053
+ };
1054
+ function resolveJsonSource(source, as) {
1055
+ const [sourceType, sourceData] = Object.entries(source).find(([_, selected]) => selected !== void 0) ?? [];
1056
+ if (!sourceType || !(sourceType in jsonSourceResolvers) || !sourceData) {
1057
+ throw new Error("Invalid source data");
1058
+ }
1059
+ const sourceTypeResolvers = jsonSourceResolvers[sourceType](
1060
+ sourceData
1061
+ );
1062
+ const resolved = util.morph(sourceTypeResolvers, (key, v) => {
1063
+ try {
1064
+ const value = v();
1065
+ return !as || key === as ? [key, value] : [];
1066
+ } catch (e) {
1067
+ throw new Error(`Failed to resolve ${key} from ${sourceType}`);
1068
+ }
1069
+ });
1070
+ if (as) {
1071
+ return resolved[as];
1072
+ }
1073
+ return resolved;
1074
+ }
1075
+
1076
+ function resolveEditPath(path, options) {
1077
+ const { pathSeparator = "." } = {};
1078
+ const arr = toArray(path);
1079
+ return arr.map((path2) => {
1080
+ if (typeof path2 === "string") {
1081
+ return pathSeparator === false ? path2 : path2.split(pathSeparator);
1082
+ }
1083
+ return path2;
1084
+ }).flat();
1085
+ }
1086
+ function parseJSONCEdits(edits) {
1087
+ if (Array.isArray(edits)) {
1088
+ return edits.map(({ path, ...edit }) => ({
1089
+ path: resolveEditPath(path),
1090
+ ...edit
1091
+ }));
1092
+ }
1093
+ return Object.entries(edits).map(
1094
+ ([path, value]) => ({
1095
+ path: resolveEditPath(path),
1096
+ ...value
1097
+ })
1098
+ );
1099
+ }
1100
+ function modifyJSON({
1101
+ json,
1102
+ edits,
1103
+ defaultEditOptions
1104
+ }) {
1105
+ return checkResult(() => {
1106
+ const text = resolveJsonSource(json, "text");
1107
+ const jsoncEdits = parseJSONCEdits(edits);
1108
+ const editResult = jsoncEdits.flatMap(
1109
+ (edit) => jsoncParser.modify(text, edit.path, edit.value, {
1110
+ ...defaultEditOptions,
1111
+ ...edit.options
1112
+ })
1113
+ );
1114
+ const updated = jsoncParser.applyEdits(text, editResult);
1115
+ return resolveJsonSource({ text: updated });
1116
+ });
1117
+ }
1118
+ function modifyJSONFile(filepath, edits, options) {
1119
+ return checkResult(() => {
1120
+ const { autoCommit = true, defaultEditOptions } = options || {};
1121
+ const { data: json, error } = modifyJSON({
1122
+ json: { filepath },
1123
+ edits,
1124
+ defaultEditOptions
1125
+ });
1126
+ if (error) {
1127
+ throw error;
1128
+ }
1129
+ const commit = () => node_fs.writeFileSync(filepath, json.text);
1130
+ if (autoCommit) {
1131
+ commit();
1132
+ return json;
1133
+ }
1134
+ return {
1135
+ json,
1136
+ commit
1137
+ };
1138
+ });
1139
+ }
1140
+
1141
+ function isStorageValue(input) {
1142
+ return input === null || typeof input === "string" || typeof input === "number" || typeof input === "boolean" || typeof input === "object";
1143
+ }
1144
+
1145
+ const storage = unstorage.createStorage({ driver: defineMemoryDriver__default() });
1146
+ const tempFileSystem = defineFileSystemStorage({
1147
+ base: path.join(os__default.tmpdir(), ".package-manager")
1148
+ });
1149
+ function defineFileSystemEntries(definition) {
1150
+ const fileSystemEntries = Object.entries(definition).map(([k, v]) => {
1151
+ if (v instanceof Function) {
1152
+ const {
1153
+ file,
1154
+ options,
1155
+ serialize = (input) => JSON.stringify(input),
1156
+ deserialize = (input) => {
1157
+ try {
1158
+ return JSON.parse(input);
1159
+ } catch {
1160
+ return input;
1161
+ }
1162
+ }
1163
+ } = v();
1164
+ return {
1165
+ key: k,
1166
+ value: serialize(file),
1167
+ options,
1168
+ serialize,
1169
+ deserialize
1170
+ };
1171
+ }
1172
+ if (isStorageValue(v)) {
1173
+ return {
1174
+ key: k,
1175
+ value: JSON.stringify(v)
1176
+ };
1177
+ }
1178
+ return void 0;
1179
+ }).filter((v) => v !== void 0);
1180
+ const resolved = {
1181
+ definition,
1182
+ fileSystemEntries
1183
+ };
1184
+ return resolved;
1185
+ }
1186
+ function defineFileSystemStorage(options) {
1187
+ const { base: root, initial, ...storageOptions } = options;
1188
+ let initialFileEntriesData = defineFileSystemEntries(initial ?? {});
1189
+ const storage2 = unstorage.createStorage({
1190
+ driver: defineFsLiteDriver__default({ base: root, ...storageOptions })
1191
+ });
1192
+ const fileStorage = {
1193
+ createFile: async (key, data) => {
1194
+ await storage2.setItem(key, data);
1195
+ return {
1196
+ key,
1197
+ filepath: path.join(root, key),
1198
+ get: async () => storage2.getItem(key),
1199
+ update: async (data2) => storage2.setItem(key, data2)
1200
+ };
1201
+ },
1202
+ async getFilePath(key) {
1203
+ return (await this.getFile(key)).filepath;
1204
+ },
1205
+ getFile: async (key) => {
1206
+ const storageData = await storage2.getItem(key);
1207
+ return {
1208
+ key,
1209
+ filepath: path.join(root, key),
1210
+ data: storageData,
1211
+ read: async () => (await storage2.getItemRaw(key))?.toString()
1212
+ };
1213
+ },
1214
+ async readFile(key) {
1215
+ const { read } = await this.getFile(key);
1216
+ const content = await read();
1217
+ return content;
1218
+ },
1219
+ snapshotFs: async (base = root) => {
1220
+ return unstorage.snapshot(storage2, base);
1221
+ },
1222
+ restoreFs: async (snapshot2) => {
1223
+ return unstorage.restoreSnapshot(storage2, snapshot2);
1224
+ },
1225
+ initializeFs: async (override) => {
1226
+ if (override) {
1227
+ initialFileEntriesData = defineFileSystemEntries(override);
1228
+ }
1229
+ await storage2.clear();
1230
+ return storage2.setItems(initialFileEntriesData.fileSystemEntries);
1231
+ },
1232
+ defineFileSystemEntries,
1233
+ removeAllFiles: storage2.clear,
1234
+ async deleteFileSystem() {
1235
+ await this.removeAllFiles();
1236
+ await storage2.unmount(root, true);
1237
+ await promises.rm(root, { recursive: true, force: true });
1238
+ },
1239
+ storage: storage2,
1240
+ meta: {
1241
+ fileEntriesData: initialFileEntriesData
1242
+ }
1243
+ };
1244
+ if (initial) {
1245
+ return {
1246
+ initialize: async () => {
1247
+ await fileStorage.initializeFs(initial);
1248
+ return fileStorage;
1249
+ }
1250
+ };
1251
+ }
1252
+ return fileStorage;
1253
+ }
1254
+
1255
+ exports._dirname = _dirname;
1256
+ exports._filename = _filename;
1257
+ exports.defineFileSystemEntries = defineFileSystemEntries;
1258
+ exports.defineFileSystemStorage = defineFileSystemStorage;
1259
+ exports.definePackage = definePackage;
1260
+ exports.definePackageManagerClient = definePackageManagerClient;
1261
+ exports.definePathAliases = definePathAliases;
1262
+ exports.detectGlobalPackageManagers = detectGlobalPackageManagers;
1263
+ exports.detectLockfilePackageManagers = detectLockfilePackageManagers;
1264
+ exports.detectPackageManagers = detectPackageManagers;
1265
+ exports.filterPackageManagers = filterPackageManagers;
1266
+ exports.findDependencyInPackageJson = findDependencyInPackageJson;
1267
+ exports.findPackageManager = findPackageManager;
1268
+ exports.findPackageManagerSafely = findPackageManagerSafely;
1269
+ exports.findResolvedModulePath = findResolvedModulePath;
1270
+ exports.getAliasMap = getAliasMap;
1271
+ exports.getFolderByPackageName = getFolderByPackageName;
1272
+ exports.getGitRootFolder = getGitRootFolder;
1273
+ exports.getGlobalVersions = getGlobalVersions;
1274
+ exports.getPackageFolder = getPackageFolder;
1275
+ exports.getPath = getPath;
1276
+ exports.getWorkspaceFolder = getWorkspaceFolder;
1277
+ exports.importMap = importMap;
1278
+ exports.importer = importer;
1279
+ exports.isDependencyInPackageJson = isDependencyInPackageJson;
1280
+ exports.isPackageDependency = isPackageDependency;
1281
+ exports.isPackageModuleFound = isPackageModuleFound;
1282
+ exports.mapPackageManagers = mapPackageManagers;
1283
+ exports.modifyJSON = modifyJSON;
1284
+ exports.modifyJSONFile = modifyJSONFile;
1285
+ exports.packageManagerConfigs = packageManagerConfigs;
1286
+ exports.predefinedPathAliases = predefinedPathAliases;
1287
+ exports.project = project;
1288
+ exports.resolveModule = resolveModule;
1289
+ exports.resolveModulePath = resolveModulePath;
1290
+ exports.resolvePackageModulePath = resolvePackageModulePath;
1291
+ exports.storage = storage;
1292
+ exports.tempFileSystem = tempFileSystem;
1293
+ exports.workspace = workspace;