tsdown.client.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 is compiled by
  6. * lightningcss inside the bundle: `x.module.css` yields its hashed class map
  7. * and injects a tagged style at factory execution, while `x.css?inline`
  8. * exports compiled text for a plugin-owned lifecycle effect. The virtual
  9. * loaders register each real stylesheet as a watch dependency.
  10. */
  11. import { readFile } from 'node:fs/promises'
  12. import { existsSync, globSync, readFileSync } from 'node:fs'
  13. import { isBuiltin } from 'node:module'
  14. import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path'
  15. import { fileURLToPath } from 'node:url'
  16. import type { UserConfig } from 'tsdown'
  17. import { transform } from 'lightningcss'
  18. import { optionalStringArray } from './modules/src/client/manifest.ts'
  19. import { PLATFORM_MODULES, PRELOADED_CLIENT_EXTERNALS } from './web/src/platform.ts'
  20. import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts'
  21. /**
  22. * Virtual-id wrapper keeping module CSS away from tsdown's own css pipeline
  23. * (which requires @tsdown/css). The suffix matters: tsdown's guard matches ids
  24. * ending in `.css`, so the virtual id must not.
  25. */
  26. const CSS_VIRTUAL_PREFIX = '\0dsh-css:'
  27. const GLOBAL_CSS_VIRTUAL_PREFIX = '\0dsh-global-css:'
  28. const INLINE_CSS_VIRTUAL_PREFIX = '\0dsh-inline-css:'
  29. const CSS_VIRTUAL_SUFFIX = '.mjs'
  30. const INLINE_CSS_QUERY = '?inline'
  31. /** Emit one plugin-owned style injector and an optional CSS Modules export. */
  32. function styleInjectionModule(
  33. id: string,
  34. fileId: string,
  35. css: string,
  36. classMap?: Readonly<Record<string, string>>,
  37. ): string {
  38. const source = [
  39. `const css = ${JSON.stringify(css)};`,
  40. `const tagId = ${JSON.stringify(`${id}/${basename(fileId)}`)};`,
  41. 'if (typeof document !== \'undefined\' && document.querySelector(\'style[data-plugin-css=\' + JSON.stringify(tagId) + \']\') === null) {',
  42. ' const tag = document.createElement(\'style\');',
  43. ` tag.dataset.plugin = ${JSON.stringify(id)};`,
  44. ' tag.dataset.pluginCss = tagId;',
  45. ' tag.textContent = css;',
  46. ' document.head.appendChild(tag);',
  47. '}',
  48. ]
  49. source.push(classMap === undefined ? 'export {};' : `export default ${JSON.stringify(classMap)};`)
  50. return source.join('\n')
  51. }
  52. /**
  53. * Contract layers and pure folds a client bundle may inline: browser-safe
  54. * values with no runtime identity to share (no Symbol/instanceof/singleton state).
  55. * Everything else under @deepseek-ai/* is either a module-table entry
  56. * (external) or a leak the purity gate rejects.
  57. */
  58. export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-agent-presets\/display$|@deepseek-ai\/dsh-spill-policy\/notice$)/
  59. /**
  60. * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
  61. * would read them as plugin packages. They carry no cross-plugin runtime
  62. * identity to share — the framework itself is a requested module-table row
  63. * (external), while these are ordinary libraries a browser bundle inlines.
  64. */
  65. const VENDORED_LIBRARY = /^@deepseek-ai\/(cosmokit|schemastery)(\/|$)/
  66. /** Generated descriptor/codec contribution with no shared runtime identity. */
  67. const GENERATED_REMOTE = /^@deepseek-ai\/dsh-[a-z0-9]+(?:-[a-z0-9]+)*\/remote$/
  68. /**
  69. * Workspace mode replaces an empty config array with the root defaults. A
  70. * falsey entry instead removes this package before entry resolution.
  71. */
  72. const SKIP_WORKSPACE_BUILD: UserConfig = { entry: '' }
  73. const REPOSITORY_ROOT = fileURLToPath(new URL('../..', import.meta.url))
  74. /** Rebase a physical lib-relative source onto a browser URL that mirrors the repository directories. */
  75. function browserSourcePath(source: string, sourcemapPath: string): string {
  76. if (!source.startsWith('.')) return source
  77. const physicalSource = resolvePath(dirname(sourcemapPath), source)
  78. const repositoryPath = relative(REPOSITORY_ROOT, physicalSource).split(sep).join('/')
  79. return repositoryPath.startsWith('packages/') ? `../../../${repositoryPath}` : source
  80. }
  81. /**
  82. * Build the tsdown config for one UI plugin package: the node-half lib build
  83. * plus the browser client bundle. Client packages emit both halves during the
  84. * Client pass by default; packages needed for Host reflection may opt into the
  85. * earlier Host pass. A package-level tsdown.config.ts REPLACES the root
  86. * workspace layout, so the lib half must be restated here — dropping it leaves
  87. * the package without lib/index.js and the host Loader cannot import its node
  88. * half. The Client build consumes `lib/types` and chains those tsc maps, with
  89. * original source content, into the standalone plugin map.
  90. * @param id - plugin id (package name), stamped into the __ModuleLoader__.load
  91. * handoff and onto the injected style tags.
  92. * @param libEntry - node-half entries, spelled at the call site so the
  93. * package-invariants gate can see `lib/types/invariant.js` in each package's
  94. * own tsdown.config.ts (a preset-side glob hides it from the mechanical check).
  95. * @param options - phase placement, lib overrides, and companion Node configs.
  96. * @returns ENV-selected tsdown config for the current build face.
  97. */
  98. export function clientBundle(
  99. id: string,
  100. libEntry: readonly string[],
  101. options: ClientBundleOptions = {},
  102. ): BuildFaceConfig {
  103. const lib = clientLibraryConfig(id, libEntry, options.lib)
  104. return ({ env }) => {
  105. const face = buildFace(env?.DSH_BUILD_FACE)
  106. const clientEntry = face === undefined ? 'src/client/index.ts' : 'lib/types/client/index.js'
  107. const client = clientConfig(id, clientEntry)
  108. const node = [lib, ...(options.companions ?? [])]
  109. if (face === 'host') return options.hostPhase === true ? node : [SKIP_WORKSPACE_BUILD]
  110. if (face === 'client') {
  111. return options.hostPhase === true ? [client] : [...node, client]
  112. }
  113. return [...node, client]
  114. }
  115. }
  116. /**
  117. * Build the tsdown config for a client library the compile shell links
  118. * statically (the static assembly channel: `apps/web` resolves the package
  119. * name, bundles the artifact, and owns the chunk layout and the CSS pipeline).
  120. *
  121. * Calling this preset is what puts a package in the static assembly channel,
  122. * so the call sites are the roster: gates read it through
  123. * {@link isStaticLinkedConfig} rather than a second hand-kept list. A package on
  124. * this roster must not be a module-table row as well — the browser would take
  125. * the statically linked copy and a provider's bytes would sit unused in its
  126. * bundle.
  127. *
  128. * Four artifact contracts:
  129. * 1. every bare specifier stays an import. The shell attributes chunk bytes by
  130. * `node_modules/<pkg>`, so a dependency inlined into a workspace file is
  131. * attributed to no npm package and its bytes fall into the index chunk,
  132. * which collapses the vendor/index cache split.
  133. * 2. `esm` on `platform: 'browser'` — the shell is the only consumer.
  134. * 3. sourcemaps, chained through the tsc maps under `lib/types` to the sources.
  135. * 4. stylesheets ship with the package: a relative `.css` import survives as a
  136. * relative external and the sheet is emitted under `lib/` at its
  137. * `src`-relative path, so vite stays the only owner of class hashing.
  138. * @param id - package name, used in tsdown diagnostics.
  139. * @param libEntry - emitted JavaScript entries consumed from `lib/types`, one
  140. * bundle each: a multi-entry build would emit a hash-named shared chunk that
  141. * the exact `files` list cannot publish.
  142. * @returns ENV-selected tsdown config for the Client build face.
  143. */
  144. export function staticLinked(id: string, libEntry: readonly string[]): BuildFaceConfig {
  145. // Each entry names its own output file, so two entries with the same basename
  146. // would overwrite one artifact instead of emitting two.
  147. const names = new Set(libEntry.map(entry => basename(entry, '.js')))
  148. if (names.size !== libEntry.length) {
  149. throw new Error(`tsdown: ${id} entries collide on an output name: ${libEntry.join(', ')}`)
  150. }
  151. return clientOnly(libEntry.map(entry => staticLinkedConfig(id, entry)))
  152. }
  153. /**
  154. * Whether a package's tsdown configs put it in the static assembly channel.
  155. * The roster has no separate list: gates load each package's own
  156. * `tsdown.config.ts`, call it for the Client face, and ask this.
  157. * @param configs - configs a package's build-face function returned.
  158. * @returns true when at least one config was built by {@link staticLinked}.
  159. */
  160. export function isStaticLinkedConfig(configs: readonly UserConfig[]): boolean {
  161. return configs.some(config => (config.plugins as readonly { name?: string }[] | undefined ?? [])
  162. .some(plugin => plugin.name === STATIC_LINKED_PLUGIN))
  163. }
  164. /**
  165. * Build a Client-only Node library during the Client pass.
  166. * @param id - Package name used in tsdown diagnostics.
  167. * @param libEntry - Emitted JavaScript entries consumed from `lib/types`.
  168. * @returns ENV-selected tsdown config for the Client build face.
  169. */
  170. export function clientLibrary(id: string, libEntry: readonly string[]): BuildFaceConfig {
  171. const lib = clientLibraryConfig(id, libEntry)
  172. return clientOnly([lib])
  173. }
  174. /**
  175. * Select arbitrary package-local configs only during the Client pass.
  176. * @param configs - Node-side configs emitted after Client tsc.
  177. * @returns ENV-selected tsdown config for the Client build face.
  178. */
  179. export function clientOnly(configs: readonly UserConfig[]): BuildFaceConfig {
  180. return ({ env }) => buildFace(env?.DSH_BUILD_FACE) === 'host'
  181. ? [SKIP_WORKSPACE_BUILD]
  182. : [...configs]
  183. }
  184. interface ClientBundleOptions {
  185. /** Emit the Node-side artifacts during the Host pass instead of the Client pass. */
  186. readonly hostPhase?: boolean
  187. /** Additional Node-side configs emitted alongside the package library. */
  188. readonly companions?: readonly UserConfig[]
  189. /** Overrides for the package's primary Node-side library config. */
  190. readonly lib?: UserConfig
  191. }
  192. type BuildFace = 'host' | 'client' | undefined
  193. type BuildFaceConfig = (inlineConfig: Pick<UserConfig, 'env'>) => UserConfig[]
  194. function buildFace(value: unknown): BuildFace {
  195. if (value === undefined || value === 'host' || value === 'client') return value
  196. throw new Error(`tsdown: --env.DSH_BUILD_FACE must be host or client, received ${String(value)}`)
  197. }
  198. function clientLibraryConfig(
  199. id: string,
  200. libEntry: readonly string[],
  201. overrides: UserConfig = {},
  202. ): UserConfig {
  203. const isProductionDependency = (specifier: string): boolean =>
  204. matchesSpecifier(productionExternals(id), specifier)
  205. return {
  206. name: id,
  207. entry: [...libEntry],
  208. outDir: 'lib',
  209. format: ['esm'],
  210. platform: 'node',
  211. target: 'es2024',
  212. fixedExtension: false,
  213. dts: false,
  214. clean: false,
  215. deps: {
  216. // The Node half runs from a real install: a production dependency is on
  217. // disk there and stays an import, everything else inlines. Stating both
  218. // halves takes the artifact off tsdown's getProductionDeps fallback, where
  219. // moving a dependency between npm sections silently re-bundles it.
  220. // Builtins keep tsdown's own handling (neither side claims them).
  221. neverBundle: isProductionDependency,
  222. alwaysBundle: (specifier: string) => !isBuiltin(specifier) && !isProductionDependency(specifier),
  223. },
  224. ...overrides,
  225. }
  226. }
  227. /** The slice of the rolldown plugin context the stylesheet plugin uses. */
  228. interface AssetEmitter {
  229. emitFile(file: {
  230. type: 'asset'
  231. fileName: string
  232. source: Uint8Array
  233. originalFileName: string
  234. }): string
  235. }
  236. function staticLinkedConfig(id: string, entry: string, outputName = basename(entry, '.js')): UserConfig {
  237. const emitted = new Set<string>()
  238. return {
  239. name: id,
  240. entry: { [outputName]: entry },
  241. outDir: 'lib',
  242. format: ['esm'],
  243. platform: 'browser',
  244. target: 'es2024',
  245. fixedExtension: false,
  246. dts: false,
  247. clean: false,
  248. // The shell compiles this artifact, so its map is the only path from a
  249. // browser stack frame back to the TSX (tsc emits the lib/types half).
  250. sourcemap: true,
  251. outputOptions: { sourcemapExcludeSources: false },
  252. plugins: [{
  253. // Contract 1. `pre` because tsdown's own deps plugin would otherwise
  254. // resolve and inline every specifier missing from the npm production
  255. // sections, which is the coupling this preset exists to remove. The name
  256. // is also the roster marker {@link isStaticLinkedConfig} reads.
  257. name: STATIC_LINKED_PLUGIN,
  258. resolveId: {
  259. order: 'pre' as const,
  260. handler(source: string, importer: string | undefined) {
  261. // An entry arrives without an importer and must stay internal.
  262. if (importer === undefined) return null
  263. return isBareSpecifier(source) ? { id: source, external: true } : null
  264. },
  265. },
  266. }, tscSourceMapPlugin(), {
  267. // Contract 4. The import survives verbatim and the sheet lands beside the
  268. // JavaScript, so the shell's CSS Modules pipeline sees a real stylesheet.
  269. name: 'dsh-css-asset',
  270. async resolveId(this: AssetEmitter, source: string, importer: string | undefined) {
  271. if (!source.endsWith('.css') || importer === undefined) return null
  272. const { file, fileName } = stylesheetAsset(source, importer)
  273. if (!emitted.has(fileName)) {
  274. emitted.add(fileName)
  275. // originalFileName also puts the physical sheet in the watch graph.
  276. this.emitFile({ type: 'asset', fileName, source: await readFile(file), originalFileName: file })
  277. }
  278. // Every emitted chunk sits at the lib/ root, so the src-relative name
  279. // is what resolves from there. Rolldown keeps relative externals as
  280. // written instead of re-normalizing them.
  281. return { id: `./${fileName}`, external: true }
  282. },
  283. }],
  284. }
  285. }
  286. /** Whether a specifier names a package rather than a file next to its importer. */
  287. function isBareSpecifier(specifier: string): boolean {
  288. return !specifier.startsWith('.') && !specifier.startsWith('\0') && !isAbsolute(specifier)
  289. }
  290. /**
  291. * Locate a stylesheet import against the package sources and name its emitted position.
  292. * @param source - relative import specifier as written in the source.
  293. * @param importer - absolute path of the importing module, emitted or source.
  294. * @returns the stylesheet on disk plus its `src`-relative name under `lib/`.
  295. */
  296. function stylesheetAsset(source: string, importer: string): { readonly file: string, readonly fileName: string } {
  297. const file = sourceAssetPath(source, importer)
  298. const boundary = file.lastIndexOf(SOURCE_MARKER)
  299. if (boundary < 0) throw new Error(`tsdown: stylesheet ${file} is outside the package sources`)
  300. return { file, fileName: file.slice(boundary + SOURCE_MARKER.length).split(sep).join('/') }
  301. }
  302. /** The manifest fields the build faces read to state their own module edges. */
  303. interface WorkspaceManifest {
  304. readonly name?: string
  305. /** Sections a real install materializes on disk next to the built package. */
  306. readonly dependencies?: Record<string, string>
  307. readonly peerDependencies?: Record<string, string>
  308. readonly optionalDependencies?: Record<string, string>
  309. readonly dsh?: { readonly client?: { readonly external?: unknown } }
  310. }
  311. const manifestCache = new Map<string, WorkspaceManifest>()
  312. const productionExternalCache = new Map<string, readonly RegExp[]>()
  313. const clientExternalCache = new Map<string, ReadonlySet<string>>()
  314. /**
  315. * Read one workspace package's manifest. Located by package name rather than by
  316. * cwd, because tsdown evaluates every package config with the repository root as
  317. * `process.cwd()` during a workspace build. Callers read it on the first
  318. * resolveId of a build, not while a config is built, so selecting a build face
  319. * never touches a manifest.
  320. * @param id - package name, as spelled at the preset call site.
  321. * @returns the parsed manifest.
  322. * @throws {Error} when no workspace package declares that name.
  323. */
  324. function workspaceManifest(id: string): WorkspaceManifest {
  325. const cached = manifestCache.get(id)
  326. if (cached !== undefined) return cached
  327. for (const manifestPath of globSync('packages/*/*/package.json', { cwd: REPOSITORY_ROOT })) {
  328. const manifest = JSON.parse(
  329. readFileSync(resolvePath(REPOSITORY_ROOT, manifestPath), 'utf8'),
  330. ) as WorkspaceManifest
  331. if (manifest.name !== id) continue
  332. manifestCache.set(id, manifest)
  333. return manifest
  334. }
  335. throw new Error(`tsdown: no packages/*/*/package.json declares the name ${id}`)
  336. }
  337. /**
  338. * External patterns for one package's Node half: its own production sections,
  339. * subpaths included.
  340. * @param id - package name, as spelled at the preset call site.
  341. * @returns one `^name(/|$)` pattern per production dependency, name-sorted.
  342. */
  343. function productionExternals(id: string): readonly RegExp[] {
  344. const cached = productionExternalCache.get(id)
  345. if (cached !== undefined) return cached
  346. const manifest = workspaceManifest(id)
  347. const names = new Set([
  348. ...Object.keys(manifest.dependencies ?? {}),
  349. ...Object.keys(manifest.peerDependencies ?? {}),
  350. ...Object.keys(manifest.optionalDependencies ?? {}),
  351. ])
  352. const patterns = [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`))
  353. productionExternalCache.set(id, patterns)
  354. return patterns
  355. }
  356. /**
  357. * Module-table specifiers one `dsh.client` declaration requests. Matching is
  358. * exact, never normalized: a package declares the specifier its own code
  359. * imports, and the loader keys static entries the same way.
  360. * @param subject - package name, used in diagnostics.
  361. * @param declaration - the package's `dsh.client` object.
  362. * @returns the requested specifiers, empty when the package declares none.
  363. * @throws {Error} when `external` is not a string array.
  364. */
  365. export function requestedExternals(
  366. subject: string,
  367. declaration: { readonly external?: unknown },
  368. ): ReadonlySet<string> {
  369. return new Set(optionalStringArray(subject, 'dsh.client.external', declaration.external) ?? [])
  370. }
  371. /**
  372. * Module-table specifiers one package requests. The shell baseline is implicit
  373. * for every dynamic bundle; `dsh.client.external` only adds package-specific
  374. * dynamic rows or subpaths.
  375. * @param id - package name, as spelled at the preset call site.
  376. * @returns the baseline plus the package's explicit requests.
  377. */
  378. function clientExternals(id: string): ReadonlySet<string> {
  379. const cached = clientExternalCache.get(id)
  380. if (cached !== undefined) return cached
  381. const externals = new Set([
  382. ...PLATFORM_MODULES,
  383. ...PRELOADED_CLIENT_EXTERNALS,
  384. ...requestedExternals(id, workspaceManifest(id).dsh?.client ?? {}),
  385. ])
  386. clientExternalCache.set(id, externals)
  387. return externals
  388. }
  389. /** Escape a package name for literal use inside a RegExp source. */
  390. function escapeSpecifier(name: string): string {
  391. return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  392. }
  393. /** Whether an import specifier is the package a pattern names, or one of its subpaths. */
  394. function matchesSpecifier(patterns: readonly RegExp[], specifier: string): boolean {
  395. return patterns.some(pattern => pattern.test(specifier))
  396. }
  397. function clientConfig(id: string, entry: string): UserConfig {
  398. const isRequested = (specifier: string): boolean => clientExternals(id).has(specifier)
  399. return {
  400. name: `${id}/client`,
  401. entry: { client: entry },
  402. // Browser bundle lands next to the node half (single lib/ artifact dir;
  403. // the entryFileNames pin keeps it exactly lib/client.js). clean must stay
  404. // off — a default clean would wipe the node-half output emitted above.
  405. outDir: 'lib',
  406. format: 'cjs',
  407. platform: 'browser',
  408. // Types ship from lib/types (tsc); dts here would wrap the banner/footer into .d.cts and break parsing.
  409. dts: false,
  410. // Plugin code is fetched outside Vite's module graph, so its own bundle
  411. // must carry the TS/TSX mapping consumed by browser profiling tools.
  412. sourcemap: true,
  413. clean: false,
  414. deps: {
  415. neverBundle: isRequested,
  416. // Anything NOT requested from the loader module table must inline
  417. // (wire/type layers, zod, clsx — every non-shared dep). A require() the
  418. // table cannot answer is a guaranteed runtime throw, so the rule is the
  419. // package's own request list: requested specifiers stay imports,
  420. // everything else is bundled.
  421. alwaysBundle: (specifier: string) => !isRequested(specifier),
  422. },
  423. // Dual-mode libraries (lexical's exports carry development/production/
  424. // node conditions; the node file picks its flavor with a top-level await
  425. // a CJS bundle cannot carry) resolve their static flavor matching the
  426. // NODE_ENV the defines below bake in.
  427. inputOptions: {
  428. resolve: {
  429. conditionNames: [
  430. (process.env.NODE_ENV ?? 'production') === 'development' ? 'development' : 'production',
  431. 'browser', 'import', 'module', 'default',
  432. ],
  433. },
  434. },
  435. // Browser bundles inline node-idiom deps (zustand/immer read
  436. // process.env.NODE_ENV; zustand's esm build also probes
  437. // import.meta.env.MODE, which a CJS output cannot carry — rolldown flags
  438. // EMPTY_IMPORT_META). vite defined both on the seed path; tsdown inlining
  439. // needs the substitutions here or the factory throws ReferenceError at
  440. // boot / the build gate reds. Both keys honor the build's NODE_ENV so a
  441. // dev build keeps the dev-branch semantics; artifacts default to production.
  442. // The bare `import.meta.env` key is required alongside the precise MODE
  443. // key: zustand probes `import.meta.env ? import.meta.env.MODE : ...`, and
  444. // the truthiness probe would otherwise survive as an empty import.meta.
  445. define: {
  446. ...clientBuildEnvironmentDefines(process.env),
  447. 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  448. 'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
  449. 'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
  450. },
  451. plugins: [{
  452. // Bundle purity gate (build-time mirror of the module-edge rules): the
  453. // baseline and package-specific requests stay external, inline-safe wire layers
  454. // inline, and every other @deepseek-ai value import is a build error — a
  455. // cross-plugin value import either inlines a duplicate runtime instance
  456. // or requires a specifier the module table cannot answer for this package.
  457. // Cross-plugin collaboration goes through cordis services instead.
  458. name: 'dsh-client-bundle-purity',
  459. resolveId(source: string) {
  460. if (!source.startsWith('@deepseek-ai/')) return null
  461. if (isRequested(source)) return null // requested module-table row: external wins
  462. if (VENDORED_LIBRARY.test(source)) return null // vendored library: inline, no shared identity
  463. if (INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null // wire contribution: inline is the point
  464. throw new Error(
  465. `client bundle purity: "${source}" is not in the default client externals or ${id}'s dsh.client.external, an inline-safe wire layer, or a generated /remote contribution — `
  466. + 'cross-plugin value imports are forbidden; declare a non-default module request or collaborate through cordis services '
  467. + '(type-only imports are erased and never reach this gate)',
  468. )
  469. },
  470. }, tscSourceMapPlugin(), {
  471. name: 'dsh-css-modules-inline',
  472. resolveId(source: string, importer: string | undefined) {
  473. if (!source.endsWith('.module.css')) return null
  474. const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
  475. return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  476. },
  477. async load(virtualId: string) {
  478. if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
  479. const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  480. // The virtual id otherwise hides the physical stylesheet from Rolldown's watch graph.
  481. this.addWatchFile(fileId)
  482. const source = await readFile(fileId)
  483. const { code, exports: cssExports } = transform({
  484. filename: fileId,
  485. code: source,
  486. cssModules: { pattern: '[hash]_[local]' },
  487. minify: true,
  488. })
  489. const classMap: Record<string, string> = {}
  490. const exportEntries = Object.entries(cssExports ?? {})
  491. .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
  492. for (const [local, exp] of exportEntries) classMap[local] = exp.name
  493. return styleInjectionModule(id, fileId, code.toString(), classMap)
  494. },
  495. }, {
  496. name: 'dsh-css-text-inline',
  497. resolveId(source: string, importer: string | undefined) {
  498. if (!source.endsWith(`.css${INLINE_CSS_QUERY}`)) return null
  499. const stylesheet = source.slice(0, -INLINE_CSS_QUERY.length)
  500. const abs = importer !== undefined ? sourceAssetPath(stylesheet, importer) : stylesheet
  501. return INLINE_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  502. },
  503. async load(virtualId: string) {
  504. if (!virtualId.startsWith(INLINE_CSS_VIRTUAL_PREFIX)) return null
  505. const fileId = virtualId.slice(INLINE_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  506. this.addWatchFile(fileId)
  507. const source = await readFile(fileId)
  508. const { code } = transform({ filename: fileId, code: source, minify: true })
  509. return `export default ${JSON.stringify(code.toString())};`
  510. },
  511. }, {
  512. name: 'dsh-css-global-inline',
  513. resolveId(source: string, importer: string | undefined) {
  514. if (!source.endsWith('.css') || source.endsWith('.module.css')) return null
  515. const abs = importer !== undefined ? sourceAssetPath(source, importer) : source
  516. return GLOBAL_CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
  517. },
  518. async load(virtualId: string) {
  519. if (!virtualId.startsWith(GLOBAL_CSS_VIRTUAL_PREFIX)) return null
  520. const fileId = virtualId.slice(GLOBAL_CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
  521. this.addWatchFile(fileId)
  522. const source = await readFile(fileId)
  523. const { code } = transform({ filename: fileId, code: source, minify: true })
  524. return styleInjectionModule(id, fileId, code.toString())
  525. },
  526. }],
  527. outputOptions: {
  528. entryFileNames: 'client.js',
  529. sourcemapExcludeSources: false,
  530. // The map is served from /plugins/<scoped-package>/client.js.map. The
  531. // browser resolves its local sources back into URLs that mirror the
  532. // /packages/<group>/<package>/src directories; sourcesContent keeps them usable
  533. // without exposing that tree as an HTTP route.
  534. sourcemapPathTransform: browserSourcePath,
  535. banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(id)}, factory: (require) => {`,
  536. footer: 'return module.exports; } });',
  537. intro: 'var module = { exports: {} }; var exports = module.exports;',
  538. },
  539. }
  540. }
  541. /** Chain tsc's emitted maps into any Client bundle that consumes `lib/types`. */
  542. function tscSourceMapPlugin() {
  543. return {
  544. name: 'dsh-tsc-sourcemap',
  545. async load(id: string) {
  546. if (!id.includes(TYPES_MARKER) || !id.endsWith('.js') || !existsSync(`${id}.map`)) return null
  547. const code = await readFile(id, 'utf8')
  548. const mapPath = `${id}.map`
  549. const map = JSON.parse(await readFile(mapPath, 'utf8')) as {
  550. sourceRoot?: unknown
  551. sources?: unknown
  552. sourcesContent?: unknown
  553. [key: string]: unknown
  554. }
  555. if (!Array.isArray(map.sources) || map.sources.some(source => typeof source !== 'string')) {
  556. throw new Error(`client sourcemap: ${mapPath} has invalid sources`)
  557. }
  558. const sources = map.sources as string[]
  559. if (
  560. !Array.isArray(map.sourcesContent)
  561. || map.sourcesContent.length !== sources.length
  562. || map.sourcesContent.some(source => typeof source !== 'string')
  563. ) {
  564. const sourceRoot = typeof map.sourceRoot === 'string' ? map.sourceRoot : ''
  565. map.sourcesContent = await Promise.all(sources.map(async source =>
  566. await readFile(resolvePath(dirname(mapPath), sourceRoot, source), 'utf8')))
  567. }
  568. return { code: code.replace(SOURCEMAP_COMMENT, ''), map }
  569. },
  570. }
  571. }
  572. /** Path segment separating a package's tsc output from the sources it was emitted from. */
  573. const TYPES_MARKER = `${sep}lib${sep}types${sep}`
  574. /** Plugin name carrying contract 1, and the marker that identifies a statically linked config. */
  575. const STATIC_LINKED_PLUGIN = 'dsh-static-linked-external'
  576. /** Path segment a package's sources hang under, and the root emitted assets mirror. */
  577. const SOURCE_MARKER = `${sep}src${sep}`
  578. /** Trailing sourcemap reference tsc appends to every emitted module. */
  579. const SOURCEMAP_COMMENT = /\n\/\/# sourceMappingURL=.*\s*$/
  580. /** Resolve an emitted JS asset import against its source-tree counterpart. */
  581. function sourceAssetPath(source: string, importer: string): string {
  582. const emitted = resolvePath(dirname(importer), source)
  583. if (existsSync(emitted)) return emitted
  584. const boundary = emitted.indexOf(TYPES_MARKER)
  585. if (boundary < 0) return emitted
  586. return resolvePath(emitted.slice(0, boundary), 'src', emitted.slice(boundary + TYPES_MARKER.length))
  587. }