index.ts 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. /**
  2. * Node half of the client module system (`dsh.client` dual-face package): scans
  3. * the host Loader's entries for packages declaring `dsh.client`, composes the
  4. * `window.__DSH_BOOT__` entry graph (wire single source: {@link WebBootEntry}
  5. * in `./client/manifest.ts`) in module-graph order, serves one-or-more-plugin
  6. * combo scripts plus their source maps,
  7. * contributes the registration facade, application preloads, bootstrap scripts,
  8. * and graph to the webserver's index injection table, and provides the
  9. * `clientModules` service (the HMR node half's registration/notification
  10. * face).
  11. *
  12. * Scanning is incremental per package — there is no full-rescan code path.
  13. * Every cordis `internal/plugin` emission (fiber construction/disposal) marks
  14. * the fiber's entry name dirty; a microtask flush reconciles each dirty name
  15. * against the live loader entries. The activation pass seeds the same dirty
  16. * set with all current entries and flushes synchronously, so first scan and
  17. * steady state share one implementation. Package metadata (including the
  18. * negative "not a client package" verdict) is cached per Loader specifier and
  19. * owning-tree base URL until restart. The manifest package name identifies
  20. * the browser module; distinct active Loader sources for that package are a
  21. * composition error. Bundle content changes reach the graph only through
  22. * {@link ClientModuleRegistry.rebuilt}.
  23. * @module @deepseek-ai/dsh-client-modules
  24. */
  25. import { createHash, randomBytes } from 'node:crypto'
  26. import { existsSync, readFileSync, statSync } from 'node:fs'
  27. import type { IncomingMessage, ServerResponse } from 'node:http'
  28. import { createRequire } from 'node:module'
  29. import { dirname, isAbsolute, join } from 'node:path'
  30. import { fileURLToPath, pathToFileURL } from 'node:url'
  31. import { Service } from '@deepseek-ai/cordis'
  32. import type { Context } from '@deepseek-ai/cordis'
  33. import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
  34. import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
  35. import { exactPackageSpecifier, parseDshClient, stripClientSuffix } from './client/manifest.ts'
  36. import type { WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph } from './client/manifest.ts'
  37. export { stripClientSuffix } from './client/manifest.ts'
  38. export type {
  39. BootManifest, BootModuleRow, BootPluginRow, WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph,
  40. } from './client/manifest.ts'
  41. declare module '@deepseek-ai/cordis' {
  42. interface Context {
  43. /** The web plugin table (provided by the client-modules node half). */
  44. clientModules: ClientModuleRegistry
  45. }
  46. }
  47. /** The declared fields a graph row carries, normalized (absent array declarations become empty). */
  48. interface WebBootRowFields {
  49. inject?: string[]
  50. /** Module specifiers the package requests from the module table. */
  51. external: string[]
  52. immediately: boolean
  53. }
  54. /** Filesystem baseline captured before a client artifact snapshot is read. */
  55. export interface ClientArtifactBaseline {
  56. /** Absolute path of the client bundle. */
  57. readonly path: string
  58. /** Bundle modification time in milliseconds. */
  59. readonly mtimeMs: number
  60. /** Bundle size in bytes. */
  61. readonly size: number
  62. }
  63. /** Resolved metadata cached for one Loader specifier and owning-tree base URL until restart. */
  64. interface PkgMeta extends WebBootRowFields {
  65. clientPath: string
  66. }
  67. interface ResolvedPkgMeta {
  68. packageName: string
  69. meta: PkgMeta
  70. }
  71. /** One active Loader source and the browser package manifest it resolves to. */
  72. interface ClientPackageSource extends ResolvedPkgMeta {
  73. /** Loader specifier from the active row. */
  74. loaderName: string
  75. /** Resolution base of the config tree that owns the row. */
  76. baseUrl: string
  77. /** Stable cache and contribution key for this source. */
  78. sourceKey: string
  79. }
  80. /** Recovery instruction shared by grouped startup and steady-state bundle diagnostics. */
  81. const CLIENT_BUNDLE_BUILD_INSTRUCTION = 'run `pnpm run build` before launch'
  82. /** Missing built client export, retained as structured data for activation-error grouping. */
  83. class MissingClientBundleError extends Error {
  84. constructor(
  85. readonly packageName: string,
  86. readonly clientPath: string,
  87. cause: unknown,
  88. ) {
  89. super(
  90. [
  91. `client-modules: client bundle not found; ${CLIENT_BUNDLE_BUILD_INSTRUCTION}:`,
  92. ` package: ${packageName}`,
  93. ` path: ${clientPath}`,
  94. ].join('\n'),
  95. { cause },
  96. )
  97. }
  98. }
  99. /** Activation failures grouped by actionable package-build errors and unrelated failures. */
  100. class ClientPackageCompositionError extends AggregateError {
  101. constructor(failures: Error[]) {
  102. const missingBundles = failures.filter((error): error is MissingClientBundleError => error instanceof MissingClientBundleError)
  103. const otherFailures = failures.filter(error => !(error instanceof MissingClientBundleError))
  104. const packageNoun = failures.length === 1 ? 'package' : 'packages'
  105. const lines = [`client-modules: ${String(failures.length)} client ${packageNoun} failed to compose:`]
  106. if (missingBundles.length > 0) {
  107. lines.push(` client bundles not found; ${CLIENT_BUNDLE_BUILD_INSTRUCTION}:`)
  108. for (const error of missingBundles) {
  109. lines.push(` - package: ${error.packageName}`, ` path: ${error.clientPath}`)
  110. }
  111. }
  112. if (otherFailures.length > 0) {
  113. lines.push(' other failures:', ...otherFailures.map(error => ` - ${error.message}`))
  114. }
  115. super(failures, lines.join('\n'))
  116. }
  117. }
  118. /** One composed table row: the wire entry plus the resolved package metadata behind it. */
  119. interface WebPluginRecord {
  120. entry: WebBootEntry
  121. /** Loader specifier whose active row contributes this browser module. */
  122. loaderName: string
  123. /** Loader resolution input that selected this package instance. */
  124. sourceKey: string
  125. meta: PkgMeta
  126. /** Exact build artifact included in the startup batches. */
  127. bundle: Buffer
  128. /** Pre-read filesystem baseline handed to the HMR watcher. */
  129. baseline: ClientArtifactBaseline
  130. }
  131. /** Immutable inputs captured for one resource in a generated combo. */
  132. interface ComboResource {
  133. id: string
  134. rev: string
  135. clientPath: string
  136. fileName: string
  137. bundle: Buffer
  138. }
  139. /** One lazily materialized immutable response body. */
  140. interface LazyResponse {
  141. contentType: string
  142. body: () => Promise<Buffer>
  143. }
  144. /** Fields shared by every generated combo plan. */
  145. interface ComboArtifact {
  146. url: string
  147. rev: string
  148. entries: string[]
  149. sourceMapUrl: string
  150. scriptBody: () => Promise<Buffer>
  151. sourceMapBody: () => Promise<Buffer>
  152. }
  153. /** One generated initial-load response and its wire descriptor. */
  154. type BatchArtifact = ComboArtifact & { descriptor: WebBootBatch }
  155. /** Versioned code is immutable; mismatched revisions are rejected instead of serving newer bytes. */
  156. const IMMUTABLE_CACHE = 'public, max-age=31536000, immutable'
  157. /** Generated request URLs stay below conservative browser and intermediary request-target limits. */
  158. const MAX_COMBO_URL_BYTES = 3 * 1024
  159. const HASH_REVISION_LENGTH = 12
  160. const COMBO_REVISION_PLACEHOLDER = '0'.repeat(HASH_REVISION_LENGTH)
  161. /** Source-map trailer emitted by tsdown at the end of every client bundle. */
  162. const SOURCE_MAP_TRAILER = /(?:\r?\n)?\/\/# sourceMappingURL=[^\r\n]*(?:\r?\n)?$/
  163. /** Debugger source name appended to page bundles in the WebWorker image. */
  164. const SOURCE_URL_TRAILER = /(?:\r?\n)?\/\/# sourceURL=([^\r\n]+)(?:\r?\n)?$/
  165. /** Published package-local client chunk names accepted by the on-demand route. */
  166. const CLIENT_CHUNK = /^client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js$/
  167. /** Resolve `exports["./client"]` to a relative path, accepting the string and one-level conditional forms. */
  168. function clientExportOf(pkgName: string, exportsField: unknown): string | undefined {
  169. if (typeof exportsField !== 'object' || exportsField === null) return undefined
  170. const client = (exportsField as Record<string, unknown>)['./client']
  171. if (client === undefined) return undefined
  172. if (typeof client === 'string') return client
  173. if (typeof client === 'object' && client !== null) {
  174. const fallback = (client as Record<string, unknown>).default
  175. if (typeof fallback === 'string') return fallback
  176. }
  177. throw new Error(`client-modules: ${pkgName} exports["./client"] must be a string or an object with a string default`)
  178. }
  179. /** sha1 content hash shortened to 12 hex chars (combo / graph / rebuilt-artifact rev). */
  180. function shortHash(input: string | Buffer): string {
  181. return createHash('sha1').update(input).digest('hex').slice(0, HASH_REVISION_LENGTH)
  182. }
  183. /** Hash several response fields without allowing bytes to move across field boundaries. */
  184. function framedHash(domain: string, parts: readonly Buffer[]): string {
  185. const hash = createHash('sha1').update(domain).update('\0')
  186. for (const part of parts) hash.update(`${String(part.byteLength)}:`).update(part)
  187. return hash.digest('hex').slice(0, HASH_REVISION_LENGTH)
  188. }
  189. /** Hash one completed build generation observed through its entry artifact. */
  190. function artifactRevision(bundle: Buffer, baseline: ClientArtifactBaseline): string {
  191. return framedHash('plugin-artifact', [bundle, Buffer.from(String(baseline.mtimeMs))])
  192. }
  193. /** Address one ordered plugin-file list through the shared combo route. */
  194. function comboUrl(ids: readonly string[], rev: string, sourceMap = false): string {
  195. const resources = ids.map(id => `${id}/client.js${sourceMap ? '.map' : ''}`).join(',')
  196. return `/plugins/??${resources}&rev=${rev}`
  197. }
  198. /** Address one package-local chunk through the same revision as its entry. */
  199. function chunkUrl(id: string, fileName: string, rev: string, sourceMap = false): string {
  200. return `/plugins/${id}/${fileName}${sourceMap ? '.map' : ''}?rev=${rev}`
  201. }
  202. /** Measure the longer map-form URL used to partition a startup resource list. */
  203. function projectedComboUrlBytes(records: readonly WebPluginRecord[]): number {
  204. return Buffer.byteLength(comboUrl(
  205. records.map(record => record.entry.id),
  206. COMBO_REVISION_PLACEHOLDER,
  207. true,
  208. ))
  209. }
  210. /** Partition one phase in graph order without allowing a generated URL above the protocol limit. */
  211. function partitionComboRecords(records: readonly WebPluginRecord[]): WebPluginRecord[][] {
  212. const chunks: WebPluginRecord[][] = []
  213. let current: WebPluginRecord[] = []
  214. for (const record of records) {
  215. const candidate = [...current, record]
  216. if (projectedComboUrlBytes(candidate) <= MAX_COMBO_URL_BYTES) {
  217. current = candidate
  218. continue
  219. }
  220. if (current.length === 0) {
  221. throw new Error(
  222. `client-modules: ${record.entry.id} exceeds the ${String(MAX_COMBO_URL_BYTES)}-byte combo URL limit`,
  223. )
  224. }
  225. chunks.push(current)
  226. current = [record]
  227. if (projectedComboUrlBytes(current) > MAX_COMBO_URL_BYTES) {
  228. throw new Error(
  229. `client-modules: ${record.entry.id} exceeds the ${String(MAX_COMBO_URL_BYTES)}-byte combo URL limit`,
  230. )
  231. }
  232. }
  233. if (current.length > 0) chunks.push(current)
  234. return chunks
  235. }
  236. /** Executable source plus the generated-file name used when no authored map exists. */
  237. interface PreparedSource {
  238. source: string
  239. fallbackSource: string
  240. }
  241. /** Remove bundle-local debug directives and retain their stable generated-file name. */
  242. function prepareSource(resource: ComboResource): PreparedSource {
  243. let source = resource.bundle.toString('utf8')
  244. const sourceUrl = SOURCE_URL_TRAILER.exec(source)?.[1]
  245. source = source.replace(SOURCE_URL_TRAILER, '').replace(SOURCE_MAP_TRAILER, '')
  246. if (!source.endsWith('\n')) source += '\n'
  247. const fallbackSource = sourceUrl === undefined
  248. ? `/plugins/${resource.id}/${resource.fileName}`
  249. : /^(?:[A-Za-z][A-Za-z\d+.-]*:|\/)/.test(sourceUrl) ? sourceUrl : `/${sourceUrl}`
  250. return { source, fallbackSource }
  251. }
  252. /** Stamp a combo script's absolute indexed-map URL onto its executable bytes. */
  253. function comboScript(input: string, sourceMapUrl?: string): Buffer {
  254. return Buffer.from(sourceMapUrl === undefined ? input : `${input}//# sourceMappingURL=${sourceMapUrl}\n`)
  255. }
  256. /** Read and parse an optional source map when its combo-map endpoint is requested. */
  257. function readSourceMap(clientPath: string): Record<string, unknown> | undefined {
  258. let body: Buffer
  259. try {
  260. body = readFileSync(`${clientPath}.map`)
  261. } catch (error) {
  262. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
  263. throw error
  264. }
  265. const value = JSON.parse(body.toString('utf8')) as unknown
  266. const parsed = typeof value === 'object' && value !== null ? value as Record<string, unknown> : undefined
  267. if (
  268. parsed === undefined
  269. || parsed.version !== 3
  270. || !Array.isArray(parsed.sources)
  271. || parsed.sources.some(source => typeof source !== 'string')
  272. || !Array.isArray(parsed.names)
  273. || parsed.names.some(name => typeof name !== 'string')
  274. || typeof parsed.mappings !== 'string'
  275. ) {
  276. throw new Error(`client-modules: ${clientPath}.map is not a regular Source Map v3 object`)
  277. }
  278. return parsed
  279. }
  280. /** Count generated lines while assembling indexed-map section offsets. */
  281. function newlineCount(value: string): number {
  282. let count = 0
  283. for (const char of value) if (char === '\n') count += 1
  284. return count
  285. }
  286. /** Resolve section sources against their original per-plugin map URL before combo relocation. */
  287. function comboSectionMap(resource: ComboResource, original: Record<string, unknown>): Record<string, unknown> {
  288. const sourcePaths = original.sources as string[]
  289. const sourceRoot = typeof original.sourceRoot === 'string' ? original.sourceRoot : ''
  290. const base = new URL(`/plugins/${resource.id}/client.js.map`, 'http://dsh.invalid')
  291. const relocated = sourcePaths.map((source) => {
  292. const separator = sourceRoot !== '' && !sourceRoot.endsWith('/') && !source.startsWith('/') ? '/' : ''
  293. const resolved = new URL(`${sourceRoot}${separator}${source}`, base)
  294. return resolved.origin === base.origin
  295. ? `${resolved.pathname}${resolved.search}${resolved.hash}`
  296. : resolved.href
  297. })
  298. const section: Record<string, unknown> = { ...original, sources: relocated }
  299. delete section.sourceRoot
  300. return section
  301. }
  302. /** Map each generated line to the same line in a bundled JavaScript source. */
  303. function identitySectionMap(source: string, sourceUrl: string): Record<string, unknown> {
  304. const mappings = Array.from({ length: newlineCount(source) }, (_, index) => index === 0 ? 'AAAA' : 'AACA')
  305. .join(';')
  306. return {
  307. version: 3,
  308. names: [],
  309. sources: [sourceUrl],
  310. sourcesContent: [source],
  311. mappings,
  312. }
  313. }
  314. /** Run one producer in the first requester's microtask, not off-thread, and share its settlement. */
  315. function lazyBody(produce: () => Buffer): () => Promise<Buffer> {
  316. let result: Promise<Buffer> | undefined
  317. return () => {
  318. result ??= Promise.resolve().then(produce)
  319. return result
  320. }
  321. }
  322. /** Derive one combo revision from the ordered immutable row revisions. */
  323. function comboRevision(resources: readonly ComboResource[]): string {
  324. return framedHash('combo', resources.flatMap(resource => [
  325. Buffer.from(resource.id),
  326. Buffer.from(resource.rev),
  327. ]))
  328. }
  329. /** Concatenate one or more factory registrations without reading or composing source maps. */
  330. function buildComboScript(resources: readonly ComboResource[], sourceMapUrl: string): Buffer {
  331. let source = ''
  332. for (const resource of resources) source += `${prepareSource(resource).source};\n`
  333. return comboScript(source, sourceMapUrl)
  334. }
  335. /** Compose one indexed map from source-map files read only for this request. */
  336. function buildComboSourceMap(
  337. resources: readonly ComboResource[],
  338. sourceMapOf: (clientPath: string) => Record<string, unknown> | undefined,
  339. fileName = 'client.js',
  340. ): Buffer {
  341. const sections: { offset: { line: number; column: 0 }; map: Record<string, unknown> }[] = []
  342. let line = 0
  343. for (const resource of resources) {
  344. const prepared = prepareSource(resource)
  345. const sourceMap = sourceMapOf(resource.clientPath)
  346. let section = identitySectionMap(prepared.source, prepared.fallbackSource)
  347. if (sourceMap !== undefined) {
  348. try {
  349. section = comboSectionMap(resource, sourceMap)
  350. } catch {
  351. // An invalid authored source URL is a malformed map, so the generated
  352. // bundle remains debuggable through the same identity fallback.
  353. }
  354. }
  355. sections.push({ offset: { line, column: 0 }, map: section })
  356. line += newlineCount(`${prepared.source};\n`)
  357. }
  358. return Buffer.from(`${JSON.stringify({ version: 3, file: fileName, sections })}\n`)
  359. }
  360. /** Describe one combo and defer its executable and debug payloads independently. */
  361. function buildCombo(
  362. records: readonly WebPluginRecord[],
  363. sourceMapOf: (clientPath: string) => Record<string, unknown> | undefined,
  364. revision?: string,
  365. ): ComboArtifact {
  366. const resources = records.map(record => ({
  367. id: record.entry.id,
  368. rev: record.entry.rev,
  369. clientPath: record.meta.clientPath,
  370. fileName: 'client.js',
  371. bundle: record.bundle,
  372. }))
  373. const rev = revision ?? comboRevision(resources)
  374. const entries = resources.map(resource => resource.id)
  375. const url = comboUrl(entries, rev)
  376. const sourceMapUrl = comboUrl(entries, rev, true)
  377. return {
  378. url,
  379. rev,
  380. entries,
  381. sourceMapUrl,
  382. scriptBody: lazyBody(() => buildComboScript(resources, sourceMapUrl)),
  383. sourceMapBody: lazyBody(() => buildComboSourceMap(resources, sourceMapOf)),
  384. }
  385. }
  386. /** Add initial-load scheduling metadata to a combo artifact. */
  387. function buildBatch(
  388. phase: WebBootBatchPhase,
  389. records: readonly WebPluginRecord[],
  390. sourceMapOf: (clientPath: string) => Record<string, unknown> | undefined,
  391. ): BatchArtifact {
  392. const artifact = buildCombo(records, sourceMapOf)
  393. return {
  394. ...artifact,
  395. descriptor: { phase, url: artifact.url, rev: artifact.rev, entries: artifact.entries },
  396. }
  397. }
  398. /** Graph row for one bundle rev (url carries the rev as its cache-busting query). */
  399. function graphRow(id: string, rev: string, fields: WebBootRowFields): WebBootEntry {
  400. return {
  401. id,
  402. url: comboUrl([id], rev),
  403. rev,
  404. ...(fields.inject !== undefined ? { inject: fields.inject } : {}),
  405. ...(fields.immediately ? { immediately: true } : {}),
  406. ...(fields.external.length > 0 ? { external: fields.external } : {}),
  407. }
  408. }
  409. /**
  410. * Order composed rows so every requested dynamic package precedes its
  411. * consumers. An `external` specifier is either the package row it names
  412. * (`<pkg>/client` aliases the bare package) or a static-table name that adds no
  413. * graph edge.
  414. * @param entries - composed rows in scan order.
  415. * @returns the same rows reordered; scan order breaks every tie.
  416. * @throws {Error} when a row requests itself or when the module graph has a
  417. * cycle; the message lists the packages on it.
  418. */
  419. export function orderByModuleGraph(entries: readonly WebBootEntry[]): WebBootEntry[] {
  420. const rowsById = new Map<string, WebBootEntry>()
  421. for (const entry of entries) rowsById.set(entry.id, entry)
  422. const ordered: WebBootEntry[] = []
  423. const placed = new Set<string>()
  424. const open: string[] = []
  425. const visit = (entry: WebBootEntry): void => {
  426. if (placed.has(entry.id)) return
  427. const cycleStart = open.indexOf(entry.id)
  428. if (cycleStart !== -1) {
  429. throw new Error(
  430. `client-modules: module graph cycle ${[...open.slice(cycleStart), entry.id].join(' -> ')} `
  431. + '— a requested package row must precede its consumers, and factory-form CJS cannot deliver partial exports',
  432. )
  433. }
  434. open.push(entry.id)
  435. for (const name of entry.external ?? []) {
  436. const dependency = rowsById.get(name) ?? rowsById.get(stripClientSuffix(name))
  437. if (dependency === entry) {
  438. throw new Error(
  439. `client-modules: "${entry.id}" requests module "${name}" that it answers itself `
  440. + '— a row must not declare its own package in dsh.client.external',
  441. )
  442. }
  443. if (dependency !== undefined) visit(dependency)
  444. }
  445. open.pop()
  446. placed.add(entry.id)
  447. ordered.push(entry)
  448. }
  449. for (const entry of entries) visit(entry)
  450. return ordered
  451. }
  452. /** Bootstrap package whose ordinary client bundle supplies the module-system implementation. */
  453. const CLIENT_MODULES_ID = '@deepseek-ai/dsh-client-modules'
  454. /** Dynamic bundles grouped into the parser bootstrap batch before the Vite shell. */
  455. const PARSER_PRELOAD_IDS = [CLIENT_MODULES_ID] as const
  456. /**
  457. * The boot protocol as index injection rows. The inline registration queue
  458. * precedes the application-batch preload and the blocking bootstrap batch. Its
  459. * `create()` method materializes the modules
  460. * bundle, delegates construction to that bundle, and leaves the same facade
  461. * in live-registration mode. The graph global follows before the shell reads
  462. * it.
  463. * @param graph - the composed entry graph.
  464. * @returns head rows in execution order: queue script, application preloads,
  465. * blocking bootstrap scripts, graph global.
  466. */
  467. export function bootInjections(graph: WebBootGraph): IndexInjection[] {
  468. const bootstrapId = JSON.stringify(CLIENT_MODULES_ID)
  469. const queue = `(()=>{
  470. const pendingQueue=[]
  471. window.__ModuleLoader__={
  472. mode:"queue",
  473. pendingQueue,
  474. load(registration){pendingQueue.push(registration)},
  475. create(options){
  476. if(this.mode!=="queue")throw new Error("client-modules: window.__ModuleLoader__.create called after module-system boot")
  477. const index=pendingQueue.findIndex(registration=>registration.id===${bootstrapId})
  478. const registration=pendingQueue[index]
  479. if(registration===undefined)throw new Error("client-modules: HTML did not preload ${CLIENT_MODULES_ID}/client.js")
  480. pendingQueue.splice(index,1)
  481. const exports=registration.factory(specifier=>{
  482. throw new Error('client-modules: ${CLIENT_MODULES_ID}/client.js requested external "'+specifier+'" before the module system existed')
  483. })
  484. if(typeof exports!=="object"||exports===null||typeof exports.createClientModuleSystem!=="function"||typeof exports.apply!=="function"){
  485. throw new Error("client-modules: ${CLIENT_MODULES_ID}/client.js did not export the bootstrap module face")
  486. }
  487. return exports.createClientModuleSystem(this,{id:registration.id,exports},options)
  488. }
  489. }
  490. })()`
  491. const bootstrap = graph.batches.filter(batch => batch.phase === 'bootstrap')
  492. const application = graph.batches.filter(batch => batch.phase === 'application')
  493. const rows: IndexInjection[] = [{ kind: 'script', placement: 'head', text: queue }]
  494. for (const batch of application) {
  495. rows.push({ kind: 'script-preload', src: batch.url })
  496. }
  497. for (const batch of bootstrap) {
  498. rows.push({ kind: 'script-src', placement: 'head', src: batch.url })
  499. }
  500. rows.push({ kind: 'global', name: '__DSH_BOOT__', value: graph })
  501. return rows
  502. }
  503. /**
  504. * The web plugin table service: incremental `dsh.client` scan + wire composition
  505. * + bundle route + index injection rows. Construction runs the activation scan
  506. * synchronously — a malformed declaration or missing bundle among the
  507. * already-loaded entries aggregates into one loud throw (FAILED fiber; the
  508. * boot activation audit reports it).
  509. */
  510. export class ClientModuleRegistry extends Service {
  511. static inject = ['loader']
  512. private readonly table = new Map<string, WebPluginRecord>()
  513. private readonly sources = new Map<string, ClientPackageSource>()
  514. // Resolution is entry-local: the same specifier can resolve differently in
  515. // separate config trees. Negative verdicts remain stable until restart.
  516. private readonly pkgMeta = new Map<string, ResolvedPkgMeta | null>()
  517. private readonly rebuildListeners = new Set<(id: string, rev: string) => void>()
  518. private readonly graphListeners = new Set<() => void>()
  519. private readonly dirty = new Set<string>()
  520. private readonly initialRevisionNonce = randomBytes(8).toString('hex')
  521. private nextInitialRevision = 0
  522. private responses = new Map<string, LazyResponse>()
  523. private batchResponses = new Map<string, LazyResponse>()
  524. /** One prior graph generation covers a request racing the HMR recomposition that replaced its URL. */
  525. private previousBatchResponses = new Map<string, LazyResponse>()
  526. private flushQueued = false
  527. private composed: WebBootGraph
  528. /**
  529. * Build the service: subscribe, seed, and run the activation flush.
  530. * Bundle routes follow the optional Web carrier's injected lifecycle.
  531. * @param ctx - plugin context carrying Loader and an optional Web carrier.
  532. */
  533. constructor(ctx: Context) {
  534. super(ctx, 'clientModules')
  535. // Subscribe before seeding so a fiber arriving mid-activation lands in the
  536. // same dirty set (Set idempotence makes the overlap harmless). An entry-less
  537. // fiber is a child plugin or a manual mount — never a loader row; O(1) drop.
  538. ctx.on('internal/plugin', (fiber) => {
  539. const entryName = fiber.entry?.options.name
  540. if (entryName === undefined) return
  541. this.dirty.add(entryName)
  542. if (this.flushQueued) return
  543. this.flushQueued = true
  544. queueMicrotask(() => {
  545. this.flushQueued = false
  546. this.flush((err) => { ctx.logger.warn(err) })
  547. })
  548. })
  549. // Activation pass: the initial scan IS the incremental path over the
  550. // current entries, flushed synchronously (nothing async between subscribe,
  551. // seed, and flush).
  552. for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name)
  553. this.composed = this.compose()
  554. const failures: Error[] = []
  555. this.flush(err => failures.push(err))
  556. if (failures.length > 0) {
  557. throw new ClientPackageCompositionError(failures)
  558. }
  559. const registerWebCarrier = (webCtx: Context): void => {
  560. webCtx.effect(
  561. () => webCtx.webServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }),
  562. 'client-modules: bundle route',
  563. )
  564. }
  565. ctx.inject(['webServer'], registerWebCarrier)
  566. ctx.on('webserver/index-inject', (table) => {
  567. table.push(...bootInjections(this.composed))
  568. })
  569. }
  570. /**
  571. * Current composed entry graph (stable object between changes).
  572. * @returns the graph served as `window.__DSH_BOOT__`.
  573. */
  574. graph(): WebBootGraph {
  575. return this.composed
  576. }
  577. /**
  578. * Absolute path of an entry's client bundle.
  579. * @param id - entry id (package name).
  580. * @returns the path, or undefined for an unknown id.
  581. */
  582. clientPath(id: string): string | undefined {
  583. return this.table.get(id)?.meta.clientPath
  584. }
  585. /**
  586. * Serve an advertised revisioned bundle or source map without a Web server.
  587. * Unknown URLs return 404, unsupported methods return 405, and `HEAD`
  588. * returns the same immutable headers without materializing a body. Each body
  589. * is built once on its first `GET`; script construction never reads maps.
  590. * @param request - shell-carrier request for a `/plugins` resource.
  591. * @returns the exact response also exposed by the optional Web route.
  592. */
  593. async fetchBundle(request: Request): Promise<Response> {
  594. const resource = await this.bundleResource(request.method, request.url)
  595. const body = resource.body === undefined ? null : Uint8Array.from(resource.body)
  596. return new Response(body, {
  597. status: resource.status,
  598. ...(resource.headers === undefined ? {} : { headers: resource.headers }),
  599. })
  600. }
  601. /**
  602. * Filesystem baseline captured before an entry's current bytes were read.
  603. * HMR compares it with the live files when installing a watch, so a write
  604. * between startup composition and watch installation cannot disappear into
  605. * the watcher's initial state.
  606. * @param id - entry id (package name).
  607. * @returns the path and baseline, or undefined for an unknown id.
  608. */
  609. artifactBaseline(id: string): ClientArtifactBaseline | undefined {
  610. const baseline = this.table.get(id)?.baseline
  611. return baseline === undefined ? undefined : { ...baseline }
  612. }
  613. /**
  614. * Publish one completed bundle generation (the HMR watch's registration
  615. * hook — the only entry point through which build changes reach the graph).
  616. * @param id - entry id (package name).
  617. * @returns the new rev, or undefined for an unknown id.
  618. */
  619. rebuilt(id: string): string | undefined {
  620. const record = this.table.get(id)
  621. if (record === undefined) return undefined
  622. const baseline = this.captureArtifactBaseline(record.meta.clientPath)
  623. const bundle = readFileSync(record.meta.clientPath)
  624. const rev = artifactRevision(bundle, baseline)
  625. record.baseline = baseline
  626. if (rev === record.entry.rev) return rev
  627. record.entry = graphRow(id, rev, record.meta)
  628. record.bundle = bundle
  629. this.composed = this.compose()
  630. for (const notify of this.rebuildListeners) {
  631. // Containment: rebuilt() runs inside the HMR watch callback — a
  632. // throwing subscriber must not kill the poll or skip later subscribers.
  633. try {
  634. notify(id, rev)
  635. } catch (error) {
  636. this.ctx.logger.error(error)
  637. }
  638. }
  639. this.notifyGraphChanged()
  640. return rev
  641. }
  642. /**
  643. * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev.
  644. * @param listener - receives the entry id and its new bundle rev.
  645. * @returns the unsubscriber.
  646. */
  647. onRebuilt(listener: (id: string, rev: string) => void): () => void {
  648. this.rebuildListeners.add(listener)
  649. return () => { this.rebuildListeners.delete(listener) }
  650. }
  651. /**
  652. * Fires after any flush that recomposed the graph (row added/removed, or a
  653. * rebuilt rev change). Pull model: listeners re-read {@link graph}.
  654. * @param listener - notified with no payload.
  655. * @returns the unsubscriber.
  656. */
  657. onGraphChanged(listener: () => void): () => void {
  658. this.graphListeners.add(listener)
  659. return () => { this.graphListeners.delete(listener) }
  660. }
  661. private compose(): WebBootGraph {
  662. const entries = orderByModuleGraph([...this.table.values()].map(record => record.entry))
  663. const bootstrap = PARSER_PRELOAD_IDS
  664. .map(id => this.table.get(id))
  665. .filter((record): record is WebPluginRecord => record !== undefined)
  666. const bootstrapIds = new Set(bootstrap.map(record => record.entry.id))
  667. const application = entries
  668. .filter(entry => !bootstrapIds.has(entry.id))
  669. .map(entry => this.table.get(entry.id))
  670. .filter((record): record is WebPluginRecord => record !== undefined)
  671. const artifacts: BatchArtifact[] = []
  672. for (const records of partitionComboRecords(bootstrap)) {
  673. artifacts.push(buildBatch('bootstrap', records, this.readSourceMap))
  674. }
  675. for (const records of partitionComboRecords(application)) {
  676. artifacts.push(buildBatch('application', records, this.readSourceMap))
  677. }
  678. const batchResponses = new Map<string, LazyResponse>()
  679. for (const artifact of artifacts) {
  680. batchResponses.set(artifact.descriptor.url, this.responses.get(artifact.descriptor.url) ?? {
  681. body: artifact.scriptBody,
  682. contentType: 'text/javascript; charset=utf-8',
  683. })
  684. batchResponses.set(artifact.sourceMapUrl, this.responses.get(artifact.sourceMapUrl) ?? {
  685. body: artifact.sourceMapBody,
  686. contentType: 'application/json; charset=utf-8',
  687. })
  688. }
  689. const responses = new Map(batchResponses)
  690. for (const record of this.table.values()) {
  691. const artifact = buildCombo([record], this.readSourceMap, record.entry.rev)
  692. responses.set(artifact.url, responses.get(artifact.url) ?? this.responses.get(artifact.url) ?? {
  693. body: artifact.scriptBody,
  694. contentType: 'text/javascript; charset=utf-8',
  695. })
  696. responses.set(artifact.sourceMapUrl, responses.get(artifact.sourceMapUrl) ?? this.responses.get(artifact.sourceMapUrl) ?? {
  697. body: artifact.sourceMapBody,
  698. contentType: 'application/json; charset=utf-8',
  699. })
  700. }
  701. for (const [resourceUrl, response] of this.responses) {
  702. if (this.chunkRequest(new URL(resourceUrl, 'http://x')) !== undefined) responses.set(resourceUrl, response)
  703. }
  704. this.previousBatchResponses = this.batchResponses
  705. this.batchResponses = batchResponses
  706. this.responses = responses
  707. const batches = artifacts.map(artifact => artifact.descriptor)
  708. return { rev: shortHash(JSON.stringify({ entries, batches })), entries, batches }
  709. }
  710. private notifyGraphChanged(): void {
  711. for (const listener of this.graphListeners) {
  712. // A throwing subscriber must not skip later subscribers (or escape into
  713. // whatever triggered the flush — possibly an fs.watchFile callback).
  714. try {
  715. listener()
  716. } catch (error) {
  717. this.ctx.logger.error(error)
  718. }
  719. }
  720. }
  721. private resolveMeta(loaderName: string, baseUrl: string): ResolvedPkgMeta | null {
  722. const sourceKey = this.sourceKey(loaderName, baseUrl)
  723. const cached = this.pkgMeta.get(sourceKey)
  724. if (cached !== undefined) return cached
  725. const located = this.locatePkgJson(loaderName, baseUrl)
  726. if (located === undefined) {
  727. // Not a resolvable package root: loader builtins (cordis:include) and
  728. // subpath entries (…/gateway) land here — permanently not a client row.
  729. this.pkgMeta.set(sourceKey, null)
  730. return null
  731. }
  732. const { packageName, path: pkgPath } = located
  733. const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>
  734. const dsh = pkg.dsh
  735. const decl = parseDshClient(
  736. packageName,
  737. dsh !== null && typeof dsh === 'object' ? (dsh as Record<string, unknown>).client : undefined,
  738. )
  739. if (decl === undefined || decl.platform !== 'web') {
  740. this.pkgMeta.set(sourceKey, null)
  741. return null
  742. }
  743. const clientRel = clientExportOf(packageName, pkg.exports)
  744. if (clientRel === undefined) {
  745. throw new Error(`client-modules: ${packageName} declares dsh.client but exports no "./client" bundle`)
  746. }
  747. const meta: PkgMeta = {
  748. clientPath: join(dirname(pkgPath), clientRel),
  749. ...(decl.inject !== undefined ? { inject: decl.inject } : {}),
  750. external: decl.external ?? [],
  751. immediately: decl.immediately === true,
  752. }
  753. const resolved = { packageName, meta }
  754. this.pkgMeta.set(sourceKey, resolved)
  755. return resolved
  756. }
  757. /**
  758. * Locate the manifest of the package the Loader mounts for a row. The row's
  759. * module location is authoritative: the specifier resolves through the same
  760. * Loader resolution that imported the row's host half — including any
  761. * active ESM hooks — and the nearest ancestor manifest declaring the name
  762. * owns the module. Tree-anchored `require` resolution remains only for
  763. * runtimes without Node internals.
  764. * @param loaderName - module specifier of the loader row.
  765. * @param baseUrl - resolution base of the tree that owns the row.
  766. * @returns the manifest path, or `undefined` when the name resolves to no package root.
  767. */
  768. private locatePkgJson(loaderName: string, baseUrl: string): { path: string; packageName: string } | undefined {
  769. if (loaderName.startsWith('cordis:')) return undefined
  770. const pathLike = loaderName.startsWith('.') || loaderName.startsWith('file:') || isAbsolute(loaderName)
  771. const expectedPackageName = pathLike ? undefined : exactPackageSpecifier(loaderName)
  772. if (!pathLike && expectedPackageName === undefined) return undefined
  773. const internal = this.ctx.loader.internal
  774. if (internal === undefined || typeof Reflect.get(internal, 'resolveSync') !== 'function') {
  775. if (expectedPackageName === undefined) {
  776. const moduleUrl = loaderName.startsWith('file:')
  777. ? loaderName
  778. : isAbsolute(loaderName) ? pathToFileURL(loaderName).href : new URL(loaderName, baseUrl).href
  779. return this.nearestPackage(moduleUrl)
  780. }
  781. try {
  782. return {
  783. path: createRequire(baseUrl).resolve(`${expectedPackageName}/package.json`),
  784. packageName: expectedPackageName,
  785. }
  786. } catch {
  787. // Without Node internals the owning tree is the only resolver; an
  788. // unresolvable name is classified exactly as below.
  789. return undefined
  790. }
  791. }
  792. let moduleUrl: string
  793. try {
  794. moduleUrl = internal.version === 'v2'
  795. ? internal.resolveSync(baseUrl, { specifier: loaderName, attributes: {} }).url
  796. : internal.resolveSync(loaderName, baseUrl, {}).url
  797. } catch {
  798. // The Loader cannot resolve the name: its row cannot have imported, so
  799. // the name is permanently not a client row.
  800. return undefined
  801. }
  802. return this.nearestPackage(moduleUrl, expectedPackageName)
  803. }
  804. private nearestPackage(
  805. moduleUrl: string,
  806. expectedPackageName?: string,
  807. ): { path: string; packageName: string } | undefined {
  808. if (!moduleUrl.startsWith('file:')) return undefined
  809. let dir = dirname(fileURLToPath(moduleUrl))
  810. while (true) {
  811. const candidate = join(dir, 'package.json')
  812. if (existsSync(candidate)) {
  813. try {
  814. const name = (JSON.parse(readFileSync(candidate, 'utf8')) as { name?: unknown }).name
  815. if (typeof name === 'string' && (expectedPackageName === undefined || name === expectedPackageName)) {
  816. return { path: candidate, packageName: name }
  817. }
  818. } catch {
  819. // An unreadable or malformed intermediate manifest cannot own the
  820. // module; keep walking toward the declaring package root.
  821. }
  822. }
  823. const parent = dirname(dir)
  824. if (parent === dir) break
  825. dir = parent
  826. }
  827. return undefined
  828. }
  829. private sourceKey(loaderName: string, baseUrl: string): string {
  830. return `${baseUrl}\0${loaderName}`
  831. }
  832. /** Capture the bundle stats before reading its bytes. */
  833. private captureArtifactBaseline(clientPath: string): ClientArtifactBaseline {
  834. const bundle = statSync(clientPath)
  835. return {
  836. path: clientPath,
  837. mtimeMs: bundle.mtimeMs,
  838. size: bundle.size,
  839. }
  840. }
  841. /** Allocate an opaque initial row revision without inspecting artifact bytes. */
  842. private allocateInitialRevision(): string {
  843. return `${this.initialRevisionNonce}-${String(this.nextInitialRevision++)}`
  844. }
  845. /**
  846. * Read the activation-time bundle snapshot.
  847. * @param pkgName - package that declares the client bundle.
  848. * @param clientPath - absolute path of the built client artifact.
  849. * @returns the immutable bytes plus the pre-read filesystem baseline.
  850. * @throws {MissingClientBundleError} when the read fails with `ENOENT`; other filesystem errors are rethrown unchanged.
  851. */
  852. private initialBundleSnapshot(pkgName: string, clientPath: string): {
  853. bundle: Buffer
  854. baseline: ClientArtifactBaseline
  855. } {
  856. try {
  857. const baseline = this.captureArtifactBaseline(clientPath)
  858. const bundle = readFileSync(clientPath)
  859. return { bundle, baseline }
  860. } catch (error) {
  861. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  862. throw new MissingClientBundleError(pkgName, clientPath, error)
  863. }
  864. }
  865. /** Treat a missing, torn, or malformed development map as an identity section. */
  866. private readonly readSourceMap = (clientPath: string): Record<string, unknown> | undefined => {
  867. try {
  868. return readSourceMap(clientPath)
  869. } catch (error) {
  870. this.ctx.logger.warn(error)
  871. return undefined
  872. }
  873. }
  874. /** Reconcile one entry name against the live Loader sources. @returns whether the table changed. */
  875. private processOne(entryName: string, onError: (err: Error) => void): boolean {
  876. const nextSources = new Map<string, ClientPackageSource>()
  877. for (const entry of this.ctx.loader.entries()) {
  878. if (entry.options.name !== entryName || entry.fiber === undefined || entry.disabled) continue
  879. const source = this.resolveSource(entry)
  880. if (source !== undefined) nextSources.set(source.sourceKey, source)
  881. }
  882. const affectedPackages = new Set<string>()
  883. for (const [sourceKey, source] of this.sources) {
  884. if (source.loaderName !== entryName) continue
  885. affectedPackages.add(source.packageName)
  886. if (!nextSources.has(sourceKey)) this.sources.delete(sourceKey)
  887. }
  888. for (const [sourceKey, source] of nextSources) {
  889. affectedPackages.add(source.packageName)
  890. this.sources.set(sourceKey, source)
  891. }
  892. let changed = false
  893. for (const packageName of affectedPackages) {
  894. try {
  895. if (this.reconcilePackage(packageName)) changed = true
  896. } catch (error) {
  897. onError(error instanceof Error ? error : new Error(String(error)))
  898. }
  899. }
  900. return changed
  901. }
  902. private resolveSource(entry: Entry): ClientPackageSource | undefined {
  903. const loaderName = entry.options.name
  904. const baseUrl = entry.parent.tree.ctx.baseUrl
  905. if (baseUrl === undefined) {
  906. throw new Error(`client-modules: loader entry ${loaderName} has no resolution base URL`)
  907. }
  908. const resolved = this.resolveMeta(loaderName, baseUrl)
  909. if (resolved === null) return undefined
  910. return { ...resolved, loaderName, baseUrl, sourceKey: this.sourceKey(loaderName, baseUrl) }
  911. }
  912. private reconcilePackage(packageName: string): boolean {
  913. const sources: ClientPackageSource[] = []
  914. for (const source of this.sources.values()) {
  915. if (source.packageName === packageName) sources.push(source)
  916. }
  917. if (sources.length > 1) {
  918. const locations = sources
  919. .map(source => `${JSON.stringify(source.loaderName)} from ${source.baseUrl}`)
  920. .join(', ')
  921. throw new Error(
  922. `client-modules: package ${packageName} resolves from multiple active Loader sources: ${locations}; remove one entry`,
  923. )
  924. }
  925. const source = sources[0]
  926. if (source === undefined) return this.table.delete(packageName)
  927. if (this.table.get(packageName)?.sourceKey === source.sourceKey) return false
  928. // The opaque initial rev rides the row until HMR observes a file change;
  929. // a fiber restart from the same source reuses the existing row.
  930. const snapshot = this.initialBundleSnapshot(packageName, source.meta.clientPath)
  931. const rev = this.allocateInitialRevision()
  932. this.table.set(packageName, {
  933. entry: graphRow(packageName, rev, source.meta),
  934. loaderName: source.loaderName,
  935. sourceKey: source.sourceKey,
  936. meta: source.meta,
  937. bundle: snapshot.bundle,
  938. baseline: snapshot.baseline,
  939. })
  940. return true
  941. }
  942. private flush(onError: (err: Error) => void): void {
  943. let changed = false
  944. for (const entryName of [...this.dirty]) {
  945. this.dirty.delete(entryName)
  946. try {
  947. if (this.processOne(entryName, onError)) changed = true
  948. } catch (error) {
  949. // Steady state: one broken package must not poison the others; the
  950. // activation pass aggregates these into a loud throw instead.
  951. onError(error instanceof Error ? error : new Error(String(error)))
  952. }
  953. }
  954. if (!changed) return
  955. let composed: WebBootGraph
  956. try {
  957. composed = this.compose()
  958. } catch (error) {
  959. // An unorderable module graph is a property of the whole table, not of
  960. // the arriving package, so it surfaces here: aggregated into the
  961. // activation throw, or warned in steady state while the last orderable
  962. // graph stays served.
  963. onError(error as Error)
  964. return
  965. }
  966. this.composed = composed
  967. this.notifyGraphChanged()
  968. }
  969. /** Match an exact current-revision package-local chunk URL without reading its file. */
  970. private chunkRequest(requestUrl: URL): {
  971. record: WebPluginRecord
  972. fileName: string
  973. sourceMap: boolean
  974. resourceUrl: string
  975. } | undefined {
  976. const resourceUrl = `${requestUrl.pathname}${requestUrl.search}`
  977. for (const record of this.table.values()) {
  978. const prefix = `/plugins/${record.entry.id}/`
  979. if (!requestUrl.pathname.startsWith(prefix)) continue
  980. const requested = requestUrl.pathname.slice(prefix.length)
  981. const sourceMap = requested.endsWith('.map')
  982. const fileName = sourceMap ? requested.slice(0, -'.map'.length) : requested
  983. if (!CLIENT_CHUNK.test(fileName)) return undefined
  984. if (resourceUrl !== chunkUrl(record.entry.id, fileName, record.entry.rev, sourceMap)) return undefined
  985. return { record, fileName, sourceMap, resourceUrl }
  986. }
  987. return undefined
  988. }
  989. /** Build a package-local chunk response only when its URL is requested. */
  990. private chunkResponse(requestUrl: URL): LazyResponse | undefined {
  991. const request = this.chunkRequest(requestUrl)
  992. if (request === undefined) return undefined
  993. const { record, fileName, sourceMap, resourceUrl } = request
  994. const clientPath = join(dirname(record.meta.clientPath), fileName)
  995. if (!existsSync(clientPath)) return undefined
  996. const sourceMapUrl = chunkUrl(record.entry.id, fileName, record.entry.rev, true)
  997. const resource = (): ComboResource => ({
  998. id: record.entry.id,
  999. rev: record.entry.rev,
  1000. clientPath,
  1001. fileName,
  1002. bundle: readFileSync(clientPath),
  1003. })
  1004. const response: LazyResponse = sourceMap
  1005. ? {
  1006. body: lazyBody(() => buildComboSourceMap([resource()], this.readSourceMap, fileName)),
  1007. contentType: 'application/json; charset=utf-8',
  1008. }
  1009. : {
  1010. body: lazyBody(() => buildComboScript([resource()], sourceMapUrl)),
  1011. contentType: 'text/javascript; charset=utf-8',
  1012. }
  1013. this.responses.set(resourceUrl, response)
  1014. return response
  1015. }
  1016. private async bundleResource(method: string | undefined, url: string): Promise<{
  1017. status: number
  1018. headers?: Record<string, string>
  1019. body?: Buffer
  1020. }> {
  1021. if (method !== 'GET' && method !== 'HEAD') return { status: 405 }
  1022. const requestUrl = new URL(url, 'http://x')
  1023. const resourceUrl = `${requestUrl.pathname}${requestUrl.search}`
  1024. const response = this.responses.get(resourceUrl)
  1025. ?? this.previousBatchResponses.get(resourceUrl)
  1026. ?? this.chunkResponse(requestUrl)
  1027. if (response !== undefined) {
  1028. return {
  1029. status: 200,
  1030. headers: { 'content-type': response.contentType, 'cache-control': IMMUTABLE_CACHE },
  1031. ...(method === 'HEAD' ? {} : { body: await response.body() }),
  1032. }
  1033. }
  1034. // Anything else under /plugins (including unadvertised combinations and
  1035. // /plugins/events when the HMR row is absent) is an unknown resource.
  1036. return { status: 404 }
  1037. }
  1038. private readonly serveBundle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
  1039. /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */
  1040. const response = await this.bundleResource(req.method, req.url ?? '/')
  1041. res.writeHead(response.status, response.headers)
  1042. res.end(response.body)
  1043. }
  1044. }
  1045. export default ClientModuleRegistry