| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | 'use strict'; |
| 8 | |
| 9 | module.exports = function externalRuntime() { |
| 10 | // When generating the source code for the Fizz runtime chunks we use global identifiers to refer |
| 11 | // to different parts of the implementation. When generating the external runtime we need to |
| 12 | // replace those with local identifiers instead. |
| 13 | return { |
| 14 | name: 'scripts/rollup/plugins/dynamic-imports', |
| 15 | renderChunk(source) { |
| 16 | // This replaces "window['$globalVar']" with "$globalVar". |
| 17 | const variables = new Set(); |
| 18 | source = source.replace( |
| 19 | /window\[['"](\$[A-z0-9_]*)['"]\]/g, |
| 20 | (_, variableName) => { |
| 21 | variables.add(variableName); |
| 22 | return variableName; |
| 23 | } |
| 24 | ); |
| 25 | const startOfFn = 'use strict'; |
| 26 | let index = source.indexOf(startOfFn); |
| 27 | if (index === -1) { |
| 28 | return source; |
| 29 | } |
| 30 | index += startOfFn.length + 2; |
| 31 | |
| 32 | // Insert the declarations in the beginning of the function closure |
| 33 | // to scope them to inside the runtime. |
| 34 | let declarations = 'let '; |
| 35 | variables.forEach(variable => { |
| 36 | if (declarations !== 'let ') { |
| 37 | declarations += ', '; |
| 38 | } |
| 39 | declarations += variable; |
| 40 | }); |
| 41 | declarations += ';'; |
| 42 | source = source.slice(0, index) + declarations + source.slice(index); |
| 43 | return source; |
| 44 | }, |
| 45 | }; |
| 46 | }; |