1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra, Zackary Jackson @ScriptedAlchemy, Marais Rossouw @maraisr
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const { OriginalSource, RawSource } = require("webpack-sources");
|
---|
9 | const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
|
---|
10 | const Module = require("../Module");
|
---|
11 | const RuntimeGlobals = require("../RuntimeGlobals");
|
---|
12 | const Template = require("../Template");
|
---|
13 | const makeSerializable = require("../util/makeSerializable");
|
---|
14 | const ContainerExposedDependency = require("./ContainerExposedDependency");
|
---|
15 |
|
---|
16 | /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
|
---|
17 | /** @typedef {import("../ChunkGraph")} ChunkGraph */
|
---|
18 | /** @typedef {import("../ChunkGroup")} ChunkGroup */
|
---|
19 | /** @typedef {import("../Compilation")} Compilation */
|
---|
20 | /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
|
---|
21 | /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
|
---|
22 | /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
|
---|
23 | /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
|
---|
24 | /** @typedef {import("../RequestShortener")} RequestShortener */
|
---|
25 | /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
|
---|
26 | /** @typedef {import("../WebpackError")} WebpackError */
|
---|
27 | /** @typedef {import("../util/Hash")} Hash */
|
---|
28 | /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
|
---|
29 | /** @typedef {import("./ContainerEntryDependency")} ContainerEntryDependency */
|
---|
30 |
|
---|
31 | /**
|
---|
32 | * @typedef {Object} ExposeOptions
|
---|
33 | * @property {string[]} import requests to exposed modules (last one is exported)
|
---|
34 | * @property {string} name custom chunk name for the exposed module
|
---|
35 | */
|
---|
36 |
|
---|
37 | const SOURCE_TYPES = new Set(["javascript"]);
|
---|
38 |
|
---|
39 | class ContainerEntryModule extends Module {
|
---|
40 | /**
|
---|
41 | * @param {string} name container entry name
|
---|
42 | * @param {[string, ExposeOptions][]} exposes list of exposed modules
|
---|
43 | * @param {string} shareScope name of the share scope
|
---|
44 | */
|
---|
45 | constructor(name, exposes, shareScope) {
|
---|
46 | super("javascript/dynamic", null);
|
---|
47 | this._name = name;
|
---|
48 | this._exposes = exposes;
|
---|
49 | this._shareScope = shareScope;
|
---|
50 | }
|
---|
51 |
|
---|
52 | /**
|
---|
53 | * @returns {Set<string>} types available (do not mutate)
|
---|
54 | */
|
---|
55 | getSourceTypes() {
|
---|
56 | return SOURCE_TYPES;
|
---|
57 | }
|
---|
58 |
|
---|
59 | /**
|
---|
60 | * @returns {string} a unique identifier of the module
|
---|
61 | */
|
---|
62 | identifier() {
|
---|
63 | return `container entry (${this._shareScope}) ${JSON.stringify(
|
---|
64 | this._exposes
|
---|
65 | )}`;
|
---|
66 | }
|
---|
67 |
|
---|
68 | /**
|
---|
69 | * @param {RequestShortener} requestShortener the request shortener
|
---|
70 | * @returns {string} a user readable identifier of the module
|
---|
71 | */
|
---|
72 | readableIdentifier(requestShortener) {
|
---|
73 | return `container entry`;
|
---|
74 | }
|
---|
75 |
|
---|
76 | /**
|
---|
77 | * @param {LibIdentOptions} options options
|
---|
78 | * @returns {string | null} an identifier for library inclusion
|
---|
79 | */
|
---|
80 | libIdent(options) {
|
---|
81 | return `webpack/container/entry/${this._name}`;
|
---|
82 | }
|
---|
83 |
|
---|
84 | /**
|
---|
85 | * @param {NeedBuildContext} context context info
|
---|
86 | * @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
|
---|
87 | * @returns {void}
|
---|
88 | */
|
---|
89 | needBuild(context, callback) {
|
---|
90 | return callback(null, !this.buildMeta);
|
---|
91 | }
|
---|
92 |
|
---|
93 | /**
|
---|
94 | * @param {WebpackOptions} options webpack options
|
---|
95 | * @param {Compilation} compilation the compilation
|
---|
96 | * @param {ResolverWithOptions} resolver the resolver
|
---|
97 | * @param {InputFileSystem} fs the file system
|
---|
98 | * @param {function(WebpackError=): void} callback callback function
|
---|
99 | * @returns {void}
|
---|
100 | */
|
---|
101 | build(options, compilation, resolver, fs, callback) {
|
---|
102 | this.buildMeta = {};
|
---|
103 | this.buildInfo = {
|
---|
104 | strict: true,
|
---|
105 | topLevelDeclarations: new Set(["moduleMap", "get", "init"])
|
---|
106 | };
|
---|
107 |
|
---|
108 | this.clearDependenciesAndBlocks();
|
---|
109 |
|
---|
110 | for (const [name, options] of this._exposes) {
|
---|
111 | const block = new AsyncDependenciesBlock(
|
---|
112 | {
|
---|
113 | name: options.name
|
---|
114 | },
|
---|
115 | { name },
|
---|
116 | options.import[options.import.length - 1]
|
---|
117 | );
|
---|
118 | let idx = 0;
|
---|
119 | for (const request of options.import) {
|
---|
120 | const dep = new ContainerExposedDependency(name, request);
|
---|
121 | dep.loc = {
|
---|
122 | name,
|
---|
123 | index: idx++
|
---|
124 | };
|
---|
125 |
|
---|
126 | block.addDependency(dep);
|
---|
127 | }
|
---|
128 | this.addBlock(block);
|
---|
129 | }
|
---|
130 |
|
---|
131 | callback();
|
---|
132 | }
|
---|
133 |
|
---|
134 | /**
|
---|
135 | * @param {CodeGenerationContext} context context for code generation
|
---|
136 | * @returns {CodeGenerationResult} result
|
---|
137 | */
|
---|
138 | codeGeneration({ moduleGraph, chunkGraph, runtimeTemplate }) {
|
---|
139 | const sources = new Map();
|
---|
140 | const runtimeRequirements = new Set([
|
---|
141 | RuntimeGlobals.definePropertyGetters,
|
---|
142 | RuntimeGlobals.hasOwnProperty,
|
---|
143 | RuntimeGlobals.exports
|
---|
144 | ]);
|
---|
145 | const getters = [];
|
---|
146 |
|
---|
147 | for (const block of this.blocks) {
|
---|
148 | const { dependencies } = block;
|
---|
149 |
|
---|
150 | const modules = dependencies.map(dependency => {
|
---|
151 | const dep = /** @type {ContainerExposedDependency} */ (dependency);
|
---|
152 | return {
|
---|
153 | name: dep.exposedName,
|
---|
154 | module: moduleGraph.getModule(dep),
|
---|
155 | request: dep.userRequest
|
---|
156 | };
|
---|
157 | });
|
---|
158 |
|
---|
159 | let str;
|
---|
160 |
|
---|
161 | if (modules.some(m => !m.module)) {
|
---|
162 | str = runtimeTemplate.throwMissingModuleErrorBlock({
|
---|
163 | request: modules.map(m => m.request).join(", ")
|
---|
164 | });
|
---|
165 | } else {
|
---|
166 | str = `return ${runtimeTemplate.blockPromise({
|
---|
167 | block,
|
---|
168 | message: "",
|
---|
169 | chunkGraph,
|
---|
170 | runtimeRequirements
|
---|
171 | })}.then(${runtimeTemplate.returningFunction(
|
---|
172 | runtimeTemplate.returningFunction(
|
---|
173 | `(${modules
|
---|
174 | .map(({ module, request }) =>
|
---|
175 | runtimeTemplate.moduleRaw({
|
---|
176 | module,
|
---|
177 | chunkGraph,
|
---|
178 | request,
|
---|
179 | weak: false,
|
---|
180 | runtimeRequirements
|
---|
181 | })
|
---|
182 | )
|
---|
183 | .join(", ")})`
|
---|
184 | )
|
---|
185 | )});`;
|
---|
186 | }
|
---|
187 |
|
---|
188 | getters.push(
|
---|
189 | `${JSON.stringify(modules[0].name)}: ${runtimeTemplate.basicFunction(
|
---|
190 | "",
|
---|
191 | str
|
---|
192 | )}`
|
---|
193 | );
|
---|
194 | }
|
---|
195 |
|
---|
196 | const source = Template.asString([
|
---|
197 | `var moduleMap = {`,
|
---|
198 | Template.indent(getters.join(",\n")),
|
---|
199 | "};",
|
---|
200 | `var get = ${runtimeTemplate.basicFunction("module, getScope", [
|
---|
201 | `${RuntimeGlobals.currentRemoteGetScope} = getScope;`,
|
---|
202 | // reusing the getScope variable to avoid creating a new var (and module is also used later)
|
---|
203 | "getScope = (",
|
---|
204 | Template.indent([
|
---|
205 | `${RuntimeGlobals.hasOwnProperty}(moduleMap, module)`,
|
---|
206 | Template.indent([
|
---|
207 | "? moduleMap[module]()",
|
---|
208 | `: Promise.resolve().then(${runtimeTemplate.basicFunction(
|
---|
209 | "",
|
---|
210 | "throw new Error('Module \"' + module + '\" does not exist in container.');"
|
---|
211 | )})`
|
---|
212 | ])
|
---|
213 | ]),
|
---|
214 | ");",
|
---|
215 | `${RuntimeGlobals.currentRemoteGetScope} = undefined;`,
|
---|
216 | "return getScope;"
|
---|
217 | ])};`,
|
---|
218 | `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [
|
---|
219 | `if (!${RuntimeGlobals.shareScopeMap}) return;`,
|
---|
220 | `var oldScope = ${RuntimeGlobals.shareScopeMap}[${JSON.stringify(
|
---|
221 | this._shareScope
|
---|
222 | )}];`,
|
---|
223 | `var name = ${JSON.stringify(this._shareScope)}`,
|
---|
224 | `if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");`,
|
---|
225 | `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`,
|
---|
226 | `return ${RuntimeGlobals.initializeSharing}(name, initScope);`
|
---|
227 | ])};`,
|
---|
228 | "",
|
---|
229 | "// This exports getters to disallow modifications",
|
---|
230 | `${RuntimeGlobals.definePropertyGetters}(exports, {`,
|
---|
231 | Template.indent([
|
---|
232 | `get: ${runtimeTemplate.returningFunction("get")},`,
|
---|
233 | `init: ${runtimeTemplate.returningFunction("init")}`
|
---|
234 | ]),
|
---|
235 | "});"
|
---|
236 | ]);
|
---|
237 |
|
---|
238 | sources.set(
|
---|
239 | "javascript",
|
---|
240 | this.useSourceMap || this.useSimpleSourceMap
|
---|
241 | ? new OriginalSource(source, "webpack/container-entry")
|
---|
242 | : new RawSource(source)
|
---|
243 | );
|
---|
244 |
|
---|
245 | return {
|
---|
246 | sources,
|
---|
247 | runtimeRequirements
|
---|
248 | };
|
---|
249 | }
|
---|
250 |
|
---|
251 | /**
|
---|
252 | * @param {string=} type the source type for which the size should be estimated
|
---|
253 | * @returns {number} the estimated size of the module (must be non-zero)
|
---|
254 | */
|
---|
255 | size(type) {
|
---|
256 | return 42;
|
---|
257 | }
|
---|
258 |
|
---|
259 | serialize(context) {
|
---|
260 | const { write } = context;
|
---|
261 | write(this._name);
|
---|
262 | write(this._exposes);
|
---|
263 | write(this._shareScope);
|
---|
264 | super.serialize(context);
|
---|
265 | }
|
---|
266 |
|
---|
267 | static deserialize(context) {
|
---|
268 | const { read } = context;
|
---|
269 | const obj = new ContainerEntryModule(read(), read(), read());
|
---|
270 | obj.deserialize(context);
|
---|
271 | return obj;
|
---|
272 | }
|
---|
273 | }
|
---|
274 |
|
---|
275 | makeSerializable(
|
---|
276 | ContainerEntryModule,
|
---|
277 | "webpack/lib/container/ContainerEntryModule"
|
---|
278 | );
|
---|
279 |
|
---|
280 | module.exports = ContainerEntryModule;
|
---|