vite.config.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import { readFile, writeFile } from 'node:fs/promises'
  2. import { fileURLToPath } from 'node:url'
  3. import { defineConfig } from 'vite'
  4. import type { Plugin } from 'vite'
  5. import react from '@vitejs/plugin-react'
  6. import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts'
  7. const src = (rel: string): string => fileURLToPath(new URL(rel, import.meta.url))
  8. const STANDALONE_ERROR = 'apps/web is not a standalone application: bare Vite cannot inject window.__DSH_BOOT__. '
  9. + 'From a repository checkout, run `pnpm dsh web`; an installed package uses `dsh web`. '
  10. + 'For client-plugin HMR, run `pnpm dsh web` together with `pnpm run dev:web`.'
  11. const DEFAULT_CLIENT_TITLE = 'DSH Local Build'
  12. /** Escape build-time text before placing it in the HTML title element. */
  13. function escapeHtmlText(value: string): string {
  14. return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  15. }
  16. /** Project the public build title into the initial HTML document. */
  17. function clientDocumentTitle(): Plugin {
  18. const title = escapeHtmlText(process.env.DSH_CLIENT_TITLE ?? DEFAULT_CLIENT_TITLE)
  19. return {
  20. name: 'dsh-client-document-title',
  21. transformIndexHtml(html) {
  22. return html.replace('<title>DSH Local Build</title>', `<title>${title}</title>`)
  23. },
  24. }
  25. }
  26. /** Fail before a Vite dev or preview server can expose the boot-manifest-free shell. */
  27. function rejectStandaloneServe(): Plugin {
  28. return {
  29. name: 'dsh-reject-standalone-web-serve',
  30. config(_config, env) {
  31. if (env.command === 'serve') throw new Error(STANDALONE_ERROR)
  32. },
  33. }
  34. }
  35. /**
  36. * Emit preview.html beside index.html: the built index page with one module
  37. * script — the worker bootstrap entry — spliced ahead of its entry tag. Both
  38. * pages share every chunk; the extra tag is the only difference, so the
  39. * static worker deployment ships the served page verbatim plus its
  40. * bootstrap.
  41. */
  42. function emitPreviewPage(): Plugin {
  43. let bootstrapFile: string | undefined
  44. return {
  45. name: 'dsh-emit-preview-page',
  46. generateBundle(_options, bundle) {
  47. for (const item of Object.values(bundle)) {
  48. if (item.type === 'chunk' && item.isEntry && item.name === 'bootstrap') bootstrapFile = item.fileName
  49. }
  50. if (bootstrapFile === undefined) throw new Error('vite: preview bootstrap entry missing from the bundle')
  51. },
  52. async closeBundle() {
  53. // A build that failed before generateBundle has no page to splice.
  54. if (bootstrapFile === undefined) return
  55. const page = await readFile(src('./dist/index.html'), 'utf8')
  56. const anchor = page.indexOf('<script type="module"')
  57. if (anchor === -1) throw new Error('vite: built index.html lost its module entry tag')
  58. const tag = `<script type="module" crossorigin src="./${bootstrapFile}"></script>`
  59. await writeFile(src('./dist/preview.html'), `${page.slice(0, anchor)}${tag}${page.slice(anchor)}`)
  60. },
  61. }
  62. }
  63. /**
  64. * Vendor-chunk membership, by exact npm package name — the heavy render
  65. * families (math, highlight, markdown) that change only on dependency bumps.
  66. * Only packages workspace code imports DIRECTLY need listing: their private
  67. * transitive dependencies (oniguruma machinery, character tables, …) are
  68. * imported solely by these and rollup's chunk coloring pulls them into
  69. * vendor automatically. A dependency shared with index-side code falls back
  70. * to index — a few kB of dilution, never a correctness problem. Anything not
  71. * listed (react family, the vendored cordis workspace, tiny helpers like
  72. * anser/clsx, all workspace code) stays in the default `index` chunk, so
  73. * editing shell code re-hashes only index and returning clients keep the
  74. * cached vendor chunk.
  75. *
  76. * Every member must be React-free. A package that
  77. * imports react/jsx-runtime must never be listed — rollup folds a module
  78. * shared between the entry and a manual chunk into the manual chunk, so one
  79. * react-importing member would drag the single shared react copy into
  80. * vendor. The React side of markdown/math rendering is workspace code and
  81. * rides index.
  82. */
  83. const VENDOR_PACKAGES: ReadonlySet<string> = new Set([
  84. // math
  85. 'katex',
  86. // syntax highlight (@shikijs/langs is handled separately below —
  87. // lazy grammars must not land here)
  88. 'shiki',
  89. // markdown parse pipeline (micromark/mdast; the incremental React renderer
  90. // over it is workspace code)
  91. 'mdast-util-from-markdown',
  92. 'mdast-util-gfm',
  93. 'mdast-util-math',
  94. 'micromark-core-commonmark',
  95. 'micromark-extension-gfm',
  96. 'micromark-extension-math',
  97. 'micromark-factory-space',
  98. 'micromark-util-character',
  99. 'micromark-util-classify-character',
  100. 'micromark-util-sanitize-uri',
  101. 'micromark-util-symbol',
  102. 'micromark-util-types',
  103. ])
  104. /**
  105. * Boot grammars statically imported by ui-primitives' highlight.ts
  106. * (`@shikijs/langs/typescript` → `dist/typescript.mjs`, etc.). They live in
  107. * the same package as the lazy read-card grammars, but unlike those they are
  108. * part of the initial load and belong in the vendor chunk; the lazy ones must
  109. * stay unassigned so each keeps its own on-demand chunk.
  110. */
  111. const BOOT_GRAMMAR_FILES: readonly string[] = [
  112. 'dist/typescript.mjs',
  113. 'dist/shellscript.mjs',
  114. 'dist/json.mjs',
  115. ]
  116. /** Font asset extensions routed to assets/fonts/ (KaTeX's woff2/woff/ttf faces). */
  117. const FONT_EXTENSIONS: readonly string[] = ['.woff2', '.woff', '.ttf']
  118. /**
  119. * npm package name of a resolved module id: the segment after the last
  120. * `node_modules/`. pnpm nests the real package under an inner node_modules.
  121. */
  122. function npmPackageOf(id: string): string | undefined {
  123. const parts = id.split('/node_modules/')
  124. if (parts.length === 1) return undefined
  125. const [first, second] = parts[parts.length - 1].split('/')
  126. if (first.startsWith('.')) return undefined // .pnpm store segment, not a package
  127. if (first.startsWith('@')) return second === undefined ? undefined : `${first}/${second}`
  128. return first
  129. }
  130. export default defineConfig({
  131. // Relative asset URLs: preview.html mounts the same output under any base
  132. // directory, and the served index resolves identically from the site root.
  133. base: './',
  134. plugins: [rejectStandaloneServe(), clientDocumentTitle(), react(), emitPreviewPage()],
  135. build: {
  136. // The worker bootstrap holds its page at top-level await; Vite's default
  137. // `modules` target (es2020-era) rejects that syntax.
  138. target: 'es2022',
  139. sourcemap: true,
  140. rollupOptions: {
  141. input: {
  142. index: src('./index.html'),
  143. // Standalone entry, not an index.html script tag: Vite folds every
  144. // module tag of one page into a single synthetic entry, and only a
  145. // separate input keeps the shared page chunks bootstrap-free.
  146. bootstrap: src('./src/preview.ts'),
  147. },
  148. output: {
  149. // The worker-preview surface groups under dist/preview/ (the page
  150. // itself stays at dist/preview.html), so the published payload can
  151. // exclude it as one directory.
  152. entryFileNames(chunk): string {
  153. return chunk.name === 'bootstrap' ? 'preview/[name]-[hash].js' : 'assets/[name]-[hash].js'
  154. },
  155. // Output layout: the two main chunks stay at assets/ root; lazy
  156. // @shikijs/langs grammar chunks group under assets/langs/; fonts
  157. // (all KaTeX faces referenced by vendor.css) group under
  158. // assets/fonts/. Sourcemaps need no arrangement: rollup writes each
  159. // .map next to its js and references it by bare relative filename.
  160. chunkFileNames(chunk): string {
  161. // Grammar chunks are recognized by their member modules, not the
  162. // facade: shared embedded-grammar chunks (e.g. html+javascript,
  163. // split out because php/ruby/mdx embed them) have no facade at all.
  164. // index and vendor are excluded by name — vendor legitimately
  165. // carries the three boot grammars.
  166. if (chunk.name === 'index' || chunk.name === 'vendor') return 'assets/[name]-[hash].js'
  167. const isLangChunk = chunk.moduleIds.some(id => id.includes('/node_modules/@shikijs/langs/'))
  168. return isLangChunk ? 'assets/langs/[name]-[hash].js' : 'assets/[name]-[hash].js'
  169. },
  170. assetFileNames(asset): string {
  171. const fileName = asset.names[0] ?? ''
  172. const isFont = FONT_EXTENSIONS.some(ext => fileName.endsWith(ext))
  173. return isFont ? 'assets/fonts/[name]-[hash][extname]' : 'assets/[name]-[hash][extname]'
  174. },
  175. manualChunks(id: string): string | undefined {
  176. const pkg = npmPackageOf(id)
  177. if (pkg === undefined) return undefined // workspace + vendored cordis: index
  178. if (pkg === '@shikijs/langs') {
  179. return BOOT_GRAMMAR_FILES.some(file => id.endsWith(`/${file}`)) ? 'vendor' : undefined
  180. }
  181. return VENDOR_PACKAGES.has(pkg) ? 'vendor' : undefined
  182. },
  183. },
  184. },
  185. },
  186. worker: {
  187. // The preview worker rides dist/preview/ with the rest of that surface.
  188. rollupOptions: { output: { entryFileNames: 'preview/[name]-[hash].js' } },
  189. },
  190. resolve: {
  191. // One instance per shared npm identity: a bare specifier otherwise resolves
  192. // from the importer's directory, so a diverging range ships a second React
  193. // and splits hook and element identity. Entries are package ids — they cover
  194. // react/jsx-runtime and react-dom/client — and resolve from this package's
  195. // node_modules, so react must stay a devDependency here and any watcher must
  196. // run vite from this directory (scripts/dev-web.ts). Workspace packages need
  197. // no entry: pnpm links each of them to a single directory.
  198. dedupe: ['react', 'react-dom'],
  199. // Workspace packages are consumed as built lib products: each resolves
  200. // through its own package.json exports from the importer's directory, and
  201. // CSS still rides Vite's pipeline because the client build preset emits it
  202. // beside the bundle. Plugin packages never enter this graph; they arrive as
  203. // runtime bundles through the client module system. The remaining alias
  204. // browserizes the vendored Cordis Loader's only Node import.
  205. alias: [
  206. { find: /^node:module$/, replacement: src('./src/node-module-stub.ts') },
  207. ],
  208. },
  209. define: {
  210. ...clientBuildEnvironmentDefines(process.env),
  211. // vendored loader internal.ts: fromInternal() probes the Node major —
  212. // "0.0.0" takes neither branch, returning undefined (exactly the empty
  213. // internal slot the shell boot fills with the client module loader).
  214. 'process.versions.node': '"0.0.0"',
  215. 'process.execArgv': '[]',
  216. // vendored loader index.ts: envData falls to its default branch.
  217. 'process.env.CORDIS_SHARED': 'undefined',
  218. },
  219. })