@modern-js/utils 1.2.1 → 1.2.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,131 +0,0 @@
1
- /* eslint-disable no-param-reassign */
2
- /* eslint-disable max-statements */
3
- /**
4
- * Copyright (c) 2015-present, Facebook, Inc.
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE file at
8
- * https://github.com/facebook/create-react-app/blob/master/LICENSE
9
- */
10
-
11
- // Modified by Chao Xu (xuchaobei)
12
-
13
- import webpack, { StatsCompilation } from 'webpack';
14
-
15
- const friendlySyntaxErrorLabel = 'Syntax error:';
16
-
17
- function isLikelyASyntaxError(message: string) {
18
- return message.includes(friendlySyntaxErrorLabel);
19
- }
20
-
21
- // Cleans up webpack error messages.
22
- function formatMessage(message: webpack.StatsError | string) {
23
- let lines: string[] = [];
24
-
25
- // webpack 5 stats error object
26
- if (typeof message === 'object') {
27
- message = `${(message.moduleName && `${message.moduleName}\n`) as string}${
28
- message.details || message.stack || message.message
29
- }`;
30
- }
31
-
32
- lines = message.split('\n');
33
-
34
- // Strip webpack-added headers off errors/warnings
35
- // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
36
- lines = lines.filter(line => !/Module [A-z ]+\(from/.test(line));
37
-
38
- // Transform parsing error into syntax error
39
- lines = lines.map(line => {
40
- const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
41
- line,
42
- );
43
- if (!parsingError) {
44
- return line;
45
- }
46
- const [, errorLine, errorColumn, errorMessage] = parsingError;
47
- return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
48
- });
49
-
50
- message = lines.join('\n');
51
-
52
- // Smoosh syntax errors (commonly found in CSS)
53
- message = message.replace(
54
- /SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
55
- `${friendlySyntaxErrorLabel} $3 ($1:$2)\n`,
56
- );
57
-
58
- lines = message.split('\n');
59
-
60
- // Remove leading newline
61
- if (lines.length > 2 && lines[1].trim() === '') {
62
- lines.splice(1, 1);
63
- }
64
- // Clean up file name
65
- lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1');
66
-
67
- // Cleans up verbose "module not found" messages for files and packages.
68
- if (lines[1]?.startsWith('Module not found: ')) {
69
- lines = [
70
- lines[0],
71
- lines[1]
72
- .replace('Error: ', '')
73
- .replace('Module not found: Cannot find file:', 'Cannot find file:')
74
- .replace('[CaseSensitivePathsPlugin] ', '')
75
- .replace("Cannot resolve 'file' or 'directory' ", ''),
76
- ];
77
- }
78
-
79
- message = lines.join('\n');
80
- // Internal stacks are generally useless so we strip them... with the
81
- // exception of stacks containing `webpack:` because they're normally
82
- // from user code generated by webpack. For more information see
83
- // https://github.com/facebook/create-react-app/pull/1050
84
- message = message.replace(
85
- /^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
86
- '',
87
- ); // at ... ...:x:y
88
- message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous>
89
- lines = message.split('\n');
90
-
91
- // Remove duplicated newlines
92
- lines = lines.filter(
93
- (line, index, arr) =>
94
- index === 0 ||
95
- line.trim() !== '' ||
96
- line.trim() !== arr[index - 1].trim(),
97
- );
98
-
99
- // Reassemble the message
100
- message = lines.join('\n');
101
- return message.trim();
102
- }
103
-
104
- function formatWebpackMessages(json: StatsCompilation): {
105
- errors: string[];
106
- warnings: string[];
107
- } {
108
- const formattedErrors = json.errors?.map(formatMessage);
109
- const formattedWarnings = json.warnings?.map(formatMessage);
110
-
111
- const result = {
112
- errors: formattedErrors || [],
113
- warnings: formattedWarnings || [],
114
- };
115
-
116
- if (result.errors?.some(isLikelyASyntaxError)) {
117
- // If there are any syntax errors, show just them.
118
- result.errors = result.errors.filter(isLikelyASyntaxError);
119
- }
120
-
121
- // First error is usually it.
122
- if (result.errors.length > 1) {
123
- result.errors.length = 1;
124
- }
125
-
126
- return result;
127
- }
128
-
129
- export { formatWebpackMessages };
130
- /* eslint-enable max-statements */
131
- /* eslint-enable no-param-reassign */
@@ -1,75 +0,0 @@
1
- /**
2
- * Copyright JS Foundation and other contributors.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file at
6
- * https://github.com/jantimon/html-webpack-plugin/blob/main/LICENSE
7
- *
8
- * Modified from https://github.com/jantimon/html-webpack-plugin/blob/2f5de7ab9e8bca60e9e200f2e4b4cfab90db28d4/index.js#L800
9
- */
10
- export type MetaAttributes = { [attributeName: string]: string | boolean };
11
-
12
- export interface MetaOptions {
13
- [name: string]:
14
- | string
15
- | false // name content pair e.g. {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}`
16
- | MetaAttributes; // custom properties e.g. { name:"viewport" content:"width=500, initial-scale=1" }
17
- }
18
-
19
- const tagObjectToString = (tagDefinition: {
20
- tagName: string;
21
- voidTag: boolean;
22
- attributes: MetaAttributes;
23
- innerHTML?: string;
24
- }) => {
25
- const attributes = Object.keys(tagDefinition.attributes || {})
26
- .filter(attributeName => tagDefinition.attributes[attributeName] !== false)
27
- .map(attributeName => {
28
- if (tagDefinition.attributes[attributeName] === true) {
29
- return attributeName;
30
- }
31
- return `${attributeName}="${
32
- tagDefinition.attributes[attributeName] as string
33
- }"`;
34
- });
35
- return `<${[tagDefinition.tagName].concat(attributes).join(' ')}>${
36
- tagDefinition.innerHTML || ''
37
- }${tagDefinition.voidTag ? '' : `</${tagDefinition.tagName}>`}`;
38
- };
39
-
40
- export const generateMetaTags = (metaOptions?: MetaOptions): string => {
41
- if (!metaOptions) {
42
- return '';
43
- }
44
- // Make tags self-closing in case of xhtml
45
- // Turn { "viewport" : "width=500, initial-scale=1" } into
46
- // [{ name:"viewport" content:"width=500, initial-scale=1" }]
47
- const metaTagAttributeObjects = Object.keys(metaOptions)
48
- .map(metaName => {
49
- const metaTagContent = metaOptions[metaName];
50
- return typeof metaTagContent === 'string'
51
- ? {
52
- name: metaName,
53
- content: metaTagContent,
54
- }
55
- : metaTagContent;
56
- })
57
- .filter(attribute => attribute !== false);
58
- // Turn [{ name:"viewport" content:"width=500, initial-scale=1" }] into
59
- // the html-webpack-plugin tag structure
60
- return metaTagAttributeObjects
61
- .map(metaTagAttributes => {
62
- if (metaTagAttributes === false) {
63
- throw new Error('Invalid meta tag');
64
- }
65
- return {
66
- tagName: 'meta',
67
- voidTag: true,
68
- attributes: metaTagAttributes,
69
- };
70
- })
71
- .reduce(
72
- (memo, tagObject) => `${memo}\n${tagObjectToString(tagObject)}`,
73
- '',
74
- );
75
- };
@@ -1,6 +0,0 @@
1
- import { loadConfig } from 'browserslist';
2
-
3
- export const defaults = ['> 0.01%', 'not dead', 'not op_mini all'];
4
-
5
- export const getBrowserslist = (appDirectory: string) =>
6
- loadConfig({ path: appDirectory }) || defaults;
@@ -1,30 +0,0 @@
1
- import { isProd, isDev, isTest } from './is';
2
-
3
- /**
4
- * Generate cache identifier from some packages and config files.
5
- */
6
- export function getCacheIdentifier(
7
- packages: {
8
- name: string;
9
- version: string;
10
- }[],
11
- _files?: string[],
12
- ) {
13
- /* eslint-disable no-nested-ternary */
14
- let cacheIdentifier = isProd()
15
- ? 'production'
16
- : isDev()
17
- ? 'development'
18
- : isTest()
19
- ? 'test'
20
- : '';
21
- /* eslint-enable no-nested-ternary */
22
-
23
- for (const { name, version } of packages) {
24
- cacheIdentifier += `:${name}@${version}`;
25
- }
26
-
27
- // TODO: config file hash
28
-
29
- return cacheIdentifier;
30
- }
@@ -1,37 +0,0 @@
1
- import { isPlainObject } from './is';
2
- import { MAIN_ENTRY_NAME } from './constants';
3
-
4
- export const getEntryOptions = <T>(
5
- name: string,
6
- baseOptions?: T,
7
- optionsByEntries?: Record<string, T>,
8
- packageName?: string,
9
- ) => {
10
- if (optionsByEntries) {
11
- let optionsByEntry = getOptionsByEntryName(name, optionsByEntries);
12
-
13
- // compatible with main entry using packageName as the key
14
- if (
15
- optionsByEntry === undefined &&
16
- name === MAIN_ENTRY_NAME &&
17
- packageName
18
- ) {
19
- optionsByEntry = getOptionsByEntryName(packageName, optionsByEntries);
20
- }
21
-
22
- // eslint-disable-next-line no-nested-ternary
23
- return optionsByEntry !== undefined
24
- ? isPlainObject(optionsByEntry) && isPlainObject(baseOptions)
25
- ? { ...baseOptions, ...optionsByEntry }
26
- : optionsByEntry
27
- : baseOptions;
28
- } else {
29
- return baseOptions;
30
- }
31
- };
32
-
33
- const getOptionsByEntryName = <T>(
34
- name: string,
35
- optionsByEntries: Record<string, T>,
36
- ) =>
37
- optionsByEntries.hasOwnProperty(name) ? optionsByEntries[name] : undefined;
@@ -1,30 +0,0 @@
1
- import os from 'os';
2
- import path from 'path';
3
- import fs from 'fs-extra';
4
- import { canUsePnpm, canUseYarn } from './nodeEnv';
5
-
6
- const MAX_TIMES = 5;
7
- export async function getPackageManager(cwd: string = process.cwd()) {
8
- let appDirectory = cwd;
9
- let times = 0;
10
- while (os.homedir() !== appDirectory && times < MAX_TIMES) {
11
- times++;
12
- if (fs.existsSync(path.resolve(appDirectory, 'pnpm-lock.yaml'))) {
13
- return 'pnpm';
14
- }
15
- if (fs.existsSync(path.resolve(appDirectory, 'yarn.lock'))) {
16
- return 'yarn';
17
- }
18
- if (fs.existsSync(path.resolve(appDirectory, 'package-lock.json'))) {
19
- return 'npm';
20
- }
21
- appDirectory = path.join(appDirectory, '..');
22
- }
23
- if (await canUsePnpm()) {
24
- return 'pnpm';
25
- }
26
- if (await canUseYarn()) {
27
- return 'yarn';
28
- }
29
- return 'npm';
30
- }
package/src/getPort.ts DELETED
@@ -1,62 +0,0 @@
1
- import net from 'net';
2
- import { chalk } from './chalk';
3
- import { logger } from './logger';
4
-
5
- /**
6
- * Get available free port.
7
- * @param port - Current port want to use.
8
- * @param tryLimits - Maximum number of retries.
9
- * @returns Available port number.
10
- */
11
- /* eslint-disable no-param-reassign, @typescript-eslint/no-loop-func */
12
- export const getPort = async (
13
- port: string | number,
14
- tryLimits = 20,
15
- ): Promise<number> => {
16
- if (typeof port === 'string') {
17
- port = parseInt(port, 10);
18
- }
19
-
20
- const original = port;
21
-
22
- let found = false;
23
- let attempts = 0;
24
- while (!found && attempts <= tryLimits) {
25
- try {
26
- await new Promise((resolve, reject) => {
27
- const server = net.createServer();
28
- server.unref();
29
- server.on('error', reject);
30
- server.listen(
31
- {
32
- port,
33
- host: '0.0.0.0',
34
- },
35
- () => {
36
- found = true;
37
- server.close(resolve);
38
- },
39
- );
40
- });
41
- } catch (e: any) {
42
- if (e.code !== 'EADDRINUSE') {
43
- throw e;
44
- }
45
- port++;
46
- attempts++;
47
- }
48
- }
49
-
50
- if (port !== original) {
51
- logger.info(
52
- chalk.red(
53
- `Something is already running on port ${original}. ${chalk.yellow(
54
- `Use port ${port} instead.`,
55
- )}`,
56
- ),
57
- );
58
- }
59
-
60
- return port;
61
- };
62
- /* eslint-enable no-param-reassign, @typescript-eslint/no-loop-func */
package/src/import.ts DELETED
@@ -1,10 +0,0 @@
1
- // cover: https://rushstack.io/pages/api/node-core-library.import.lazy/
2
- const lazy = (moduleName: string, requireFn: (id: string) => unknown): any => {
3
- const importLazyLocal: (moduleName: string) => unknown =
4
- require('import-lazy')(requireFn);
5
- return importLazyLocal(moduleName);
6
- };
7
-
8
- export { lazy as lazyImport };
9
-
10
- export const Import = { lazy };
package/src/index.ts DELETED
@@ -1,31 +0,0 @@
1
- export * as fs from 'fs-extra';
2
- export * from './chalk';
3
- export * from './formatWebpackMessages';
4
- export * from './FileSizeReporter';
5
- export * from './printBuildError';
6
- export * from './debug';
7
- export * from './findExists';
8
- export * from './is';
9
- export * from './compatRequire';
10
- export * from './logger';
11
- export * from './constants';
12
- export * from './ensureAbsolutePath';
13
- export * from './getCacheIdentifier';
14
- export * from './clearConsole';
15
- export * from './pkgUp';
16
- export * from './applyOptionsChain';
17
- export * from './getBrowserslist';
18
- export * from './removeSlash';
19
- export * from './getEntryOptions';
20
- export * from './getPort';
21
- export * from './monorepo';
22
- export * from './getPackageManager';
23
- export * from './runtimeExports';
24
- export * from './readTsConfig';
25
- export * from './path';
26
- export * from './generateMetaTags';
27
- export * from './prettyInstructions';
28
- export * from './alias';
29
- export * from './import';
30
- export * from './watch';
31
- export * from './nodeEnv';
package/src/is/index.ts DELETED
@@ -1,78 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { isDev } from './node-env';
4
-
5
- /**
6
- * Check if the package name is in dependencies or devDependencies.
7
- *
8
- * @param appDirectory - Project root directory.
9
- * @param name - Package name.
10
- * @returns True if the name is in dependencies or devDependencies, false otherwise.
11
- */
12
- export const isDepExists = (appDirectory: string, name: string): boolean => {
13
- const json = require(path.resolve(appDirectory, './package.json'));
14
-
15
- const { dependencies = {}, devDependencies = {} } = json;
16
-
17
- return (
18
- dependencies.hasOwnProperty(name) || devDependencies.hasOwnProperty(name)
19
- );
20
- };
21
-
22
- /**
23
- * Is typescript project.
24
- *
25
- * @param root - App directory.
26
- * @returns Whether to use typescript.
27
- */
28
- export const isTypescript = (root: string): boolean =>
29
- fs.existsSync(path.resolve(root, './tsconfig.json'));
30
-
31
- /**
32
- * Is Empty object
33
- *
34
- * @param o - Any object.
35
- * @returns Whether it is empty object.
36
- */
37
- export const isEmpty = (o: Record<string, unknown>) =>
38
- Object.entries(o).length === 0 && o.constructor === Object;
39
-
40
- /**
41
- * Is SSR project
42
- *
43
- * @param config - User config.
44
- * @returns Whether to use server side render.
45
- */
46
- export const isSSR = (config: any): boolean => {
47
- const { server } = config;
48
-
49
- if (server?.ssr) {
50
- return true;
51
- }
52
-
53
- if (server?.ssrByEntries && !isEmpty(server.ssrByEntries)) {
54
- for (const name of Object.keys(server.ssrByEntries)) {
55
- if (server.ssrByEntries[name]) {
56
- return true;
57
- }
58
- }
59
- }
60
-
61
- return false;
62
- };
63
-
64
- export const isUseSSRBundle = (config: any): boolean => {
65
- const { output } = config;
66
- if (output?.ssg) {
67
- return true;
68
- }
69
-
70
- return isSSR(config);
71
- };
72
-
73
- export const isFastRefresh = () =>
74
- isDev() && process.env.FAST_REFRESH !== 'false';
75
-
76
- export * from './node-env';
77
- export * from './platform';
78
- export * from './type';
@@ -1,9 +0,0 @@
1
- export const isDev = (): boolean => process.env.NODE_ENV === 'development';
2
-
3
- export const isProd = (): boolean => process.env.NODE_ENV === 'production';
4
-
5
- export const isTest = () => process.env.NODE_ENV === 'test';
6
-
7
- // Variable used for enabling profiling in Production.
8
- export const isProdProfile = () =>
9
- isProd() && process.argv.includes('--profile');
@@ -1,7 +0,0 @@
1
- export const isNodeJS = (): boolean =>
2
- typeof process !== 'undefined' &&
3
- process.versions != null &&
4
- process.versions.node != null &&
5
- (process.versions as any).electron == null;
6
-
7
- export const isBrowser = (): boolean => typeof window !== 'undefined';
package/src/is/type.ts DELETED
@@ -1,43 +0,0 @@
1
- export function isString(str: any): str is string {
2
- return typeof str === 'string';
3
- }
4
-
5
- export function isUndefined(obj: any): obj is undefined {
6
- return typeof obj === 'undefined';
7
- }
8
-
9
- export function isArray(obj: any): obj is any[] {
10
- return Object.prototype.toString.call(obj) === '[object Array]';
11
- }
12
-
13
- // eslint-disable-next-line @typescript-eslint/ban-types
14
- export function isFunction(func: any): func is Function {
15
- return typeof func === 'function';
16
- }
17
-
18
- // eslint-disable-next-line @typescript-eslint/ban-types
19
- export function isObject(obj: any): obj is object {
20
- return typeof obj === 'object';
21
- }
22
-
23
- export function isPlainObject(obj: any): obj is Record<string, any> {
24
- return (
25
- obj &&
26
- typeof obj === 'object' &&
27
- Object.prototype.toString.call(obj) === '[object Object]'
28
- );
29
- }
30
-
31
- export function isPromise(obj: any): obj is Promise<any> {
32
- /* eslint-disable promise/prefer-await-to-then */
33
- return (
34
- Boolean(obj) &&
35
- (typeof obj === 'object' || typeof obj === 'function') &&
36
- typeof obj.then === 'function'
37
- );
38
- /* eslint-enable promise/prefer-await-to-then */
39
- }
40
-
41
- export function isRegExp(obj: any): obj is RegExp {
42
- return Object.prototype.toString.call(obj) === '[object RegExp]';
43
- }