index.ts 41 KB

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