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