node-half.client.spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /** Node-half composition diagnostics for package metadata and built client bundles. */
  2. import { mkdirSync, mkdtempSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
  3. import type { IncomingMessage, ServerResponse } from 'node:http'
  4. import { SourceMap } from 'node:module'
  5. import { tmpdir } from 'node:os'
  6. import { dirname, join } from 'node:path'
  7. import { pathToFileURL } from 'node:url'
  8. import { runInNewContext } from 'node:vm'
  9. import { Context, type Fiber } from '@deepseek-ai/cordis'
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import { renderIndexInjections, type WebServer, type WebRoute } from '@deepseek-ai/dsh-host-webserver'
  12. import * as modulesClient from '../src/client/index.ts'
  13. import { ClientModuleRegistry, bootInjections, orderByModuleGraph } from '../src/index.ts'
  14. import type { ClientModuleLoaderTarget, WebBootEntry, WebBootGraph } from '../src/client/index.ts'
  15. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  16. const UI_RENDERER_ID = '@deepseek-ai/dsh-client-ui-renderer'
  17. const comboUrl = (ids: readonly string[], rev: string): string =>
  18. `/plugins/??${ids.map(id => `${id}/client.js`).join(',')}&rev=${rev}`
  19. const mapUrl = (url: string): string => url.replace(/\/client\.js(?=,|&rev=)/g, '/client.js.map')
  20. const BOOTSTRAP_URL = comboUrl([MODULES_ID], 'boot')
  21. const APPLICATION_URL = comboUrl([UI_RENDERER_ID], 'app')
  22. let root: string | undefined
  23. afterEach(() => {
  24. if (root !== undefined) rmSync(root, { recursive: true, force: true })
  25. root = undefined
  26. })
  27. /** Create a resolvable package whose client export points at the returned path. */
  28. function writePackage(
  29. packageName: string,
  30. metadata: Record<string, unknown> = { dsh: { client: { platform: 'web' } } },
  31. ): string {
  32. root ??= realpathSync(mkdtempSync(join(tmpdir(), 'dsh-client-modules-')))
  33. const pkgRoot = join(root, 'node_modules', ...packageName.split('/'))
  34. const clientPath = join(pkgRoot, 'lib', 'client.js')
  35. mkdirSync(pkgRoot, { recursive: true })
  36. writeFileSync(join(pkgRoot, 'package.json'), JSON.stringify({
  37. name: packageName,
  38. exports: {
  39. './client': './lib/client.js',
  40. './package.json': './package.json',
  41. },
  42. ...metadata,
  43. }))
  44. return clientPath
  45. }
  46. /** Create a built package with the supplied client declaration. */
  47. function writeBuiltPackage(packageName: string, client: Record<string, unknown>): void {
  48. const clientPath = writePackage(packageName, { dsh: { client: { platform: 'web', ...client } } })
  49. mkdirSync(dirname(clientPath), { recursive: true })
  50. writeFileSync(clientPath, 'module.exports = {}\n')
  51. }
  52. /** Construct the node-half service and capture its plugin-bundle route. */
  53. function constructWithRoute(
  54. packageNames: string[],
  55. options: {
  56. contextBaseUrl?: string
  57. entryBaseUrl?: string
  58. internal?: NonNullable<Context['loader']['internal']>
  59. } = {},
  60. ): { context: Context; service: ClientModuleRegistry; route: WebRoute } {
  61. const ctx = new Context()
  62. ctx.baseUrl = options.contextBaseUrl ?? pathToFileURL(root!).href + '/'
  63. ctx.provide('loader', {
  64. internal: options.internal,
  65. *entries() {
  66. for (const packageName of packageNames) {
  67. yield {
  68. options: { name: packageName },
  69. fiber: {},
  70. disabled: false,
  71. parent: { tree: { ctx: { baseUrl: options.entryBaseUrl ?? ctx.baseUrl } } },
  72. }
  73. }
  74. },
  75. })
  76. let route: WebRoute | undefined
  77. const webServer: Pick<WebServer, 'port' | 'register' | 'tapIndex'> = {
  78. port: 0,
  79. register: (candidate) => {
  80. if (candidate.path === '/plugins') route = candidate
  81. return () => {}
  82. },
  83. tapIndex: () => () => {},
  84. }
  85. ctx.provide('webServer', webServer as WebServer)
  86. const service = new ClientModuleRegistry(ctx)
  87. if (route === undefined) throw new Error('client bundle route was not registered')
  88. return { context: ctx, service, route }
  89. }
  90. /** Construct the node-half service over the enabled fixture entries. */
  91. function construct(packageNames: string[]): ClientModuleRegistry {
  92. return constructWithRoute(packageNames).service
  93. }
  94. /** Invoke the registered plugin route and capture status, headers, and bytes. */
  95. async function routeRequest(route: WebRoute, url: string, method = 'GET'): Promise<{
  96. status: number
  97. headers: Record<string, string> | undefined
  98. body: Buffer
  99. }> {
  100. let status = 0
  101. let headers: Record<string, string> | undefined
  102. let body = Buffer.alloc(0)
  103. const response = {
  104. writeHead(nextStatus: number, nextHeaders?: Record<string, string>) {
  105. status = nextStatus
  106. headers = nextHeaders
  107. return response
  108. },
  109. end(chunk?: Uint8Array) {
  110. body = chunk === undefined ? Buffer.alloc(0) : Buffer.from(chunk)
  111. return response
  112. },
  113. } as unknown as ServerResponse
  114. await route.handler({ method, url } as IncomingMessage, response)
  115. return { status, headers, body }
  116. }
  117. /** Execute the exact first inline script emitted by the Host boot rows. */
  118. function injectedFacade(graph: WebBootGraph): { html: string; target: ClientModuleLoaderTarget } {
  119. const html = renderIndexInjections(
  120. '<html><head></head><body><script type="module" src="/index.js"></script></body></html>',
  121. bootInjections(graph),
  122. )
  123. const source = /<head><script>([\s\S]*?)<\/script>/.exec(html)?.[1]
  124. if (source === undefined) throw new Error('missing injected ModuleLoader facade script')
  125. const window: { __ModuleLoader__?: ClientModuleLoaderTarget } = {}
  126. runInNewContext(source, { window })
  127. if (window.__ModuleLoader__ === undefined) throw new Error('facade script did not install __ModuleLoader__')
  128. return { html, target: window.__ModuleLoader__ }
  129. }
  130. const bootGraph = (): WebBootGraph => ({
  131. rev: 'graph',
  132. entries: [
  133. { id: MODULES_ID, url: comboUrl([MODULES_ID], 'm'), rev: 'm' },
  134. { id: UI_RENDERER_ID, url: comboUrl([UI_RENDERER_ID], 'r'), rev: 'r' },
  135. ],
  136. batches: [
  137. {
  138. phase: 'bootstrap',
  139. url: BOOTSTRAP_URL,
  140. rev: 'boot',
  141. entries: [MODULES_ID],
  142. },
  143. {
  144. phase: 'application',
  145. url: APPLICATION_URL,
  146. rev: 'app',
  147. entries: [UI_RENDERER_ID],
  148. },
  149. ],
  150. })
  151. describe('HTML bootstrap facade', () => {
  152. it('precedes blocking preloads and the boot graph, then becomes the live registration target', async () => {
  153. const graph = bootGraph()
  154. const { html, target } = injectedFacade(graph)
  155. const facadeAt = html.indexOf('window.__ModuleLoader__=')
  156. const applicationAt = html.indexOf(
  157. `<link rel="preload" as="script" href="${APPLICATION_URL.replaceAll('&', '&amp;')}">`,
  158. )
  159. const bootstrapAt = html.indexOf(`<script src="${BOOTSTRAP_URL.replaceAll('&', '&amp;')}"></script>`)
  160. const graphAt = html.indexOf('globalThis["__DSH_BOOT__"] = ')
  161. const entryAt = html.indexOf('<script type="module" src="/index.js"></script>')
  162. expect([facadeAt, applicationAt, bootstrapAt, graphAt, entryAt]).toEqual([...new Set([
  163. facadeAt, applicationAt, bootstrapAt, graphAt, entryAt,
  164. ])].sort((a, b) => a - b))
  165. target.load({ id: MODULES_ID, factory: () => modulesClient })
  166. const system = target.create({
  167. boot: graph,
  168. staticModules: {},
  169. loadBundle: async (url) => {
  170. expect(url).toBe(APPLICATION_URL)
  171. target.load({ id: UI_RENDERER_ID, factory: () => ({ marker: 'ui-renderer' }) })
  172. },
  173. })
  174. expect(target.mode).toBe('live')
  175. expect(target.pendingQueue).toEqual([])
  176. expect(system.manifest.rev).toBe('graph')
  177. expect(await system.import(MODULES_ID)).toBe(modulesClient)
  178. expect(await system.import(`${UI_RENDERER_ID}/client`)).toEqual({ marker: 'ui-renderer' })
  179. expect(() => target.create({ boot: graph, staticModules: {} }))
  180. .toThrow('create called after module-system boot')
  181. })
  182. it('preloads every application combo', () => {
  183. const graph = bootGraph()
  184. const secondId = '@fixture/second-application-combo'
  185. const secondUrl = comboUrl([secondId], 'app-2')
  186. graph.entries.push({ id: secondId, url: comboUrl([secondId], 'row-2'), rev: 'row-2' })
  187. graph.batches.push({ phase: 'application', url: secondUrl, rev: 'app-2', entries: [secondId] })
  188. expect(bootInjections(graph).flatMap(row => row.kind === 'script-preload' ? [row.src] : []))
  189. .toEqual([APPLICATION_URL, secondUrl])
  190. })
  191. it('rejects a page that did not preload the modules bundle', () => {
  192. const graph = bootGraph()
  193. const { target } = injectedFacade(graph)
  194. expect(() => target.create({ boot: graph, staticModules: {} }))
  195. .toThrow(`HTML did not preload ${MODULES_ID}/client.js`)
  196. })
  197. it('rejects a bootstrap bundle with a runtime external', () => {
  198. const graph = bootGraph()
  199. const { target } = injectedFacade(graph)
  200. target.load({
  201. id: MODULES_ID,
  202. factory: (require) => {
  203. require('react')
  204. return modulesClient
  205. },
  206. })
  207. expect(() => target.create({ boot: graph, staticModules: {} }))
  208. .toThrow(`${MODULES_ID}/client.js requested external "react"`)
  209. })
  210. it.each([
  211. null,
  212. { ...modulesClient, createClientModuleSystem: undefined },
  213. { ...modulesClient, apply: undefined },
  214. ])('rejects a bootstrap bundle without the complete module face', (exports) => {
  215. const graph = bootGraph()
  216. const { target } = injectedFacade(graph)
  217. target.load({ id: MODULES_ID, factory: () => exports as unknown as Record<string, unknown> })
  218. expect(() => target.create({ boot: graph, staticModules: {} }))
  219. .toThrow(`${MODULES_ID}/client.js did not export the bootstrap module face`)
  220. })
  221. })
  222. describe('client bundle activation', () => {
  223. it.each(['v1', 'v2'] as const)(
  224. 'resolves %s package metadata from the owning entry tree',
  225. (version) => {
  226. const packageName = `@fixture/entry-base-${version}`
  227. const clientPath = writePackage(packageName)
  228. const hostPath = join(dirname(clientPath), 'index.js')
  229. mkdirSync(dirname(hostPath), { recursive: true })
  230. writeFileSync(hostPath, 'export default {}\n')
  231. writeFileSync(clientPath, 'module.exports = {}\n')
  232. const contextBaseUrl = pathToFileURL(join(root!, 'profile')).href + '/'
  233. const entryBaseUrl = pathToFileURL(join(root!, 'overlay')).href + '/'
  234. const calls: unknown[][] = []
  235. const resolveSync = (...args: unknown[]) => {
  236. calls.push(args)
  237. return { format: 'module' as const, url: pathToFileURL(hostPath).href }
  238. }
  239. const internal = { version, resolveSync }
  240. const { service } = constructWithRoute([packageName], {
  241. contextBaseUrl,
  242. entryBaseUrl,
  243. internal: internal as NonNullable<Context['loader']['internal']>,
  244. })
  245. expect(calls).toEqual(version === 'v2'
  246. ? [[entryBaseUrl, { specifier: packageName, attributes: {} }]]
  247. : [[packageName, entryBaseUrl, {}]])
  248. expect(service.clientPath(packageName)).toBe(clientPath)
  249. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  250. },
  251. )
  252. it('derives the browser module id from a file entry owning manifest', () => {
  253. const packageName = '@fixture/file-entry'
  254. const clientPath = writePackage(packageName)
  255. const hostPath = join(dirname(clientPath), 'index.js')
  256. mkdirSync(dirname(hostPath), { recursive: true })
  257. writeFileSync(hostPath, 'export default {}\n')
  258. writeFileSync(clientPath, 'module.exports = {}\n')
  259. const service = construct([pathToFileURL(hostPath).href])
  260. expect(service.clientPath(packageName)).toBe(clientPath)
  261. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  262. })
  263. it.each(['relative', 'absolute'] as const)(
  264. 'finds the owning manifest through the %s-path fallback without Node loader internals',
  265. (kind) => {
  266. const packageName = `@fixture/${kind}-fallback-entry`
  267. const clientPath = writePackage(packageName)
  268. const packageRoot = dirname(dirname(clientPath))
  269. const hostPath = join(packageRoot, 'index.js')
  270. mkdirSync(dirname(clientPath), { recursive: true })
  271. writeFileSync(hostPath, 'export default {}\n')
  272. writeFileSync(clientPath, 'module.exports = {}\n')
  273. const loaderName = kind === 'relative' ? './index.js' : hostPath
  274. const { service } = constructWithRoute([loaderName], {
  275. entryBaseUrl: pathToFileURL(packageRoot).href + '/',
  276. })
  277. expect(service.clientPath(packageName)).toBe(clientPath)
  278. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  279. },
  280. )
  281. it.each(['v1', 'v2', 'worker'] as const)(
  282. 'derives a file entry package id through the %s Loader resolver',
  283. (version) => {
  284. const packageName = `@fixture/file-entry-${version}`
  285. const clientPath = writePackage(packageName)
  286. const hostPath = join(dirname(clientPath), 'index.js')
  287. mkdirSync(dirname(hostPath), { recursive: true })
  288. writeFileSync(hostPath, 'export default {}\n')
  289. writeFileSync(clientPath, 'module.exports = {}\n')
  290. const loaderName = pathToFileURL(hostPath).href
  291. const entryBaseUrl = pathToFileURL(join(root!, 'overlay')).href + '/'
  292. const calls: unknown[][] = []
  293. const resolveSync = (...args: unknown[]) => {
  294. calls.push(args)
  295. return { format: 'module' as const, url: loaderName }
  296. }
  297. const internal = { version, resolveSync }
  298. const { service } = constructWithRoute([loaderName], {
  299. entryBaseUrl,
  300. internal: internal as NonNullable<Context['loader']['internal']>,
  301. })
  302. expect(calls).toEqual(version === 'v2'
  303. ? [[entryBaseUrl, { specifier: loaderName, attributes: {} }]]
  304. : [[loaderName, entryBaseUrl, {}]])
  305. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  306. },
  307. )
  308. it('rejects distinct active Loader sources for one browser package', () => {
  309. const packageName = '@fixture/duplicate-source'
  310. const clientPath = writePackage(packageName)
  311. const hostPath = join(dirname(clientPath), 'index.js')
  312. mkdirSync(dirname(hostPath), { recursive: true })
  313. writeFileSync(hostPath, 'export default {}\n')
  314. writeFileSync(clientPath, 'module.exports = {}\n')
  315. const alias = './duplicate-source.js'
  316. const internal = {
  317. version: 'v2' as const,
  318. resolveSync: () => ({ format: 'module' as const, url: pathToFileURL(hostPath).href }),
  319. }
  320. expect(() => constructWithRoute([packageName, alias], {
  321. internal: internal as unknown as NonNullable<Context['loader']['internal']>,
  322. })).toThrow(
  323. `client-modules: package ${packageName} resolves from multiple active Loader sources:`,
  324. )
  325. })
  326. it('promotes the remaining Loader source after the selected alias unloads', async () => {
  327. const packageName = '@fixture/duplicate-source-recovery'
  328. const clientPath = writePackage(packageName)
  329. const hostPath = join(dirname(clientPath), 'index.js')
  330. mkdirSync(dirname(hostPath), { recursive: true })
  331. writeFileSync(hostPath, 'export default {}\n')
  332. writeFileSync(clientPath, 'module.exports = {}\n')
  333. const alias = './duplicate-source-recovery.js'
  334. const entries = [packageName]
  335. const internal = {
  336. version: 'v2' as const,
  337. resolveSync: () => ({ format: 'module' as const, url: pathToFileURL(hostPath).href }),
  338. }
  339. const { context, service } = constructWithRoute(entries, {
  340. internal: internal as unknown as NonNullable<Context['loader']['internal']>,
  341. })
  342. const firstRevision = service.graph().entries[0]!.rev
  343. const warning = vi.spyOn(context.logger, 'warn').mockImplementation(() => undefined)
  344. entries.push(alias)
  345. emitLoaderEntryChange(context, alias)
  346. await Promise.resolve()
  347. expect(warning).toHaveBeenCalledWith(expect.objectContaining({
  348. message: expect.stringContaining(`package ${packageName} resolves from multiple active Loader sources`) as string,
  349. }))
  350. expect(service.graph().entries[0]!.rev).toBe(firstRevision)
  351. entries.splice(entries.indexOf(packageName), 1)
  352. emitLoaderEntryChange(context, packageName)
  353. await Promise.resolve()
  354. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  355. expect(service.graph().entries[0]!.rev).not.toBe(firstRevision)
  356. expect(service.clientPath(packageName)).toBe(clientPath)
  357. })
  358. it('uses owning-tree package resolution for an import-only Worker module loader', () => {
  359. const packageName = '@fixture/worker-loader'
  360. writeBuiltPackage(packageName, {})
  361. const internal = {
  362. version: 'worker',
  363. import: async () => ({}),
  364. } as unknown as NonNullable<Context['loader']['internal']>
  365. const { service } = constructWithRoute([packageName], { internal })
  366. expect(service.graph().entries.map(entry => entry.id)).toEqual([packageName])
  367. })
  368. it('allows sibling dsh roles', () => {
  369. const currentName = '@fixture/current-client-field'
  370. const clientPath = writePackage(currentName, {
  371. dsh: {
  372. bundle: { patch: './cordis.patch.yml' },
  373. client: { platform: 'web' },
  374. profile: { bundles: [] },
  375. },
  376. })
  377. mkdirSync(dirname(clientPath), { recursive: true })
  378. writeFileSync(clientPath, 'module.exports = {}\n')
  379. expect(construct([currentName]).graph().entries.map(entry => entry.id)).toEqual([currentName])
  380. })
  381. it('groups missing bundles under one source-build instruction with a package/path list', () => {
  382. const firstName = '@fixture/missing-first'
  383. const secondName = '@fixture/missing-second'
  384. const firstPath = writePackage(firstName)
  385. const secondPath = writePackage(secondName)
  386. expect(() => construct([firstName, secondName])).toThrow([
  387. 'client-modules: 2 client packages failed to compose:',
  388. ' client bundles not found; run `pnpm run build` before launch:',
  389. ` - package: ${firstName}`,
  390. ` path: ${firstPath}`,
  391. ` - package: ${secondName}`,
  392. ` path: ${secondPath}`,
  393. ].join('\n'))
  394. })
  395. it('does not report other bundle read failures as missing builds', () => {
  396. const packageName = '@fixture/unreadable-client'
  397. const clientPath = writePackage(packageName)
  398. mkdirSync(clientPath, { recursive: true })
  399. let thrown: unknown
  400. try {
  401. construct([packageName])
  402. } catch (error) {
  403. thrown = error
  404. }
  405. expect(String(thrown)).toContain('client-modules: 1 client package failed to compose:')
  406. expect(String(thrown)).toContain(' other failures:')
  407. expect(String(thrown)).toContain('EISDIR')
  408. expect(String(thrown)).not.toContain('pnpm run build')
  409. })
  410. it('falls back to a generated-file map when an authored map is malformed', async () => {
  411. const packageName = '@fixture/malformed-source-map'
  412. const clientPath = writePackage(packageName)
  413. mkdirSync(dirname(clientPath), { recursive: true })
  414. writeFileSync(clientPath, 'module.exports = {}\n')
  415. writeFileSync(`${clientPath}.map`, '{')
  416. const torn = constructWithRoute([packageName])
  417. const tornRow = torn.service.graph().entries[0]!
  418. expect((await routeRequest(torn.route, tornRow.url)).body.toString('utf8'))
  419. .toContain(`sourceMappingURL=${mapUrl(tornRow.url)}`)
  420. const fallback = await routeRequest(torn.route, mapUrl(torn.service.graph().batches[0]!.url))
  421. expect(JSON.parse(fallback.body.toString('utf8'))).toMatchObject({
  422. sections: [{ map: { sources: [`/plugins/${packageName}/client.js`] } }],
  423. })
  424. writeFileSync(`${clientPath}.map`, '{"version":3,"sources":[null]}\n')
  425. expect(() => construct([packageName])).not.toThrow()
  426. })
  427. it('maps packed combo sections back to each generated client bundle', async () => {
  428. const names = ['@fixture/generated-first', '@fixture/generated-second']
  429. for (const [index, packageName] of names.entries()) {
  430. const clientPath = writePackage(packageName)
  431. mkdirSync(dirname(clientPath), { recursive: true })
  432. writeFileSync(
  433. clientPath,
  434. `window.generation = ${String(index)}\n//# sourceURL=packages/client/generated-${String(index)}/lib/client.js`,
  435. )
  436. }
  437. const { service, route } = constructWithRoute(names)
  438. const batch = service.graph().batches[0]!
  439. const script = (await routeRequest(route, batch.url)).body.toString('utf8')
  440. expect(script).not.toContain('//# sourceURL=')
  441. expect(script).toContain(`//# sourceMappingURL=${mapUrl(batch.url)}`)
  442. const payload = JSON.parse((await routeRequest(route, mapUrl(batch.url))).body.toString('utf8')) as {
  443. sections: { map: { mappings: string; sources: string[]; sourcesContent: string[] } }[]
  444. }
  445. expect(payload.sections.map(section => section.map)).toEqual([
  446. {
  447. version: 3,
  448. names: [],
  449. mappings: 'AAAA',
  450. sources: ['/packages/client/generated-0/lib/client.js'],
  451. sourcesContent: ['window.generation = 0\n'],
  452. },
  453. {
  454. version: 3,
  455. names: [],
  456. mappings: 'AAAA',
  457. sources: ['/packages/client/generated-1/lib/client.js'],
  458. sourcesContent: ['window.generation = 1\n'],
  459. },
  460. ])
  461. const consumer = new SourceMap(payload as unknown as ConstructorParameters<typeof SourceMap>[0])
  462. expect(consumer.findEntry(0, 0)).toMatchObject({
  463. originalSource: '/packages/client/generated-0/lib/client.js',
  464. })
  465. expect(consumer.findEntry(2, 0)).toMatchObject({
  466. originalSource: '/packages/client/generated-1/lib/client.js',
  467. })
  468. })
  469. it('retains one prior immutable batch generation across rebuild recomposition', async () => {
  470. const packageName = '@fixture/batch-rebuild-race'
  471. const clientPath = writePackage(packageName)
  472. mkdirSync(dirname(clientPath), { recursive: true })
  473. writeFileSync(clientPath, 'module.exports = { generation: 1 }\n')
  474. const { service, route } = constructWithRoute([packageName])
  475. const first = service.graph().batches[0]!.url
  476. const firstSize = service.artifactBaseline(packageName)!.size
  477. writeFileSync(clientPath, 'module.exports = { generation: 200 }\n')
  478. service.rebuilt(packageName)
  479. const second = service.graph().batches[0]!.url
  480. expect(second).not.toBe(first)
  481. expect(service.artifactBaseline(packageName)!.size).toBeGreaterThan(firstSize)
  482. expect((await routeRequest(route, first)).status).toBe(200)
  483. expect((await routeRequest(route, second)).status).toBe(200)
  484. writeFileSync(clientPath, 'module.exports = { generation: 3 }\n')
  485. service.rebuilt(packageName)
  486. const third = service.graph().batches[0]!.url
  487. expect((await routeRequest(route, first)).status).toBe(404)
  488. expect((await routeRequest(route, second)).status).toBe(200)
  489. expect((await routeRequest(route, third)).status).toBe(200)
  490. })
  491. it('assigns opaque startup revisions instead of deriving them from artifact content', () => {
  492. const firstName = '@fixture/startup-revision-first'
  493. const secondName = '@fixture/startup-revision-second'
  494. writeBuiltPackage(firstName, {})
  495. writeBuiltPackage(secondName, {})
  496. const service = construct([firstName, secondName])
  497. const [first, second] = service.graph().entries
  498. const firstMatch = /^(?<nonce>[a-f\d]{16})-(?<sequence>\d+)$/.exec(first!.rev)
  499. const secondMatch = /^(?<nonce>[a-f\d]{16})-(?<sequence>\d+)$/.exec(second!.rev)
  500. expect(firstMatch?.groups).toMatchObject({ sequence: '0' })
  501. expect(secondMatch?.groups).toMatchObject({ nonce: firstMatch?.groups?.nonce, sequence: '1' })
  502. const firstPath = service.clientPath(firstName)!
  503. const firstStat = statSync(firstPath)
  504. expect(service.artifactBaseline(firstName)).toEqual({
  505. path: firstPath,
  506. mtimeMs: firstStat.mtimeMs,
  507. size: firstStat.size,
  508. })
  509. expect(service.artifactBaseline('@fixture/unknown')).toBeUndefined()
  510. })
  511. it('splits startup combos before the map-form URL exceeds 3 KiB', async () => {
  512. const packageNames = Array.from({ length: 48 }, (_, index) => (
  513. `@fixture/combo-url-${String(index).padStart(3, '0')}-${'x'.repeat(40)}`
  514. ))
  515. const sourceMap = JSON.stringify({
  516. version: 3,
  517. names: [],
  518. mappings: 'AAAA',
  519. sources: ['src/index.ts'],
  520. })
  521. for (const packageName of packageNames) {
  522. const clientPath = writePackage(packageName)
  523. mkdirSync(dirname(clientPath), { recursive: true })
  524. writeFileSync(clientPath, 'module.exports = {}\n')
  525. writeFileSync(`${clientPath}.map`, sourceMap)
  526. }
  527. const { service, route } = constructWithRoute(packageNames)
  528. const batches = service.graph().batches.filter(batch => batch.phase === 'application')
  529. expect(batches.length).toBeGreaterThan(1)
  530. expect(batches.flatMap(batch => batch.entries)).toEqual(packageNames)
  531. for (const batch of batches) {
  532. expect(Buffer.byteLength(batch.url)).toBeLessThanOrEqual(3 * 1024)
  533. expect(Buffer.byteLength(mapUrl(batch.url))).toBeLessThanOrEqual(3 * 1024)
  534. expect((await routeRequest(route, batch.url)).status).toBe(200)
  535. expect((await routeRequest(route, mapUrl(batch.url))).status).toBe(200)
  536. }
  537. for (let index = 0; index < batches.length - 1; index += 1) {
  538. const entries = [...batches[index]!.entries, batches[index + 1]!.entries[0]!]
  539. expect(Buffer.byteLength(mapUrl(comboUrl(entries, '0'.repeat(12))))).toBeGreaterThan(3 * 1024)
  540. }
  541. })
  542. it('serves the source map beside a registered client bundle', async () => {
  543. const packageName = '@fixture/source-map'
  544. const clientPath = writePackage(packageName)
  545. mkdirSync(dirname(clientPath), { recursive: true })
  546. writeFileSync(clientPath, 'module.exports = {}\n//# sourceMappingURL=client.js.map')
  547. const map = '{"version":3,"names":[],"mappings":"AAAA","sources":["../../../packages/client/demo/src/index.tsx","https://cdn.example.test/library.js"]}\n'
  548. writeFileSync(`${clientPath}.map`, map)
  549. const { service, route } = constructWithRoute([packageName])
  550. const row = service.graph().entries[0]!
  551. const singleScript = await routeRequest(route, row.url)
  552. expect(singleScript.body.toString('utf8')).toContain(`sourceMappingURL=${mapUrl(row.url)}`)
  553. const singleMap = await routeRequest(route, mapUrl(row.url))
  554. expect(singleMap.status).toBe(200)
  555. expect(singleMap.headers).toEqual({
  556. 'content-type': 'application/json; charset=utf-8',
  557. 'cache-control': 'public, max-age=31536000, immutable',
  558. })
  559. expect(JSON.parse(singleMap.body.toString('utf8'))).toMatchObject({
  560. version: 3,
  561. file: 'client.js',
  562. sections: [{
  563. offset: { line: 0, column: 0 },
  564. map: {
  565. ...(JSON.parse(map) as Record<string, unknown>),
  566. sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'],
  567. },
  568. }],
  569. })
  570. const batch = service.graph().batches[0]!
  571. expect(batch).toMatchObject({ phase: 'application', entries: [packageName] })
  572. const batchScript = await routeRequest(route, batch.url)
  573. expect(batchScript.status).toBe(200)
  574. expect(batchScript.headers?.['cache-control']).toBe('public, max-age=31536000, immutable')
  575. expect(batchScript.body.toString('utf8')).toContain(`//# sourceMappingURL=${mapUrl(batch.url)}`)
  576. expect((await routeRequest(route, batch.url, 'HEAD')).body).toHaveLength(0)
  577. expect((await routeRequest(route, batch.url, 'POST')).status).toBe(405)
  578. const batchMap = await routeRequest(route, mapUrl(batch.url))
  579. const parsedBatchMap = JSON.parse(batchMap.body.toString('utf8')) as unknown
  580. const parsedPluginMap = JSON.parse(map) as Record<string, unknown>
  581. expect(parsedBatchMap).toMatchObject({
  582. version: 3,
  583. file: 'client.js',
  584. sections: [{
  585. offset: { line: 0, column: 0 },
  586. map: {
  587. ...parsedPluginMap,
  588. sources: ['/packages/client/demo/src/index.tsx', 'https://cdn.example.test/library.js'],
  589. },
  590. }],
  591. })
  592. expect((await routeRequest(route, `${row.url}&stale=1`.replace(`rev=${row.rev}`, 'rev=stale'))).status).toBe(404)
  593. writeFileSync(`${clientPath}.map`, '{"version":3,"names":[],"mappings":"AAAA","sources":["src/changed.tsx"]}\n')
  594. const nextRev = service.rebuilt(packageName)
  595. expect(nextRev).not.toBe(row.rev)
  596. const nextRow = service.graph().entries[0]!
  597. expect(nextRow.rev).toBe(nextRev)
  598. const nextMap = await routeRequest(route, mapUrl(nextRow.url))
  599. expect(JSON.parse(nextMap.body.toString('utf8'))).toMatchObject({
  600. sections: [{ map: { sources: ['/plugins/@fixture/source-map/src/changed.tsx'] } }],
  601. })
  602. })
  603. it('applies sourceRoot before relocating absolute-looking section sources', async () => {
  604. const packageName = '@fixture/source-root'
  605. const clientPath = writePackage(packageName)
  606. mkdirSync(dirname(clientPath), { recursive: true })
  607. writeFileSync(clientPath, 'module.exports = {}\n')
  608. writeFileSync(`${clientPath}.map`, JSON.stringify({
  609. version: 3,
  610. names: [],
  611. mappings: 'AAAA',
  612. sourceRoot: '../root',
  613. sources: ['/absolute.ts'],
  614. }))
  615. const { service, route } = constructWithRoute([packageName])
  616. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  617. const map = JSON.parse(response.body.toString('utf8')) as {
  618. sections: { map: { sourceRoot?: string; sources: string[] } }[]
  619. }
  620. expect(map.sections[0]?.map).toMatchObject({
  621. sources: ['/plugins/@fixture/root/absolute.ts'],
  622. })
  623. expect(map.sections[0]?.map).not.toHaveProperty('sourceRoot')
  624. })
  625. it('maps a non-zero second batch section through a standard source-map consumer', async () => {
  626. const firstName = '@fixture/offset-first'
  627. const secondName = '@fixture/offset-second'
  628. const firstPath = writePackage(firstName)
  629. const secondPath = writePackage(secondName)
  630. for (const [path, source] of [
  631. [firstPath, '../../../packages/demo/first.ts'],
  632. [secondPath, '../../../packages/demo/second.ts'],
  633. ] as const) {
  634. mkdirSync(dirname(path), { recursive: true })
  635. writeFileSync(path, 'window.first = true\nwindow.second = true\n')
  636. writeFileSync(`${path}.map`, JSON.stringify({
  637. version: 3,
  638. names: [],
  639. mappings: 'AAAA',
  640. sources: [source],
  641. sourcesContent: ['export {}\n'],
  642. }))
  643. }
  644. const { service, route } = constructWithRoute([firstName, secondName])
  645. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  646. const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters<typeof SourceMap>[0]
  647. const sections = (payload as unknown as {
  648. sections: { offset: { line: number; column: number } }[]
  649. }).sections
  650. expect(sections.map(section => section.offset)).toEqual([
  651. { line: 0, column: 0 },
  652. { line: 3, column: 0 },
  653. ])
  654. const consumer = new SourceMap(payload)
  655. expect(consumer.findEntry(0, 0)).toMatchObject({ originalSource: '/packages/demo/first.ts' })
  656. expect(consumer.findEntry(3, 0)).toMatchObject({ originalSource: '/packages/demo/second.ts' })
  657. })
  658. it('combines a generated-file fallback with a later authored map', async () => {
  659. const unmappedName = '@fixture/unmapped-first'
  660. const mappedName = '@fixture/mapped-second'
  661. const unmappedPath = writePackage(unmappedName)
  662. const mappedPath = writePackage(mappedName)
  663. mkdirSync(dirname(unmappedPath), { recursive: true })
  664. mkdirSync(dirname(mappedPath), { recursive: true })
  665. writeFileSync(unmappedPath, 'window.unmapped = true\n')
  666. writeFileSync(mappedPath, 'window.mapped = true\n')
  667. writeFileSync(`${mappedPath}.map`, JSON.stringify({
  668. version: 3,
  669. names: [],
  670. mappings: 'AAAA',
  671. sources: ['../../../packages/demo/mapped.ts'],
  672. sourcesContent: ['export {}\n'],
  673. }))
  674. const { service, route } = constructWithRoute([unmappedName, mappedName])
  675. const response = await routeRequest(route, mapUrl(service.graph().batches[0]!.url))
  676. const payload = JSON.parse(response.body.toString('utf8')) as ConstructorParameters<typeof SourceMap>[0]
  677. const consumer = new SourceMap(payload)
  678. expect(consumer.findEntry(0, 0)).toMatchObject({
  679. originalSource: `/plugins/${unmappedName}/client.js`,
  680. })
  681. expect(consumer.findEntry(2, 0)).toMatchObject({ originalSource: '/packages/demo/mapped.ts' })
  682. })
  683. })
  684. function emitLoaderEntryChange(context: Context, name: string): void {
  685. context.emit('internal/plugin', {
  686. entry: { options: { name } },
  687. } as unknown as Fiber)
  688. }
  689. describe('shared module declarations', () => {
  690. it('accepts external requests and carries them onto the graph row', () => {
  691. const packageName = '@fixture/shared-declared'
  692. writeBuiltPackage(packageName, { external: ['react'] })
  693. expect(construct([packageName]).graph().entries).toEqual([{
  694. id: packageName,
  695. url: expect.stringContaining(`/plugins/??${packageName}/client.js&rev=`) as unknown as string,
  696. rev: expect.any(String) as unknown as string,
  697. external: ['react'],
  698. }])
  699. })
  700. it('omits external when the package declares no requests', () => {
  701. const packageName = '@fixture/shared-absent'
  702. writeBuiltPackage(packageName, {})
  703. const [row] = construct([packageName]).graph().entries
  704. expect(row).not.toHaveProperty('external')
  705. })
  706. it('rejects a non-array external', () => {
  707. const packageName = '@fixture/external-not-array'
  708. writeBuiltPackage(packageName, { external: 'react' })
  709. expect(() => construct([packageName]))
  710. .toThrow(`client-modules: ${packageName} dsh.client.external must be a string array`)
  711. })
  712. })
  713. describe('module graph order', () => {
  714. const entry = (id: string, fields: Partial<WebBootEntry> = {}): WebBootEntry =>
  715. ({ id, url: comboUrl([id], '0'), rev: '0', ...fields })
  716. const ids = (entries: readonly WebBootEntry[]): string[] => entries.map(row => row.id)
  717. it('places every requested package row before its consumers along a chain', () => {
  718. expect(ids(orderByModuleGraph([
  719. entry('ui', { external: ['slots'] }),
  720. entry('slots', { external: ['render'] }),
  721. entry('render'),
  722. ]))).toEqual(['render', 'slots', 'ui'])
  723. })
  724. it('places a shared package row before both arms of a diamond', () => {
  725. expect(ids(orderByModuleGraph([
  726. entry('app', { external: ['left', 'right'] }),
  727. entry('left', { external: ['vendor'] }),
  728. entry('right', { external: ['vendor'] }),
  729. entry('vendor'),
  730. ]))).toEqual(['vendor', 'left', 'right', 'app'])
  731. })
  732. it('resolves a /client request onto the requested package row', () => {
  733. expect(ids(orderByModuleGraph([
  734. entry('ui', { external: ['runtime/client'] }),
  735. entry('runtime'),
  736. ]))).toEqual(['runtime', 'ui'])
  737. })
  738. it('leaves a request no row answers to the static assembly channel', () => {
  739. expect(ids(orderByModuleGraph([
  740. entry('consumer', { external: ['@deepseek-ai/cordis'] }),
  741. entry('other'),
  742. ]))).toEqual(['consumer', 'other'])
  743. })
  744. it('rejects a cycle and names the packages on it', () => {
  745. expect(() => orderByModuleGraph([
  746. entry('a', { external: ['b'] }),
  747. entry('b', { external: ['a'] }),
  748. ])).toThrow('client-modules: module graph cycle a -> b -> a')
  749. })
  750. it('rejects a row requesting its own package name', () => {
  751. expect(() => orderByModuleGraph([entry('solo', { external: ['solo'] })]))
  752. .toThrow('client-modules: "solo" requests module "solo" that it answers itself')
  753. })
  754. it('composes the served graph in module-graph order', () => {
  755. const consumerName = '@fixture/order-consumer'
  756. const dependencyName = '@fixture/order-dependency'
  757. writeBuiltPackage(consumerName, { external: [dependencyName] })
  758. writeBuiltPackage(dependencyName, {})
  759. expect(ids(construct([consumerName, dependencyName]).graph().entries))
  760. .toEqual([dependencyName, consumerName])
  761. })
  762. it('fails activation loud when scanned packages form a module cycle', () => {
  763. writeBuiltPackage('@fixture/cycle-a', { external: ['@fixture/cycle-b'] })
  764. writeBuiltPackage('@fixture/cycle-b', { external: ['@fixture/cycle-a'] })
  765. expect(() => construct(['@fixture/cycle-a', '@fixture/cycle-b']))
  766. .toThrow('module graph cycle @fixture/cycle-a -> @fixture/cycle-b -> @fixture/cycle-a')
  767. })
  768. })