fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

722
node_modules/webpack/lib/css/CssGenerator.js generated vendored Normal file
View File

@@ -0,0 +1,722 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const {
ConcatSource,
RawSource,
ReplaceSource,
SourceMapSource
} = require("webpack-sources");
const { UsageState } = require("../ExportsInfo");
const Generator = require("../Generator");
const InitFragment = require("../InitFragment");
const {
CSS_TYPE,
CSS_TYPES,
JAVASCRIPT_AND_CSS_TYPES,
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const CssImportDependency = require("../dependencies/CssImportDependency");
const HarmonyImportSideEffectDependency = require("../dependencies/HarmonyImportSideEffectDependency");
const memoize = require("../util/memoize");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
/** @typedef {import("../Compilation").DependencyConstructor} DependencyConstructor */
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").CssData} CssData */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceType} SourceType */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */
/** @typedef {import("./CssModulesPlugin").ModuleFactoryCacheEntry} ModuleFactoryCacheEntry */
/** @typedef {import("../CssModule")} CssModule */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("../../declarations/WebpackOptions").CssParserExportType} CssParserExportType */
const getPropertyName = memoize(() => require("../util/property"));
const getCssModulesPlugin = memoize(() => require("./CssModulesPlugin"));
class CssGenerator extends Generator {
/**
* Creates an instance of CssGenerator.
* @param {CssModuleGeneratorOptions} options options
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(options, moduleGraph) {
super();
this.options = options;
this._exportsOnly = options.exportsOnly;
this._esModule = options.esModule;
this._moduleGraph = moduleGraph;
/** @type {WeakMap<Source, ModuleFactoryCacheEntry>} */
this._moduleFactoryCache = new WeakMap();
}
/**
* Returns the reason this module cannot be concatenated, when one exists.
* @param {NormalModule} module module for which the bailout reason should be determined
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(module, context) {
if (!this._esModule) {
return "Module is not an ECMAScript module";
}
return undefined;
}
/**
* Generate JavaScript code that requires and concatenates all CSS imports
* @param {NormalModule} module the module to generate CSS text for
* @param {GenerateContext} generateContext the generate context
* @param {boolean} getDefaultExport whether to get the default export
* @returns {{ expr: string, type: CssParserExportType }[]} JavaScript code that concatenates all imported CSS
*/
_generateImportCode(module, generateContext, getDefaultExport = true) {
const moduleGraph = generateContext.moduleGraph;
/** @type {{ expr: string, type: CssParserExportType }[]} */
const parts = [];
// Iterate through module.dependencies to maintain source order
for (const dep of module.dependencies) {
if (dep instanceof CssImportDependency) {
const depModule = /** @type {CssModule} */ (moduleGraph.getModule(dep));
const importVar = generateContext.runtimeTemplate.moduleExports({
module: depModule,
chunkGraph: generateContext.chunkGraph,
request: depModule.userRequest,
weak: false,
runtimeRequirements: generateContext.runtimeRequirements
});
if (getDefaultExport) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.compatGetDefaultExport
);
parts.push({
expr: `(${RuntimeGlobals.compatGetDefaultExport}(${importVar})() || "")`,
type: /** @type {CssParserExportType} */ (depModule.exportType)
});
} else {
parts.push({
expr: importVar,
type: /** @type {CssParserExportType} */ (depModule.exportType)
});
}
}
}
return parts;
}
/**
* Generate CSS source for the current module
* @param {NormalModule} module the module to generate CSS source for
* @param {GenerateContext} generateContext the generate context
* @returns {Source | null} the CSS source
*/
_generateContentSource(module, generateContext) {
const moduleSourceContent = /** @type {Source} */ (
this.generate(module, {
...generateContext,
type: CSS_TYPE
})
);
if (!moduleSourceContent) {
return null;
}
const compilation = generateContext.runtimeTemplate.compilation;
// For non-link exportTypes (style, text, css-style-sheet), url() in the CSS
// is resolved relative to the document URL (for <style> tags and CSSStyleSheet),
// not relative to any output file. Use empty undoPath so urls are relative to
// the output root.
const undoPath = "";
const CssModulesPlugin = getCssModulesPlugin();
const hooks = CssModulesPlugin.getCompilationHooks(compilation);
return CssModulesPlugin.renderModule(
/** @type {CssModule} */ (module),
{
undoPath,
moduleSourceContent,
moduleFactoryCache: this._moduleFactoryCache,
runtimeTemplate: generateContext.runtimeTemplate
},
hooks
);
}
/**
* Convert a CSS Source to a JS string literal Source, preserving source map.
* Wraps the CSS content with JSON.stringify so it can be embedded in JS code.
* @param {Source} cssSource the CSS source
* @param {NormalModule} module the module
* @returns {Source} a Source representing a JS string literal
*/
_cssSourceToJsStringLiteral(cssSource, module) {
const { source, map } = cssSource.sourceAndMap();
const content = /** @type {string} */ (source);
const escaped = JSON.stringify(content);
if (map) {
return new SourceMapSource(escaped, module.identifier(), map, content);
}
return new RawSource(escaped);
}
/**
* Processes the provided module.
* @param {NormalModule} module the current module
* @param {Dependency} dependency the dependency to generate
* @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
* @param {ReplaceSource} source the current replace source which can be modified
* @param {GenerateContext & { cssData: CssData }} generateContext the render context
* @returns {void}
*/
sourceDependency(module, dependency, initFragments, source, generateContext) {
const constructor =
/** @type {DependencyConstructor} */
(dependency.constructor);
const template = generateContext.dependencyTemplates.get(constructor);
if (!template) {
throw new Error(
`No template for dependency: ${dependency.constructor.name}`
);
}
/** @type {DependencyTemplateContext} */
/** @type {InitFragment<GenerateContext>[] | undefined} */
let chunkInitFragments;
/** @type {DependencyTemplateContext} */
const templateContext = {
runtimeTemplate: generateContext.runtimeTemplate,
dependencyTemplates: generateContext.dependencyTemplates,
moduleGraph: generateContext.moduleGraph,
chunkGraph: generateContext.chunkGraph,
module,
runtime: generateContext.runtime,
runtimeRequirements: generateContext.runtimeRequirements,
concatenationScope: generateContext.concatenationScope,
codeGenerationResults:
/** @type {CodeGenerationResults} */
(generateContext.codeGenerationResults),
initFragments,
cssData: generateContext.cssData,
type: generateContext.type,
get chunkInitFragments() {
if (!chunkInitFragments) {
const data =
/** @type {NonNullable<GenerateContext["getData"]>} */
(generateContext.getData)();
chunkInitFragments = data.get("chunkInitFragments");
if (!chunkInitFragments) {
chunkInitFragments = [];
data.set("chunkInitFragments", chunkInitFragments);
}
}
return chunkInitFragments;
}
};
template.apply(dependency, source, templateContext);
}
/**
* Processes the provided module.
* @param {NormalModule} module the module to generate
* @param {InitFragment<GenerateContext>[]} initFragments mutable list of init fragments
* @param {ReplaceSource} source the current replace source which can be modified
* @param {GenerateContext & { cssData: CssData }} generateContext the generateContext
* @returns {void}
*/
sourceModule(module, initFragments, source, generateContext) {
for (const dependency of module.dependencies) {
this.sourceDependency(
module,
dependency,
initFragments,
source,
generateContext
);
}
if (module.presentationalDependencies !== undefined) {
for (const dependency of module.presentationalDependencies) {
this.sourceDependency(
module,
dependency,
initFragments,
source,
generateContext
);
}
}
}
/**
* Generates generated code for this runtime module.
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(module, generateContext) {
const exportType = /** @type {CssModule} */ (module).exportType || "link";
const source =
generateContext.type === JAVASCRIPT_TYPE && exportType === "link"
? new ReplaceSource(new RawSource(""))
: new ReplaceSource(/** @type {Source} */ (module.originalSource()));
/** @type {InitFragment<GenerateContext>[]} */
const initFragments = [];
/** @type {CssData} */
const cssData = {
esModule: /** @type {boolean} */ (this._esModule),
exports: new Map()
};
this.sourceModule(module, initFragments, source, {
...generateContext,
cssData
});
switch (generateContext.type) {
case JAVASCRIPT_TYPE: {
const generateContentCode = () => {
switch (exportType) {
case "style": {
const cssSource = this._generateContentSource(
module,
generateContext
);
if (!cssSource) return "";
const moduleId = generateContext.chunkGraph.getModuleId(module);
generateContext.runtimeRequirements.add(
RuntimeGlobals.cssInjectStyle
);
return new ConcatSource(
`${RuntimeGlobals.cssInjectStyle}(${JSON.stringify(moduleId || "")}, `,
this._cssSourceToJsStringLiteral(cssSource, module),
");"
);
}
default:
return "";
}
};
const generateImportCode = () => {
switch (exportType) {
case "style": {
return this._generateImportCode(module, generateContext, false)
.map((part) => `${part.expr};`)
.join("\n");
}
default:
return "";
}
};
const generateExportCode = () => {
/** @returns {Source} generated CSS text as JS expression */
const generateCssText = () => {
const importCode = this._generateImportCode(
module,
generateContext
);
const cssSource = this._generateContentSource(
module,
generateContext
);
let jsLiteral = cssSource
? this._cssSourceToJsStringLiteral(cssSource, module)
: new RawSource('""');
if (importCode.length > 0) {
if (
exportType === "css-style-sheet" ||
importCode.some((part) => part.type !== exportType)
) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.cssMergeStyleSheets
);
const args = importCode.map((part) => part.expr);
jsLiteral = new ConcatSource(
`${RuntimeGlobals.cssMergeStyleSheets}([${args.join(", ")}, `,
jsLiteral,
"])"
);
} else {
jsLiteral = new ConcatSource(
`${generateContext.runtimeTemplate.concatenation(
...importCode
)} + `,
jsLiteral
);
}
}
if (
exportType === "css-style-sheet" &&
typeof (/** @type {BuildInfo} */ (module.buildInfo).charset) !==
"undefined"
) {
jsLiteral = new ConcatSource(
`'@charset "${/** @type {BuildInfo} */ (module.buildInfo).charset}";\\n' + `,
jsLiteral
);
}
return jsLiteral;
};
/**
* Generates js default export.
* @returns {Source | null} the default export
*/
const generateJSDefaultExport = () => {
switch (exportType) {
case "text": {
return generateCssText();
}
case "css-style-sheet": {
const constOrVar =
generateContext.runtimeTemplate.renderConst();
const cssText = generateCssText();
const fnPrefix =
generateContext.runtimeTemplate.supportsArrowFunction()
? "() => {\n"
: "function() {\n";
const body =
`${constOrVar} sheet = new CSSStyleSheet();\n` +
"sheet.replaceSync(cssText);\n" +
"return sheet;\n";
return new ConcatSource(
`(${fnPrefix}${constOrVar} cssText = `,
cssText,
`;\n${body}})()`
);
}
default:
return null;
}
};
const isCSSModule = /** @type {BuildMeta} */ (module.buildMeta)
.isCSSModule;
/** @type {Source | null} */
const defaultExport = generateJSDefaultExport();
/** @type {BuildInfo} */
(module.buildInfo).cssData = cssData;
// Required for HMR
if (module.hot) {
generateContext.runtimeRequirements.add(RuntimeGlobals.module);
}
if (!defaultExport && cssData.exports.size === 0 && !isCSSModule) {
return new RawSource("");
}
if (generateContext.concatenationScope) {
const source = new ConcatSource();
/** @type {Set<string>} */
const usedIdentifiers = new Set();
const { RESERVED_IDENTIFIER } = getPropertyName();
if (defaultExport) {
const usedName = generateContext.moduleGraph
.getExportInfo(module, "default")
.getUsedName("default", generateContext.runtime);
if (usedName) {
let identifier = Template.toIdentifier(usedName);
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
usedIdentifiers.add(identifier);
generateContext.concatenationScope.registerExport(
"default",
identifier
);
source.add(
`${generateContext.runtimeTemplate.renderConst()} ${identifier} = `
);
source.add(defaultExport);
source.add(";\n");
}
}
for (const [name, v] of cssData.exports) {
const usedName = generateContext.moduleGraph
.getExportInfo(module, name)
.getUsedName(name, generateContext.runtime);
if (!usedName) {
continue;
}
let identifier = Template.toIdentifier(usedName);
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
let i = 0;
while (usedIdentifiers.has(identifier)) {
identifier = Template.toIdentifier(name + i);
i += 1;
}
usedIdentifiers.add(identifier);
generateContext.concatenationScope.registerExport(
name,
identifier
);
source.add(
`${generateContext.runtimeTemplate.renderConst()} ${identifier} = ${JSON.stringify(v)};\n`
);
}
return source;
}
const needNsObj =
this._esModule &&
generateContext.moduleGraph
.getExportsInfo(module)
.otherExportsInfo.getUsed(generateContext.runtime) !==
UsageState.Unused;
if (needNsObj) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.makeNamespaceObject
);
}
// Should be after `concatenationScope` to allow module inlining
generateContext.runtimeRequirements.add(RuntimeGlobals.module);
if (!isCSSModule && !needNsObj) {
return new ConcatSource(
`${module.moduleArgument}.exports = `,
/** @type {Source} */ (defaultExport)
);
}
const result = new ConcatSource();
result.add(
`${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
module.moduleArgument
}.exports = {\n`
);
if (defaultExport) {
result.add('\t"default": ');
result.add(defaultExport);
if (cssData.exports.size > 0) {
result.add(",\n");
}
}
/** @type {string[]} */
const exportEntries = [];
for (const [name, v] of cssData.exports) {
exportEntries.push(
`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`
);
}
if (exportEntries.length > 0) {
result.add(exportEntries.join(",\n"));
}
result.add(`\n}${needNsObj ? ")" : ""};`);
return result;
};
const codeParts = this._exportsOnly
? [generateExportCode()]
: [generateImportCode(), generateContentCode(), generateExportCode()];
const source = new ConcatSource();
for (const part of codeParts) {
if (part) {
source.add(part);
source.add("\n");
}
}
return source;
}
case CSS_TYPE: {
if (
!(
this._exportsOnly ||
/** @type {boolean} */ (exportType && exportType !== "link")
)
) {
generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
}
return InitFragment.addToSource(source, initFragments, generateContext);
}
default:
return null;
}
}
/**
* Generates fallback output for the provided error condition.
* @param {Error} error the error
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case JAVASCRIPT_TYPE: {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
case CSS_TYPE: {
return new RawSource(`/**\n ${error.message} \n**/`);
}
default:
return null;
}
}
/**
* Returns the source types available for this module.
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
const exportType = /** @type {CssModule} */ (module).exportType || "link";
if (exportType === "style") {
return JAVASCRIPT_TYPES;
}
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
if (
exportType === "link" &&
connection.dependency instanceof CssImportDependency
) {
continue;
}
// when no hmr required, css module js output contains no sideEffects at all
// js sideeffect connection doesn't require js type output
if (connection.dependency instanceof HarmonyImportSideEffectDependency) {
continue;
}
if (!connection.originModule) {
continue;
}
if (connection.originModule.type.split("/")[0] !== CSS_TYPE) {
sourceTypes.add(JAVASCRIPT_TYPE);
} else {
const originModule = /** @type {CssModule} */ connection.originModule;
const originExportType = /** @type {CssModule} */ (originModule)
.exportType;
if (
/** @type {boolean} */ (
originExportType && originExportType !== "link"
)
) {
sourceTypes.add(JAVASCRIPT_TYPE);
}
}
}
if (
this._exportsOnly ||
/** @type {boolean} */ (exportType && exportType !== "link")
) {
if (sourceTypes.has(JAVASCRIPT_TYPE)) {
return JAVASCRIPT_TYPES;
}
return new Set();
}
if (sourceTypes.has(JAVASCRIPT_TYPE)) {
return JAVASCRIPT_AND_CSS_TYPES;
}
return CSS_TYPES;
}
/**
* Returns the estimated size for the requested source type.
* @param {NormalModule} module the module
* @param {SourceType=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
switch (type) {
case JAVASCRIPT_TYPE: {
const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData;
if (!cssData) {
return 42;
}
if (cssData.exports.size === 0) {
if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) {
return 42;
}
return 0;
}
const exports = cssData.exports;
/** @type {Record<string, string>} */
const exportsObj = {};
for (const [key, value] of exports) {
exportsObj[key] = value;
}
const stringifiedExports = JSON.stringify(exportsObj);
return stringifiedExports.length + 42;
}
case CSS_TYPE: {
const originalSource = module.originalSource();
if (!originalSource) {
return 0;
}
return originalSource.size();
}
default:
return 0;
}
}
/**
* Updates the hash with the data contributed by this instance.
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
updateHash(hash, { module }) {
hash.update(/** @type {boolean} */ (this._esModule).toString());
hash.update(/** @type {boolean} */ (this._exportsOnly).toString());
}
}
module.exports = CssGenerator;

View File

@@ -0,0 +1,180 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Natsu @xiaoxiaojx
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/**
* @typedef {object} CssInjectCompilationHooks
* @property {SyncWaterfallHook<[string, Chunk]>} createStyle
*/
/** @type {WeakMap<Compilation, CssInjectCompilationHooks>} */
const compilationHooksMap = new WeakMap();
class CssInjectStyleRuntimeModule extends RuntimeModule {
/**
* @param {Compilation} compilation the compilation
* @returns {CssInjectCompilationHooks} hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
createStyle: new SyncWaterfallHook(["source", "chunk"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("css inject style", RuntimeModule.STAGE_ATTACH);
/** @type {ReadOnlyRuntimeRequirements} */
this._runtimeRequirements = runtimeRequirements;
}
/**
* Generates runtime code for this runtime module.
* @returns {string | null} runtime code
*/
generate() {
const compilation = /** @type {Compilation} */ (this.compilation);
const { runtimeTemplate, outputOptions } = compilation;
const { uniqueName } = outputOptions;
const { _runtimeRequirements } = this;
/** @type {boolean} */
const withHmr =
_runtimeRequirements &&
_runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers);
const { createStyle } =
CssInjectStyleRuntimeModule.getCompilationHooks(compilation);
const createStyleElementCode = Template.asString([
"var style = document.createElement('style');",
"",
`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
`style.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
),
"}",
'style.setAttribute("data-webpack", getDataWebpackId(key));'
]);
return Template.asString([
`var dataWebpackPrefix = ${uniqueName ? JSON.stringify(`${uniqueName}:`) : '"webpack:"'};`,
"",
"function getDataWebpackId(identifier) {",
Template.indent("return dataWebpackPrefix + identifier;"),
"}",
"",
"function applyStyle(styleElement, css) {",
Template.indent("styleElement.textContent = css;"),
"}",
"",
"function removeStyleElement(styleElement) {",
Template.indent([
"if (styleElement.parentNode) {",
Template.indent("styleElement.parentNode.removeChild(styleElement);"),
"}"
]),
"}",
"",
"function findStyleElement(identifier) {",
Template.indent([
"var elements = document.getElementsByTagName('style');",
"for (var i = 0; i < elements.length; i++) {",
Template.indent([
"var el = elements[i];",
"if (el.getAttribute('data-webpack') === getDataWebpackId(identifier)) {",
Template.indent("return el;"),
"}"
]),
"}",
"return null;"
]),
"}",
"",
"function insertStyleElement(key) {",
Template.indent([
createStyle.call(
createStyleElementCode,
/** @type {Chunk} */ (this.chunk)
),
"",
"document.head.appendChild(style);",
"",
"return style;"
]),
"}",
"",
`${RuntimeGlobals.cssInjectStyle} = ${runtimeTemplate.basicFunction(
"identifier, css",
[
"var element = findStyleElement(identifier);",
"if (element) {",
Template.indent("applyStyle(element, css);"),
"} else {",
Template.indent([
"var element = insertStyleElement(identifier);",
"applyStyle(element, css);"
]),
"}"
]
)};`,
"",
`${RuntimeGlobals.cssInjectStyle}.removeModules = ${runtimeTemplate.basicFunction(
"removedModules",
[
"if (!removedModules) return;",
"var identifiers = Array.isArray(removedModules) ? removedModules : [removedModules];",
"for (var i = 0; i < identifiers.length; i++) {",
Template.indent([
"var identifier = identifiers[i];",
"var element = findStyleElement(identifier);",
"if (element) {",
Template.indent("removeStyleElement(element);"),
"}"
]),
"}"
]
)};`,
withHmr
? Template.asString([
`${RuntimeGlobals.hmrDownloadUpdateHandlers}.cssInjectStyle = ${runtimeTemplate.basicFunction(
"chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
[
"if (removedModules) {",
Template.indent(
`${RuntimeGlobals.cssInjectStyle}.removeModules(removedModules);`
),
"}"
]
)};`
])
: "// no css inject style HMR download handler"
]);
}
}
module.exports = CssInjectStyleRuntimeModule;

511
node_modules/webpack/lib/css/CssLoadingRuntimeModule.js generated vendored Normal file
View File

@@ -0,0 +1,511 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
const compileBooleanMatcher = require("../util/compileBooleanMatcher");
const { chunkHasCss } = require("./CssModulesPlugin");
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Chunk").ChunkId} ChunkId */
/** @typedef {import("../ChunkGraph")} ChunkGraph */
/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
/**
* @typedef {object} CssLoadingRuntimeModulePluginHooks
* @property {SyncWaterfallHook<[string, Chunk]>} createStylesheet
* @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
* @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
*/
/** @type {WeakMap<Compilation, CssLoadingRuntimeModulePluginHooks>} */
const compilationHooksMap = new WeakMap();
class CssLoadingRuntimeModule extends RuntimeModule {
/**
* @param {Compilation} compilation the compilation
* @returns {CssLoadingRuntimeModulePluginHooks} hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
createStylesheet: new SyncWaterfallHook(["source", "chunk"]),
linkPreload: new SyncWaterfallHook(["source", "chunk"]),
linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("css loading", 10);
this._runtimeRequirements = runtimeRequirements;
}
/**
* Generates runtime code for this runtime module.
* @returns {string | null} runtime code
*/
generate() {
const { _runtimeRequirements } = this;
const compilation = /** @type {Compilation} */ (this.compilation);
const chunk = /** @type {Chunk} */ (this.chunk);
const {
chunkGraph,
runtimeTemplate,
outputOptions: {
crossOriginLoading,
uniqueName,
chunkLoadTimeout: loadTimeout,
charset
}
} = compilation;
const fn = RuntimeGlobals.ensureChunkHandlers;
const conditionMap = chunkGraph.getChunkConditionMap(
chunk,
/**
* @param {Chunk} chunk the chunk
* @param {ChunkGraph} chunkGraph the chunk graph
* @returns {boolean} true, if the chunk has css
*/
(chunk, chunkGraph) =>
Boolean(chunkGraph.getChunkModulesIterableBySourceType(chunk, CSS_TYPE))
);
const hasCssMatcher = compileBooleanMatcher(conditionMap);
const withLoading =
_runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) &&
hasCssMatcher !== false;
/** @type {boolean} */
const withHmr = _runtimeRequirements.has(
RuntimeGlobals.hmrDownloadUpdateHandlers
);
/** @type {Set<ChunkId>} */
const initialChunkIds = new Set();
for (const c of chunk.getAllInitialChunks()) {
if (chunkHasCss(c, chunkGraph)) {
initialChunkIds.add(/** @type {ChunkId} */ (c.id));
}
}
if (!withLoading && !withHmr) {
return null;
}
const environment = compilation.outputOptions.environment;
const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
const withPrefetch =
this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
(environment.document || isNeutralPlatform) &&
chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasCss);
const withPreload =
this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
(environment.document || isNeutralPlatform) &&
chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasCss);
const { linkPreload, linkPrefetch, createStylesheet } =
CssLoadingRuntimeModule.getCompilationHooks(compilation);
const withFetchPriority = _runtimeRequirements.has(
RuntimeGlobals.hasFetchPriority
);
const stateExpression = withHmr
? `${RuntimeGlobals.hmrRuntimeStatePrefix}_css`
: undefined;
const code = Template.asString([
"link = document.createElement('link');",
charset ? "link.charset = 'utf-8';" : "",
`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
`link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
),
"}",
uniqueName
? 'link.setAttribute("data-webpack", uniqueName + ":" + key);'
: "",
withFetchPriority
? Template.asString([
"if(fetchPriority) {",
Template.indent(
'link.setAttribute("fetchpriority", fetchPriority);'
),
"}"
])
: "",
"link.setAttribute(loadingAttribute, 1);",
'link.rel = "stylesheet";',
"link.href = url;",
crossOriginLoading
? crossOriginLoading === "use-credentials"
? 'link.crossOrigin = "use-credentials";'
: Template.asString([
"if (link.href.indexOf(window.location.origin + '/') !== 0) {",
Template.indent(
`link.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
),
"}"
])
: ""
]);
return Template.asString([
"// object to store loaded and loading chunks",
"// undefined = chunk not loaded, null = chunk preloaded/prefetched",
"// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded",
`var installedChunks = ${
stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
}{`,
Template.indent(
Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join(
",\n"
)
),
"};",
"",
uniqueName
? `var uniqueName = ${JSON.stringify(
runtimeTemplate.outputOptions.uniqueName
)};`
: "// data-webpack is not used as build has no uniqueName",
withLoading || withHmr
? Template.asString([
'var loadingAttribute = "data-webpack-loading";',
`var loadStylesheet = ${runtimeTemplate.basicFunction(
`chunkId, url, done${
withFetchPriority ? ", fetchPriority" : ""
}${withHmr ? ", hmr" : ""}`,
[
'var link, needAttach, key = "chunk-" + chunkId;',
withHmr ? "if(!hmr) {" : "",
'var links = document.getElementsByTagName("link");',
"for(var i = 0; i < links.length; i++) {",
Template.indent([
"var l = links[i];",
`if(l.rel == "stylesheet" && (${
withHmr
? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)'
: 'l.href == url || l.getAttribute("href") == url'
}${
uniqueName
? ' || l.getAttribute("data-webpack") == uniqueName + ":" + key'
: ""
})) { link = l; break; }`
]),
"}",
"if(!done) return link;",
withHmr ? "}" : "",
"if(!link) {",
Template.indent([
"needAttach = true;",
createStylesheet.call(code, /** @type {Chunk} */ (this.chunk))
]),
"}",
`var onLinkComplete = ${runtimeTemplate.basicFunction(
"prev, event",
Template.asString([
"link.onerror = link.onload = null;",
"link.removeAttribute(loadingAttribute);",
"clearTimeout(timeout);",
'if(event && event.type != "load") link.parentNode.removeChild(link)',
"done(event);",
"if(prev) return prev(event);"
])
)};`,
"if(link.getAttribute(loadingAttribute)) {",
Template.indent([
`var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`,
"link.onerror = onLinkComplete.bind(null, link.onerror);",
"link.onload = onLinkComplete.bind(null, link.onload);"
]),
"} else onLinkComplete(undefined, { type: 'load', target: link });", // We assume any existing stylesheet is render blocking
withHmr && withFetchPriority
? 'if (hmr && hmr.getAttribute("fetchpriority")) link.setAttribute("fetchpriority", hmr.getAttribute("fetchpriority"));'
: "",
withHmr ? "hmr ? document.head.insertBefore(link, hmr) :" : "",
"needAttach && document.head.appendChild(link);",
"return link;"
]
)};`
])
: "",
withLoading
? Template.asString([
`${fn}.css = ${runtimeTemplate.basicFunction(
`chunkId, promises${withFetchPriority ? " , fetchPriority" : ""}`,
[
"// css chunk loading",
`var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
'if(installedChunkData !== 0) { // 0 means "already installed".',
Template.indent([
"",
'// a Promise means "currently loading".',
"if(installedChunkData) {",
Template.indent(["promises.push(installedChunkData[2]);"]),
"} else {",
Template.indent([
hasCssMatcher === true
? "if(true) { // all chunks have CSS"
: `if(${hasCssMatcher("chunkId")}) {`,
Template.indent([
"// setup Promise in chunk cache",
`var promise = new Promise(${runtimeTemplate.expressionFunction(
"installedChunkData = installedChunks[chunkId] = [resolve, reject]",
"resolve, reject"
)});`,
"promises.push(installedChunkData[2] = promise);",
"",
"// start chunk loading",
`var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`var loadingEnded = ${runtimeTemplate.basicFunction(
"event",
[
`if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`,
Template.indent([
"installedChunkData = installedChunks[chunkId];",
"if(installedChunkData !== 0) installedChunks[chunkId] = undefined;",
"if(installedChunkData) {",
Template.indent([
'if(event.type !== "load") {',
Template.indent([
"var errorType = event && event.type;",
"var realHref = event && event.target && event.target.href;",
"error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';",
"error.name = 'ChunkLoadError';",
"error.type = errorType;",
"error.request = realHref;",
"installedChunkData[1](error);"
]),
"} else {",
Template.indent([
"installedChunks[chunkId] = 0;",
"installedChunkData[0]();"
]),
"}"
]),
"}"
]),
"}"
]
)};`,
isNeutralPlatform
? "if (typeof document !== 'undefined') {"
: "",
Template.indent([
`loadStylesheet(chunkId, url, loadingEnded${
withFetchPriority ? ", fetchPriority" : ""
});`
]),
isNeutralPlatform
? "} else { loadingEnded({ type: 'load' }); }"
: ""
]),
"} else installedChunks[chunkId] = 0;"
]),
"}"
]),
"}"
]
)};`
])
: "// no chunk loading",
"",
withPrefetch && hasCssMatcher !== false
? `${
RuntimeGlobals.prefetchChunkHandlers
}.s = ${runtimeTemplate.basicFunction("chunkId", [
`if((!${
RuntimeGlobals.hasOwnProperty
}(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
hasCssMatcher === true ? "true" : hasCssMatcher("chunkId")
}) {`,
Template.indent([
"installedChunks[chunkId] = null;",
isNeutralPlatform
? "if (typeof document === 'undefined') return;"
: "",
linkPrefetch.call(
Template.asString([
"var link = document.createElement('link');",
charset ? "link.charset = 'utf-8';" : "",
crossOriginLoading
? `link.crossOrigin = ${JSON.stringify(
crossOriginLoading
)};`
: "",
`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
`link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
),
"}",
'link.rel = "prefetch";',
'link.as = "style";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`
]),
chunk
),
"document.head.appendChild(link);"
]),
"}"
])};`
: "// no prefetching",
"",
withPreload && hasCssMatcher !== false
? `${
RuntimeGlobals.preloadChunkHandlers
}.s = ${runtimeTemplate.basicFunction("chunkId", [
`if((!${
RuntimeGlobals.hasOwnProperty
}(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
hasCssMatcher === true ? "true" : hasCssMatcher("chunkId")
}) {`,
Template.indent([
"installedChunks[chunkId] = null;",
isNeutralPlatform
? "if (typeof document === 'undefined') return;"
: "",
linkPreload.call(
Template.asString([
"var link = document.createElement('link');",
charset ? "link.charset = 'utf-8';" : "",
`if (${RuntimeGlobals.scriptNonce}) {`,
Template.indent(
`link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
),
"}",
'link.rel = "preload";',
'link.as = "style";',
`link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
crossOriginLoading
? crossOriginLoading === "use-credentials"
? 'link.crossOrigin = "use-credentials";'
: Template.asString([
"if (link.href.indexOf(window.location.origin + '/') !== 0) {",
Template.indent(
`link.crossOrigin = ${JSON.stringify(
crossOriginLoading
)};`
),
"}"
])
: ""
]),
chunk
),
"document.head.appendChild(link);"
]),
"}"
])};`
: "// no preloaded",
withHmr
? Template.asString([
"var oldTags = [];",
"var newTags = [];",
`var applyHandler = ${runtimeTemplate.basicFunction("options", [
`return { dispose: ${runtimeTemplate.basicFunction("", [
"while(oldTags.length) {",
Template.indent([
"var oldTag = oldTags.pop();",
"if(oldTag && oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"
]),
"}"
])}, apply: ${runtimeTemplate.basicFunction("", [
"while(newTags.length) {",
Template.indent([
"var newTag = newTags.pop();",
"newTag.sheet.disabled = false"
]),
"}"
])} };`
])}`,
`var cssTextKey = ${runtimeTemplate.returningFunction(
`Array.from(link.sheet.cssRules, ${runtimeTemplate.returningFunction(
"r.cssText",
"r"
)}).join()`,
"link"
)};`,
`${
RuntimeGlobals.hmrDownloadUpdateHandlers
}.css = ${runtimeTemplate.basicFunction(
"chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
[
isNeutralPlatform
? "if (typeof document === 'undefined') return;"
: "",
"applyHandlers.push(applyHandler);",
"// Read CSS removed chunks from update manifest",
"var cssRemovedChunks = css && css.r;",
`chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [
`var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`,
`var url = ${RuntimeGlobals.publicPath} + filename;`,
"var oldTag = loadStylesheet(chunkId, url);",
`if(!oldTag && !${withHmr} ) return;`,
"// Skip if CSS was removed",
"if(cssRemovedChunks && cssRemovedChunks.indexOf(chunkId) >= 0) {",
Template.indent(["oldTags.push(oldTag);", "return;"]),
"}",
"",
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
`promises.push(new Promise(${runtimeTemplate.basicFunction(
"resolve, reject",
[
`var link = loadStylesheet(chunkId, url + (url.indexOf("?") < 0 ? "?" : "&") + "hmr=" + Date.now(), ${runtimeTemplate.basicFunction(
"event",
[
'if(event.type !== "load") {',
Template.indent([
"var errorType = event && event.type;",
"var realHref = event && event.target && event.target.href;",
"error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';",
"error.name = 'ChunkLoadError';",
"error.type = errorType;",
"error.request = realHref;",
"reject(error);"
]),
"} else {",
Template.indent([
"try { if(cssTextKey(oldTag) == cssTextKey(link)) { if(link.parentNode) link.parentNode.removeChild(link); return resolve(); } } catch(e) {}",
"link.sheet.disabled = true;",
"oldTags.push(oldTag);",
"newTags.push(link);",
"resolve();"
]),
"}"
]
)}, ${withFetchPriority ? "undefined," : ""} oldTag);`
]
)}));`
])});`
]
)}`
])
: "// no hmr"
]);
}
}
module.exports = CssLoadingRuntimeModule;

View File

@@ -0,0 +1,57 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Natsu @xiaoxiaojx
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
/** @typedef {import("../Chunk")} Chunk */
class CssMergeStyleSheetsRuntimeModule extends RuntimeModule {
constructor() {
super("css merge stylesheets");
}
/**
* Generates runtime code for this runtime module.
* @returns {string | null} runtime code
*/
generate() {
const { runtimeTemplate } = /** @type {import("../Compilation")} */ (
this.compilation
);
return Template.asString([
`${RuntimeGlobals.cssMergeStyleSheets} = ${runtimeTemplate.basicFunction(
"sheets",
[
"var sheetsArray = Array.isArray(sheets) ? sheets : [sheets];",
"var cssTexts = [];",
"for (var i = 0; i < sheetsArray.length; i++) {",
Template.indent([
"var s = sheetsArray[i];",
"if (!s) continue;",
"if (typeof s === 'string') {",
Template.indent("cssTexts.push(s);"),
"} else if (s.cssRules) {",
Template.indent([
"var rules = s.cssRules;",
"for (var j = 0; j < rules.length; j++) {",
Template.indent("cssTexts.push(rules[j].cssText);"),
"}"
]),
"}"
]),
"}",
"return cssTexts.join('');"
]
)};`
]);
}
}
module.exports = CssMergeStyleSheetsRuntimeModule;

1104
node_modules/webpack/lib/css/CssModulesPlugin.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

2788
node_modules/webpack/lib/css/CssParser.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1874
node_modules/webpack/lib/css/walkCssTokens.js generated vendored Normal file

File diff suppressed because it is too large Load Diff