loader.client.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // @vitest-environment jsdom
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { afterEach, describe, expect, it, vi } from 'vitest'
  4. import {
  5. apply, createClientModuleSystem, parseBootManifest,
  6. type BootModuleRow, type ClientBundleRegistration, type ClientModuleCreateOptions,
  7. type ClientModuleLoader, type ClientModuleLoaderTarget, type DshWindow,
  8. } from '../src/client/index.ts'
  9. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  10. const win = globalThis as DshWindow
  11. const bootstrapExports = { apply, createClientModuleSystem }
  12. type Factory = ClientBundleRegistration['factory']
  13. afterEach(() => {
  14. vi.unstubAllGlobals()
  15. delete win.__ModuleLoader__
  16. for (const el of document.querySelectorAll('style, script')) el.remove()
  17. })
  18. const row = (id: string, fields: Partial<BootModuleRow> = {}): BootModuleRow =>
  19. ({ id, url: `/plugins/${id}/client.js?rev=0`, rev: '0', inject: [], external: [], ...fields })
  20. interface Bench {
  21. loader: ClientModuleLoader
  22. target: ClientModuleLoaderTarget
  23. fetched: string[]
  24. gates: Map<string, () => void>
  25. }
  26. /** Build the page-global facade shape consumed by the module system. */
  27. function registrationTarget(pending: ClientBundleRegistration[] = []): ClientModuleLoaderTarget {
  28. const pendingQueue = [...pending]
  29. const target: ClientModuleLoaderTarget = {
  30. mode: 'queue',
  31. pendingQueue,
  32. load: (registration) => { pendingQueue.push(registration) },
  33. create: options => createClientModuleSystem(target, {
  34. id: MODULES_ID,
  35. exports: bootstrapExports,
  36. }, options),
  37. }
  38. return target
  39. }
  40. /**
  41. * Loader over scripted bundles: load records the row URL, optionally waits on
  42. * a release callback, then registers the scripted factory through the window
  43. * sink (`null` scripts a bundle that never calls load).
  44. */
  45. function bench(
  46. entries: BootModuleRow[],
  47. bundles: Record<string, Factory | null> = {},
  48. opts: {
  49. seed?: Record<string, unknown>
  50. gated?: string[]
  51. pending?: ClientBundleRegistration[]
  52. defaultTransport?: boolean
  53. } = {},
  54. ): Bench {
  55. const fetched: string[] = []
  56. const gates = new Map<string, () => void>()
  57. const target = registrationTarget(opts.pending)
  58. win.__ModuleLoader__ = target
  59. const loadBundle = async (url: string): Promise<void> => {
  60. fetched.push(url)
  61. if (opts.gated?.includes(url) === true) {
  62. await new Promise<void>((resolve) => { gates.set(url, resolve) })
  63. }
  64. const id = /\/plugins\/(.+)\/client\.js/.exec(url)?.[1]
  65. const factory = id === undefined ? undefined : bundles[id]
  66. if (factory == null || id === undefined) return
  67. win.__ModuleLoader__?.load({ id, factory })
  68. }
  69. const loader = target.create({
  70. boot: { rev: 'graph', entries },
  71. staticModules: opts.seed ?? {},
  72. ...(opts.defaultTransport === true ? {} : { loadBundle }),
  73. })
  74. return { loader, target, fetched, gates }
  75. }
  76. describe('Cordis plugin face', () => {
  77. it('rejects activation before the HTML facade creates the module system', () => {
  78. expect(() => { apply(new Context()) }).toThrow('createClientModuleSystem must run before plugin boot')
  79. })
  80. })
  81. describe('lazy CJS arrival', () => {
  82. it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
  83. const b = bench([row('runtime')], {}, {
  84. pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
  85. })
  86. const exports = await b.loader.import('runtime', '', {})
  87. expect((exports as { marker: string }).marker).toBe('preloaded')
  88. expect(b.target.pendingQueue).toEqual([])
  89. expect(b.fetched).toEqual([])
  90. expect(win.__ModuleLoader__).toBe(b.target)
  91. expect(b.target.mode).toBe('live')
  92. })
  93. it('prefetch loads and registers but does not run the factory', async () => {
  94. const ran: string[] = []
  95. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  96. await b.loader.prefetch('a')
  97. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  98. expect(ran).toEqual([])
  99. expect(b.loader.loadCache.has('a')).toBe(false)
  100. })
  101. it('import materializes once and memoizes the exports', async () => {
  102. const ran: string[] = []
  103. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  104. const first = await b.loader.import('a', '', {})
  105. const second = await b.loader.import('a', '', {})
  106. expect(first).toBe(second)
  107. expect((first as { marker: string }).marker).toBe('a')
  108. expect(ran).toEqual(['a'])
  109. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  110. })
  111. it('import without prefetch loads, registers, and materializes in one call', async () => {
  112. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  113. const exports = await b.loader.import('a', '', {})
  114. expect((exports as { marker: string }).marker).toBe('direct')
  115. expect(b.fetched).toHaveLength(1)
  116. })
  117. it('registers declared dynamic requests before materializing their consumer', async () => {
  118. const b = bench([
  119. row('consumer', { external: ['provider/client', 'react'] }),
  120. row('provider'),
  121. ], {
  122. consumer: req => ({ provider: req('provider/client'), react: req('react') }),
  123. provider: () => ({ marker: 'provider' }),
  124. }, { seed: { react: { marker: 'react' } } })
  125. const exports = await b.loader.import('consumer', '', {}) as {
  126. provider: { marker: string }
  127. react: { marker: string }
  128. }
  129. expect(b.fetched).toEqual([
  130. '/plugins/provider/client.js?rev=0',
  131. '/plugins/consumer/client.js?rev=0',
  132. ])
  133. expect(exports.provider.marker).toBe('provider')
  134. expect(exports.react.marker).toBe('react')
  135. })
  136. it('registers injected package factories before materializing a consumer', async () => {
  137. const b = bench([
  138. row('consumer', { inject: ['provider'] }),
  139. row('provider', { inject: ['consumer'] }),
  140. ], {
  141. consumer: req => ({ provider: req('provider/client') }),
  142. provider: () => ({ marker: 'provider' }),
  143. })
  144. const exports = await b.loader.import('consumer', '', {}) as { provider: { marker: string } }
  145. expect(b.fetched).toEqual([
  146. '/plugins/provider/client.js?rev=0',
  147. '/plugins/consumer/client.js?rev=0',
  148. ])
  149. expect(exports.provider.marker).toBe('provider')
  150. })
  151. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  152. const ran: string[] = []
  153. const url = '/plugins/a/client.js?rev=0'
  154. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  155. const first = b.loader.import('a', '', {})
  156. const second = b.loader.import('a', '', {})
  157. const third = b.loader.prefetch('a')
  158. b.gates.get(url)?.()
  159. const [s1, s2] = await Promise.all([first, second, third])
  160. expect(s1).toBe(s2)
  161. expect(b.fetched).toEqual([url])
  162. expect(ran).toEqual(['a'])
  163. })
  164. it('prefetch after registration is a no-op without invalidate', async () => {
  165. const b = bench([row('a')], { a: () => ({}) })
  166. await b.loader.prefetch('a')
  167. await b.loader.prefetch('a')
  168. expect(b.fetched).toHaveLength(1)
  169. })
  170. })
  171. describe('require resolution', () => {
  172. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  173. const order: string[] = []
  174. const b = bench([row('a'), row('b')], {
  175. a: (req) => {
  176. order.push('a')
  177. const dep = req('b/client') as { helper: string }
  178. return { got: dep.helper }
  179. },
  180. b: () => { order.push('b'); return { helper: 'from-b' } },
  181. })
  182. await b.loader.prefetch('a')
  183. await b.loader.prefetch('b')
  184. const exports = await b.loader.import('a', '', {})
  185. expect((exports as { got: string }).got).toBe('from-b')
  186. expect(order).toEqual(['a', 'b'])
  187. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  188. expect(b.loader.loadCache.has('b')).toBe(true)
  189. })
  190. it('require prefers the platform seed word over the module table', async () => {
  191. const react = { marker: 'react' }
  192. const b = bench([row('a')], {
  193. a: req => ({ dep: req('react') }),
  194. }, { seed: { react } })
  195. const exports = await b.loader.import('a', '', {})
  196. expect((exports as { dep: unknown }).dep).toBe(react)
  197. expect(await b.loader.import('react', '', {})).toBe(react)
  198. expect(b.loader.loadCache.has('react')).toBe(false)
  199. })
  200. it('require answers an already-materialized module from the cache', async () => {
  201. let built = 0
  202. const b = bench([row('a'), row('c')], {
  203. a: req => ({ dep: req('c') }),
  204. c: () => { built += 1; return { marker: 'c' } },
  205. })
  206. const c = await b.loader.import('c', '', {})
  207. const a = await b.loader.import('a', '', {})
  208. expect((a as { dep: unknown }).dep).toBe(c)
  209. expect(built).toBe(1)
  210. })
  211. it('a require that misses the module table is loud', async () => {
  212. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  213. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  214. })
  215. it('a require cycle is fatal', async () => {
  216. const b = bench([row('a'), row('b')], {
  217. a: req => ({ dep: req('b') }),
  218. b: req => ({ dep: req('a') }),
  219. })
  220. await b.loader.prefetch('b')
  221. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  222. })
  223. })
  224. describe('bootstrap module', () => {
  225. it('caches the materialized modules exports under the package id and /client alias', async () => {
  226. const b = bench([
  227. row('consumer', { external: [`${MODULES_ID}/client`] }),
  228. row(MODULES_ID),
  229. ], {
  230. consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
  231. })
  232. await b.loader.prefetch(MODULES_ID)
  233. const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
  234. expect(exports.dep).toBe(bootstrapExports)
  235. expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
  236. expect(b.fetched).toEqual(['/plugins/consumer/client.js?rev=0'])
  237. })
  238. it('publishes the same closed-over system when the modules Cordis plugin activates', () => {
  239. const b = bench([])
  240. const ctx = new Context()
  241. apply(ctx)
  242. expect(ctx.modules).toBe(b.loader)
  243. })
  244. it('rejects a second queued registration for the bootstrap id', () => {
  245. expect(() => bench([], {}, {
  246. pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
  247. })).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
  248. })
  249. })
  250. describe('failure modes', () => {
  251. it('duplicate factory registration is loud', () => {
  252. bench([])
  253. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  254. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  255. .toThrow('duplicate factory registration for "x"')
  256. })
  257. it('a bundle that never registers its id is loud', async () => {
  258. const b = bench([row('a')], { a: null })
  259. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  260. })
  261. it('an unknown import specifier is loud', async () => {
  262. const b = bench([])
  263. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  264. })
  265. it('an unknown prefetch id is loud', async () => {
  266. const b = bench([])
  267. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  268. })
  269. it('a duplicate graph entry is loud at construction', () => {
  270. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  271. })
  272. it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
  273. const b = bench([
  274. row('a', { external: ['b'] }),
  275. row('b', { external: ['a'] }),
  276. ])
  277. await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
  278. })
  279. it('double boot is loud', () => {
  280. const b = bench([])
  281. const options: ClientModuleCreateOptions = {
  282. boot: { rev: 'graph', entries: [] },
  283. staticModules: {},
  284. }
  285. expect(() => b.target.create(options)).toThrow('create called after module-system boot')
  286. })
  287. })
  288. describe('boot manifest wire', () => {
  289. it('normalizes absent shared-module fields and carries the declared ones', () => {
  290. const manifest = parseBootManifest({
  291. rev: 'graph',
  292. entries: [
  293. { id: 'a', url: '/plugins/a/client.js', rev: '1', inject: ['b'] },
  294. { id: 'b', url: '/plugins/b/client.js', rev: '2', external: ['react'] },
  295. ],
  296. })
  297. expect(manifest.modules).toEqual([
  298. { id: 'a', url: '/plugins/a/client.js', rev: '1', inject: ['b'], external: [] },
  299. { id: 'b', url: '/plugins/b/client.js', rev: '2', inject: [], external: ['react'] },
  300. ])
  301. })
  302. it('rejects a non-array external', () => {
  303. expect(() => parseBootManifest({
  304. rev: 'graph',
  305. entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
  306. })).toThrow('client-modules: boot manifest entry "a" external must be a string array')
  307. })
  308. })
  309. describe('HMR reset', () => {
  310. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  311. let generation = 0
  312. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  313. const first = await b.loader.import('a', '', {})
  314. b.loader.invalidate('a')
  315. expect(b.loader.loadCache.has('a')).toBe(false)
  316. await b.loader.prefetch('a')
  317. const second = await b.loader.import('a', '', {})
  318. expect(b.fetched).toHaveLength(2)
  319. expect((first as { generation: number }).generation).toBe(1)
  320. expect((second as { generation: number }).generation).toBe(2)
  321. })
  322. })
  323. describe('style claiming', () => {
  324. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  325. const foreign = document.createElement('style')
  326. foreign.setAttribute('data-plugin', 'other')
  327. document.head.appendChild(foreign)
  328. const b = bench([row('a')], {
  329. a: () => {
  330. document.head.appendChild(document.createElement('style'))
  331. const tagged = document.createElement('style')
  332. tagged.setAttribute('data-plugin', 'a')
  333. tagged.setAttribute('data-plugin-css', 'sheet-1')
  334. document.head.appendChild(tagged)
  335. return {}
  336. },
  337. })
  338. await b.loader.import('a', '', {})
  339. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  340. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  341. expect(foreign.getAttribute('data-plugin')).toBe('other')
  342. })
  343. it('materialization without a document skips the style inventory', async () => {
  344. const b = bench([row('a')], { a: () => ({}) })
  345. vi.stubGlobal('document', undefined)
  346. try {
  347. await b.loader.import('a', '', {})
  348. } finally {
  349. vi.unstubAllGlobals()
  350. }
  351. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  352. })
  353. })
  354. describe('default transport seam', () => {
  355. it('loads through an external classic script and removes the settled node', async () => {
  356. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  357. const script = nodes[0]
  358. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  359. expect(script.async).toBe(true)
  360. expect(script.getAttribute('src')).toBe('/plugins/dee/client.js?rev=0')
  361. queueMicrotask(() => {
  362. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  363. script.dispatchEvent(new Event('load'))
  364. })
  365. })
  366. const b = bench([row('dee')], {}, { defaultTransport: true })
  367. const exports = await b.loader.import('dee', '', {})
  368. expect((exports as { marker: string }).marker).toBe('via-script')
  369. expect(append).toHaveBeenCalledOnce()
  370. expect([...document.querySelectorAll('script')]).toEqual([])
  371. })
  372. it('a script load failure is loud and removes the node', async () => {
  373. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  374. const script = nodes[0]
  375. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  376. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  377. })
  378. const b = bench([row('dee')], {}, { defaultTransport: true })
  379. await expect(b.loader.prefetch('dee')).rejects.toThrow(
  380. 'bundle script /plugins/dee/client.js?rev=0 failed to load',
  381. )
  382. expect([...document.querySelectorAll('script')]).toEqual([])
  383. })
  384. })