package-management 0.0.9 → 0.0.10

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