client-build-environment.ts 1.1 KB

123456789101112131415161718192021222324
  1. /** Prefix reserved for build-time values that may be embedded in browser artifacts. */
  2. const CLIENT_BUILD_ENV_PREFIX = 'DSH_CLIENT_'
  3. /**
  4. * Create bundler substitutions for public client build environment variables.
  5. *
  6. * The empty `process.env` fallback makes an unset static property read
  7. * evaluate to `undefined` without providing a browser `process` global.
  8. * Exact substitutions remain longer matches than that fallback. Dynamic
  9. * property reads and enumeration deliberately observe the empty object.
  10. *
  11. * @param environment - environment inherited by the build process.
  12. * @returns deterministic Vite/tsdown `define` expressions.
  13. */
  14. export function clientBuildEnvironmentDefines(
  15. environment: NodeJS.ProcessEnv,
  16. ): Record<string, string> {
  17. const defines: Record<string, string> = { 'process.env': '{}' }
  18. for (const [name, value] of Object.entries(environment).sort(([left], [right]) => left.localeCompare(right))) {
  19. if (!name.startsWith(CLIENT_BUILD_ENV_PREFIX) || value === undefined) continue
  20. defines[`process.env.${name}`] = JSON.stringify(value)
  21. }
  22. return defines
  23. }