1 | import { xglobal } from '@polkadot/x-global';
|
2 | import { isFunction } from './is/function.js';
|
3 | const DEDUPE = 'Either remove and explicitly install matching versions or dedupe using your package manager.\nThe following conflicting packages were found:';
|
4 |
|
5 | function getEntry(name) {
|
6 | const _global = xglobal;
|
7 | if (!_global.__polkadotjs) {
|
8 | _global.__polkadotjs = {};
|
9 | }
|
10 | if (!_global.__polkadotjs[name]) {
|
11 | _global.__polkadotjs[name] = [];
|
12 | }
|
13 | return _global.__polkadotjs[name];
|
14 | }
|
15 |
|
16 | function formatDisplay(all, fmt) {
|
17 | let max = 0;
|
18 | for (let i = 0, count = all.length; i < count; i++) {
|
19 | max = Math.max(max, all[i].version.length);
|
20 | }
|
21 | return all
|
22 | .map((d) => `\t${fmt(d.version.padEnd(max), d).join('\t')}`)
|
23 | .join('\n');
|
24 | }
|
25 |
|
26 | function formatInfo(version, { name }) {
|
27 | return [
|
28 | version,
|
29 | name
|
30 | ];
|
31 | }
|
32 |
|
33 | function formatVersion(version, { path, type }) {
|
34 | let extracted;
|
35 | if (path && path.length >= 5) {
|
36 | const nmIndex = path.indexOf('node_modules');
|
37 | extracted = nmIndex === -1
|
38 | ? path
|
39 | : path.substring(nmIndex);
|
40 | }
|
41 | else {
|
42 | extracted = '<unknown>';
|
43 | }
|
44 | return [
|
45 | `${`${type || ''}`.padStart(3)} ${version}`,
|
46 | extracted
|
47 | ];
|
48 | }
|
49 |
|
50 | function getPath(infoPath, pathOrFn) {
|
51 | if (infoPath) {
|
52 | return infoPath;
|
53 | }
|
54 | else if (isFunction(pathOrFn)) {
|
55 | try {
|
56 | return pathOrFn() || '';
|
57 | }
|
58 | catch {
|
59 | return '';
|
60 | }
|
61 | }
|
62 | return pathOrFn || '';
|
63 | }
|
64 |
|
65 | function warn(pre, all, fmt) {
|
66 | console.warn(`${pre}\n${DEDUPE}\n${formatDisplay(all, fmt)}`);
|
67 | }
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | export function detectPackage({ name, path, type, version }, pathOrFn, deps = []) {
|
74 | if (!name.startsWith('@polkadot')) {
|
75 | throw new Error(`Invalid package descriptor ${name}`);
|
76 | }
|
77 | const entry = getEntry(name);
|
78 | entry.push({ path: getPath(path, pathOrFn), type, version });
|
79 | if (entry.length !== 1) {
|
80 | warn(`${name} has multiple versions, ensure that there is only one installed.`, entry, formatVersion);
|
81 | }
|
82 | else {
|
83 | const mismatches = deps.filter((d) => d && d.version !== version);
|
84 | if (mismatches.length) {
|
85 | warn(`${name} requires direct dependencies exactly matching version ${version}.`, mismatches, formatInfo);
|
86 | }
|
87 | }
|
88 | }
|