This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { LoadedPlugin } from '@docusaurus/types';
/**
* Aliases used for Webpack resolution (useful for implementing swizzling)
*/
type ThemeAliases = {
[alias: string]: string;
};
/**
* Order of Webpack aliases is important because one alias can shadow another.
* This ensures `@theme/NavbarItem` alias is after
* `@theme/NavbarItem/LocaleDropdown`.
*
* @see https://github.com/facebook/docusaurus/pull/3922
* @see https://github.com/facebook/docusaurus/issues/5382
*/
export declare function sortAliases(aliases: ThemeAliases): ThemeAliases;
export declare function createAliasesForTheme(themePath: string, addOriginalAlias: boolean): Promise<ThemeAliases>;
export declare function loadThemeAliases({ siteDir, plugins, }: {
siteDir: string;
plugins: LoadedPlugin[];
}): Promise<ThemeAliases>;
/**
* Note: a `@docusaurus` alias would also catch `@docusaurus/theme-common`, so
* instead of naively aliasing this to `client/exports`, we use fine-grained
* aliases instead.
*/
export declare function loadDocusaurusAliases(): Promise<ThemeAliases>;
export {};

View File

@@ -0,0 +1,106 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadDocusaurusAliases = exports.loadThemeAliases = exports.createAliasesForTheme = exports.sortAliases = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const lodash_1 = tslib_1.__importDefault(require("lodash"));
const utils_1 = require("@docusaurus/utils");
const ThemeFallbackDir = path_1.default.join(__dirname, '../../client/theme-fallback');
/**
* Order of Webpack aliases is important because one alias can shadow another.
* This ensures `@theme/NavbarItem` alias is after
* `@theme/NavbarItem/LocaleDropdown`.
*
* @see https://github.com/facebook/docusaurus/pull/3922
* @see https://github.com/facebook/docusaurus/issues/5382
*/
function sortAliases(aliases) {
// Alphabetical order by default
const entries = lodash_1.default.sortBy(Object.entries(aliases), ([alias]) => alias);
// @theme/NavbarItem should be after @theme/NavbarItem/LocaleDropdown
entries.sort(([alias1], [alias2]) =>
// eslint-disable-next-line no-nested-ternary
alias1.includes(`${alias2}/`) ? -1 : alias2.includes(`${alias1}/`) ? 1 : 0);
return Object.fromEntries(entries);
}
exports.sortAliases = sortAliases;
async function createAliasesForTheme(themePath, addOriginalAlias) {
if (!(await fs_extra_1.default.pathExists(themePath))) {
return {};
}
const themeComponentFiles = await (0, utils_1.Globby)(['**/*.{js,jsx,ts,tsx}'], {
cwd: themePath,
});
const aliases = {};
themeComponentFiles.forEach((relativeSource) => {
const filePath = path_1.default.join(themePath, relativeSource);
const fileName = (0, utils_1.fileToPath)(relativeSource);
const aliasName = (0, utils_1.posixPath)((0, utils_1.normalizeUrl)(['@theme', fileName]).replace(/\/$/, ''));
aliases[aliasName] = filePath;
if (addOriginalAlias) {
// For swizzled components to access the original.
const originalAliasName = (0, utils_1.posixPath)((0, utils_1.normalizeUrl)(['@theme-original', fileName]).replace(/\/$/, ''));
aliases[originalAliasName] = filePath;
}
});
return sortAliases(aliases);
}
exports.createAliasesForTheme = createAliasesForTheme;
async function createThemeAliases(themePaths, userThemePaths) {
const aliases = {};
for (const themePath of themePaths) {
const themeAliases = await createAliasesForTheme(themePath, true);
Object.entries(themeAliases).forEach(([aliasKey, alias]) => {
// If this alias shadows a previous one, use @theme-init to preserve the
// initial one. @theme-init is only applied once: to the initial theme
// that provided this component
if (aliasKey in aliases) {
const componentName = aliasKey.substring(aliasKey.indexOf('/') + 1);
const initAlias = `@theme-init/${componentName}`;
if (!(initAlias in aliases)) {
aliases[initAlias] = aliases[aliasKey];
}
}
aliases[aliasKey] = alias;
});
}
for (const themePath of userThemePaths) {
const userThemeAliases = await createAliasesForTheme(themePath, false);
Object.assign(aliases, userThemeAliases);
}
return sortAliases(aliases);
}
function loadThemeAliases({ siteDir, plugins, }) {
const pluginThemes = plugins
.map((plugin) => plugin.getThemePath && path_1.default.resolve(plugin.path, plugin.getThemePath()))
.filter((x) => Boolean(x));
const userTheme = path_1.default.resolve(siteDir, utils_1.THEME_PATH);
return createThemeAliases([ThemeFallbackDir, ...pluginThemes], [userTheme]);
}
exports.loadThemeAliases = loadThemeAliases;
/**
* Note: a `@docusaurus` alias would also catch `@docusaurus/theme-common`, so
* instead of naively aliasing this to `client/exports`, we use fine-grained
* aliases instead.
*/
async function loadDocusaurusAliases() {
const dirPath = path_1.default.resolve(__dirname, '../../client/exports');
const extensions = ['.js', '.ts', '.tsx'];
const aliases = {};
(await fs_extra_1.default.readdir(dirPath))
.filter((fileName) => extensions.includes(path_1.default.extname(fileName)))
.forEach((fileName) => {
const fileNameWithoutExtension = path_1.default.basename(fileName, path_1.default.extname(fileName));
const aliasName = `@docusaurus/${fileNameWithoutExtension}`;
aliases[aliasName] = path_1.default.resolve(dirPath, fileName);
});
return aliases;
}
exports.loadDocusaurusAliases = loadDocusaurusAliases;

11
node_modules/@docusaurus/core/lib/webpack/base.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Configuration } from 'webpack';
import type { Props } from '@docusaurus/types';
export declare const clientDir: string;
export declare function excludeJS(modulePath: string): boolean;
export declare function createBaseConfig(props: Props, isServer: boolean, minify?: boolean): Promise<Configuration>;

217
node_modules/@docusaurus/core/lib/webpack/base.js generated vendored Normal file
View File

@@ -0,0 +1,217 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBaseConfig = exports.excludeJS = exports.clientDir = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const mini_css_extract_plugin_1 = tslib_1.__importDefault(require("mini-css-extract-plugin"));
const utils_1 = require("@docusaurus/utils");
const utils_2 = require("./utils");
const aliases_1 = require("./aliases");
const CSS_REGEX = /\.css$/i;
const CSS_MODULE_REGEX = /\.module\.css$/i;
exports.clientDir = path_1.default.join(__dirname, '..', 'client');
const LibrariesToTranspile = [
'copy-text-to-clipboard', // Contains optional catch binding, incompatible with recent versions of Edge
];
const LibrariesToTranspileRegex = new RegExp(LibrariesToTranspile.map((libName) => `(node_modules/${libName})`).join('|'));
function excludeJS(modulePath) {
// Always transpile client dir
if (modulePath.startsWith(exports.clientDir)) {
return false;
}
// Don't transpile node_modules except any docusaurus npm package
return (modulePath.includes('node_modules') &&
!/docusaurus(?:(?!node_modules).)*\.jsx?$/.test(modulePath) &&
!LibrariesToTranspileRegex.test(modulePath));
}
exports.excludeJS = excludeJS;
async function createBaseConfig(props, isServer, minify = true) {
const { outDir, siteDir, siteConfig, siteConfigPath, baseUrl, generatedFilesDir, routesPaths, siteMetadata, plugins, } = props;
const totalPages = routesPaths.length;
const isProd = process.env.NODE_ENV === 'production';
const minimizeEnabled = minify && isProd && !isServer;
const useSimpleCssMinifier = process.env.USE_SIMPLE_CSS_MINIFIER === 'true';
const fileLoaderUtils = (0, utils_1.getFileLoaderUtils)();
const name = isServer ? 'server' : 'client';
const mode = isProd ? 'production' : 'development';
const themeAliases = await (0, aliases_1.loadThemeAliases)({ siteDir, plugins });
return {
mode,
name,
cache: {
type: 'filesystem',
// Can we share the same cache across locales?
// Exploring that question at https://github.com/webpack/webpack/issues/13034
// name: `${name}-${mode}`,
name: `${name}-${mode}-${props.i18n.currentLocale}`,
// When version string changes, cache is evicted
version: [
siteMetadata.docusaurusVersion,
// Webpack does not evict the cache correctly on alias/swizzle change,
// so we force eviction.
// See https://github.com/webpack/webpack/issues/13627
(0, utils_1.md5Hash)(JSON.stringify(themeAliases)),
].join('-'),
// When one of those modules/dependencies change (including transitive
// deps), cache is invalidated
buildDependencies: {
config: [
__filename,
path_1.default.join(__dirname, isServer ? 'server.js' : 'client.js'),
// Docusaurus config changes can affect MDX/JSX compilation, so we'd
// rather evict the cache.
// See https://github.com/questdb/questdb.io/issues/493
siteConfigPath,
],
},
},
output: {
pathinfo: false,
path: outDir,
filename: isProd ? 'assets/js/[name].[contenthash:8].js' : '[name].js',
chunkFilename: isProd
? 'assets/js/[name].[contenthash:8].js'
: '[name].js',
publicPath: baseUrl,
hashFunction: 'xxhash64',
},
// Don't throw warning when asset created is over 250kb
performance: {
hints: false,
},
devtool: isProd ? undefined : 'eval-cheap-module-source-map',
resolve: {
unsafeCache: false,
extensions: ['.wasm', '.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
symlinks: true,
roots: [
// Allow resolution of url("/fonts/xyz.ttf") by webpack
// See https://webpack.js.org/configuration/resolve/#resolveroots
// See https://github.com/webpack-contrib/css-loader/issues/1256
...siteConfig.staticDirectories.map((dir) => path_1.default.resolve(siteDir, dir)),
siteDir,
process.cwd(),
],
alias: {
'@site': siteDir,
'@generated': generatedFilesDir,
...(await (0, aliases_1.loadDocusaurusAliases)()),
...themeAliases,
},
// This allows you to set a fallback for where Webpack should look for
// modules. We want `@docusaurus/core` own dependencies/`node_modules` to
// "win" if there is conflict. Example: if there is core-js@3 in user's
// own node_modules, but core depends on core-js@2, we should use
// core-js@2.
modules: [
path_1.default.resolve(__dirname, '..', '..', 'node_modules'),
'node_modules',
path_1.default.resolve(await fs_extra_1.default.realpath(process.cwd()), 'node_modules'),
],
},
resolveLoader: {
modules: ['node_modules', path_1.default.join(siteDir, 'node_modules')],
},
optimization: {
removeAvailableModules: false,
// Only minimize client bundle in production because server bundle is only
// used for static site generation
minimize: minimizeEnabled,
minimizer: minimizeEnabled
? (0, utils_2.getMinimizer)(useSimpleCssMinifier)
: undefined,
splitChunks: isServer
? false
: {
// Since the chunk name includes all origin chunk names it's
// recommended for production builds with long term caching to NOT
// include [name] in the filenames
name: false,
cacheGroups: {
// Disable the built-in cacheGroups
default: false,
common: {
name: 'common',
minChunks: totalPages > 2 ? totalPages * 0.5 : 2,
priority: 40,
},
// Only create one CSS file to avoid
// problems with code-split CSS loading in different orders
// causing inconsistent/non-deterministic styling
// See https://github.com/facebook/docusaurus/issues/2006
styles: {
name: 'styles',
type: 'css/mini-extract',
chunks: `all`,
enforce: true,
priority: 50,
},
},
},
},
module: {
rules: [
fileLoaderUtils.rules.images(),
fileLoaderUtils.rules.fonts(),
fileLoaderUtils.rules.media(),
fileLoaderUtils.rules.svg(),
fileLoaderUtils.rules.otherAssets(),
{
test: /\.[jt]sx?$/i,
exclude: excludeJS,
use: [
(0, utils_2.getCustomizableJSLoader)(siteConfig.webpack?.jsLoader)({
isServer,
babelOptions: await (0, utils_2.getCustomBabelConfigFilePath)(siteDir),
}),
],
},
{
test: CSS_REGEX,
exclude: CSS_MODULE_REGEX,
use: (0, utils_2.getStyleLoaders)(isServer, {
importLoaders: 1,
sourceMap: !isProd,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: CSS_MODULE_REGEX,
use: (0, utils_2.getStyleLoaders)(isServer, {
modules: {
localIdentName: isProd
? `[local]_[contenthash:base64:4]`
: `[local]_[path][name]`,
exportOnlyLocals: isServer,
},
importLoaders: 1,
sourceMap: !isProd,
}),
},
],
},
plugins: [
new mini_css_extract_plugin_1.default({
filename: isProd
? 'assets/css/[name].[contenthash:8].css'
: '[name].css',
chunkFilename: isProd
? 'assets/css/[name].[contenthash:8].css'
: '[name].css',
// Remove css order warnings if css imports are not sorted
// alphabetically. See https://github.com/webpack-contrib/mini-css-extract-plugin/pull/422
// for more reasoning
ignoreOrder: true,
}),
],
};
}
exports.createBaseConfig = createBaseConfig;

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Props } from '@docusaurus/types';
import type { Configuration } from 'webpack';
export default function createClientConfig(props: Props, minify?: boolean, hydrate?: boolean): Promise<Configuration>;

59
node_modules/@docusaurus/core/lib/webpack/client.js generated vendored Normal file
View File

@@ -0,0 +1,59 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
const webpackbar_1 = tslib_1.__importDefault(require("webpackbar"));
const webpack_1 = require("webpack");
const base_1 = require("./base");
const ChunkAssetPlugin_1 = tslib_1.__importDefault(require("./plugins/ChunkAssetPlugin"));
const utils_1 = require("./utils");
async function createClientConfig(props, minify = true, hydrate = true) {
const isBuilding = process.argv[2] === 'build';
const config = await (0, base_1.createBaseConfig)(props, false, minify);
const clientConfig = (0, webpack_merge_1.default)(config, {
// Useless, disabled on purpose (errors on existing sites with no
// browserslist config)
// target: 'browserslist',
entry: path_1.default.resolve(__dirname, '../client/clientEntry.js'),
optimization: {
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true,
},
plugins: [
new webpack_1.DefinePlugin({
'process.env.HYDRATE_CLIENT_ENTRY': JSON.stringify(hydrate),
}),
new ChunkAssetPlugin_1.default(),
// Show compilation progress bar and build time.
new webpackbar_1.default({
name: 'Client',
}),
],
});
// When building, include the plugin to force terminate building if errors
// happened in the client bundle.
if (isBuilding) {
clientConfig.plugins?.push({
apply: (compiler) => {
compiler.hooks.done.tap('client:done', (stats) => {
if (stats.hasErrors()) {
const errorsWarnings = stats.toJson('errors-warnings');
logger_1.default.error(`Client bundle compiled with errors therefore further build is impossible.\n${(0, utils_1.formatStatsErrorMessage)(errorsWarnings)}`);
process.exit(1);
}
});
},
});
}
return clientConfig;
}
exports.default = createClientConfig;

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type Compiler } from 'webpack';
/**
* We modify webpack runtime to add an extra function called
* "__webpack_require__.gca" that will allow us to get the corresponding chunk
* asset for a webpack chunk. Pass it the chunkName or chunkId you want to load.
* For example: if you have a chunk named "my-chunk-name" that will map to
* "/publicPath/0a84b5e7.c8e35c7a.js" as its corresponding output path
* __webpack_require__.gca("my-chunk-name") will return
* "/publicPath/0a84b5e7.c8e35c7a.js"
*
* "gca" stands for "get chunk asset"
*/
export default class ChunkAssetPlugin {
apply(compiler: Compiler): void;
}

View File

@@ -0,0 +1,51 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const webpack_1 = tslib_1.__importDefault(require("webpack"));
const pluginName = 'chunk-asset-plugin';
/**
* We modify webpack runtime to add an extra function called
* "__webpack_require__.gca" that will allow us to get the corresponding chunk
* asset for a webpack chunk. Pass it the chunkName or chunkId you want to load.
* For example: if you have a chunk named "my-chunk-name" that will map to
* "/publicPath/0a84b5e7.c8e35c7a.js" as its corresponding output path
* __webpack_require__.gca("my-chunk-name") will return
* "/publicPath/0a84b5e7.c8e35c7a.js"
*
* "gca" stands for "get chunk asset"
*/
class ChunkAssetPlugin {
apply(compiler) {
compiler.hooks.thisCompilation.tap(pluginName, ({ mainTemplate }) => {
mainTemplate.hooks.requireExtensions.tap(pluginName, (source, chunk) => {
const chunkIdToName = chunk.getChunkMaps(false).name;
const chunkNameToId = Object.fromEntries(Object.entries(chunkIdToName).map(([chunkId, chunkName]) => [
chunkName,
chunkId,
]));
const buf = [source];
buf.push('// function to get chunk asset');
buf.push(
// If chunkName is passed, we convert it to chunk asset url
// .p => public path url ("/" or "/baseUrl/")
// .u(chunkId) =>
// chunk asset url ("assets/js/x63b64xd.contentHash.js")
// not sure where this is documented, but this link was helpful:
// https://programmer.help/blogs/5d68849083e1a.html
//
// Note: __webpack_require__.gca() is called in docusaurus.ts for
// prefetching
// Note: we previously used jsonpScriptSrc (Webpack 4)
`__webpack_require__.gca = function(chunkId) { chunkId = ${JSON.stringify(chunkNameToId)}[chunkId]||chunkId; return __webpack_require__.p + __webpack_require__.u(chunkId); };`);
return webpack_1.default.Template.asString(buf);
});
});
}
}
exports.default = ChunkAssetPlugin;

View File

@@ -0,0 +1,59 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Compiler, Stats } from 'webpack';
export type Options = {
/**
* Write Logs to Console
* (Always enabled when dry is true)
*
* default: false
*/
verbose?: boolean;
/**
* Automatically remove all unused webpack assets on rebuild
*
* default: true
*/
cleanStaleWebpackAssets?: boolean;
/**
* Do not allow removal of current webpack assets
*
* default: true
*/
protectWebpackAssets?: boolean;
/**
* Removes files once prior to Webpack compilation
* Not included in rebuilds (watch mode)
*
* Use !negative patterns to exclude files
*
* default: ['**\/*']
*/
cleanOnceBeforeBuildPatterns?: string[];
};
export default class CleanWebpackPlugin {
private readonly verbose;
private readonly cleanStaleWebpackAssets;
private readonly protectWebpackAssets;
private readonly cleanOnceBeforeBuildPatterns;
private currentAssets;
private initialClean;
private outputPath;
constructor(options?: Options);
apply(compiler: Compiler): void;
/**
* Initially remove files from output directory prior to build.
*
* Only happens once.
*
* Warning: It is recommended to initially clean your build directory outside
* of webpack to minimize unexpected behavior.
*/
handleInitial(): void;
handleDone(stats: Stats): void;
removeFiles(patterns: string[]): void;
}

View File

@@ -0,0 +1,177 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
/**
* The MIT License (MIT)
* Copyright (c) 2015 John Agan
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Forked from https://github.com/johnagan/clean-webpack-plugin
// Modified to optimize performance for Docusaurus specific use case
// More context: https://github.com/facebook/docusaurus/pull/1839
const path_1 = tslib_1.__importDefault(require("path"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const del_1 = require("del");
class CleanWebpackPlugin {
constructor(options = {}) {
this.verbose = options.verbose === true || false;
this.cleanStaleWebpackAssets =
options.cleanStaleWebpackAssets === true ||
options.cleanStaleWebpackAssets === false
? options.cleanStaleWebpackAssets
: true;
this.protectWebpackAssets =
options.protectWebpackAssets === true ||
options.protectWebpackAssets === false
? options.protectWebpackAssets
: true;
this.cleanOnceBeforeBuildPatterns = Array.isArray(options.cleanOnceBeforeBuildPatterns)
? options.cleanOnceBeforeBuildPatterns
: ['**/*'];
/**
* Store webpack build assets
*/
this.currentAssets = [];
/**
* Only used with cleanOnceBeforeBuildPatterns
*/
this.initialClean = false;
this.outputPath = '';
this.apply = this.apply.bind(this);
this.handleInitial = this.handleInitial.bind(this);
this.handleDone = this.handleDone.bind(this);
this.removeFiles = this.removeFiles.bind(this);
}
apply(compiler) {
if (!compiler.options.output.path) {
console.warn('clean-webpack-plugin: options.output.path not defined. Plugin disabled...');
return;
}
this.outputPath = compiler.options.output.path;
const { hooks } = compiler;
if (this.cleanOnceBeforeBuildPatterns.length !== 0) {
hooks.compile.tap('clean-webpack-plugin', () => {
this.handleInitial();
});
}
hooks.done.tap('clean-webpack-plugin', (stats) => {
this.handleDone(stats);
});
}
/**
* Initially remove files from output directory prior to build.
*
* Only happens once.
*
* Warning: It is recommended to initially clean your build directory outside
* of webpack to minimize unexpected behavior.
*/
handleInitial() {
if (this.initialClean) {
return;
}
if (
// eslint-disable-next-line no-restricted-properties
fs_extra_1.default.pathExistsSync(this.outputPath) &&
// eslint-disable-next-line no-restricted-properties
fs_extra_1.default.statSync(this.outputPath).isFile()) {
throw new Error(`A file '${this.outputPath}' already exists. Docusaurus needs this directory to save the build output. Either remove/change the file or choose a different build directory via '--out-dir'.`);
}
this.initialClean = true;
this.removeFiles(this.cleanOnceBeforeBuildPatterns);
}
handleDone(stats) {
/**
* Do nothing if there is a webpack error
*/
if (stats.hasErrors()) {
if (this.verbose) {
console.warn('clean-webpack-plugin: pausing due to webpack errors');
}
return;
}
/**
* Fetch Webpack's output asset files
*/
const statsAssets = stats.toJson({
all: false,
assets: true,
}).assets ?? [];
const assets = statsAssets.map((asset) => asset.name);
/**
* Get all files that were in the previous build but not the current
*
* (relies on del's cwd: outputPath option)
*/
const staleFiles = this.currentAssets.filter((previousAsset) => !assets.includes(previousAsset));
/**
* Save assets for next compilation
*/
this.currentAssets = assets.sort();
const removePatterns = [];
/**
* Remove unused webpack assets
*/
if (this.cleanStaleWebpackAssets && staleFiles.length !== 0) {
removePatterns.push(...staleFiles);
}
if (removePatterns.length !== 0) {
this.removeFiles(removePatterns);
}
}
removeFiles(patterns) {
try {
const deleted = (0, del_1.sync)(patterns, {
force: false,
// Change context to build directory
cwd: this.outputPath,
dryRun: false,
dot: true,
ignore: this.protectWebpackAssets ? this.currentAssets : [],
});
/**
* Log if verbose is enabled
*/
if (this.verbose) {
deleted.forEach((file) => {
const filename = path_1.default.relative(process.cwd(), file);
/**
* Use console.warn over .log
* https://github.com/webpack/webpack/issues/1904
* https://github.com/johnagan/clean-webpack-plugin/issues/11
*/
console.warn(`clean-webpack-plugin: removed ${filename}`);
});
}
}
catch (err) {
const needsForce = err.message.includes('Cannot delete files/folders outside the current working directory.');
if (needsForce) {
const message = 'clean-webpack-plugin: Cannot delete files/folders outside the current working directory. Can be overridden with the "dangerouslyAllowCleanPatternsOutsideProject" option.';
throw new Error(message);
}
throw err;
}
}
}
exports.default = CleanWebpackPlugin;

View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Compiler } from 'webpack';
type WaitPluginOptions = {
filepath: string;
};
export default class WaitPlugin {
filepath: string;
constructor(options: WaitPluginOptions);
apply(compiler: Compiler): void;
}
export {};

View File

@@ -0,0 +1,47 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
class WaitPlugin {
constructor(options) {
this.filepath = options.filepath;
}
apply(compiler) {
// Before finishing the compilation step
compiler.hooks.make.tapPromise('WaitPlugin', () => waitOn(this.filepath));
}
}
exports.default = WaitPlugin;
// This is a re-implementation of the algorithm used by the "wait-on" package
// https://github.com/jeffbski/wait-on/blob/master/lib/wait-on.js#L200
async function waitOn(filepath) {
const pollingIntervalMs = 300;
const stabilityWindowMs = 750;
let lastFileSize = -1;
let lastFileTime = -1;
for (;;) {
let size = -1;
try {
size = (await fs_extra_1.default.stat(filepath)).size;
}
catch (err) { }
if (size !== -1) {
if (lastFileTime === -1 || size !== lastFileSize) {
lastFileSize = size;
lastFileTime = performance.now();
}
else if (performance.now() - lastFileTime >= stabilityWindowMs) {
return;
}
}
await new Promise((resolve) => {
setTimeout(resolve, pollingIntervalMs);
});
}
}

12
node_modules/@docusaurus/core/lib/webpack/server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { type Locals } from '@slorber/static-site-generator-webpack-plugin';
import type { Props } from '@docusaurus/types';
import type { Configuration } from 'webpack';
export default function createServerConfig({ props, onLinksCollected, onHeadTagsCollected, }: Pick<Locals, 'onLinksCollected' | 'onHeadTagsCollected'> & {
props: Props;
}): Promise<Configuration>;

83
node_modules/@docusaurus/core/lib/webpack/server.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path_1 = tslib_1.__importDefault(require("path"));
const webpack_merge_1 = tslib_1.__importDefault(require("webpack-merge"));
const utils_1 = require("@docusaurus/utils");
// Forked for Docusaurus: https://github.com/slorber/static-site-generator-webpack-plugin
const static_site_generator_webpack_plugin_1 = tslib_1.__importDefault(require("@slorber/static-site-generator-webpack-plugin"));
const webpackbar_1 = tslib_1.__importDefault(require("webpackbar"));
const base_1 = require("./base");
const WaitPlugin_1 = tslib_1.__importDefault(require("./plugins/WaitPlugin"));
const ssr_html_template_1 = tslib_1.__importDefault(require("./templates/ssr.html.template"));
async function createServerConfig({ props, onLinksCollected, onHeadTagsCollected, }) {
const { baseUrl, routesPaths, generatedFilesDir, headTags, preBodyTags, postBodyTags, siteConfig: { noIndex, trailingSlash, ssrTemplate }, } = props;
const config = await (0, base_1.createBaseConfig)(props, true);
const routesLocation = {};
// Array of paths to be rendered. Relative to output directory
const ssgPaths = routesPaths.map((str) => {
const ssgPath = baseUrl === '/' ? str : str.replace(new RegExp(`^${baseUrl}`), '/');
routesLocation[ssgPath] = str;
return ssgPath;
});
const serverConfig = (0, webpack_merge_1.default)(config, {
target: `node${utils_1.NODE_MAJOR_VERSION}.${utils_1.NODE_MINOR_VERSION}`,
entry: {
main: path_1.default.resolve(__dirname, '../client/serverEntry.js'),
},
output: {
filename: 'server.bundle.js',
libraryTarget: 'commonjs2',
// Workaround for Webpack 4 Bug (https://github.com/webpack/webpack/issues/6522)
globalObject: 'this',
},
plugins: [
// Wait until manifest from client bundle is generated
new WaitPlugin_1.default({
filepath: path_1.default.join(generatedFilesDir, 'client-manifest.json'),
}),
// Static site generator webpack plugin.
new static_site_generator_webpack_plugin_1.default({
entry: 'main',
locals: {
baseUrl,
generatedFilesDir,
routesLocation,
headTags,
preBodyTags,
postBodyTags,
onLinksCollected,
onHeadTagsCollected,
ssrTemplate: ssrTemplate ?? ssr_html_template_1.default,
noIndex,
DOCUSAURUS_VERSION: utils_1.DOCUSAURUS_VERSION,
},
paths: ssgPaths,
preferFoldersOutput: trailingSlash,
// When using "new URL('file.js', import.meta.url)", Webpack will emit
// __filename, and this plugin will throw. not sure the __filename value
// has any importance for this plugin, just using an empty string to
// avoid the error. See https://github.com/facebook/docusaurus/issues/4922
globals: { __filename: '' },
// Secret way to set SSR plugin concurrency option
// Waiting for feedback before documenting this officially?
concurrency: process.env.DOCUSAURUS_SSR_CONCURRENCY
? parseInt(process.env.DOCUSAURUS_SSR_CONCURRENCY, 10)
: undefined,
}),
// Show compilation progress bar.
new webpackbar_1.default({
name: 'Server',
color: 'yellow',
}),
],
});
return serverConfig;
}
exports.default = createServerConfig;

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="Docusaurus">
<title><%= htmlWebpackPlugin.options.title %></title>
<%= htmlWebpackPlugin.options.headTags %>
<%= htmlWebpackPlugin.tags.headTags %>
</head>
<body>
<%= htmlWebpackPlugin.options.preBodyTags %>
<div id="__docusaurus"></div>
<%= htmlWebpackPlugin.tags.bodyTags %>
<%= htmlWebpackPlugin.options.postBodyTags %>
</body>
</html>

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare const _default: "\n<!DOCTYPE html>\n<html <%~ it.htmlAttributes %>>\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"generator\" content=\"Docusaurus v<%= it.version %>\">\n <% it.metaAttributes.forEach((metaAttribute) => { %>\n <%~ metaAttribute %>\n <% }); %>\n <%~ it.headTags %>\n <% it.stylesheets.forEach((stylesheet) => { %>\n <link rel=\"stylesheet\" href=\"<%= it.baseUrl %><%= stylesheet %>\" />\n <% }); %>\n <% it.scripts.forEach((script) => { %>\n <script src=\"<%= it.baseUrl %><%= script %>\" defer></script>\n <% }); %>\n </head>\n <body <%~ it.bodyAttributes %>>\n <%~ it.preBodyTags %>\n <div id=\"__docusaurus\"><%~ it.appHtml %></div>\n <%~ it.postBodyTags %>\n </body>\n</html>\n";
export default _default;

View File

@@ -0,0 +1,32 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = `
<!DOCTYPE html>
<html <%~ it.htmlAttributes %>>
<head>
<meta charset="UTF-8">
<meta name="generator" content="Docusaurus v<%= it.version %>">
<% it.metaAttributes.forEach((metaAttribute) => { %>
<%~ metaAttribute %>
<% }); %>
<%~ it.headTags %>
<% it.stylesheets.forEach((stylesheet) => { %>
<link rel="stylesheet" href="<%= it.baseUrl %><%= stylesheet %>" />
<% }); %>
<% it.scripts.forEach((script) => { %>
<script src="<%= it.baseUrl %><%= script %>" defer></script>
<% }); %>
</head>
<body <%~ it.bodyAttributes %>>
<%~ it.preBodyTags %>
<div id="__docusaurus"><%~ it.appHtml %></div>
<%~ it.postBodyTags %>
</body>
</html>
`;

47
node_modules/@docusaurus/core/lib/webpack/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import webpack, { type Configuration, type RuleSetRule, type WebpackPluginInstance } from 'webpack';
import type { TransformOptions } from '@babel/core';
import type { Plugin } from '@docusaurus/types';
export declare function formatStatsErrorMessage(statsJson: ReturnType<webpack.Stats['toJson']> | undefined): string | undefined;
export declare function printStatsWarnings(statsJson: ReturnType<webpack.Stats['toJson']> | undefined): void;
export declare function getStyleLoaders(isServer: boolean, cssOptionsArg?: {
[key: string]: unknown;
}): RuleSetRule[];
export declare function getCustomBabelConfigFilePath(siteDir: string): Promise<string | undefined>;
export declare function getBabelOptions({ isServer, babelOptions, }?: {
isServer?: boolean;
babelOptions?: TransformOptions | string;
}): TransformOptions;
export declare const getCustomizableJSLoader: (jsLoader?: "babel" | ((isServer: boolean) => RuleSetRule)) => ({ isServer, babelOptions, }: {
isServer: boolean;
babelOptions?: string | TransformOptions | undefined;
}) => RuleSetRule;
/**
* Helper function to modify webpack config
* @param configureWebpack a webpack config or a function to modify config
* @param config initial webpack config
* @param isServer indicates if this is a server webpack configuration
* @param jsLoader custom js loader config
* @param content content loaded by the plugin
* @returns final/ modified webpack config
*/
export declare function applyConfigureWebpack(configureWebpack: NonNullable<Plugin['configureWebpack']>, config: Configuration, isServer: boolean, jsLoader: 'babel' | ((isServer: boolean) => RuleSetRule) | undefined, content: unknown): Configuration;
export declare function applyConfigurePostCss(configurePostCss: NonNullable<Plugin['configurePostCss']>, config: Configuration): Configuration;
declare global {
interface Error {
/** @see https://webpack.js.org/api/node/#error-handling */
details: unknown;
}
}
export declare function compile(config: Configuration[]): Promise<void>;
export declare function getHttpsConfig(): Promise<boolean | {
cert: Buffer;
key: Buffer;
}>;
export declare function getMinimizer(useSimpleCssMinifier?: boolean): WebpackPluginInstance[];

350
node_modules/@docusaurus/core/lib/webpack/utils.js generated vendored Normal file
View File

@@ -0,0 +1,350 @@
"use strict";
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMinimizer = exports.getHttpsConfig = exports.compile = exports.applyConfigurePostCss = exports.applyConfigureWebpack = exports.getCustomizableJSLoader = exports.getBabelOptions = exports.getCustomBabelConfigFilePath = exports.getStyleLoaders = exports.printStatsWarnings = exports.formatStatsErrorMessage = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const crypto_1 = tslib_1.__importDefault(require("crypto"));
const logger_1 = tslib_1.__importDefault(require("@docusaurus/logger"));
const utils_1 = require("@docusaurus/utils");
const mini_css_extract_plugin_1 = tslib_1.__importDefault(require("mini-css-extract-plugin"));
const webpack_merge_1 = require("webpack-merge");
const webpack_1 = tslib_1.__importDefault(require("webpack"));
const terser_webpack_plugin_1 = tslib_1.__importDefault(require("terser-webpack-plugin"));
const css_minimizer_webpack_plugin_1 = tslib_1.__importDefault(require("css-minimizer-webpack-plugin"));
const formatWebpackMessages_1 = tslib_1.__importDefault(require("react-dev-utils/formatWebpackMessages"));
function formatStatsErrorMessage(statsJson) {
if (statsJson?.errors?.length) {
// TODO formatWebpackMessages does not print stack-traces
// Also the error causal chain is lost here
// We log the stacktrace inside serverEntry.tsx for now (not ideal)
const { errors } = (0, formatWebpackMessages_1.default)(statsJson);
return errors
.map((str) => logger_1.default.red(str))
.join(`\n\n${logger_1.default.yellow('--------------------------')}\n\n`);
}
return undefined;
}
exports.formatStatsErrorMessage = formatStatsErrorMessage;
function printStatsWarnings(statsJson) {
if (statsJson?.warnings?.length) {
statsJson.warnings?.forEach((warning) => {
logger_1.default.warn(warning);
});
}
}
exports.printStatsWarnings = printStatsWarnings;
// Utility method to get style loaders
function getStyleLoaders(isServer, cssOptionsArg = {}) {
const cssOptions = {
// TODO turn esModule on later, see https://github.com/facebook/docusaurus/pull/6424
esModule: false,
...cssOptionsArg,
};
if (isServer) {
return cssOptions.modules
? [
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
]
: [
{
loader: mini_css_extract_plugin_1.default.loader,
options: {
// Don't emit CSS files for SSR (previously used null-loader)
// See https://github.com/webpack-contrib/mini-css-extract-plugin/issues/90#issuecomment-811991738
emit: false,
},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
];
}
return [
{
loader: mini_css_extract_plugin_1.default.loader,
options: {
esModule: true,
},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
postcssOptions: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: [
// eslint-disable-next-line global-require
require('autoprefixer'),
],
},
},
},
];
}
exports.getStyleLoaders = getStyleLoaders;
async function getCustomBabelConfigFilePath(siteDir) {
const customBabelConfigurationPath = path_1.default.join(siteDir, utils_1.BABEL_CONFIG_FILE_NAME);
return (await fs_extra_1.default.pathExists(customBabelConfigurationPath))
? customBabelConfigurationPath
: undefined;
}
exports.getCustomBabelConfigFilePath = getCustomBabelConfigFilePath;
function getBabelOptions({ isServer, babelOptions, } = {}) {
if (typeof babelOptions === 'string') {
return {
babelrc: false,
configFile: babelOptions,
caller: { name: isServer ? 'server' : 'client' },
};
}
return {
...(babelOptions ?? { presets: [require.resolve('../babel/preset')] }),
babelrc: false,
configFile: false,
caller: { name: isServer ? 'server' : 'client' },
};
}
exports.getBabelOptions = getBabelOptions;
// Name is generic on purpose
// we want to support multiple js loader implementations (babel + esbuild)
function getDefaultBabelLoader({ isServer, babelOptions, }) {
return {
loader: require.resolve('babel-loader'),
options: getBabelOptions({ isServer, babelOptions }),
};
}
const getCustomizableJSLoader = (jsLoader = 'babel') => ({ isServer, babelOptions, }) => jsLoader === 'babel'
? getDefaultBabelLoader({ isServer, babelOptions })
: jsLoader(isServer);
exports.getCustomizableJSLoader = getCustomizableJSLoader;
/**
* Helper function to modify webpack config
* @param configureWebpack a webpack config or a function to modify config
* @param config initial webpack config
* @param isServer indicates if this is a server webpack configuration
* @param jsLoader custom js loader config
* @param content content loaded by the plugin
* @returns final/ modified webpack config
*/
function applyConfigureWebpack(configureWebpack, config, isServer, jsLoader, content) {
// Export some utility functions
const utils = {
getStyleLoaders,
getJSLoader: (0, exports.getCustomizableJSLoader)(jsLoader),
};
if (typeof configureWebpack === 'function') {
const { mergeStrategy, ...res } = configureWebpack(config, isServer, utils, content) ?? {};
const customizeRules = mergeStrategy ?? {};
return (0, webpack_merge_1.mergeWithCustomize)({
customizeArray: (0, webpack_merge_1.customizeArray)(customizeRules),
customizeObject: (0, webpack_merge_1.customizeObject)(customizeRules),
})(config, res);
}
return config;
}
exports.applyConfigureWebpack = applyConfigureWebpack;
function applyConfigurePostCss(configurePostCss, config) {
// Not ideal heuristic but good enough for our use-case?
function isPostCssLoader(loader) {
return !!loader?.options?.postcssOptions;
}
// Does not handle all edge cases, but good enough for now
function overridePostCssOptions(entry) {
if (isPostCssLoader(entry)) {
entry.options.postcssOptions = configurePostCss(entry.options.postcssOptions);
}
else if (Array.isArray(entry.oneOf)) {
entry.oneOf.forEach((r) => {
if (r) {
overridePostCssOptions(r);
}
});
}
else if (Array.isArray(entry.use)) {
entry.use
.filter((u) => typeof u === 'object')
.forEach((rule) => overridePostCssOptions(rule));
}
}
config.module?.rules?.forEach((rule) => overridePostCssOptions(rule));
return config;
}
exports.applyConfigurePostCss = applyConfigurePostCss;
function compile(config) {
return new Promise((resolve, reject) => {
const compiler = (0, webpack_1.default)(config);
compiler.run((err, stats) => {
if (err) {
logger_1.default.error(err.stack ?? err);
if (err.details) {
logger_1.default.error(err.details);
}
reject(err);
}
// Let plugins consume all the stats
const errorsWarnings = stats?.toJson('errors-warnings');
if (stats?.hasErrors()) {
const statsErrorMessage = formatStatsErrorMessage(errorsWarnings);
reject(new Error(`Failed to compile due to Webpack errors.\n${statsErrorMessage}`));
}
printStatsWarnings(errorsWarnings);
// Webpack 5 requires calling close() so that persistent caching works
// See https://github.com/webpack/webpack.js.org/pull/4775
compiler.close((errClose) => {
if (errClose) {
logger_1.default.error(`Error while closing Webpack compiler: ${errClose}`);
reject(errClose);
}
else {
resolve();
}
});
});
});
}
exports.compile = compile;
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile, }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto_1.default.publicEncrypt(cert, Buffer.from('test'));
}
catch (err) {
logger_1.default.error `The certificate path=${crtFile} is invalid.`;
throw err;
}
try {
// privateDecrypt will throw an error with an invalid key
crypto_1.default.privateDecrypt(key, encrypted);
}
catch (err) {
logger_1.default.error `The certificate key path=${keyFile} is invalid.`;
throw err;
}
}
// Read file and throw an error if it doesn't exist
async function readEnvFile(file, type) {
if (!(await fs_extra_1.default.pathExists(file))) {
throw new Error(`You specified ${type} in your env, but the file "${file}" can't be found.`);
}
return fs_extra_1.default.readFile(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
async function getHttpsConfig() {
const appDirectory = await fs_extra_1.default.realpath(process.cwd());
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path_1.default.resolve(appDirectory, SSL_CRT_FILE);
const keyFile = path_1.default.resolve(appDirectory, SSL_KEY_FILE);
const config = {
cert: await readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: await readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
exports.getHttpsConfig = getHttpsConfig;
// See https://github.com/webpack-contrib/terser-webpack-plugin#parallel
function getTerserParallel() {
let terserParallel = true;
if (process.env.TERSER_PARALLEL === 'false') {
terserParallel = false;
}
else if (process.env.TERSER_PARALLEL &&
parseInt(process.env.TERSER_PARALLEL, 10) > 0) {
terserParallel = parseInt(process.env.TERSER_PARALLEL, 10);
}
return terserParallel;
}
function getMinimizer(useSimpleCssMinifier = false) {
const minimizer = [
new terser_webpack_plugin_1.default({
parallel: getTerserParallel(),
terserOptions: {
parse: {
// We want uglify-js to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 2020,
},
compress: {
ecma: 5,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using
// default. See https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
];
if (useSimpleCssMinifier) {
minimizer.push(new css_minimizer_webpack_plugin_1.default());
}
else {
minimizer.push(
// Using the array syntax to add 2 minimizers
// see https://github.com/webpack-contrib/css-minimizer-webpack-plugin#array
new css_minimizer_webpack_plugin_1.default({
minimizerOptions: [
// CssNano options
{
preset: require.resolve('@docusaurus/cssnano-preset'),
},
// CleanCss options
{
inline: false,
level: {
1: {
all: false,
removeWhitespace: true,
},
2: {
all: true,
restructureRules: true,
removeUnusedAtRules: false,
},
},
},
],
minify: [
css_minimizer_webpack_plugin_1.default.cssnanoMinify,
css_minimizer_webpack_plugin_1.default.cleanCssMinify,
],
}));
}
return minimizer;
}
exports.getMinimizer = getMinimizer;