GetChunkFilenameRuntimeModule.js
9.0 KB
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
const { first } = require("../util/SetHelpers");
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compilation")} Compilation */
/** @typedef {import("../Compilation").AssetInfo} AssetInfo */
/** @typedef {import("../Compilation").PathData} PathData */
/** @typedef {function(PathData, AssetInfo=): string} FilenameFunction */
class GetChunkFilenameRuntimeModule extends RuntimeModule {
/**
* @param {string} contentType the contentType to use the content hash for
* @param {string} name kind of filename
* @param {string} global function name to be assigned
* @param {function(Chunk): string | FilenameFunction} getFilenameForChunk functor to get the filename or function
* @param {boolean} allChunks when false, only async chunks are included
*/
constructor(contentType, name, global, getFilenameForChunk, allChunks) {
super(`get ${name} chunk filename`);
this.contentType = contentType;
this.global = global;
this.getFilenameForChunk = getFilenameForChunk;
this.allChunks = allChunks;
this.dependentHash = true;
}
/**
* @returns {string} runtime code
*/
generate() {
const {
global,
chunk,
chunkGraph,
contentType,
getFilenameForChunk,
allChunks,
compilation
} = this;
const { runtimeTemplate } = compilation;
/** @type {Map<string | FilenameFunction, Set<Chunk>>} */
const chunkFilenames = new Map();
let maxChunks = 0;
/** @type {string | undefined} */
let dynamicFilename;
/**
* @param {Chunk} c the chunk
* @returns {void}
*/
const addChunk = c => {
const chunkFilename = getFilenameForChunk(c);
if (chunkFilename) {
let set = chunkFilenames.get(chunkFilename);
if (set === undefined) {
chunkFilenames.set(chunkFilename, (set = new Set()));
}
set.add(c);
if (typeof chunkFilename === "string") {
if (set.size < maxChunks) return;
if (set.size === maxChunks) {
if (
chunkFilename.length <
/** @type {string} */ (dynamicFilename).length
) {
return;
}
if (
chunkFilename.length ===
/** @type {string} */ (dynamicFilename).length
) {
if (chunkFilename < /** @type {string} */ (dynamicFilename)) {
return;
}
}
}
maxChunks = set.size;
dynamicFilename = chunkFilename;
}
}
};
/** @type {string[]} */
const includedChunksMessages = [];
if (allChunks) {
includedChunksMessages.push("all chunks");
for (const c of chunk.getAllReferencedChunks()) {
addChunk(c);
}
} else {
includedChunksMessages.push("async chunks");
for (const c of chunk.getAllAsyncChunks()) {
addChunk(c);
}
const includeEntries = chunkGraph
.getTreeRuntimeRequirements(chunk)
.has(RuntimeGlobals.ensureChunkIncludeEntries);
if (includeEntries) {
includedChunksMessages.push("sibling chunks for the entrypoint");
for (const c of chunkGraph.getChunkEntryDependentChunksIterable(
chunk
)) {
addChunk(c);
}
}
}
for (const entrypoint of chunk.getAllReferencedAsyncEntrypoints()) {
addChunk(entrypoint.chunks[entrypoint.chunks.length - 1]);
}
/** @type {Map<string, Set<string | number | null>>} */
const staticUrls = new Map();
/** @type {Set<Chunk>} */
const dynamicUrlChunks = new Set();
/**
* @param {Chunk} c the chunk
* @param {string | FilenameFunction} chunkFilename the filename template for the chunk
* @returns {void}
*/
const addStaticUrl = (c, chunkFilename) => {
/**
* @param {string | number} value a value
* @returns {string} string to put in quotes
*/
const unquotedStringify = value => {
const str = `${value}`;
if (str.length >= 5 && str === `${c.id}`) {
// This is shorter and generates the same result
return '" + chunkId + "';
}
const s = JSON.stringify(str);
return s.slice(1, s.length - 1);
};
/**
* @param {string} value string
* @returns {function(number): string} string to put in quotes with length
*/
const unquotedStringifyWithLength = value => length =>
unquotedStringify(`${value}`.slice(0, length));
const chunkFilenameValue =
typeof chunkFilename === "function"
? JSON.stringify(
chunkFilename({
chunk: c,
contentHashType: contentType
})
)
: JSON.stringify(chunkFilename);
const staticChunkFilename = compilation.getPath(chunkFilenameValue, {
hash: `" + ${RuntimeGlobals.getFullHash}() + "`,
hashWithLength: length =>
`" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`,
chunk: {
id: unquotedStringify(/** @type {number | string} */ (c.id)),
hash: unquotedStringify(/** @type {string} */ (c.renderedHash)),
hashWithLength: unquotedStringifyWithLength(
/** @type {string} */ (c.renderedHash)
),
name: unquotedStringify(
c.name || /** @type {number | string} */ (c.id)
),
contentHash: {
[contentType]: unquotedStringify(c.contentHash[contentType])
},
contentHashWithLength: {
[contentType]: unquotedStringifyWithLength(
c.contentHash[contentType]
)
}
},
contentHashType: contentType
});
let set = staticUrls.get(staticChunkFilename);
if (set === undefined) {
staticUrls.set(staticChunkFilename, (set = new Set()));
}
set.add(c.id);
};
for (const [filename, chunks] of chunkFilenames) {
if (filename !== dynamicFilename) {
for (const c of chunks) addStaticUrl(c, filename);
} else {
for (const c of chunks) dynamicUrlChunks.add(c);
}
}
/**
* @param {function(Chunk): string | number} fn function from chunk to value
* @returns {string} code with static mapping of results of fn
*/
const createMap = fn => {
/** @type {Record<number | string, number | string>} */
const obj = {};
let useId = false;
/** @type {number | string | undefined} */
let lastKey;
let entries = 0;
for (const c of dynamicUrlChunks) {
const value = fn(c);
if (value === c.id) {
useId = true;
} else {
obj[/** @type {number | string} */ (c.id)] = value;
lastKey = /** @type {number | string} */ (c.id);
entries++;
}
}
if (entries === 0) return "chunkId";
if (entries === 1) {
return useId
? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify(
obj[/** @type {number | string} */ (lastKey)]
)} : chunkId)`
: JSON.stringify(obj[/** @type {number | string} */ (lastKey)]);
}
return useId
? `(${JSON.stringify(obj)}[chunkId] || chunkId)`
: `${JSON.stringify(obj)}[chunkId]`;
};
/**
* @param {function(Chunk): string | number} fn function from chunk to value
* @returns {string} code with static mapping of results of fn for including in quoted string
*/
const mapExpr = fn => {
return `" + ${createMap(fn)} + "`;
};
/**
* @param {function(Chunk): string | number} fn function from chunk to value
* @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length
*/
const mapExprWithLength = fn => length => {
return `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`;
};
const url =
dynamicFilename &&
compilation.getPath(JSON.stringify(dynamicFilename), {
hash: `" + ${RuntimeGlobals.getFullHash}() + "`,
hashWithLength: length =>
`" + ${RuntimeGlobals.getFullHash}().slice(0, ${length}) + "`,
chunk: {
id: `" + chunkId + "`,
hash: mapExpr(c => /** @type {string} */ (c.renderedHash)),
hashWithLength: mapExprWithLength(
c => /** @type {string} */ (c.renderedHash)
),
name: mapExpr(c => c.name || /** @type {number | string} */ (c.id)),
contentHash: {
[contentType]: mapExpr(c => c.contentHash[contentType])
},
contentHashWithLength: {
[contentType]: mapExprWithLength(c => c.contentHash[contentType])
}
},
contentHashType: contentType
});
return Template.asString([
`// This function allow to reference ${includedChunksMessages.join(
" and "
)}`,
`${global} = ${runtimeTemplate.basicFunction(
"chunkId",
staticUrls.size > 0
? [
"// return url for filenames not based on template",
// it minimizes to `x===1?"...":x===2?"...":"..."`
Template.asString(
Array.from(staticUrls, ([url, ids]) => {
const condition =
ids.size === 1
? `chunkId === ${JSON.stringify(first(ids))}`
: `{${Array.from(
ids,
id => `${JSON.stringify(id)}:1`
).join(",")}}[chunkId]`;
return `if (${condition}) return ${url};`;
})
),
"// return url for filenames based on template",
`return ${url};`
]
: ["// return url for filenames based on template", `return ${url};`]
)};`
]);
}
}
module.exports = GetChunkFilenameRuntimeModule;