2
0

build.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // @ts-check
  2. /*
  3. Produces production builds and stitches together d.ts files.
  4. To specify the package to build, simply pass its name and the desired build
  5. formats to output (defaults to `buildOptions.formats` specified in that package,
  6. or "esm,cjs"):
  7. ```
  8. # name supports fuzzy match. will build all packages with name containing "dom":
  9. nr build dom
  10. # specify the format to output
  11. nr build core --formats cjs
  12. ```
  13. */
  14. import fs from 'node:fs'
  15. import { parseArgs } from 'node:util'
  16. import { existsSync, readFileSync } from 'node:fs'
  17. import path from 'node:path'
  18. import { brotliCompressSync, gzipSync } from 'node:zlib'
  19. import pico from 'picocolors'
  20. import { cpus } from 'node:os'
  21. import { targets as allTargets, exec, fuzzyMatchTarget } from './utils.js'
  22. import { scanEnums } from './inline-enums.js'
  23. import prettyBytes from 'pretty-bytes'
  24. import { spawnSync } from 'node:child_process'
  25. const commit = spawnSync('git', ['rev-parse', '--short=7', 'HEAD'])
  26. .stdout.toString()
  27. .trim()
  28. const { values, positionals: targets } = parseArgs({
  29. allowPositionals: true,
  30. options: {
  31. formats: {
  32. type: 'string',
  33. short: 'f',
  34. },
  35. devOnly: {
  36. type: 'boolean',
  37. short: 'd',
  38. },
  39. prodOnly: {
  40. type: 'boolean',
  41. short: 'p',
  42. },
  43. withTypes: {
  44. type: 'boolean',
  45. short: 't',
  46. },
  47. sourceMap: {
  48. type: 'boolean',
  49. short: 's',
  50. },
  51. release: {
  52. type: 'boolean',
  53. },
  54. all: {
  55. type: 'boolean',
  56. short: 'a',
  57. },
  58. size: {
  59. type: 'boolean',
  60. },
  61. },
  62. })
  63. const {
  64. formats,
  65. all: buildAllMatching,
  66. devOnly,
  67. prodOnly,
  68. withTypes: buildTypes,
  69. sourceMap,
  70. release: isRelease,
  71. size: writeSize,
  72. } = values
  73. const sizeDir = path.resolve('temp/size')
  74. run()
  75. async function run() {
  76. if (writeSize) fs.mkdirSync(sizeDir, { recursive: true })
  77. const removeCache = scanEnums()
  78. try {
  79. const resolvedTargets = targets.length
  80. ? fuzzyMatchTarget(targets, buildAllMatching)
  81. : allTargets
  82. await buildAll(resolvedTargets)
  83. await checkAllSizes(resolvedTargets)
  84. if (buildTypes) {
  85. await exec(
  86. 'pnpm',
  87. [
  88. 'run',
  89. 'build-dts',
  90. ...(targets.length
  91. ? ['--environment', `TARGETS:${resolvedTargets.join(',')}`]
  92. : []),
  93. ],
  94. {
  95. stdio: 'inherit',
  96. },
  97. )
  98. }
  99. } finally {
  100. removeCache()
  101. }
  102. }
  103. /**
  104. * Builds all the targets in parallel.
  105. * @param {Array<string>} targets - An array of targets to build.
  106. * @returns {Promise<void>} - A promise representing the build process.
  107. */
  108. async function buildAll(targets) {
  109. await runParallel(cpus().length, targets, build)
  110. }
  111. /**
  112. * Runs iterator function in parallel.
  113. * @template T - The type of items in the data source
  114. * @param {number} maxConcurrency - The maximum concurrency.
  115. * @param {Array<T>} source - The data source
  116. * @param {(item: T) => Promise<void>} iteratorFn - The iteratorFn
  117. * @returns {Promise<void[]>} - A Promise array containing all iteration results.
  118. */
  119. async function runParallel(maxConcurrency, source, iteratorFn) {
  120. /**@type {Promise<void>[]} */
  121. const ret = []
  122. /**@type {Promise<void>[]} */
  123. const executing = []
  124. for (const item of source) {
  125. const p = Promise.resolve().then(() => iteratorFn(item))
  126. ret.push(p)
  127. if (maxConcurrency <= source.length) {
  128. const e = p.then(() => {
  129. executing.splice(executing.indexOf(e), 1)
  130. })
  131. executing.push(e)
  132. if (executing.length >= maxConcurrency) {
  133. await Promise.race(executing)
  134. }
  135. }
  136. }
  137. return Promise.all(ret)
  138. }
  139. const privatePackages = fs.readdirSync('packages-private')
  140. /**
  141. * Builds the target.
  142. * @param {string} target - The target to build.
  143. * @returns {Promise<void>} - A promise representing the build process.
  144. */
  145. async function build(target) {
  146. const pkgBase = privatePackages.includes(target)
  147. ? `packages-private`
  148. : `packages`
  149. const pkgDir = path.resolve(`${pkgBase}/${target}`)
  150. const pkg = JSON.parse(readFileSync(`${pkgDir}/package.json`, 'utf-8'))
  151. // if this is a full build (no specific targets), ignore private packages
  152. if ((isRelease || !targets.length) && pkg.private) {
  153. return
  154. }
  155. // if building a specific format, do not remove dist.
  156. if (!formats && existsSync(`${pkgDir}/dist`)) {
  157. fs.rmSync(`${pkgDir}/dist`, { recursive: true })
  158. }
  159. const env =
  160. (pkg.buildOptions && pkg.buildOptions.env) ||
  161. (devOnly ? 'development' : 'production')
  162. await exec(
  163. 'rollup',
  164. [
  165. '-c',
  166. '--environment',
  167. [
  168. `COMMIT:${commit}`,
  169. `NODE_ENV:${env}`,
  170. `TARGET:${target}`,
  171. formats ? `FORMATS:${formats}` : ``,
  172. prodOnly ? `PROD_ONLY:true` : ``,
  173. sourceMap ? `SOURCE_MAP:true` : ``,
  174. ]
  175. .filter(Boolean)
  176. .join(','),
  177. ],
  178. { stdio: 'inherit' },
  179. )
  180. }
  181. /**
  182. * Checks the sizes of all targets.
  183. * @param {string[]} targets - The targets to check sizes for.
  184. * @returns {Promise<void>}
  185. */
  186. async function checkAllSizes(targets) {
  187. if (devOnly || (formats && !formats.includes('global'))) {
  188. return
  189. }
  190. console.log()
  191. for (const target of targets) {
  192. await checkSize(target)
  193. }
  194. console.log()
  195. }
  196. /**
  197. * Checks the size of a target.
  198. * @param {string} target - The target to check the size for.
  199. * @returns {Promise<void>}
  200. */
  201. async function checkSize(target) {
  202. const pkgDir = path.resolve(`packages/${target}`)
  203. await checkFileSize(`${pkgDir}/dist/${target}.global.prod.js`)
  204. if (!formats || formats.includes('global-runtime')) {
  205. await checkFileSize(`${pkgDir}/dist/${target}.runtime.global.prod.js`)
  206. }
  207. }
  208. /**
  209. * Checks the file size.
  210. * @param {string} filePath - The path of the file to check the size for.
  211. * @returns {Promise<void>}
  212. */
  213. async function checkFileSize(filePath) {
  214. if (!existsSync(filePath)) {
  215. return
  216. }
  217. const file = fs.readFileSync(filePath)
  218. const fileName = path.basename(filePath)
  219. const gzipped = gzipSync(file)
  220. const brotli = brotliCompressSync(file)
  221. console.log(
  222. `${pico.gray(pico.bold(fileName))} min:${prettyBytes(
  223. file.length,
  224. )} / gzip:${prettyBytes(gzipped.length)} / brotli:${prettyBytes(
  225. brotli.length,
  226. )}`,
  227. )
  228. if (writeSize)
  229. fs.writeFileSync(
  230. path.resolve(sizeDir, `${fileName}.json`),
  231. JSON.stringify({
  232. file: fileName,
  233. size: file.length,
  234. gzip: gzipped.length,
  235. brotli: brotli.length,
  236. }),
  237. 'utf-8',
  238. )
  239. }