inline-enums.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 { parseSync } from 'oxc-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', `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. let i = 0
  57. for (const relativeFile of files) {
  58. const file = path.resolve(process.cwd(), relativeFile)
  59. const content = readFileSync(file, 'utf-8')
  60. const res = parseSync(content, {
  61. // plugins: ['typescript'],
  62. sourceFilename: file,
  63. sourceType: 'module',
  64. })
  65. /** @type {Set<string>} */
  66. const enumIds = new Set()
  67. for (const node of res.program.body) {
  68. let decl
  69. if (node.type === 'TSEnumDeclaration') {
  70. decl = node
  71. }
  72. if (
  73. node.type === 'ExportNamedDeclaration' &&
  74. node.declaration &&
  75. node.declaration.type === 'TSEnumDeclaration'
  76. ) {
  77. decl = node.declaration
  78. }
  79. if (decl) {
  80. const id = decl.id.name
  81. if (enumIds.has(id)) {
  82. throw new Error(
  83. `not support declaration merging for enum ${id} in ${file}`,
  84. )
  85. }
  86. enumIds.add(id)
  87. /** @type {string | number | undefined} */
  88. let lastInitialized
  89. /** @type {Array<EnumMember>} */
  90. const members = []
  91. for (let i = 0; i < decl.members.length; i++) {
  92. const e = decl.members[i]
  93. const key = e.id.type === 'Identifier' ? e.id.name : e.id.value
  94. const fullKey = /** @type {const} */ (`${id}.${key}`)
  95. const saveValue = (/** @type {string | number} */ value) => {
  96. // We need allow same name enum in different file.
  97. // For example: enum ErrorCodes exist in both @vue/compiler-core and @vue/runtime-core
  98. // But not allow `ErrorCodes.__EXTEND_POINT__` appear in two same name enum
  99. if (fullKey in defines) {
  100. throw new Error(`name conflict for enum ${id} in ${file}`)
  101. }
  102. members.push({
  103. name: key,
  104. value,
  105. })
  106. defines[fullKey] = JSON.stringify(value)
  107. }
  108. const init = e.initializer
  109. if (init) {
  110. /** @type {string | number} */
  111. let value
  112. if (
  113. init.type === 'StringLiteral' ||
  114. init.type === 'NumericLiteral'
  115. ) {
  116. value = init.value
  117. }
  118. // e.g. 1 << 2
  119. else if (init.type === 'BinaryExpression') {
  120. const resolveValue = (
  121. /** @type {import('@babel/types').Expression | import('@babel/types').PrivateName} */ node,
  122. ) => {
  123. assert.ok(typeof node.start === 'number')
  124. assert.ok(typeof node.end === 'number')
  125. if (
  126. node.type === 'NumericLiteral' ||
  127. node.type === 'StringLiteral'
  128. ) {
  129. return node.value
  130. } else if (
  131. node.type === 'MemberExpression' ||
  132. // @ts-expect-error oxc only type
  133. node.type === 'StaticMemberExpression'
  134. ) {
  135. const exp = /** @type {`${string}.${string}`} */ (
  136. content.slice(node.start, node.end)
  137. )
  138. if (!(exp in defines)) {
  139. throw new Error(
  140. `unhandled enum initialization expression ${exp} in ${file}`,
  141. )
  142. }
  143. return defines[exp]
  144. } else {
  145. throw new Error(
  146. `unhandled BinaryExpression operand type ${node.type} in ${file}`,
  147. )
  148. }
  149. }
  150. const exp = `${resolveValue(init.left)}${
  151. init.operator
  152. }${resolveValue(init.right)}`
  153. value = evaluate(exp)
  154. } else if (init.type === 'UnaryExpression') {
  155. if (
  156. init.argument.type === 'StringLiteral' ||
  157. init.argument.type === 'NumericLiteral'
  158. ) {
  159. const exp = `${init.operator}${init.argument.value}`
  160. value = evaluate(exp)
  161. } else {
  162. throw new Error(
  163. `unhandled UnaryExpression argument type ${init.argument.type} in ${file}`,
  164. )
  165. }
  166. } else {
  167. throw new Error(
  168. `unhandled initializer type ${init.type} for ${fullKey} in ${file}`,
  169. )
  170. }
  171. lastInitialized = value
  172. saveValue(lastInitialized)
  173. } else {
  174. if (lastInitialized === undefined) {
  175. // first initialized
  176. lastInitialized = 0
  177. saveValue(lastInitialized)
  178. } else if (typeof lastInitialized === 'number') {
  179. lastInitialized++
  180. saveValue(lastInitialized)
  181. } else {
  182. // should not happen
  183. throw new Error(`wrong enum initialization sequence in ${file}`)
  184. }
  185. }
  186. }
  187. if (!(file in declarations)) {
  188. declarations[file] = []
  189. }
  190. assert.ok(typeof node.start === 'number')
  191. assert.ok(typeof node.end === 'number')
  192. declarations[file].push({
  193. id,
  194. range: [node.start, node.end],
  195. members,
  196. })
  197. }
  198. }
  199. }
  200. // 3. save cache
  201. if (!existsSync('temp')) mkdirSync('temp')
  202. /** @type {EnumData} */
  203. const enumData = {
  204. declarations,
  205. defines,
  206. }
  207. writeFileSync(ENUM_CACHE_PATH, JSON.stringify(enumData))
  208. return () => {
  209. rmSync(ENUM_CACHE_PATH, { force: true })
  210. }
  211. }
  212. /**
  213. * @returns {[import('rollup').Plugin, Record<string, string>]}
  214. */
  215. export function inlineEnums() {
  216. if (!existsSync(ENUM_CACHE_PATH)) {
  217. throw new Error('enum cache needs to be initialized before creating plugin')
  218. }
  219. /**
  220. * @type {EnumData}
  221. */
  222. const enumData = JSON.parse(readFileSync(ENUM_CACHE_PATH, 'utf-8'))
  223. // 3. during transform:
  224. // 3.1 files w/ enum declaration: rewrite declaration as object literal
  225. // 3.2 files using enum: inject into rolldown define
  226. /**
  227. * @type {import('rollup').Plugin}
  228. */
  229. const plugin = {
  230. name: 'inline-enum',
  231. transform(code, id) {
  232. /**
  233. * @type {MagicString | undefined}
  234. */
  235. let s
  236. if (id in enumData.declarations) {
  237. s = s || new MagicString(code)
  238. for (const declaration of enumData.declarations[id]) {
  239. const {
  240. range: [start, end],
  241. id,
  242. members,
  243. } = declaration
  244. s.update(
  245. start,
  246. end,
  247. `export const ${id} = {${members
  248. .flatMap(({ name, value }) => {
  249. const forwardMapping =
  250. JSON.stringify(name) + ': ' + JSON.stringify(value)
  251. const reverseMapping =
  252. JSON.stringify(value.toString()) + ': ' + JSON.stringify(name)
  253. // see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
  254. return typeof value === 'string'
  255. ? [
  256. forwardMapping,
  257. // string enum members do not get a reverse mapping generated at all
  258. ]
  259. : [
  260. forwardMapping,
  261. // other enum members should support enum reverse mapping
  262. reverseMapping,
  263. ]
  264. })
  265. .join(',\n')}}`,
  266. )
  267. }
  268. }
  269. if (s) {
  270. return {
  271. code: s.toString(),
  272. map: s.generateMap(),
  273. }
  274. }
  275. },
  276. }
  277. return [plugin, enumData.defines]
  278. }