1
0

client-build-environment.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { createHash } from 'node:crypto'
  2. import { execFileSync, spawnSync } from 'node:child_process'
  3. import {
  4. existsSync,
  5. globSync,
  6. mkdirSync,
  7. readFileSync,
  8. statSync,
  9. writeFileSync,
  10. } from 'node:fs'
  11. import { dirname, resolve } from 'node:path'
  12. /** Prefix reserved for build-time values that may be embedded in browser artifacts. */
  13. const CLIENT_BUILD_ENV_PREFIX = 'DSH_CLIENT_'
  14. /** Non-public selector used by build orchestration to request a named client profile. */
  15. export const CLIENT_BUILD_PROFILE_SELECTOR = 'DSH_BUILD_CLIENT_PROFILE'
  16. /** Public client environment required by official DSH artifacts. */
  17. const OFFICIAL_CLIENT_BUILD_ENVIRONMENT = {
  18. DSH_CLIENT_BUILD_PROFILE: 'official',
  19. DSH_CLIENT_TITLE: 'DeepSeek Harness',
  20. } as const
  21. /** Public variable carrying the source commit embedded in client artifacts. */
  22. const CLIENT_COMMIT_HASH_VARIABLE = 'DSH_CLIENT_COMMIT_HASH'
  23. /** Public variable carrying the repository package version embedded in client artifacts. */
  24. const CLIENT_VERSION_VARIABLE = 'DSH_CLIENT_VERSION'
  25. /** Repository-relative path of the complete client build record. */
  26. export const CLIENT_BUILD_RECORD_PATH = '.dsh-build/client-build-environment.json'
  27. const CLIENT_BUILD_RECORD_FORMAT = 1
  28. const CLIENT_ARTIFACT_PATTERNS = [
  29. 'apps/web/dist/**/*',
  30. 'packages/*/*/lib/client.js',
  31. 'packages/*/*/lib/client.js.map',
  32. ] as const
  33. /** Public values embedded in one set of client artifacts. */
  34. export type ClientBuildEnvironment = Readonly<Record<string, string>>
  35. /**
  36. * Resolve the short source commit used by browser build metadata.
  37. * @param root - repository root used when no explicit value is supplied.
  38. * @param environment - environment that may already carry a commit value.
  39. * @returns lowercase 7-character Git commit prefix.
  40. */
  41. export function repositoryCommitHash(root: string, environment: NodeJS.ProcessEnv = process.env): string {
  42. const explicit = environment[CLIENT_COMMIT_HASH_VARIABLE]
  43. const value = explicit ?? execFileSync('git', ['rev-parse', 'HEAD'], {
  44. cwd: root,
  45. encoding: 'utf8',
  46. stdio: ['ignore', 'pipe', 'ignore'],
  47. }).trim()
  48. if (!/^[0-9a-f]{7,40}$/iu.test(value)) {
  49. throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} must be a Git commit hash; got ${JSON.stringify(value)}`)
  50. }
  51. return value.slice(0, 7).toLowerCase()
  52. }
  53. /**
  54. * Resolve the repository package version used by browser build metadata.
  55. * @param root - repository root containing the authoritative package.json.
  56. * @returns the repository's semver-compatible package version.
  57. */
  58. export function repositoryVersion(root: string): string {
  59. const path = resolve(root, 'package.json')
  60. let manifest: unknown
  61. try {
  62. manifest = JSON.parse(readFileSync(path, 'utf8'))
  63. } catch (error) {
  64. const detail = error instanceof Error ? error.message : String(error)
  65. throw new Error(`cannot read repository version from ${path}: ${detail}`)
  66. }
  67. if (!isObject(manifest) || typeof manifest.version !== 'string'
  68. || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(manifest.version)) {
  69. throw new Error(`repository package.json has an invalid version ${JSON.stringify(isObject(manifest) ? manifest.version : undefined)}`)
  70. }
  71. return manifest.version
  72. }
  73. /**
  74. * Read whether Git reports any staged, unstaged, untracked, or submodule change.
  75. * @param root - repository root whose worktree is inspected.
  76. * @returns true or false inside a Git worktree; undefined without Git metadata.
  77. */
  78. export function repositoryGitDirty(root: string): boolean | undefined {
  79. const probe = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], {
  80. cwd: root,
  81. encoding: 'utf8',
  82. stdio: ['ignore', 'pipe', 'ignore'],
  83. })
  84. if (probe.error !== undefined || probe.status !== 0 || probe.stdout.trim() !== 'true') return undefined
  85. const status = spawnSync('git', ['status', '--porcelain=v1', '--untracked-files=normal'], {
  86. cwd: root,
  87. encoding: 'utf8',
  88. stdio: ['ignore', 'pipe', 'pipe'],
  89. })
  90. if (status.error !== undefined) throw status.error
  91. if (status.status !== 0) {
  92. throw new Error(`git status failed in ${root}: ${status.stderr.trim() || String(status.status)}`)
  93. }
  94. return status.stdout !== ''
  95. }
  96. /**
  97. * Resolve the public environment for a complete default build from one checkout.
  98. * Repository-owned metadata replaces inherited values; other public values pass through.
  99. * @param root - repository root supplying version and Git metadata.
  100. * @param environment - caller environment supplying optional commit and public extensions.
  101. * @returns complete public client environment for the default build.
  102. */
  103. export function repositoryClientBuildEnvironment(
  104. root: string,
  105. environment: NodeJS.ProcessEnv = process.env,
  106. ): ClientBuildEnvironment {
  107. const inherited = { ...clientBuildEnvironment(environment) }
  108. delete inherited.DSH_CLIENT_COMMIT_HASH
  109. delete inherited.DSH_CLIENT_GIT_DIRTY
  110. delete inherited.DSH_CLIENT_VERSION
  111. const dirty = repositoryGitDirty(root)
  112. return {
  113. ...inherited,
  114. DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment),
  115. ...(dirty === true ? { DSH_CLIENT_GIT_DIRTY: 'true' } : {}),
  116. DSH_CLIENT_VERSION: repositoryVersion(root),
  117. }
  118. }
  119. /**
  120. * Resolve the exact public values required by an official build at one commit.
  121. * @param root - repository root whose HEAD must match the built source.
  122. * @param environment - optional explicit commit source for non-Git build environments.
  123. * @returns complete official client environment.
  124. */
  125. export function officialClientBuildEnvironment(
  126. root: string,
  127. environment: NodeJS.ProcessEnv = process.env,
  128. ): Readonly<Record<`DSH_CLIENT_${string}`, string>> {
  129. return {
  130. DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment),
  131. DSH_CLIENT_VERSION: repositoryVersion(root),
  132. ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT,
  133. }
  134. }
  135. /** Digest of every client artifact produced by the complete root build. */
  136. interface ClientArtifactDigest {
  137. /** Number of files covered by the digest. */
  138. readonly fileCount: number
  139. /** Lowercase SHA-256 digest of sorted paths and file contents. */
  140. readonly sha256: string
  141. }
  142. /** Durable description of one complete root client build. */
  143. export interface ClientBuildRecord {
  144. /** Record schema version. */
  145. readonly formatVersion: number
  146. /** Exact public environment embedded by Vite and tsdown. */
  147. readonly environment: ClientBuildEnvironment
  148. /** Digest that binds the environment to the current artifacts. */
  149. readonly artifacts: ClientArtifactDigest
  150. }
  151. /**
  152. * Collect the public client environment in deterministic key order.
  153. * @param environment - environment inherited by the build process.
  154. * @returns defined `DSH_CLIENT_*` values only.
  155. */
  156. function clientBuildEnvironment(environment: NodeJS.ProcessEnv): ClientBuildEnvironment {
  157. return Object.fromEntries(Object.entries(environment)
  158. .filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
  159. .sort(([left], [right]) => left.localeCompare(right))) as Record<string, string>
  160. }
  161. /**
  162. * Resolve the exact public environment selected for a complete client build.
  163. * @param environment - parent process environment.
  164. * @param profile - explicit profile, or the non-public selector when omitted.
  165. * @returns the inherited public values when no profile is selected, otherwise the named profile.
  166. */
  167. export function resolveClientBuildEnvironment(
  168. environment: NodeJS.ProcessEnv,
  169. profile: string | undefined = environment[CLIENT_BUILD_PROFILE_SELECTOR],
  170. ): ClientBuildEnvironment {
  171. if (profile === undefined) return clientBuildEnvironment(environment)
  172. if (profile === 'official') {
  173. const commitHash = environment[CLIENT_COMMIT_HASH_VARIABLE]
  174. const version = environment[CLIENT_VERSION_VARIABLE]
  175. if (commitHash === undefined) {
  176. throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} is required for the official client build profile`)
  177. }
  178. if (version === undefined) {
  179. throw new Error(`${CLIENT_VERSION_VARIABLE} is required for the official client build profile`)
  180. }
  181. return {
  182. DSH_CLIENT_COMMIT_HASH: commitHash,
  183. DSH_CLIENT_VERSION: version,
  184. ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT,
  185. }
  186. }
  187. throw new Error(`unknown client build profile ${JSON.stringify(profile)}; expected "official"`)
  188. }
  189. /**
  190. * Construct a subprocess environment containing exactly the selected public values.
  191. * @param environment - parent process environment.
  192. * @param clientEnvironment - complete public environment selected for the build.
  193. * @returns the parent environment with selectors and inherited public values replaced.
  194. */
  195. export function clientBuildProcessEnvironment(
  196. environment: NodeJS.ProcessEnv,
  197. clientEnvironment: ClientBuildEnvironment,
  198. ): NodeJS.ProcessEnv {
  199. const child: NodeJS.ProcessEnv = {}
  200. for (const [name, value] of Object.entries(environment)) {
  201. if (name === CLIENT_BUILD_PROFILE_SELECTOR || name.startsWith(CLIENT_BUILD_ENV_PREFIX)) continue
  202. child[name] = value
  203. }
  204. return { ...child, ...clientEnvironment }
  205. }
  206. /**
  207. * Require the public client environment to match an artifact profile exactly.
  208. *
  209. * An exact key set matters because every prefixed value is eligible for
  210. * inlining: an unexpected variable can change published bytes just as surely
  211. * as a missing or incorrect required value.
  212. *
  213. * @param environment - public environment from a build process or build record.
  214. * @param expected - complete public client environment for the artifact profile.
  215. */
  216. export function assertClientBuildEnvironment(
  217. environment: Readonly<Record<string, string | undefined>>,
  218. expected: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
  219. ): void {
  220. const actual = Object.fromEntries(Object.entries(environment)
  221. .filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
  222. .sort(([left], [right]) => left.localeCompare(right)))
  223. const normalizedExpected = Object.fromEntries(Object.entries(expected)
  224. .sort(([left], [right]) => left.localeCompare(right)))
  225. if (JSON.stringify(actual) === JSON.stringify(normalizedExpected)) return
  226. const names = [...new Set([...Object.keys(actual), ...Object.keys(normalizedExpected)])].sort()
  227. const differences = names.filter(name => actual[name] !== normalizedExpected[name])
  228. throw new Error(`client build environment differs from the required artifact profile: ${differences.join(', ')}`)
  229. }
  230. /**
  231. * Create bundler substitutions for public client build environment variables.
  232. *
  233. * The empty `process.env` fallback makes an unset static property read
  234. * evaluate to `undefined` without providing a browser `process` global.
  235. * Exact substitutions remain longer matches than that fallback. Dynamic
  236. * property reads and enumeration deliberately observe the empty object.
  237. *
  238. * @param environment - environment inherited by the build process.
  239. * @returns deterministic Vite/tsdown `define` expressions.
  240. */
  241. export function clientBuildEnvironmentDefines(
  242. environment: NodeJS.ProcessEnv,
  243. ): Record<string, string> {
  244. const defines: Record<string, string> = { 'process.env': '{}' }
  245. for (const [name, value] of Object.entries(clientBuildEnvironment(environment))) {
  246. defines[`process.env.${name}`] = JSON.stringify(value)
  247. }
  248. return defines
  249. }
  250. /**
  251. * Write the build record after a complete root build succeeds.
  252. * @param root - repository root containing the generated artifacts.
  253. * @param environment - exact public environment supplied to both bundlers.
  254. * @returns the record written to disk.
  255. */
  256. export function writeClientBuildRecord(
  257. root: string,
  258. environment: ClientBuildEnvironment,
  259. ): ClientBuildRecord {
  260. const record: ClientBuildRecord = {
  261. formatVersion: CLIENT_BUILD_RECORD_FORMAT,
  262. environment: clientBuildEnvironment(environment),
  263. artifacts: clientArtifactDigest(root),
  264. }
  265. const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
  266. mkdirSync(dirname(path), { recursive: true })
  267. writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`)
  268. return record
  269. }
  270. /**
  271. * Read a complete build record and prove it still describes the current artifacts.
  272. * @param root - repository root containing the record and generated artifacts.
  273. * @param expected - optional exact public environment required by a consumer.
  274. * @returns the parsed and artifact-verified record.
  275. */
  276. export function readClientBuildRecord(
  277. root: string,
  278. expected?: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
  279. ): ClientBuildRecord {
  280. const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
  281. if (!existsSync(path)) {
  282. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is missing; run a complete pnpm run build first`)
  283. }
  284. let parsed: unknown
  285. try {
  286. parsed = JSON.parse(readFileSync(path, 'utf8'))
  287. } catch (error) {
  288. const detail = error instanceof Error ? error.message : String(error)
  289. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is invalid JSON: ${detail}`)
  290. }
  291. const record = parseClientBuildRecord(parsed)
  292. if (expected !== undefined) assertClientBuildEnvironment(record.environment, expected)
  293. const current = clientArtifactDigest(root)
  294. if (current.fileCount !== record.artifacts.fileCount || current.sha256 !== record.artifacts.sha256) {
  295. throw new Error(
  296. `client artifacts differ from ${CLIENT_BUILD_RECORD_PATH}; run a complete pnpm run build before consuming them`,
  297. )
  298. }
  299. return record
  300. }
  301. /** Return the deterministic digest of every artifact affected by the public client environment. */
  302. function clientArtifactDigest(root: string): ClientArtifactDigest {
  303. const paths = globSync([...CLIENT_ARTIFACT_PATTERNS], { cwd: root })
  304. .map(path => path.replaceAll('\\', '/'))
  305. .filter(path => statSync(resolve(root, path)).isFile())
  306. .sort()
  307. if (paths.length === 0) throw new Error('complete client build produced no Vite or dynamic client artifacts')
  308. const digest = createHash('sha256')
  309. for (const path of paths) {
  310. const content = readFileSync(resolve(root, path))
  311. digest.update(`${Buffer.byteLength(path)}:`)
  312. digest.update(path)
  313. digest.update(`${content.byteLength}:`)
  314. digest.update(content)
  315. }
  316. return { fileCount: paths.length, sha256: digest.digest('hex') }
  317. }
  318. /** Parse and validate the persisted record before any consumer trusts it. */
  319. function parseClientBuildRecord(value: unknown): ClientBuildRecord {
  320. if (!isObject(value) || !hasExactKeys(value, ['artifacts', 'environment', 'formatVersion'])) {
  321. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid top-level schema`)
  322. }
  323. if (value.formatVersion !== CLIENT_BUILD_RECORD_FORMAT) {
  324. throw new Error(
  325. `client build record ${CLIENT_BUILD_RECORD_PATH} uses format ${String(value.formatVersion)}; expected ${String(CLIENT_BUILD_RECORD_FORMAT)}`,
  326. )
  327. }
  328. if (!isObject(value.environment)) {
  329. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment`)
  330. }
  331. const environment: Record<string, string> = {}
  332. for (const [name, entry] of Object.entries(value.environment).sort(([left], [right]) => left.localeCompare(right))) {
  333. if (!name.startsWith(CLIENT_BUILD_ENV_PREFIX) || typeof entry !== 'string') {
  334. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment entry ${name}`)
  335. }
  336. environment[name] = entry
  337. }
  338. if (!isObject(value.artifacts) || !hasExactKeys(value.artifacts, ['fileCount', 'sha256'])) {
  339. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact digest`)
  340. }
  341. if (!Number.isSafeInteger(value.artifacts.fileCount) || Number(value.artifacts.fileCount) < 1) {
  342. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact count`)
  343. }
  344. if (typeof value.artifacts.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(value.artifacts.sha256)) {
  345. throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid SHA-256 digest`)
  346. }
  347. return {
  348. formatVersion: CLIENT_BUILD_RECORD_FORMAT,
  349. environment,
  350. artifacts: {
  351. fileCount: Number(value.artifacts.fileCount),
  352. sha256: value.artifacts.sha256,
  353. },
  354. }
  355. }
  356. function isObject(value: unknown): value is Record<string, unknown> {
  357. return typeof value === 'object' && value !== null && !Array.isArray(value)
  358. }
  359. function hasExactKeys(value: Record<string, unknown>, expected: readonly string[]): boolean {
  360. const actual = Object.keys(value).sort()
  361. return actual.length === expected.length && actual.every((key, index) => key === expected[index])
  362. }