UNPKG

2.59 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { xglobal } from '@polkadot/x-global';
4import { isFunction } from "./is/function.js";
5const DEDUPE = 'Either remove and explicitly install matching versions or dedupe using your package manager.\nThe following conflicting packages were found:';
6/** @internal */
7
8function getEntry(name) {
9 const _global = xglobal;
10
11 if (!_global.__polkadotjs) {
12 _global.__polkadotjs = {};
13 }
14
15 if (!_global.__polkadotjs[name]) {
16 _global.__polkadotjs[name] = [];
17 }
18
19 return _global.__polkadotjs[name];
20}
21/** @internal */
22
23
24function formatDisplay(all, fmt) {
25 let max = 0;
26
27 for (let i = 0; i < all.length; i++) {
28 max = Math.max(max, all[i].version.length);
29 }
30
31 return all.map(d => `\t${fmt(d.version.padEnd(max), d).join('\t')}`).join('\n');
32}
33/** @internal */
34
35
36function formatInfo(version, {
37 name
38}) {
39 return [version, name];
40}
41/** @internal */
42
43
44function formatVersion(version, {
45 path,
46 type
47}) {
48 let extracted;
49
50 if (path && path.length >= 5) {
51 const nmIndex = path.indexOf('node_modules');
52 extracted = nmIndex === -1 ? path : path.substring(nmIndex);
53 } else {
54 extracted = '<unknown>';
55 }
56
57 return [`${`${type || ''}`.padStart(3)} ${version}`, extracted];
58}
59/** @internal */
60
61
62function getPath(infoPath, pathOrFn) {
63 if (infoPath) {
64 return infoPath;
65 } else if (isFunction(pathOrFn)) {
66 try {
67 return pathOrFn() || '';
68 } catch (error) {
69 return '';
70 }
71 }
72
73 return pathOrFn || '';
74}
75/** @internal */
76
77
78function warn(pre, all, fmt) {
79 console.warn(`${pre}\n${DEDUPE}\n${formatDisplay(all, fmt)}`);
80}
81/**
82 * @name detectPackage
83 * @summary Checks that a specific package is only imported once
84 * @description A `@polkadot/*` version detection utility, checking for one occurence of a package in addition to checking for ddependency versions.
85 */
86
87
88export function detectPackage({
89 name,
90 path,
91 type,
92 version
93}, pathOrFn, deps = []) {
94 if (!name.startsWith('@polkadot')) {
95 throw new Error(`Invalid package descriptor ${name}`);
96 }
97
98 const entry = getEntry(name);
99 entry.push({
100 path: getPath(path, pathOrFn),
101 type,
102 version
103 });
104
105 if (entry.length !== 1) {
106 warn(`${name} has multiple versions, ensure that there is only one installed.`, entry, formatVersion);
107 } else {
108 const mismatches = deps.filter(d => d && d.version !== version);
109
110 if (mismatches.length) {
111 warn(`${name} requires direct dependencies exactly matching version ${version}.`, mismatches, formatInfo);
112 }
113 }
114}
\No newline at end of file