| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | const RuntimeGlobals = require("../RuntimeGlobals");
|
|---|
| 9 | const RuntimeModule = require("../RuntimeModule");
|
|---|
| 10 | const Template = require("../Template");
|
|---|
| 11 | const {
|
|---|
| 12 | compareModulesByIdentifier,
|
|---|
| 13 | compareStrings
|
|---|
| 14 | } = require("../util/comparators");
|
|---|
| 15 |
|
|---|
| 16 | /** @typedef {import("../Chunk")} Chunk */
|
|---|
| 17 | /** @typedef {import("../ChunkGraph")} ChunkGraph */
|
|---|
| 18 | /** @typedef {import("../Compilation")} Compilation */
|
|---|
| 19 | /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
|
|---|
| 20 |
|
|---|
| 21 | class ShareRuntimeModule extends RuntimeModule {
|
|---|
| 22 | constructor() {
|
|---|
| 23 | super("sharing");
|
|---|
| 24 | }
|
|---|
| 25 |
|
|---|
| 26 | /**
|
|---|
| 27 | * Generates runtime code for this runtime module.
|
|---|
| 28 | * @returns {string | null} runtime code
|
|---|
| 29 | */
|
|---|
| 30 | generate() {
|
|---|
| 31 | const compilation = /** @type {Compilation} */ (this.compilation);
|
|---|
| 32 | const {
|
|---|
| 33 | runtimeTemplate,
|
|---|
| 34 | outputOptions: { uniqueName, ignoreBrowserWarnings }
|
|---|
| 35 | } = compilation;
|
|---|
| 36 | const codeGenerationResults =
|
|---|
| 37 | /** @type {CodeGenerationResults} */
|
|---|
| 38 | (compilation.codeGenerationResults);
|
|---|
| 39 | const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
|
|---|
| 40 | /** @type {Map<string, Map<number, Set<string>>>} */
|
|---|
| 41 | const initCodePerScope = new Map();
|
|---|
| 42 | for (const chunk of /** @type {Chunk} */ (
|
|---|
| 43 | this.chunk
|
|---|
| 44 | ).getAllReferencedChunks()) {
|
|---|
| 45 | const modules = chunkGraph.getOrderedChunkModulesIterableBySourceType(
|
|---|
| 46 | chunk,
|
|---|
| 47 | "share-init",
|
|---|
| 48 | compareModulesByIdentifier
|
|---|
| 49 | );
|
|---|
| 50 | if (!modules) continue;
|
|---|
| 51 | for (const m of modules) {
|
|---|
| 52 | const data = codeGenerationResults.getData(
|
|---|
| 53 | m,
|
|---|
| 54 | chunk.runtime,
|
|---|
| 55 | "share-init"
|
|---|
| 56 | );
|
|---|
| 57 | if (!data) continue;
|
|---|
| 58 | for (const item of data) {
|
|---|
| 59 | const { shareScope, initStage, init } = item;
|
|---|
| 60 | let stages = initCodePerScope.get(shareScope);
|
|---|
| 61 | if (stages === undefined) {
|
|---|
| 62 | initCodePerScope.set(shareScope, (stages = new Map()));
|
|---|
| 63 | }
|
|---|
| 64 | let list = stages.get(initStage || 0);
|
|---|
| 65 | if (list === undefined) {
|
|---|
| 66 | stages.set(initStage || 0, (list = new Set()));
|
|---|
| 67 | }
|
|---|
| 68 | list.add(init);
|
|---|
| 69 | }
|
|---|
| 70 | }
|
|---|
| 71 | }
|
|---|
| 72 | return Template.asString([
|
|---|
| 73 | `${RuntimeGlobals.shareScopeMap} = {};`,
|
|---|
| 74 | "var initPromises = {};",
|
|---|
| 75 | "var initTokens = {};",
|
|---|
| 76 | `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction(
|
|---|
| 77 | "name, initScope",
|
|---|
| 78 | [
|
|---|
| 79 | "if(!initScope) initScope = [];",
|
|---|
| 80 | "// handling circular init calls",
|
|---|
| 81 | "var initToken = initTokens[name];",
|
|---|
| 82 | "if(!initToken) initToken = initTokens[name] = {};",
|
|---|
| 83 | "if(initScope.indexOf(initToken) >= 0) return;",
|
|---|
| 84 | "initScope.push(initToken);",
|
|---|
| 85 | "// only runs once",
|
|---|
| 86 | "if(initPromises[name]) return initPromises[name];",
|
|---|
| 87 | "// creates a new share scope if needed",
|
|---|
| 88 | `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`,
|
|---|
| 89 | "// runs all init snippets from all modules reachable",
|
|---|
| 90 | `var scope = ${RuntimeGlobals.shareScopeMap}[name];`,
|
|---|
| 91 | `var warn = ${
|
|---|
| 92 | ignoreBrowserWarnings
|
|---|
| 93 | ? runtimeTemplate.basicFunction("", "")
|
|---|
| 94 | : runtimeTemplate.basicFunction("msg", [
|
|---|
| 95 | 'if (typeof console !== "undefined" && console.warn) console.warn(msg);'
|
|---|
| 96 | ])
|
|---|
| 97 | };`,
|
|---|
| 98 | `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`,
|
|---|
| 99 | `var register = ${runtimeTemplate.basicFunction(
|
|---|
| 100 | "name, version, factory, eager",
|
|---|
| 101 | [
|
|---|
| 102 | "var versions = scope[name] = scope[name] || {};",
|
|---|
| 103 | "var activeVersion = versions[version];",
|
|---|
| 104 | "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };"
|
|---|
| 105 | ]
|
|---|
| 106 | )};`,
|
|---|
| 107 | `var initExternal = ${runtimeTemplate.basicFunction("id", [
|
|---|
| 108 | `var handleError = ${runtimeTemplate.expressionFunction(
|
|---|
| 109 | 'warn("Initialization of sharing external failed: " + err)',
|
|---|
| 110 | "err"
|
|---|
| 111 | )};`,
|
|---|
| 112 | "try {",
|
|---|
| 113 | Template.indent([
|
|---|
| 114 | `var module = ${RuntimeGlobals.require}(id);`,
|
|---|
| 115 | "if(!module) return;",
|
|---|
| 116 | `var initFn = ${runtimeTemplate.returningFunction(
|
|---|
| 117 | `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`,
|
|---|
| 118 | "module"
|
|---|
| 119 | )}`,
|
|---|
| 120 | "if(module.then) return promises.push(module.then(initFn, handleError));",
|
|---|
| 121 | "var initResult = initFn(module);",
|
|---|
| 122 | "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));"
|
|---|
| 123 | ]),
|
|---|
| 124 | "} catch(err) { handleError(err); }"
|
|---|
| 125 | ])}`,
|
|---|
| 126 | "var promises = [];",
|
|---|
| 127 | "switch(name) {",
|
|---|
| 128 | ...[...initCodePerScope]
|
|---|
| 129 | .sort(([a], [b]) => compareStrings(a, b))
|
|---|
| 130 | .map(([name, stages]) =>
|
|---|
| 131 | Template.indent([
|
|---|
| 132 | `case ${JSON.stringify(name)}: {`,
|
|---|
| 133 | Template.indent(
|
|---|
| 134 | [...stages]
|
|---|
| 135 | .sort(([a], [b]) => a - b)
|
|---|
| 136 | .map(([, initCode]) => Template.asString([...initCode]))
|
|---|
| 137 | ),
|
|---|
| 138 | "}",
|
|---|
| 139 | "break;"
|
|---|
| 140 | ])
|
|---|
| 141 | ),
|
|---|
| 142 | "}",
|
|---|
| 143 | "if(!promises.length) return initPromises[name] = 1;",
|
|---|
| 144 | `return initPromises[name] = Promise.all(promises).then(${runtimeTemplate.returningFunction(
|
|---|
| 145 | "initPromises[name] = 1"
|
|---|
| 146 | )});`
|
|---|
| 147 | ]
|
|---|
| 148 | )};`
|
|---|
| 149 | ]);
|
|---|
| 150 | }
|
|---|
| 151 | }
|
|---|
| 152 |
|
|---|
| 153 | module.exports = ShareRuntimeModule;
|
|---|