tsdown.client.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /**
  2. * Shared tsdown preset for UI plugin client bundles. Emits a closure-factory
  3. * artifact: the bundle calls window.__ModuleLoader__.load({id, factory})
  4. * and resolves externals through the injected require (loader module table —
  5. * cordis DI entities, no globals, no import map). CSS Modules are compiled by
  6. * lightningcss inside the bundle: importing `x.module.css` yields the
  7. * hashed class map, and the css text auto-injects a <style data-plugin="<id>">
  8. * tag at factory execution (the loader removes plugin-owned tags on unload).
  9. * The virtual loader registers each real stylesheet as a watch dependency.
  10. */
  11. import { readFile } from 'node:fs/promises'
  12. import { basename, dirname, resolve as resolvePath } from 'node:path'
  13. import type { UserConfig } from 'tsdown'
  14. import { transform } from 'lightningcss'
  15. import { PLATFORM_MODULES } from './web/src/platform.ts'
  16. /**
  17. * Virtual-id wrapper keeping module CSS away from tsdown's own css pipeline
  18. * (which requires @tsdown/css). The suffix matters: tsdown's guard matches ids
  19. * ending in `.css`, so the virtual id must not.
  20. */
  21. const CSS_VIRTUAL_PREFIX = '\0dsh-css:'
  22. const CSS_VIRTUAL_SUFFIX = '.mjs'
  23. /**
  24. * Wire/type layers a client bundle may inline: browser-safe contract surfaces
  25. * with no runtime identity to share (no Symbol/instanceof/singleton state).
  26. * Everything else under @deepseek-ai/* is either a module-table entry
  27. * (external) or a leak the purity gate rejects.
  28. */
  29. export const INLINE_SAFE = /^@deepseek-ai\/dsh-(host-apiproxy|session|llm|tools|brand)(\/|$)/
  30. /**
  31. * Documented TEMPORARY exemption, not a platform module (hence not in
  32. * platform.ts): the snapshot-store engine (createSnapshotStore/defineStore/
  33. * shallowEqual) lives in runtime pending its promotion-time rehoming, and
  34. * five importers (locale, ui-layout, ui-conversation ×3) ride this single
  35. * exemption. At runtime the lazy CJS table answers the require natively:
  36. * runtime is an immediately-tier row, its factory is registered before any
  37. * dependent bundle materializes. TODO(webload/store-rehome): remove with the
  38. * store-engine relocation follow-up.
  39. */
  40. const RUNTIME_STORE_EXEMPTION = '@deepseek-ai/dsh-client-runtime/client'
  41. /** Externals resolved from the loader module table: the platform seed entries plus the documented runtime exemption. */
  42. export const CLIENT_EXTERNALS: readonly string[] = [...PLATFORM_MODULES, RUNTIME_STORE_EXEMPTION]
  43. /**
  44. * Build the tsdown config for one UI plugin package: the node-half lib build
  45. * plus the browser client bundle. A package-level tsdown.config.ts REPLACES
  46. * the root workspace shape, so the lib half must be restated here — dropping
  47. * it leaves the package without lib/index.js and the host Loader cannot
  48. * import its node half.
  49. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load
  50. * handoff and onto the injected style tags.
  51. * @param libEntry - node-half entries, spelled at the call site so the
  52. * package-invariants gate can see `lib/types/invariant.js` in each package's
  53. * own tsdown.config.ts (a preset-side glob hides it from the mechanical check).
  54. * @returns tsdown user configs emitting lib/*.js and lib/client.js.
  55. */
  56. export function clientBundle(id: string, libEntry: readonly string[]): UserConfig[] {
  57. return [{
  58. entry: [...libEntry],
  59. outDir: 'lib',
  60. format: ['esm'],
  61. platform: 'node',
  62. target: 'es2024',
  63. fixedExtension: false,
  64. dts: false,
  65. clean: false,
  66. }, {
  67. entry: { client: 'src/client/index.ts' },
  68. // Browser bundle lands next to the node half (single lib/ artifact dir;
  69. // the entryFileNames pin keeps it exactly lib/client.js). clean must stay
  70. // off — a default clean would wipe the node-half output emitted above.
  71. outDir: 'lib',
  72. format: 'cjs',
  73. platform: 'browser',
  74. // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing.
  75. dts: false,
  76. clean: false,
  77. external: [...CLIENT_EXTERNALS],
  78. // Browser bundles inline node-idiom deps (zustand/immer read
  79. // process.env.NODE_ENV; zustand's esm build also probes
  80. // import.meta.env.MODE, which a CJS output cannot carry — rolldown flags
  81. // EMPTY_IMPORT_META). vite defined both on the seed path; tsdown inlining
  82. // needs the substitutions here or the factory throws ReferenceError at
  83. // boot / the build gate reds. Both keys honor the build's NODE_ENV so a
  84. // dev build keeps the dev-branch semantics; artifacts default to production.
  85. // The bare `import.meta.env` key is required alongside the precise MODE
  86. // key: zustand probes `import.meta.env ? import.meta.env.MODE : ...`, and
  87. // the truthiness probe would otherwise survive as an empty import.meta.
  88. define: {
  89. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  90. 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  91. 'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
  92. },
  93. // tsdown auto-externalizes package dependencies; anything NOT in the
  94. // loader module table must inline instead (wire/type layers, zod, clsx —
  95. // every non-shared dep). A require() the table cannot answer is a
  96. // guaranteed runtime throw, so the rule is the table list itself: no
  97. // opinion for table entries (external above wins), bundle everything else.
  98. noExternal: (id: string) => (CLIENT_EXTERNALS.includes(id) ? undefined : true),
  99. plugins: [{
  100. // Bundle purity gate (build-time mirror of the module-edge rules):
  101. // platform seed entries stay external, inline-safe wire layers inline,
  102. // and every other @deepseek-ai value import is a build error — a
  103. // cross-plugin value import either inlines a duplicate runtime instance
  104. // or requires a specifier the frozen module table cannot answer.
  105. // Cross-plugin collaboration goes through cordis services instead.
  106. name: 'dsh-client-bundle-purity',
  107. resolveId(source: string) {
  108. if (!source.startsWith('@deepseek-ai/')) return null
  109. if (CLIENT_EXTERNALS.includes(source)) return null // platform module: external wins
  110. if (INLINE_SAFE.test(source)) return null // wire/type layer: inline is the point
  111. throw new Error(
  112. `client bundle purity: "${source}" is not a platform module (CLIENT_EXTERNALS) and not an inline-safe wire layer — `
  113. + 'cross-plugin value imports are forbidden; collaborate through cordis services (type-only imports are erased and never reach this gate)',
  114. )
  115. },
  116. }, {
  117. name: 'dsh-css-modules-inline',
  118. resolveId(source: string, importer: string | undefined) {
  119. if (!source.endsWith('.module.css')) return null
  120. const abs = importer !== undefined ? resolvePath(dirname(importer), source) : source
  121. return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  122. },
  123. async load(virtualId: string) {
  124. if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
  125. const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  126. // The virtual id otherwise hides the physical stylesheet from Rolldown's watch graph.
  127. this.addWatchFile(fileId)
  128. const source = await readFile(fileId)
  129. const { code, exports: cssExports } = transform({
  130. filename: fileId,
  131. code: source,
  132. cssModules: { pattern: `[hash]_[local]` },
  133. minify: true,
  134. })
  135. const classMap: Record<string, string> = {}
  136. for (const [local, exp] of Object.entries(cssExports ?? {})) classMap[local] = exp.name
  137. // One <style data-plugin> per module file; idempotent under re-evaluation.
  138. return [
  139. `const css = ${JSON.stringify(code.toString())};`,
  140. `const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`,
  141. `if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css=' + JSON.stringify(tagId) + ']') === null) {`,
  142. ` const tag = document.createElement('style');`,
  143. ` tag.dataset.plugin = ${JSON.stringify(id)};`,
  144. ` tag.dataset.pluginCss = tagId;`,
  145. ` tag.textContent = css;`,
  146. ` document.head.appendChild(tag);`,
  147. `}`,
  148. `export default ${JSON.stringify(classMap)};`,
  149. ].join('\n')
  150. },
  151. }],
  152. outputOptions: {
  153. entryFileNames: 'client.js',
  154. banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`,
  155. footer: `return module.exports; } });`,
  156. intro: 'var module = { exports: {} }; var exports = module.exports;',
  157. },
  158. }]
  159. }