client-bundle-purity.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /**
  2. * Pins shared client-bundle preset rules: module-edge purity, source-map
  3. * chaining, and physical watch dependencies hidden behind virtual CSS Modules.
  4. */
  5. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  6. import { tmpdir } from 'node:os'
  7. import { join } from 'node:path'
  8. import { fileURLToPath } from 'node:url'
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { clientBundle, requestedExternals } from '../packages/client/tsdown.client.ts'
  11. type ResolveId = (source: string) => null | { id: string; external: boolean }
  12. interface CssModulePlugin {
  13. name: string
  14. resolveId?: (source: string, importer: string | undefined) => null | string
  15. load?: (this: { addWatchFile: (id: string) => void }, id: string) => Promise<unknown>
  16. }
  17. interface SourceMapPlugin {
  18. name: string
  19. load?: (id: string) => Promise<unknown>
  20. }
  21. /** A representative dynamic bundle using the shared client baseline. */
  22. const REQUESTING_PACKAGE = '@deepseek-ai/dsh-client-ui-conversation'
  23. function clientConfigs(id = REQUESTING_PACKAGE) {
  24. return clientBundle(id, ['lib/types/index.js', 'lib/types/invariant.js'])(
  25. { env: { DSH_BUILD_FACE: 'client' } },
  26. ).filter(config => config.platform === 'browser')
  27. }
  28. describe('client bundle build faces', () => {
  29. it('watches source in development and consumes emitted JavaScript in the Client build', () => {
  30. const bundle = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js'])
  31. const development = bundle({ env: {} }).find(config => config.platform === 'browser')
  32. const artifact = bundle({ env: { DSH_BUILD_FACE: 'client' } })
  33. .find(config => config.platform === 'browser')
  34. expect(development?.entry).toEqual({ client: 'src/client/index.ts' })
  35. expect(artifact?.entry).toEqual({ client: 'lib/types/client/index.js' })
  36. })
  37. })
  38. function clientSourceMapPath(packagePath: string): string {
  39. return fileURLToPath(new URL(`../packages/${packagePath}/lib/client.js.map`, import.meta.url))
  40. }
  41. function purityResolveId(id = REQUESTING_PACKAGE): ResolveId {
  42. // libEntry is spelled at every call site (no default) so the
  43. // package-invariants text check can see the invariant entry per package.
  44. const configs = clientConfigs(id)
  45. const plugins = (configs[0] as { plugins: { name: string; resolveId?: unknown }[] }).plugins
  46. const gate = plugins.find(p => p.name === 'dsh-client-bundle-purity')
  47. if (gate?.resolveId === undefined) throw new Error('purity plugin missing from client config')
  48. return gate.resolveId as ResolveId
  49. }
  50. function cssModulePlugin(): CssModulePlugin {
  51. const configs = clientConfigs()
  52. const plugins = (configs[0] as { plugins: CssModulePlugin[] }).plugins
  53. const plugin = plugins.find(candidate => candidate.name === 'dsh-css-modules-inline')
  54. if (plugin?.resolveId === undefined || plugin.load === undefined) {
  55. throw new Error('CSS Modules plugin missing from client config')
  56. }
  57. return plugin
  58. }
  59. function sourceMapPlugin(): SourceMapPlugin {
  60. const configs = clientConfigs()
  61. const plugins = (configs[0] as { plugins: SourceMapPlugin[] }).plugins
  62. const plugin = plugins.find(candidate => candidate.name === 'dsh-tsc-sourcemap')
  63. if (plugin?.load === undefined) throw new Error('tsc sourcemap plugin missing from client config')
  64. return plugin
  65. }
  66. describe('client bundle purity gate', () => {
  67. const resolveId = purityResolveId()
  68. it('leaves default externals and non-scoped specifiers alone', () => {
  69. expect(resolveId('@deepseek-ai/dsh-client-store')).toBeNull()
  70. expect(resolveId('@deepseek-ai/dsh-client-ui-slots')).toBeNull()
  71. expect(resolveId('@deepseek-ai/dsh-client-ui-primitives')).toBeNull()
  72. expect(resolveId('react')).toBeNull()
  73. expect(resolveId('zod')).toBeNull()
  74. })
  75. it('rejects the retired web-react platform package', () => {
  76. expect(() => resolveId('@deepseek-ai/dsh-client-web-react')).toThrow(/purity/)
  77. expect(() => resolveId('@deepseek-ai/dsh-client-web-react/store')).toThrow(/purity/)
  78. })
  79. it('lets inline-safe libraries inline', () => {
  80. expect(resolveId('@deepseek-ai/dsh-session/surface')).toBeNull()
  81. expect(resolveId('@deepseek-ai/dsh-brand')).toBeNull()
  82. expect(resolveId('@deepseek-ai/dsh-deque')).toBeNull()
  83. expect(resolveId('@deepseek-ai/dsh-timeout')).toBeNull()
  84. expect(resolveId('@deepseek-ai/dsh-util-values')).toBeNull()
  85. expect(resolveId('@deepseek-ai/dsh-token-meter/client')).toBeNull()
  86. expect(() => resolveId('@deepseek-ai/dsh-token-meter')).toThrow(/purity/)
  87. expect(() => resolveId('@deepseek-ai/dsh-token-meter/client/internal')).toThrow(/purity/)
  88. })
  89. it('lets exact generated Remote contributions inline without admitting their package implementation', () => {
  90. expect(resolveId('@deepseek-ai/dsh-goal/remote')).toBeNull()
  91. expect(() => resolveId('@deepseek-ai/dsh-goal')).toThrow(/purity/)
  92. expect(() => resolveId('@deepseek-ai/dsh-goal/client')).toThrow(/purity/)
  93. expect(() => resolveId('@deepseek-ai/dsh-goal/remote/nested')).toThrow(/purity/)
  94. })
  95. it('throws on any other @deepseek-ai leak', () => {
  96. expect(() => resolveId('@deepseek-ai/dsh-agent')).toThrow(/purity/)
  97. expect(() => resolveId('@deepseek-ai/dsh-client-web')).toThrow(/purity/)
  98. })
  99. it('throws on cross-plugin value imports — bare plugin names and /client subpaths alike', () => {
  100. expect(() => resolveId('@deepseek-ai/dsh-client-connection')).toThrow(/purity/)
  101. expect(() => resolveId('@deepseek-ai/dsh-client-ui-session')).toThrow(/purity/)
  102. expect(() => resolveId('@deepseek-ai/dsh-client-ui-layout/client')).toThrow(/purity/)
  103. })
  104. it('admits package-specific requests only for the declaring bundle', () => {
  105. const requesting = purityResolveId('@deepseek-ai/dsh-api-session-controller')
  106. expect(requesting('@deepseek-ai/dsh-api-gateway/client')).toBeNull()
  107. expect(() => resolveId('@deepseek-ai/dsh-api-gateway/client')).toThrow(/purity/)
  108. })
  109. it('externalizes the baseline independently of each package manifest', () => {
  110. const requesting = clientConfigs()[0]?.deps as { neverBundle: (specifier: string) => boolean }
  111. const plain = clientConfigs('@deepseek-ai/dsh-client-connection')[0]?.deps as {
  112. neverBundle: (specifier: string) => boolean
  113. }
  114. expect(requesting.neverBundle('react')).toBe(true)
  115. expect(requesting.neverBundle('zod')).toBe(false)
  116. expect(plain.neverBundle('react')).toBe(true)
  117. expect(plain.neverBundle('@deepseek-ai/dsh-client-store')).toBe(true)
  118. })
  119. })
  120. describe('client bundle module requests', () => {
  121. it('requests what the declaration lists', () => {
  122. const requests = requestedExternals('@deepseek-ai/dsh-client-fixture', {
  123. external: ['react', 'react/jsx-runtime', '@deepseek-ai/dsh-client-ui-slots'],
  124. })
  125. expect([...requests].sort()).toEqual([
  126. '@deepseek-ai/dsh-client-ui-slots', 'react', 'react/jsx-runtime',
  127. ])
  128. })
  129. it('requests nothing when the declaration is absent', () => {
  130. expect(requestedExternals('@deepseek-ai/dsh-client-fixture', {}).size).toBe(0)
  131. })
  132. it('rejects a malformed declaration instead of reading past it', () => {
  133. expect(() => requestedExternals('@deepseek-ai/dsh-client-fixture', { external: 'react' }))
  134. .toThrow(/dsh\.client\.external must be a string array/)
  135. })
  136. })
  137. describe('client bundle debug artifacts', () => {
  138. it('emits source maps for plugin TS and TSX outside the Vite module graph', () => {
  139. const configs = clientConfigs()
  140. expect(configs[0]?.sourcemap).toBe(true)
  141. expect(configs[0]?.outputOptions).toMatchObject({ sourcemapExcludeSources: false })
  142. })
  143. it('chains emitted tsc maps when the production Client build consumes lib/types', async () => {
  144. const root = mkdtempSync(join(tmpdir(), 'dsh-client-sourcemap-'))
  145. try {
  146. const entry = join(root, 'lib', 'types', 'client', 'index.js')
  147. const source = join(root, 'src', 'client', 'index.ts')
  148. const map = { version: 3, names: [], mappings: 'AAAA', sources: ['../../../src/client/index.ts'] }
  149. mkdirSync(join(root, 'lib', 'types', 'client'), { recursive: true })
  150. mkdirSync(join(root, 'src', 'client'), { recursive: true })
  151. writeFileSync(entry, 'export const marker = true\n//# sourceMappingURL=index.js.map\n')
  152. writeFileSync(`${entry}.map`, JSON.stringify(map))
  153. writeFileSync(source, 'export const marker: true = true\n')
  154. await expect(sourceMapPlugin().load!(entry)).resolves.toEqual({
  155. code: 'export const marker = true',
  156. map: { ...map, sourcesContent: ['export const marker: true = true\n'] },
  157. })
  158. } finally {
  159. rmSync(root, { recursive: true, force: true })
  160. }
  161. })
  162. it('maps first-party sources to their repository package paths', () => {
  163. const configs = clientConfigs('@deepseek-ai/dsh-client-ui-goal')
  164. const outputOptions = configs[0]?.outputOptions
  165. if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
  166. const transform = outputOptions.sourcemapPathTransform
  167. if (transform === undefined) throw new Error('client sourcemap path transform missing')
  168. const source = transform('../src/client/GoalBar.tsx', clientSourceMapPath('client/ui-goal'))
  169. expect(source).toBe('../../../packages/client/ui-goal/src/client/GoalBar.tsx')
  170. const resolved = new URL(source, 'https://dsh.test/plugins/@deepseek-ai/dsh-client-ui-goal/client.js.map')
  171. expect(resolved.pathname).toBe('/packages/client/ui-goal/src/client/GoalBar.tsx')
  172. })
  173. it('maps dual-face host sources to the host package group', () => {
  174. const configs = clientConfigs('@deepseek-ai/dsh-host-directory-picker-native')
  175. const outputOptions = configs[0]?.outputOptions
  176. if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
  177. const transform = outputOptions.sourcemapPathTransform
  178. if (transform === undefined) throw new Error('client sourcemap path transform missing')
  179. const source = transform('../src/client/index.ts', clientSourceMapPath('host/directory-picker-native'))
  180. expect(source).toBe('../../../packages/host/directory-picker-native/src/client/index.ts')
  181. })
  182. it('maps inlined workspace sources to packages and leaves dependencies outside it unchanged', () => {
  183. const configs = clientConfigs('@deepseek-ai/dsh-client-connection')
  184. const outputOptions = configs[0]?.outputOptions
  185. if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
  186. const transform = outputOptions.sourcemapPathTransform
  187. if (transform === undefined) throw new Error('client sourcemap path transform missing')
  188. const sourceMapPath = clientSourceMapPath('client/connection')
  189. const workspaceSource = transform('../src/rpc.ts', sourceMapPath)
  190. expect(workspaceSource).toBe('../../../packages/client/connection/src/rpc.ts')
  191. const resolved = new URL(workspaceSource, 'https://dsh.test/plugins/@deepseek-ai/dsh-client-connection/client.js.map')
  192. expect(resolved.pathname).toBe('/packages/client/connection/src/rpc.ts')
  193. const dependencySource = '../../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js'
  194. expect(transform(dependencySource, sourceMapPath)).toBe(dependencySource)
  195. })
  196. })
  197. describe('client bundle CSS Modules watch graph', () => {
  198. it('registers the physical stylesheet read behind a virtual module', async () => {
  199. const plugin = cssModulePlugin()
  200. const importer = fileURLToPath(new URL(
  201. '../packages/client/ui-conversation/src/client/queue/QueueDock.tsx',
  202. import.meta.url,
  203. ))
  204. const stylesheet = fileURLToPath(new URL(
  205. '../packages/client/ui-conversation/src/client/queue/QueueDock.module.css',
  206. import.meta.url,
  207. ))
  208. const virtualId = plugin.resolveId?.('./QueueDock.module.css', importer)
  209. if (virtualId === null || virtualId === undefined) throw new Error('CSS Modules import was not resolved')
  210. const addWatchFile = vi.fn()
  211. await plugin.load?.call({ addWatchFile }, virtualId)
  212. expect(addWatchFile).toHaveBeenCalledExactlyOnceWith(stylesheet)
  213. })
  214. })