index.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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 = ['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 Loader and an optional Web carrier.
  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. const registerWebCarrier = (webCtx: Context): void => {
  526. webCtx.effect(
  527. () => webCtx.webServer.register({ kind: 'prefix', path: '/plugins', handler: this.serveBundle }),
  528. 'client-modules: bundle route',
  529. )
  530. }
  531. if (ctx.get('webServer') === undefined) ctx.inject(['webServer'], registerWebCarrier)
  532. else registerWebCarrier(ctx)
  533. ctx.on('webserver/index-inject', (table) => {
  534. table.push(...bootInjections(this.composed))
  535. })
  536. }
  537. /**
  538. * Current composed entry graph (stable object between changes).
  539. * @returns the graph served as `window.__DSH_BOOT__`.
  540. */
  541. graph(): WebBootGraph {
  542. return this.composed
  543. }
  544. /**
  545. * Absolute path of an entry's client bundle.
  546. * @param id - entry id (package name).
  547. * @returns the path, or undefined for an unknown id.
  548. */
  549. clientPath(id: string): string | undefined {
  550. return this.table.get(id)?.meta.clientPath
  551. }
  552. /**
  553. * Serve an advertised revisioned bundle or source map without a Web server.
  554. * Unknown URLs return 404, unsupported methods return 405, and `HEAD`
  555. * returns the same immutable headers without a body.
  556. * @param request - shell-carrier request for a `/plugins` resource.
  557. * @returns the exact response also exposed by the optional Web route.
  558. */
  559. fetchBundle(request: Request): Response {
  560. const resource = this.bundleResource(request.method, request.url)
  561. const body = resource.body === undefined ? null : Uint8Array.from(resource.body)
  562. return new Response(body, {
  563. status: resource.status,
  564. ...(resource.headers === undefined ? {} : { headers: resource.headers }),
  565. })
  566. }
  567. /**
  568. * Filesystem baseline captured before an entry's current bytes were read.
  569. * HMR compares it with the live files when installing a watch, so a write
  570. * between startup composition and watch installation cannot disappear into
  571. * the watcher's initial state.
  572. * @param id - entry id (package name).
  573. * @returns the path and baseline, or undefined for an unknown id.
  574. */
  575. artifactBaseline(id: string): ClientArtifactBaseline | undefined {
  576. const baseline = this.table.get(id)?.baseline
  577. return baseline === undefined ? undefined : { ...baseline }
  578. }
  579. /**
  580. * Re-hash one bundle (the HMR watch's registration hook — the only entry
  581. * point through which bundle content changes reach the graph).
  582. * @param id - entry id (package name).
  583. * @returns the new rev, or undefined for an unknown id.
  584. */
  585. rebuilt(id: string): string | undefined {
  586. const record = this.table.get(id)
  587. if (record === undefined) return undefined
  588. const baseline = this.captureArtifactBaseline(record.meta.clientPath)
  589. const bundle = readFileSync(record.meta.clientPath)
  590. const sourceMap = this.readSourceMapSnapshot(record.meta.clientPath)
  591. const rev = artifactRevision(bundle, sourceMap)
  592. record.baseline = baseline
  593. if (rev === record.entry.rev) return rev
  594. record.entry = graphRow(id, rev, record.meta)
  595. record.bundle = bundle
  596. if (sourceMap === undefined) delete record.sourceMap
  597. else record.sourceMap = sourceMap
  598. this.composed = this.compose()
  599. for (const notify of this.rebuildListeners) {
  600. // Containment: rebuilt() runs inside the HMR watch callback — a
  601. // throwing subscriber must not kill the poll or skip later subscribers.
  602. try {
  603. notify(id, rev)
  604. } catch (error) {
  605. this.ctx.logger.error(error)
  606. }
  607. }
  608. this.notifyGraphChanged()
  609. return rev
  610. }
  611. /**
  612. * Subscribe to bundle rebuilds; fires only when the re-hash changed the rev.
  613. * @param listener - receives the entry id and its new bundle rev.
  614. * @returns the unsubscriber.
  615. */
  616. onRebuilt(listener: (id: string, rev: string) => void): () => void {
  617. this.rebuildListeners.add(listener)
  618. return () => { this.rebuildListeners.delete(listener) }
  619. }
  620. /**
  621. * Fires after any flush that recomposed the graph (row added/removed, or a
  622. * rebuilt rev change). Pull model: listeners re-read {@link graph}.
  623. * @param listener - notified with no payload.
  624. * @returns the unsubscriber.
  625. */
  626. onGraphChanged(listener: () => void): () => void {
  627. this.graphListeners.add(listener)
  628. return () => { this.graphListeners.delete(listener) }
  629. }
  630. private compose(): WebBootGraph {
  631. const entries = orderByModuleGraph([...this.table.values()].map(record => record.entry))
  632. const bootstrap = PARSER_PRELOAD_IDS
  633. .map(id => this.table.get(id))
  634. .filter((record): record is WebPluginRecord => record !== undefined)
  635. const bootstrapIds = new Set(bootstrap.map(record => record.entry.id))
  636. const application = entries
  637. .filter(entry => !bootstrapIds.has(entry.id))
  638. .map(entry => this.table.get(entry.id))
  639. .filter((record): record is WebPluginRecord => record !== undefined)
  640. const artifacts: BatchArtifact[] = []
  641. for (const records of partitionComboRecords(bootstrap)) {
  642. artifacts.push(buildBatch('bootstrap', records))
  643. }
  644. for (const records of partitionComboRecords(application)) {
  645. artifacts.push(buildBatch('application', records))
  646. }
  647. const batchResponses = new Map<string, { body: Buffer; contentType: string }>()
  648. for (const artifact of artifacts) {
  649. batchResponses.set(artifact.descriptor.url, {
  650. body: artifact.script,
  651. contentType: 'text/javascript; charset=utf-8',
  652. })
  653. batchResponses.set(artifact.sourceMapUrl, {
  654. body: artifact.sourceMap,
  655. contentType: 'application/json; charset=utf-8',
  656. })
  657. }
  658. const responses = new Map(batchResponses)
  659. for (const record of this.table.values()) {
  660. const artifact = buildCombo([record], record.entry.rev)
  661. responses.set(artifact.url, {
  662. body: artifact.script,
  663. contentType: 'text/javascript; charset=utf-8',
  664. })
  665. responses.set(artifact.sourceMapUrl, {
  666. body: artifact.sourceMap,
  667. contentType: 'application/json; charset=utf-8',
  668. })
  669. }
  670. this.previousBatchResponses = this.batchResponses
  671. this.batchResponses = batchResponses
  672. this.responses = responses
  673. const batches = artifacts.map(artifact => artifact.descriptor)
  674. return { rev: shortHash(JSON.stringify({ entries, batches })), entries, batches }
  675. }
  676. private notifyGraphChanged(): void {
  677. for (const listener of this.graphListeners) {
  678. // A throwing subscriber must not skip later subscribers (or escape into
  679. // whatever triggered the flush — possibly an fs.watchFile callback).
  680. try {
  681. listener()
  682. } catch (error) {
  683. this.ctx.logger.error(error)
  684. }
  685. }
  686. }
  687. private resolveMeta(loaderName: string, baseUrl: string): ResolvedPkgMeta | null {
  688. const sourceKey = this.sourceKey(loaderName, baseUrl)
  689. const cached = this.pkgMeta.get(sourceKey)
  690. if (cached !== undefined) return cached
  691. const located = this.locatePkgJson(loaderName, baseUrl)
  692. if (located === undefined) {
  693. // Not a resolvable package root: loader builtins (cordis:include) and
  694. // subpath entries (…/gateway) land here — permanently not a client row.
  695. this.pkgMeta.set(sourceKey, null)
  696. return null
  697. }
  698. const { packageName, path: pkgPath } = located
  699. const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as Record<string, unknown>
  700. const dsh = pkg.dsh
  701. const decl = parseDshClient(
  702. packageName,
  703. dsh !== null && typeof dsh === 'object' ? (dsh as Record<string, unknown>).client : undefined,
  704. )
  705. if (decl === undefined || decl.platform !== 'web') {
  706. this.pkgMeta.set(sourceKey, null)
  707. return null
  708. }
  709. const clientRel = clientExportOf(packageName, pkg.exports)
  710. if (clientRel === undefined) {
  711. throw new Error(`client-modules: ${packageName} declares dsh.client but exports no "./client" bundle`)
  712. }
  713. const meta: PkgMeta = {
  714. clientPath: join(dirname(pkgPath), clientRel),
  715. ...(decl.inject !== undefined ? { inject: decl.inject } : {}),
  716. external: decl.external ?? [],
  717. immediately: decl.immediately === true,
  718. }
  719. const resolved = { packageName, meta }
  720. this.pkgMeta.set(sourceKey, resolved)
  721. return resolved
  722. }
  723. /**
  724. * Locate the manifest of the package the Loader mounts for a row. The row's
  725. * module location is authoritative: the specifier resolves through the same
  726. * Loader resolution that imported the row's host half — including any
  727. * active ESM hooks — and the nearest ancestor manifest declaring the name
  728. * owns the module. Tree-anchored `require` resolution remains only for
  729. * runtimes without Node internals.
  730. * @param loaderName - module specifier of the loader row.
  731. * @param baseUrl - resolution base of the tree that owns the row.
  732. * @returns the manifest path, or `undefined` when the name resolves to no package root.
  733. */
  734. private locatePkgJson(loaderName: string, baseUrl: string): { path: string; packageName: string } | undefined {
  735. if (loaderName.startsWith('cordis:')) return undefined
  736. const pathLike = loaderName.startsWith('.') || loaderName.startsWith('file:') || isAbsolute(loaderName)
  737. const expectedPackageName = pathLike ? undefined : exactPackageSpecifier(loaderName)
  738. if (!pathLike && expectedPackageName === undefined) return undefined
  739. const internal = this.ctx.loader.internal
  740. if (internal === undefined || typeof Reflect.get(internal, 'resolveSync') !== 'function') {
  741. if (expectedPackageName === undefined) {
  742. const moduleUrl = loaderName.startsWith('file:')
  743. ? loaderName
  744. : isAbsolute(loaderName) ? pathToFileURL(loaderName).href : new URL(loaderName, baseUrl).href
  745. return this.nearestPackage(moduleUrl)
  746. }
  747. try {
  748. return {
  749. path: createRequire(baseUrl).resolve(`${expectedPackageName}/package.json`),
  750. packageName: expectedPackageName,
  751. }
  752. } catch {
  753. // Without Node internals the owning tree is the only resolver; an
  754. // unresolvable name is classified exactly as below.
  755. return undefined
  756. }
  757. }
  758. let moduleUrl: string
  759. try {
  760. moduleUrl = internal.version === 'v2'
  761. ? internal.resolveSync(baseUrl, { specifier: loaderName, attributes: {} }).url
  762. : internal.resolveSync(loaderName, baseUrl, {}).url
  763. } catch {
  764. // The Loader cannot resolve the name: its row cannot have imported, so
  765. // the name is permanently not a client row.
  766. return undefined
  767. }
  768. return this.nearestPackage(moduleUrl, expectedPackageName)
  769. }
  770. private nearestPackage(
  771. moduleUrl: string,
  772. expectedPackageName?: string,
  773. ): { path: string; packageName: string } | undefined {
  774. if (!moduleUrl.startsWith('file:')) return undefined
  775. let dir = dirname(fileURLToPath(moduleUrl))
  776. while (true) {
  777. const candidate = join(dir, 'package.json')
  778. if (existsSync(candidate)) {
  779. try {
  780. const name = (JSON.parse(readFileSync(candidate, 'utf8')) as { name?: unknown }).name
  781. if (typeof name === 'string' && (expectedPackageName === undefined || name === expectedPackageName)) {
  782. return { path: candidate, packageName: name }
  783. }
  784. } catch {
  785. // An unreadable or malformed intermediate manifest cannot own the
  786. // module; keep walking toward the declaring package root.
  787. }
  788. }
  789. const parent = dirname(dir)
  790. if (parent === dir) break
  791. dir = parent
  792. }
  793. return undefined
  794. }
  795. private sourceKey(loaderName: string, baseUrl: string): string {
  796. return `${baseUrl}\0${loaderName}`
  797. }
  798. /** Capture the bundle stats before reading its bytes. */
  799. private captureArtifactBaseline(clientPath: string): ClientArtifactBaseline {
  800. const bundle = statSync(clientPath)
  801. return {
  802. path: clientPath,
  803. mtimeMs: bundle.mtimeMs,
  804. size: bundle.size,
  805. }
  806. }
  807. /** Allocate an opaque initial row revision without inspecting artifact bytes. */
  808. private allocateInitialRevision(): string {
  809. return `${this.initialRevisionNonce}-${String(this.nextInitialRevision++)}`
  810. }
  811. /**
  812. * Read the activation-time bundle and optional source-map snapshots.
  813. * @param pkgName - package that declares the client bundle.
  814. * @param clientPath - absolute path of the built client artifact.
  815. * @returns the immutable bytes plus the pre-read filesystem baseline.
  816. * @throws {MissingClientBundleError} when the read fails with `ENOENT`; other filesystem errors are rethrown unchanged.
  817. */
  818. private initialBundleSnapshot(pkgName: string, clientPath: string): {
  819. bundle: Buffer
  820. baseline: ClientArtifactBaseline
  821. sourceMap?: WebPluginRecord['sourceMap']
  822. } {
  823. try {
  824. const baseline = this.captureArtifactBaseline(clientPath)
  825. const bundle = readFileSync(clientPath)
  826. const sourceMap = this.readSourceMapSnapshot(clientPath)
  827. return { bundle, baseline, ...(sourceMap === undefined ? {} : { sourceMap }) }
  828. } catch (error) {
  829. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  830. throw new MissingClientBundleError(pkgName, clientPath, error)
  831. }
  832. }
  833. /** Treat a missing, torn, or malformed development map as an identity-mapped artifact revision. */
  834. private readSourceMapSnapshot(clientPath: string): WebPluginRecord['sourceMap'] {
  835. try {
  836. return sourceMapSnapshot(clientPath)
  837. } catch (error) {
  838. this.ctx.logger.warn(error)
  839. return undefined
  840. }
  841. }
  842. /** Reconcile one entry name against the live Loader sources. @returns whether the table changed. */
  843. private processOne(entryName: string, onError: (err: Error) => void): boolean {
  844. const nextSources = new Map<string, ClientPackageSource>()
  845. for (const entry of this.ctx.loader.entries()) {
  846. if (entry.options.name !== entryName || entry.fiber === undefined || entry.disabled) continue
  847. const source = this.resolveSource(entry)
  848. if (source !== undefined) nextSources.set(source.sourceKey, source)
  849. }
  850. const affectedPackages = new Set<string>()
  851. for (const [sourceKey, source] of this.sources) {
  852. if (source.loaderName !== entryName) continue
  853. affectedPackages.add(source.packageName)
  854. if (!nextSources.has(sourceKey)) this.sources.delete(sourceKey)
  855. }
  856. for (const [sourceKey, source] of nextSources) {
  857. affectedPackages.add(source.packageName)
  858. this.sources.set(sourceKey, source)
  859. }
  860. let changed = false
  861. for (const packageName of affectedPackages) {
  862. try {
  863. if (this.reconcilePackage(packageName)) changed = true
  864. } catch (error) {
  865. onError(error instanceof Error ? error : new Error(String(error)))
  866. }
  867. }
  868. return changed
  869. }
  870. private resolveSource(entry: Entry): ClientPackageSource | undefined {
  871. const loaderName = entry.options.name
  872. const baseUrl = entry.parent.tree.ctx.baseUrl
  873. if (baseUrl === undefined) {
  874. throw new Error(`client-modules: loader entry ${loaderName} has no resolution base URL`)
  875. }
  876. const resolved = this.resolveMeta(loaderName, baseUrl)
  877. if (resolved === null) return undefined
  878. return { ...resolved, loaderName, baseUrl, sourceKey: this.sourceKey(loaderName, baseUrl) }
  879. }
  880. private reconcilePackage(packageName: string): boolean {
  881. const sources: ClientPackageSource[] = []
  882. for (const source of this.sources.values()) {
  883. if (source.packageName === packageName) sources.push(source)
  884. }
  885. if (sources.length > 1) {
  886. const locations = sources
  887. .map(source => `${JSON.stringify(source.loaderName)} from ${source.baseUrl}`)
  888. .join(', ')
  889. throw new Error(
  890. `client-modules: package ${packageName} resolves from multiple active Loader sources: ${locations}; remove one entry`,
  891. )
  892. }
  893. const source = sources[0]
  894. if (source === undefined) return this.table.delete(packageName)
  895. if (this.table.get(packageName)?.sourceKey === source.sourceKey) return false
  896. // The opaque initial rev rides the row until HMR observes a file change;
  897. // a fiber restart from the same source reuses the existing row.
  898. const snapshot = this.initialBundleSnapshot(packageName, source.meta.clientPath)
  899. const rev = this.allocateInitialRevision()
  900. this.table.set(packageName, {
  901. entry: graphRow(packageName, rev, source.meta),
  902. loaderName: source.loaderName,
  903. sourceKey: source.sourceKey,
  904. meta: source.meta,
  905. bundle: snapshot.bundle,
  906. baseline: snapshot.baseline,
  907. ...(snapshot.sourceMap === undefined ? {} : { sourceMap: snapshot.sourceMap }),
  908. })
  909. return true
  910. }
  911. private flush(onError: (err: Error) => void): void {
  912. let changed = false
  913. for (const entryName of [...this.dirty]) {
  914. this.dirty.delete(entryName)
  915. try {
  916. if (this.processOne(entryName, onError)) changed = true
  917. } catch (error) {
  918. // Steady state: one broken package must not poison the others; the
  919. // activation pass aggregates these into a loud throw instead.
  920. onError(error instanceof Error ? error : new Error(String(error)))
  921. }
  922. }
  923. if (!changed) return
  924. let composed: WebBootGraph
  925. try {
  926. composed = this.compose()
  927. } catch (error) {
  928. // An unorderable module graph is a property of the whole table, not of
  929. // the arriving package, so it surfaces here: aggregated into the
  930. // activation throw, or warned in steady state while the last orderable
  931. // graph stays served.
  932. onError(error as Error)
  933. return
  934. }
  935. this.composed = composed
  936. this.notifyGraphChanged()
  937. }
  938. private bundleResource(method: string | undefined, url: string): {
  939. status: number
  940. headers?: Record<string, string>
  941. body?: Buffer
  942. } {
  943. if (method !== 'GET' && method !== 'HEAD') return { status: 405 }
  944. const requestUrl = new URL(url, 'http://x')
  945. const resourceUrl = `${requestUrl.pathname}${requestUrl.search}`
  946. const response = this.responses.get(resourceUrl) ?? this.previousBatchResponses.get(resourceUrl)
  947. if (response !== undefined) {
  948. return {
  949. status: 200,
  950. headers: { 'content-type': response.contentType, 'cache-control': IMMUTABLE_CACHE },
  951. ...(method === 'HEAD' ? {} : { body: response.body }),
  952. }
  953. }
  954. // Anything else under /plugins (including unadvertised combinations and
  955. // /plugins/events when the HMR row is absent) is an unknown resource.
  956. return { status: 404 }
  957. }
  958. private readonly serveBundle = (req: IncomingMessage, res: ServerResponse): void => {
  959. /* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */
  960. const response = this.bundleResource(req.method, req.url ?? '/')
  961. res.writeHead(response.status, response.headers)
  962. res.end(response.body)
  963. }
  964. }
  965. export default ClientModuleRegistry