inline-enums.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // @ts-check
  2. /**
  3. * We used const enums before, but it caused some issues: #1228, so we
  4. * switched to regular enums. But we still want to keep the zero-cost benefit
  5. * of const enums, and minimize the impact on bundle size as much as possible.
  6. *
  7. * Here we pre-process all the enums in the project and turn them into
  8. * global replacements, and rewrite the original declarations as object literals.
  9. *
  10. * This file is expected to be executed with project root as cwd.
  11. */
  12. import * as assert from 'node:assert'
  13. import {
  14. existsSync,
  15. mkdirSync,
  16. readFileSync,
  17. rmSync,
  18. writeFileSync,
  19. } from 'node:fs'
  20. import * as path from 'node:path'
  21. import { parse } from '@babel/parser'
  22. import { spawnSync } from 'node:child_process'
  23. import MagicString from 'magic-string'
  24. /**
  25. * @typedef {{ readonly name: string, readonly value: string | number }} EnumMember
  26. * @typedef {{ readonly id: string, readonly range: readonly [start: number, end: number], readonly members: ReadonlyArray<EnumMember>}} EnumDeclaration
  27. * @typedef {{ readonly declarations: { readonly [file: string] : ReadonlyArray<EnumDeclaration>}, readonly defines: { readonly [ id_key: `${string}.${string}`]: string } }} EnumData
  28. */
  29. const ENUM_CACHE_PATH = 'temp/enum.json'
  30. /**
  31. * @param {string} exp
  32. * @returns {string | number}
  33. */
  34. function evaluate(exp) {
  35. return new Function(`return ${exp}`)()
  36. }
  37. // this is called in the build script entry once
  38. // so the data can be shared across concurrent Rollup processes
  39. export function scanEnums() {
  40. /** @type {{ [file: string]: EnumDeclaration[] }} */
  41. const declarations = Object.create(null)
  42. /** @type {{ [id_key: `${string}.${string}`]: string; }} */
  43. const defines = Object.create(null)
  44. // 1. grep for files with exported enum
  45. const { stdout } = spawnSync('git', ['grep', `export enum`])
  46. const files = [
  47. ...new Set(
  48. stdout
  49. .toString()
  50. .trim()
  51. .split('\n')
  52. .map(line => line.split(':')[0]),
  53. ),
  54. ]
  55. // 2. parse matched files to collect enum info
  56. for (const relativeFile of files) {
  57. const file = path.resolve(process.cwd(), relativeFile)
  58. const content = readFileSync(file, 'utf-8')
  59. const ast = parse(content, {
  60. plugins: ['typescript'],
  61. sourceType: 'module',
  62. })
  63. /** @type {Set<string>} */
  64. const enumIds = new Set()
  65. for (const node of ast.program.body) {
  66. if (
  67. node.type === 'ExportNamedDeclaration' &&
  68. node.declaration &&
  69. node.declaration.type === 'TSEnumDeclaration'
  70. ) {
  71. const decl = node.declaration
  72. const id = decl.id.name
  73. if (enumIds.has(id)) {
  74. throw new Error(
  75. `not support declaration merging for enum ${id} in ${file}`,
  76. )
  77. }
  78. enumIds.add(id)
  79. /** @type {string | number | undefined} */
  80. let lastInitialized
  81. /** @type {Array<EnumMember>} */
  82. const members = []
  83. for (let i = 0; i < decl.members.length; i++) {
  84. const e = decl.members[i]
  85. const key = e.id.type === 'Identifier' ? e.id.name : e.id.value
  86. const fullKey = /** @type {const} */ (`${id}.${key}`)
  87. const saveValue = (/** @type {string | number} */ value) => {
  88. // We need allow same name enum in different file.
  89. // For example: enum ErrorCodes exist in both @vue/compiler-core and @vue/runtime-core
  90. // But not allow `ErrorCodes.__EXTEND_POINT__` appear in two same name enum
  91. if (fullKey in defines) {
  92. throw new Error(`name conflict for enum ${id} in ${file}`)
  93. }
  94. members.push({
  95. name: key,
  96. value,
  97. })
  98. defines[fullKey] = JSON.stringify(value)
  99. }
  100. const init = e.initializer
  101. if (init) {
  102. /** @type {string | number} */
  103. let value
  104. if (
  105. init.type === 'StringLiteral' ||
  106. init.type === 'NumericLiteral'
  107. ) {
  108. value = init.value
  109. }
  110. // e.g. 1 << 2
  111. else if (init.type === 'BinaryExpression') {
  112. const resolveValue = (
  113. /** @type {import('@babel/types').Expression | import('@babel/types').PrivateName} */ node,
  114. ) => {
  115. assert.ok(typeof node.start === 'number')
  116. assert.ok(typeof node.end === 'number')
  117. if (
  118. node.type === 'NumericLiteral' ||
  119. node.type === 'StringLiteral'
  120. ) {
  121. return node.value
  122. } else if (node.type === 'MemberExpression') {
  123. const exp = /** @type {`${string}.${string}`} */ (
  124. content.slice(node.start, node.end)
  125. )
  126. if (!(exp in defines)) {
  127. throw new Error(
  128. `unhandled enum initialization expression ${exp} in ${file}`,
  129. )
  130. }
  131. return defines[exp]
  132. } else {
  133. throw new Error(
  134. `unhandled BinaryExpression operand type ${node.type} in ${file}`,
  135. )
  136. }
  137. }
  138. const exp = `${resolveValue(init.left)}${
  139. init.operator
  140. }${resolveValue(init.right)}`
  141. value = evaluate(exp)
  142. } else if (init.type === 'UnaryExpression') {
  143. if (
  144. init.argument.type === 'StringLiteral' ||
  145. init.argument.type === 'NumericLiteral'
  146. ) {
  147. const exp = `${init.operator}${init.argument.value}`
  148. value = evaluate(exp)
  149. } else {
  150. throw new Error(
  151. `unhandled UnaryExpression argument type ${init.argument.type} in ${file}`,
  152. )
  153. }
  154. } else {
  155. throw new Error(
  156. `unhandled initializer type ${init.type} for ${fullKey} in ${file}`,
  157. )
  158. }
  159. lastInitialized = value
  160. saveValue(lastInitialized)
  161. } else {
  162. if (lastInitialized === undefined) {
  163. // first initialized
  164. lastInitialized = 0
  165. saveValue(lastInitialized)
  166. } else if (typeof lastInitialized === 'number') {
  167. lastInitialized++
  168. saveValue(lastInitialized)
  169. } else {
  170. // should not happen
  171. throw new Error(`wrong enum initialization sequence in ${file}`)
  172. }
  173. }
  174. }
  175. if (!(file in declarations)) {
  176. declarations[file] = []
  177. }
  178. assert.ok(typeof node.start === 'number')
  179. assert.ok(typeof node.end === 'number')
  180. declarations[file].push({
  181. id,
  182. range: [node.start, node.end],
  183. members,
  184. })
  185. }
  186. }
  187. }
  188. // 3. save cache
  189. if (!existsSync('temp')) mkdirSync('temp')
  190. /** @type {EnumData} */
  191. const enumData = {
  192. declarations,
  193. defines,
  194. }
  195. writeFileSync(ENUM_CACHE_PATH, JSON.stringify(enumData))
  196. return () => {
  197. rmSync(ENUM_CACHE_PATH, { force: true })
  198. }
  199. }
  200. /**
  201. * @returns {[import('rollup').Plugin, Record<string, string>]}
  202. */
  203. export function inlineEnums() {
  204. if (!existsSync(ENUM_CACHE_PATH)) {
  205. throw new Error('enum cache needs to be initialized before creating plugin')
  206. }
  207. /**
  208. * @type {EnumData}
  209. */
  210. const enumData = JSON.parse(readFileSync(ENUM_CACHE_PATH, 'utf-8'))
  211. // 3. during transform:
  212. // 3.1 files w/ enum declaration: rewrite declaration as object literal
  213. // 3.2 files using enum: inject into esbuild define
  214. /**
  215. * @type {import('rollup').Plugin}
  216. */
  217. const plugin = {
  218. name: 'inline-enum',
  219. transform(code, id) {
  220. /**
  221. * @type {MagicString | undefined}
  222. */
  223. let s
  224. if (id in enumData.declarations) {
  225. s = s || new MagicString(code)
  226. for (const declaration of enumData.declarations[id]) {
  227. const {
  228. range: [start, end],
  229. id,
  230. members,
  231. } = declaration
  232. s.update(
  233. start,
  234. end,
  235. `export const ${id} = {${members
  236. .flatMap(({ name, value }) => {
  237. const forwardMapping =
  238. JSON.stringify(name) + ': ' + JSON.stringify(value)
  239. const reverseMapping =
  240. JSON.stringify(value.toString()) + ': ' + JSON.stringify(name)
  241. // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
  242. return typeof value === 'string'
  243. ? [
  244. forwardMapping,
  245. // string enum members do not get a reverse mapping generated at all
  246. ]
  247. : [
  248. forwardMapping,
  249. // other enum members should support enum reverse mapping
  250. reverseMapping,
  251. ]
  252. })
  253. .join(',\n')}}`,
  254. )
  255. }
  256. }
  257. if (s) {
  258. return {
  259. code: s.toString(),
  260. map: s.generateMap(),
  261. }
  262. }
  263. },
  264. }
  265. return [plugin, enumData.defines]
  266. }