build.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /** Run the complete repository build and bind its client artifacts to their public environment. */
  2. import { spawnSync } from 'node:child_process'
  3. import { rmSync } from 'node:fs'
  4. import { resolve } from 'node:path'
  5. import { parseArgs } from 'node:util'
  6. import {
  7. CLIENT_BUILD_RECORD_PATH,
  8. CLIENT_BUILD_PROFILE_SELECTOR,
  9. clientBuildProcessEnvironment,
  10. repositoryClientBuildEnvironment,
  11. resolveClientBuildEnvironment,
  12. writeClientBuildRecord,
  13. } from './client-build-environment.ts'
  14. import { pnpmInvocation } from './pnpm-invocation.ts'
  15. /** Run one package script through the package manager that invoked this build. */
  16. function runScript(script: string, environment: NodeJS.ProcessEnv): void {
  17. const invocation = pnpmInvocation(['run', script], environment)
  18. const result = spawnSync(invocation.command, invocation.args, {
  19. cwd: resolve(import.meta.dirname, '..'),
  20. env: environment,
  21. stdio: 'inherit',
  22. })
  23. if (result.error !== undefined) throw result.error
  24. if (result.status !== 0) {
  25. throw new Error(`build: ${script} exited with ${String(result.status ?? result.signal)}`)
  26. }
  27. }
  28. /** Run the full build selected by `--profile` or `DSH_BUILD_CLIENT_PROFILE`. */
  29. function main(): void {
  30. const { values } = parseArgs({
  31. options: { profile: { type: 'string' } },
  32. allowPositionals: false,
  33. })
  34. const root = resolve(import.meta.dirname, '..')
  35. const repositoryEnvironment = repositoryClientBuildEnvironment(root, process.env)
  36. const profile = values.profile ?? process.env[CLIENT_BUILD_PROFILE_SELECTOR]
  37. const clientEnvironment = resolveClientBuildEnvironment(repositoryEnvironment, profile)
  38. const buildEnvironment = clientBuildProcessEnvironment(process.env, clientEnvironment)
  39. rmSync(resolve(root, CLIENT_BUILD_RECORD_PATH), { force: true })
  40. runScript('build:lib', buildEnvironment)
  41. runScript('build:web', buildEnvironment)
  42. const record = writeClientBuildRecord(root, clientEnvironment)
  43. console.log(
  44. `build: recorded ${String(record.artifacts.fileCount)} client artifact(s) with ${String(Object.keys(record.environment).length)} public value(s)`,
  45. )
  46. }
  47. if (import.meta.main) main()