package-management 0.0.0-dev.1

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