| 1 |
import type { PluginPasses } from "../../config"; |
| 2 |
import convertSourceMap from "convert-source-map"; |
| 3 |
type SourceMap = any; |
| 4 |
import generate from "@babel/generator"; |
| 5 |
|
| 6 |
import type File from "./file"; |
| 7 |
import mergeSourceMap from "./merge-map"; |
| 8 |
|
| 9 |
export default function generateCode( |
| 10 |
pluginPasses: PluginPasses, |
| 11 |
file: File, |
| 12 |
): { |
| 13 |
outputCode: string; |
| 14 |
outputMap: SourceMap | null; |
| 15 |
} { |
| 16 |
const { opts, ast, code, inputMap } = file; |
| 17 |
const { generatorOpts } = opts; |
| 18 |
|
| 19 |
const results = []; |
| 20 |
for (const plugins of pluginPasses) { |
| 21 |
for (const plugin of plugins) { |
| 22 |
const { generatorOverride } = plugin; |
| 23 |
if (generatorOverride) { |
| 24 |
const result = generatorOverride(ast, generatorOpts, code, generate); |
| 25 |
|
| 26 |
if (result !== undefined) results.push(result); |
| 27 |
} |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
let result; |
| 32 |
if (results.length === 0) { |
| 33 |
result = generate(ast, generatorOpts, code); |
| 34 |
} else if (results.length === 1) { |
| 35 |
result = results[0]; |
| 36 |
|
| 37 |
if (typeof result.then === "function") { |
| 38 |
throw new Error( |
| 39 |
`You appear to be using an async codegen plugin, ` + |
| 40 |
`which your current version of Babel does not support. ` + |
| 41 |
`If you're using a published plugin, ` + |
| 42 |
`you may need to upgrade your @babel/core version.`, |
| 43 |
); |
| 44 |
} |
| 45 |
} else { |
| 46 |
throw new Error("More than one plugin attempted to override codegen."); |
| 47 |
} |
| 48 |
|
| 49 |
// Decoded maps are faster to merge, so we attempt to get use the decodedMap |
| 50 |
// first. But to preserve backwards compat with older Generator, we'll fall |
| 51 |
// back to the encoded map. |
| 52 |
let { code: outputCode, decodedMap: outputMap = result.map } = result; |
| 53 |
|
| 54 |
if (outputMap) { |
| 55 |
if (inputMap) { |
| 56 |
// mergeSourceMap returns an encoded map |
| 57 |
outputMap = mergeSourceMap( |
| 58 |
inputMap.toObject(), |
| 59 |
outputMap, |
| 60 |
generatorOpts.sourceFileName, |
| 61 |
); |
| 62 |
} else { |
| 63 |
// We cannot output a decoded map, so retrieve the encoded form. Because |
| 64 |
// the decoded form is free, it's fine to prioritize decoded first. |
| 65 |
outputMap = result.map; |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { |
| 70 |
outputCode += "\n" + convertSourceMap.fromObject(outputMap).toComment(); |
| 71 |
} |
| 72 |
|
| 73 |
if (opts.sourceMaps === "inline") { |
| 74 |
outputMap = null; |
| 75 |
} |
| 76 |
|
| 77 |
return { outputCode, outputMap }; |
| 78 |
} |