index.ts 42 KB

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