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