getRefreshGlobal.js
2.64 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
const Template = require('webpack/lib/Template');
const { refreshGlobal } = require('../globals');
/**
* @typedef {Object} RuntimeTemplate
* @property {function(string, string[]): string} basicFunction
* @property {function(): boolean} supportsConst
* @property {function(string, string=): string} returningFunction
*/
/** @type {RuntimeTemplate} */
const FALLBACK_RUNTIME_TEMPLATE = {
basicFunction(args, body) {
return `function(${args}) {\n${Template.indent(body)}\n}`;
},
supportsConst() {
return false;
},
returningFunction(returnValue, args = '') {
return `function(${args}) { return ${returnValue}; }`;
},
};
/**
* Generates the refresh global runtime template.
* @param {RuntimeTemplate} [runtimeTemplate] The runtime template helpers.
* @returns {string} The refresh global runtime template.
*/
function getRefreshGlobal(runtimeTemplate = FALLBACK_RUNTIME_TEMPLATE) {
const declaration = runtimeTemplate.supportsConst() ? 'const' : 'var';
return Template.asString([
`${refreshGlobal} = {`,
Template.indent([
`init: ${runtimeTemplate.basicFunction('', [
`${refreshGlobal}.cleanup = ${runtimeTemplate.returningFunction(
'undefined',
)};`,
`${refreshGlobal}.register = ${runtimeTemplate.returningFunction(
'undefined',
)};`,
`${refreshGlobal}.runtime = {};`,
`${refreshGlobal}.signature = ${runtimeTemplate.returningFunction(
runtimeTemplate.returningFunction('type', 'type'),
)};`,
])},`,
`setup: ${runtimeTemplate.basicFunction('currentModuleId', [
`${declaration} prevCleanup = ${refreshGlobal}.cleanup;`,
`${declaration} prevReg = ${refreshGlobal}.register;`,
`${declaration} prevSig = ${refreshGlobal}.signature;`,
'',
`${refreshGlobal}.register = ${runtimeTemplate.basicFunction(
'type, id',
[
`${declaration} typeId = currentModuleId + " " + id;`,
`${refreshGlobal}.runtime.register(type, typeId);`,
],
)}`,
'',
`${refreshGlobal}.signature = ${refreshGlobal}.runtime.createSignatureFunctionForTransform;`,
'',
`${refreshGlobal}.cleanup = ${runtimeTemplate.basicFunction(
'cleanupModuleId',
[
'if (currentModuleId === cleanupModuleId) {',
Template.indent([
`${refreshGlobal}.register = prevReg;`,
`${refreshGlobal}.signature = prevSig;`,
`${refreshGlobal}.cleanup = prevCleanup;`,
]),
'}',
],
)}`,
])},`,
]),
'};',
]);
}
module.exports = getRefreshGlobal;