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