1 | import path from 'path';
|
2 | import { promisify } from 'util';
|
3 | import fs from 'fs';
|
4 | const readFile = promisify(fs.readFile);
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | export const toLowerCase = (str) => str.toLowerCase();
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export const dashToPascalCase = (str) => toLowerCase(str)
|
17 | .split('-')
|
18 | .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
19 | .join('');
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export function sortBy(array, prop) {
|
27 | return array.slice().sort((a, b) => {
|
28 | const nameA = prop(a);
|
29 | const nameB = prop(b);
|
30 | if (nameA < nameB)
|
31 | return -1;
|
32 | if (nameA > nameB)
|
33 | return 1;
|
34 | return 0;
|
35 | });
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | export function normalizePath(str) {
|
43 |
|
44 |
|
45 |
|
46 | if (typeof str !== 'string') {
|
47 | throw new Error(`invalid path to normalize`);
|
48 | }
|
49 | str = str.trim();
|
50 | if (EXTENDED_PATH_REGEX.test(str) || NON_ASCII_REGEX.test(str)) {
|
51 | return str;
|
52 | }
|
53 | str = str.replace(SLASH_REGEX, '/');
|
54 |
|
55 |
|
56 | if (str.charAt(str.length - 1) === '/') {
|
57 | const colonIndex = str.indexOf(':');
|
58 | if (colonIndex > -1) {
|
59 | if (colonIndex < str.length - 2) {
|
60 | str = str.substring(0, str.length - 1);
|
61 | }
|
62 | }
|
63 | else if (str.length > 1) {
|
64 | str = str.substring(0, str.length - 1);
|
65 | }
|
66 | }
|
67 | return str;
|
68 | }
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | export function relativeImport(pathFrom, pathTo, ext) {
|
77 | let relativePath = path.relative(path.dirname(pathFrom), path.dirname(pathTo));
|
78 | if (relativePath === '') {
|
79 | relativePath = '.';
|
80 | }
|
81 | else if (relativePath[0] !== '.') {
|
82 | relativePath = './' + relativePath;
|
83 | }
|
84 | return normalizePath(`${relativePath}/${path.basename(pathTo, ext)}`);
|
85 | }
|
86 |
|
87 |
|
88 |
|
89 |
|
90 |
|
91 | export async function readPackageJson(rootDir) {
|
92 | const pkgJsonPath = path.join(rootDir, 'package.json');
|
93 | let pkgJson;
|
94 | try {
|
95 | pkgJson = await readFile(pkgJsonPath, 'utf8');
|
96 | }
|
97 | catch (e) {
|
98 | throw new Error(`Missing "package.json" file for distribution: ${pkgJsonPath}`);
|
99 | }
|
100 | let pkgData;
|
101 | try {
|
102 | pkgData = JSON.parse(pkgJson);
|
103 | }
|
104 | catch (e) {
|
105 | throw new Error(`Error parsing package.json: ${pkgJsonPath}, ${e}`);
|
106 | }
|
107 | return pkgData;
|
108 | }
|
109 | const EXTENDED_PATH_REGEX = /^\\\\\?\\/;
|
110 | const NON_ASCII_REGEX = /[^\x00-\x80]+/;
|
111 | const SLASH_REGEX = /\\/g;
|