package-management 0.0.1 → 0.0.3

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 CHANGED
@@ -1,50 +1,42 @@
1
1
  'use strict';
2
2
 
3
- const installPkg = require('@antfu/install-pkg');
4
- require('node:fs');
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');
5
8
  const execa = require('execa');
6
- const localPkg = require('local-pkg');
7
9
  const asyncCacheFn = require('async-cache-fn');
8
10
  const findUp = require('find-up');
9
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');
10
18
 
11
- async function resolveModule(m) {
12
- const resolved = await m;
13
- return resolved.default || resolved;
14
- }
19
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
15
20
 
16
- function importer(imports, options) {
17
- const { install = true } = options ?? {};
18
- return Promise.all(
19
- imports.map(async (option) => {
20
- if (install && "name" in option) {
21
- await ensurePackage(option.name);
22
- }
23
- const importStatement = getImportStatement(option);
24
- return resolveModule(importStatement);
25
- })
26
- );
27
- }
28
- function getImportStatement(option) {
29
- if (typeof option === "function") {
30
- return option();
31
- }
32
- if (typeof option === "object" && "import" in option && "name" in option) {
33
- return option.import();
21
+ function _interopNamespaceCompat(e) {
22
+ if (e && typeof e === 'object' && 'default' in e) return e;
23
+ const n = Object.create(null);
24
+ if (e) {
25
+ for (const k in e) {
26
+ n[k] = e[k];
27
+ }
34
28
  }
35
- return option;
29
+ n.default = e;
30
+ return n;
36
31
  }
37
32
 
38
- async function importMap(importMap2, options) {
39
- const keys = Object.keys(importMap2);
40
- const imported = await importer(
41
- keys.map((key) => importMap2[key]),
42
- options
43
- );
44
- return Object.fromEntries(
45
- keys.map((key, index) => [key, imported[index]])
46
- );
47
- }
33
+ const ErrorStackParser__default = /*#__PURE__*/_interopDefaultCompat(ErrorStackParser);
34
+ const path__default$1 = /*#__PURE__*/_interopDefaultCompat(path);
35
+ const process__default = /*#__PURE__*/_interopDefaultCompat(process);
36
+ const path__default = /*#__PURE__*/_interopDefaultCompat(path$1);
37
+ const gitignoreParser__default = /*#__PURE__*/_interopDefaultCompat(gitignoreParser);
38
+ const WST__namespace = /*#__PURE__*/_interopNamespaceCompat(WST);
39
+ const os__default = /*#__PURE__*/_interopDefaultCompat(os);
48
40
 
49
41
  const toArray = (data) => Array.isArray(data) ? data : [data];
50
42
  const entriesOf = (o) => Object.entries(o);
@@ -58,29 +50,520 @@ const select = (obj, selection, mode) => {
58
50
  });
59
51
  return fromEntries(filtered);
60
52
  };
53
+ function normalizePath(path$1, option) {
54
+ if (typeof option === "function") {
55
+ return normalizePath(path$1);
56
+ }
57
+ if (option === false) {
58
+ return path$1;
59
+ }
60
+ return path.normalize(path$1);
61
+ }
61
62
  const invariant = (predicate, message) => {
62
63
  if (!predicate) {
63
64
  throw new Error(message);
64
65
  }
65
66
  };
67
+ function getArrayItemAtOffset(arr, index, offset = 0) {
68
+ if (!index || !arr)
69
+ return void 0;
70
+ return arr[index + offset];
71
+ }
72
+ function isMatching(a, b) {
73
+ if (!a || !b)
74
+ return false;
75
+ return a === b;
76
+ }
66
77
 
67
- function isPackageDependency(packageName) {
68
- return toArray(packageName).every((name) => localPkg.isPackageExists(name));
78
+ function findCallerStackFrame(options) {
79
+ return findErrorStackFrame(options, (frame) => frame.isParentOfRootFunction);
80
+ }
81
+ function findErrorStackFrame(options, find) {
82
+ return getErrorStackFrames(options, find)[0];
83
+ }
84
+ function getErrorStackFrames(options, filter) {
85
+ const { error, rootFunctionName, startFrom = "top" } = options;
86
+ const frames = startFrom === "bottom" ? ErrorStackParser__default.parse(error).reverse() : ErrorStackParser__default.parse(error);
87
+ const { parsedFrames } = frames.reduce(
88
+ (acc, frame, index) => {
89
+ const parsed = parseFrame({
90
+ frame,
91
+ index,
92
+ rootFunctionName,
93
+ frames
94
+ });
95
+ const isValid = filter ? filter(parsed) : true;
96
+ if (isValid) {
97
+ acc.parsedFrames.push(parsed);
98
+ }
99
+ return acc;
100
+ },
101
+ { parsedFrames: [] }
102
+ );
103
+ return parsedFrames ?? [];
104
+ }
105
+ function parseFrame(options) {
106
+ const { frame, frames, index, rootFunctionName, cwd, debug } = options ?? {};
107
+ const functionName = parseFunctionName(frame.functionName);
108
+ const isRootFunction = isMatching(functionName, rootFunctionName);
109
+ const beforeFrameFunctionName = parseFunctionName(
110
+ getArrayItemAtOffset(frames, index, -1)?.functionName
111
+ );
112
+ const isParentOfRootFunction = isMatching(
113
+ beforeFrameFunctionName,
114
+ rootFunctionName
115
+ );
116
+ const fileData = frame.fileName ? getFilePathData({ filepath: frame.fileName, cwd }) : void 0;
117
+ const { isFileInCwd: isFrameInScope, ...restFileData } = fileData ?? {};
118
+ const data = {
119
+ ...restFileData,
120
+ functionName,
121
+ source: frame.source,
122
+ sourceFunctionName: frame.functionName,
123
+ isFrameInScope,
124
+ place: placeFormatter(index, frames?.length),
125
+ isRootFunction,
126
+ isParentOfRootFunction,
127
+ rootFunctionName
128
+ };
129
+ debug && console.log(data);
130
+ return data;
131
+ }
132
+ function getFilePathData({
133
+ filepath,
134
+ cwd
135
+ }) {
136
+ const workingDir = cwd ?? process__default.cwd();
137
+ const filePath = path.normalize(filepath);
138
+ const fileBasename = path.basename(filePath);
139
+ const dirPath = path.dirname(filePath);
140
+ const dirBasename = path.basename(dirPath);
141
+ const relativeFilePath = path.relative(workingDir, filePath);
142
+ const relativeDirPath = path.dirname(relativeFilePath);
143
+ const isFileInCwd = filePath.startsWith(workingDir);
144
+ return {
145
+ filePath,
146
+ dirPath,
147
+ relativeFilePath,
148
+ relativeDirPath,
149
+ fileBasename,
150
+ dirBasename,
151
+ isFileInCwd
152
+ };
153
+ }
154
+ function parseFunctionName(functionName) {
155
+ if (!functionName)
156
+ return void 0;
157
+ return removeStart(functionName, "Module.");
158
+ }
159
+ function removeStart(input, value) {
160
+ return input.startsWith(value) ? input.slice(value.length) : input;
161
+ }
162
+ function placeFormatter(index, total) {
163
+ if (!index || !total)
164
+ return void 0;
165
+ return [index, total].join("/");
166
+ }
167
+
168
+ const _filename = (options) => {
169
+ const { filePath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
170
+ return filePath;
171
+ };
172
+ const _dirname = (options) => {
173
+ const { dirPath } = findCallerStackFrame({ error: new Error(), ...options }) ?? {};
174
+ return dirPath;
175
+ };
176
+
177
+ async function resolveModule(module) {
178
+ const resolved = await module;
179
+ return resolved.default || resolved;
180
+ }
181
+ function isPackageModuleFound(name, options) {
182
+ return Boolean(resolvePackageModulePath(name, options));
183
+ }
184
+ function resolvePackageModulePath(name, options) {
185
+ const resolvedPath = findResolvedModulePath(
186
+ [`${name}/package.json`, name],
187
+ options
188
+ );
189
+ if (resolvedPath === void 0) {
190
+ console.error(`Could not resolve package ${name}`);
191
+ return void 0;
192
+ }
193
+ return resolvedPath;
194
+ }
195
+ function findResolvedModulePath(paths, options) {
196
+ for (const path of paths) {
197
+ const resolvedPath = resolveModulePath(path, options);
198
+ if (resolvedPath === void 0)
199
+ continue;
200
+ return resolvedPath;
201
+ }
69
202
  }
203
+ function resolveModulePath(modulePath, options) {
204
+ const { normalize = true, paths, ...rest } = options ?? {};
205
+ try {
206
+ const path = normalizePath(modulePath, normalize);
207
+ return mlly.resolvePathSync(path, {
208
+ url: paths,
209
+ ...rest
210
+ });
211
+ } catch (e) {
212
+ return void 0;
213
+ }
214
+ }
215
+
216
+ const tsconfig = (tsconfigDir) => ({
217
+ get paths() {
218
+ return globby.globbySync(["tsconfig.json", "tsconfig.*.json"], {
219
+ cwd: tsconfigDir
220
+ }) ?? [];
221
+ }
222
+ });
70
223
 
71
- async function ensurePackage(name, options) {
72
- if (isPackageDependency(name))
224
+ function parseGitignoreFile(gitignorePath, options) {
225
+ return gitignoreParser__default(gitignorePath, options);
226
+ }
227
+ function getGitignoreData(gitignorePath) {
228
+ const gitignoreFileContent = node_fs.readFileSync(gitignorePath, "utf-8");
229
+ const gitignores = parseGitignoreFile(gitignoreFileContent);
230
+ return gitignores;
231
+ }
232
+ const gitignore = (gitignorePath) => ({
233
+ get data() {
234
+ return getGitignoreData(gitignorePath);
235
+ },
236
+ get patterns() {
237
+ return getGitignoreData(gitignorePath).patterns;
238
+ }
239
+ });
240
+
241
+ const dependencyTypeMap = {
242
+ dependency: "dependencies",
243
+ devDependency: "devDependencies",
244
+ peerDependency: "peerDependencies",
245
+ optionalDependency: "optionalDependencies"
246
+ };
247
+
248
+ function isDependencyInPackageJson(options, packageJson) {
249
+ return Boolean(findDependencyInPackageJson(options, packageJson));
250
+ }
251
+ function findDependencyInPackageJson(option, packageJson) {
252
+ const { name, type } = typeof option === "string" ? { name: option, type: void 0 } : option;
253
+ if (!packageJson)
254
+ return void 0;
255
+ const allowedTypes = typeof type === "string" ? {
256
+ [type]: true
257
+ } : type ?? {
258
+ dependency: true,
259
+ devDependency: true
260
+ };
261
+ const allowedDependencyTypes = getAllowedDependencyTypeList(allowedTypes);
262
+ const matches = allowedDependencyTypes.map((type2) => {
263
+ return getPackageJsonDependencyItem({ name, type: type2 }, packageJson);
264
+ }).filter(notFalsy);
265
+ if (matches.length === 0)
266
+ return void 0;
267
+ return {
268
+ firstMatch: matches[0],
269
+ matches
270
+ };
271
+ }
272
+ function getPackageJsonDependencyItem({
273
+ name,
274
+ type
275
+ }, packageJson) {
276
+ if (!packageJson)
277
+ return void 0;
278
+ const dependencyMap = getPackageJsonDependencyMap(type, packageJson);
279
+ const version = dependencyMap?.[name];
280
+ if (version === void 0)
281
+ return void 0;
282
+ return {
283
+ name,
284
+ version,
285
+ type
286
+ };
287
+ }
288
+ function getAllowedDependencyTypeList(selected) {
289
+ return Object.keys(dependencyTypeMap).filter(
290
+ (key) => selected[key]
291
+ );
292
+ }
293
+ function getPackageJsonDependencyMap(type, packageJson) {
294
+ return packageJson[dependencyTypeMap[type]];
295
+ }
296
+
297
+ function getWorkspaceFolder(options) {
298
+ const {
299
+ cwd = process__default.cwd(),
300
+ fallbackToGitRoot = true,
301
+ throwIfNotFound = true
302
+ } = options ?? {};
303
+ const getFolder = fallbackToGitRoot ? WST__namespace.getWorkspaceRoot : WST__namespace.getWorkspaceRoot;
304
+ const folder = getFolder(cwd);
305
+ if (folder === void 0 && throwIfNotFound) {
306
+ throw new Error(`Could not find workspace folder`);
307
+ }
308
+ return folder;
309
+ }
310
+ getWorkspaceFolder();
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)
73
501
  return;
74
- await installPkg.installPackage(name, options);
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);
75
507
  }
76
508
 
77
- function definePackageManager(config) {
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 ?? {};
78
522
  const { command, args: agentArgs, options: agentOptions } = config;
79
- const findLockfilePath = asyncCacheFn.asyncCacheFn(async (options) => {
80
- const { cwd } = options ?? {};
523
+ const findLockfilePath = asyncCacheFn.asyncCacheFn(async (options2) => {
524
+ const { cwd = defaultCwd } = options2 ?? {};
81
525
  const lockfiles = toArray(config.meta.lockfile);
82
526
  return await findUp.findUp(lockfiles, { cwd });
83
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
+ };
84
567
  return {
85
568
  id: config.id,
86
569
  config,
@@ -96,50 +579,27 @@ function definePackageManager(config) {
96
579
  return promises.readFile(lockfilePath, "utf8");
97
580
  }),
98
581
  globalVersion: asyncCacheFn.asyncCacheFn(async (...args) => {
99
- const [options] = args;
582
+ const [options2] = args;
100
583
  try {
101
584
  const { stdout } = await $$({
102
585
  command,
103
586
  args: [agentOptions.version],
104
- ...options
587
+ cwd: defaultCwd,
588
+ ...options2
105
589
  });
106
590
  return `${stdout}`;
107
591
  } catch (e) {
108
592
  return void 0;
109
593
  }
110
594
  }),
111
- installPackage: async (packageName, options) => {
112
- const install = agentArgs.install;
113
- const { isDevDependency, preferOffline } = select(
114
- install.options,
115
- options ?? {},
116
- "pick"
117
- );
118
- const packageNames = toArray(packageName);
119
- try {
120
- await $$({
121
- command,
122
- args: [
123
- install.command,
124
- isDevDependency,
125
- preferOffline,
126
- ...packageNames
127
- ],
128
- ...options
129
- });
130
- } catch (e) {
131
- throw new Error(`Failed to install: ${packageNames.join(", ")}`);
132
- }
133
- },
134
- uninstallPackage: async (packageName, options) => {
135
- const uninstall = agentArgs.uninstall;
136
- if (!isPackageDependency(packageName))
137
- return;
138
- await $$({
139
- command,
140
- args: [uninstall.command, ...toArray(packageName)],
141
- ...options
142
- }).catch((e) => {
595
+ definePackage,
596
+ installPackage,
597
+ uninstallPackage,
598
+ defineImportMap(imports, options2) {
599
+ const { install = true } = options2 ?? {};
600
+ return importMap(imports, {
601
+ install,
602
+ installer: installPackage
143
603
  });
144
604
  }
145
605
  };
@@ -153,7 +613,11 @@ async function $$(options) {
153
613
  });
154
614
  }
155
615
 
156
- const bun = definePackageManager({
616
+ function definePackageManagerConfig(config) {
617
+ return config;
618
+ }
619
+
620
+ const bun = definePackageManagerConfig({
157
621
  id: "bun",
158
622
  name: "Bun",
159
623
  command: "bun",
@@ -165,7 +629,7 @@ const bun = definePackageManager({
165
629
  install: {
166
630
  command: "install",
167
631
  options: {
168
- isDevDependency: "-D",
632
+ dev: "-D",
169
633
  preferOffline: "--prefer-offline"
170
634
  }
171
635
  },
@@ -178,7 +642,7 @@ const bun = definePackageManager({
178
642
  }
179
643
  });
180
644
 
181
- const npm = definePackageManager({
645
+ const npm = definePackageManagerConfig({
182
646
  id: "npm",
183
647
  name: "NPM",
184
648
  command: "npm",
@@ -190,7 +654,7 @@ const npm = definePackageManager({
190
654
  install: {
191
655
  command: "install",
192
656
  options: {
193
- isDevDependency: "-D",
657
+ dev: "-D",
194
658
  preferOffline: "--prefer-offline"
195
659
  }
196
660
  },
@@ -203,7 +667,7 @@ const npm = definePackageManager({
203
667
  }
204
668
  });
205
669
 
206
- const pnpm = definePackageManager({
670
+ const pnpm = definePackageManagerConfig({
207
671
  id: "pnpm",
208
672
  name: "PNPM",
209
673
  command: "pnpm",
@@ -215,12 +679,12 @@ const pnpm = definePackageManager({
215
679
  install: {
216
680
  command: "install",
217
681
  options: {
218
- isDevDependency: "-D",
682
+ dev: "-D",
219
683
  preferOffline: "--prefer-offline"
220
684
  }
221
685
  },
222
686
  uninstall: {
223
- command: "uninstall"
687
+ command: "remove"
224
688
  }
225
689
  },
226
690
  options: {
@@ -228,7 +692,7 @@ const pnpm = definePackageManager({
228
692
  }
229
693
  });
230
694
 
231
- const yarn = definePackageManager({
695
+ const yarn = definePackageManagerConfig({
232
696
  id: "yarn",
233
697
  name: "Yarn",
234
698
  command: "yarn",
@@ -240,7 +704,7 @@ const yarn = definePackageManager({
240
704
  install: {
241
705
  command: "add",
242
706
  options: {
243
- isDevDependency: "-D",
707
+ dev: "-D",
244
708
  preferOffline: "--prefer-offline"
245
709
  }
246
710
  },
@@ -253,62 +717,289 @@ const yarn = definePackageManager({
253
717
  }
254
718
  });
255
719
 
256
- const packageManagers = fromEntries(
257
- [pnpm, yarn, bun, npm].map((e) => [e.id, e])
258
- );
259
-
260
- async function findPackageManager(options) {
720
+ async function findPackageManager(packageManagers, options) {
261
721
  const { ...rest } = options ?? {};
262
- const packageManager = await findPackageManagerSafely(rest);
722
+ const packageManager = await findPackageManagerSafely(packageManagers, rest);
263
723
  invariant(packageManager, "No package manager found");
264
724
  return packageManager;
265
725
  }
266
- async function findPackageManagerSafely(options) {
267
- const lockfilePm = (await detectLockfilePackageManagers(options))[0];
726
+ async function findPackageManagerSafely(packageManagers, options) {
727
+ const lockfilePm = (await detectLockfilePackageManagers(packageManagers, options))[0];
268
728
  if (lockfilePm) {
269
729
  return lockfilePm;
270
730
  }
271
- const globalPm = (await detectGlobalPackageManagers(options))[0];
731
+ const globalPm = (await detectGlobalPackageManagers(packageManagers, options))[0];
272
732
  return globalPm;
273
733
  }
274
- async function detectPackageManagers(options) {
734
+ async function detectPackageManagers(packageManagers, options) {
275
735
  return [
276
- ...await detectLockfilePackageManagers(options),
277
- ...await detectGlobalPackageManagers(options)
736
+ ...await detectLockfilePackageManagers(packageManagers, options),
737
+ ...await detectGlobalPackageManagers(packageManagers, options)
278
738
  ];
279
739
  }
280
- async function detectLockfilePackageManagers(options) {
281
- ({ cwd: options?.cwd });
282
- return filterPackageManagers((e) => e.hasLockfile(options), options);
283
- }
284
- async function detectGlobalPackageManagers(options) {
285
- return filterPackageManagers(async (e) => e.globalVersion(options), options);
740
+ async function detectLockfilePackageManagers(packageManagers, options) {
741
+ return filterPackageManagers(
742
+ packageManagers,
743
+ (e) => e.hasLockfile(options),
744
+ options
745
+ );
286
746
  }
287
- async function filterPackageManagers(filterFn, options) {
288
- const allowedPackageManagers = Object.entries(packageManagers).filter(
289
- ([key]) => {
290
- if (!options?.allowed)
291
- return true;
292
- return key in options.allowed;
293
- }
747
+ async function detectGlobalPackageManagers(packageManagers, options) {
748
+ return filterPackageManagers(
749
+ packageManagers,
750
+ async (e) => Boolean(e.globalVersion(options)),
751
+ options
294
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
+ });
295
760
  return (await Promise.all(
296
- allowedPackageManagers.map(async ([key, pm]) => {
761
+ allowedPackageManagers.map(async (pm) => {
297
762
  const valid = await filterFn(pm);
298
763
  return valid ? pm : void 0;
299
764
  })
300
765
  )).filter(notFalsy);
301
766
  }
302
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
+ getPath(["<workspace_folder>/node_modules/.bin"]);
959
+
960
+ function getFolderByPackageName(name, options) {
961
+ const infoMap = getWorkspacePackageInfoMap({ ...options, includeRoot: true });
962
+ const info = infoMap?.[name];
963
+ return info?.dirpath;
964
+ }
965
+
966
+ function getGitRootFolder(options) {
967
+ const output = execa.execaSync(`git rev-parse --show-toplevel`, {
968
+ ...options,
969
+ reject: false
970
+ });
971
+ if (!output.stdout) {
972
+ console.warn(`Directory "${output.cwd}" is not in a git repository`);
973
+ return void 0;
974
+ }
975
+ return path__default$1.normalize(output.stdout);
976
+ }
977
+
978
+ exports._dirname = _dirname;
979
+ exports._filename = _filename;
980
+ exports.definePackage = definePackage;
981
+ exports.definePackageManagerClient = definePackageManagerClient;
982
+ exports.definePathAliases = definePathAliases;
303
983
  exports.detectGlobalPackageManagers = detectGlobalPackageManagers;
304
984
  exports.detectLockfilePackageManagers = detectLockfilePackageManagers;
305
985
  exports.detectPackageManagers = detectPackageManagers;
306
- exports.ensurePackage = ensurePackage;
307
986
  exports.filterPackageManagers = filterPackageManagers;
308
987
  exports.findPackageManager = findPackageManager;
309
988
  exports.findPackageManagerSafely = findPackageManagerSafely;
989
+ exports.findResolvedModulePath = findResolvedModulePath;
990
+ exports.getAliasMap = getAliasMap;
991
+ exports.getFolderByPackageName = getFolderByPackageName;
992
+ exports.getGitRootFolder = getGitRootFolder;
993
+ exports.getPackageFolder = getPackageFolder;
994
+ exports.getPath = getPath;
995
+ exports.getWorkspaceFolder = getWorkspaceFolder;
310
996
  exports.importMap = importMap;
311
997
  exports.importer = importer;
312
998
  exports.isPackageDependency = isPackageDependency;
313
- exports.packageManagers = packageManagers;
999
+ exports.isPackageModuleFound = isPackageModuleFound;
1000
+ exports.packageManagerConfigs = packageManagerConfigs;
1001
+ exports.predefinedPathAliases = predefinedPathAliases;
314
1002
  exports.resolveModule = resolveModule;
1003
+ exports.resolveModulePath = resolveModulePath;
1004
+ exports.resolvePackageModulePath = resolvePackageModulePath;
1005
+ exports.workspace = workspace;