loader.client.spec.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. // @vitest-environment jsdom
  2. import { removeOwnedStyles } from '../src/client/entry-lifecycle.ts'
  3. import { readRelease } from '../src/client/manifest.ts'
  4. import { Context } from '@deepseek-ai/cordis'
  5. import { afterEach, describe, expect, it, vi } from 'vitest'
  6. import {
  7. apply, createClientModuleSystem, parseBootManifest,
  8. type BootModuleRow, type ClientBundleRegistration, type ClientModuleCreateOptions,
  9. type ClientModuleLoader, type ClientModuleLoaderTarget, type DshWindow,
  10. } from '../src/client/index.ts'
  11. const MODULES_ID = '@deepseek-ai/dsh-client-modules'
  12. // The host composes graph rows and batch descriptors as app-directory-relative
  13. // browser references, so these fixtures carry the same form.
  14. const comboReference = (ids: readonly string[], rev: string): string =>
  15. `plugins/??${ids.map(id => `${id}/client.js`).join(',')}&rev=${rev}`
  16. const chunkReference = (id: string, fileName: string, rev = '0'): string =>
  17. `plugins/${id}/${fileName}?rev=${rev}`
  18. const BOOTSTRAP_URL = comboReference([MODULES_ID], 'bootstrap')
  19. const APPLICATION_URL = comboReference(['a', 'b'], 'application')
  20. const win = globalThis as DshWindow
  21. const bootstrapExports = { apply, createClientModuleSystem }
  22. type Factory = ClientBundleRegistration['factory']
  23. afterEach(() => {
  24. vi.unstubAllGlobals()
  25. delete win.__ModuleLoader__
  26. for (const el of document.querySelectorAll('style, script')) el.remove()
  27. })
  28. const row = (id: string, fields: Partial<BootModuleRow> = {}): BootModuleRow =>
  29. ({
  30. id,
  31. url: comboReference([id], '0'),
  32. initialUrl: id === MODULES_ID ? BOOTSTRAP_URL : APPLICATION_URL,
  33. rev: '0',
  34. inject: [],
  35. external: [],
  36. ...fields,
  37. })
  38. interface Bench {
  39. loader: ClientModuleLoader
  40. target: ClientModuleLoaderTarget
  41. fetched: string[]
  42. gates: Map<string, () => void>
  43. }
  44. /** Build the page-global facade shape consumed by the module system. */
  45. function registrationTarget(pending: ClientBundleRegistration[] = []): ClientModuleLoaderTarget {
  46. const pendingQueue = [...pending]
  47. const target: ClientModuleLoaderTarget = {
  48. mode: 'queue',
  49. pendingQueue,
  50. load: (registration) => { pendingQueue.push(registration) },
  51. create: options => createClientModuleSystem(target, {
  52. id: MODULES_ID,
  53. exports: bootstrapExports,
  54. }, options),
  55. }
  56. return target
  57. }
  58. /**
  59. * Loader over scripted bundles: load records the row URL, optionally waits on
  60. * a release callback, then registers the scripted factory through the window
  61. * sink (`null` scripts a bundle that never calls load).
  62. */
  63. function bench(
  64. entries: BootModuleRow[],
  65. bundles: Record<string, Factory | null> = {},
  66. opts: {
  67. seed?: Record<string, unknown>
  68. gated?: string[]
  69. pending?: ClientBundleRegistration[]
  70. defaultTransport?: boolean
  71. chunks?: Record<string, Factory | null>
  72. /** Remaining transport rejections per URL (the `<script>` error event). */
  73. transportFailures?: Record<string, number>
  74. /** URLs whose script loads but registers only the listed ids (a runtime throw after those registrations). */
  75. registerOnly?: Record<string, string[]>
  76. } = {},
  77. ): Bench {
  78. const fetched: string[] = []
  79. const gates = new Map<string, () => void>()
  80. const target = registrationTarget(opts.pending)
  81. win.__ModuleLoader__ = target
  82. const transportFailures = { ...opts.transportFailures }
  83. const loadBundle = async (url: string): Promise<void> => {
  84. fetched.push(url)
  85. if (opts.gated?.includes(url) === true) {
  86. await new Promise<void>((resolve) => { gates.set(url, resolve) })
  87. }
  88. if ((transportFailures[url] ?? 0) > 0) {
  89. transportFailures[url] = (transportFailures[url] as number) - 1
  90. throw new Error(`client-modules: bundle script ${url} failed to load`)
  91. }
  92. const sibling = /^plugins\/(.+)\/(client\.[A-Za-z0-9][A-Za-z0-9._-]*\.js)\?rev=[^&]+$/.exec(url)
  93. if (sibling !== null) {
  94. const id = sibling[1] as string
  95. const chunk = sibling[2] as string
  96. const factory = opts.chunks?.[`${id}/${chunk}`]
  97. if (factory != null) win.__ModuleLoader__?.load({ id, chunk, factory })
  98. return
  99. }
  100. const batchIds = url === BOOTSTRAP_URL
  101. ? entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
  102. : url === APPLICATION_URL
  103. ? entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
  104. : undefined
  105. const parsed = new URL(url, 'http://dsh.invalid')
  106. const combo = parsed.search.startsWith('??') ? parsed.search.slice(2).split('&', 1)[0] : undefined
  107. const singleId = combo?.split(',').length === 1 && combo.endsWith('/client.js')
  108. ? combo.slice(0, -'/client.js'.length)
  109. : undefined
  110. const only = opts.registerOnly?.[url]
  111. for (const id of batchIds ?? (singleId === undefined ? [] : [singleId])) {
  112. if (only !== undefined && !only.includes(id)) continue
  113. const factory = bundles[id]
  114. if (factory != null) win.__ModuleLoader__?.load({ id, factory })
  115. }
  116. }
  117. const bootstrapEntries = entries.filter(entry => entry.initialUrl === BOOTSTRAP_URL).map(entry => entry.id)
  118. const applicationEntries = entries.filter(entry => entry.initialUrl === APPLICATION_URL).map(entry => entry.id)
  119. const batches = [
  120. ...(bootstrapEntries.length === 0 ? [] : [{
  121. phase: 'bootstrap' as const, url: BOOTSTRAP_URL, rev: 'bootstrap', entries: bootstrapEntries,
  122. }]),
  123. ...(applicationEntries.length === 0 ? [] : [{
  124. phase: 'application' as const, url: APPLICATION_URL, rev: 'application', entries: applicationEntries,
  125. }]),
  126. ]
  127. const loader = target.create({
  128. boot: {
  129. rev: 'graph',
  130. entries: entries.map(({ initialUrl: _initialUrl, inject, external, ...entry }) => ({
  131. ...entry,
  132. ...(inject.length === 0 ? {} : { inject }),
  133. ...(external.length === 0 ? {} : { external }),
  134. })),
  135. batches,
  136. },
  137. staticModules: opts.seed ?? {},
  138. ...(opts.defaultTransport === true ? {} : { loadBundle }),
  139. })
  140. return { loader, target, fetched, gates }
  141. }
  142. describe('Cordis plugin face', () => {
  143. it('rejects a Loader whose internal is absent or not a client module system', () => {
  144. for (const internal of [undefined, { version: 'worker' }]) {
  145. const ctx = new Context()
  146. ctx.provide('loader', { internal } as never)
  147. expect(() => { apply(ctx) }).toThrow('the Loader has no client module system')
  148. }
  149. })
  150. })
  151. describe('lazy CJS arrival', () => {
  152. it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
  153. const b = bench([row('runtime')], {}, {
  154. pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
  155. })
  156. const exports = await b.loader.import('runtime', '', {})
  157. expect((exports as { marker: string }).marker).toBe('preloaded')
  158. expect(b.target.pendingQueue).toEqual([])
  159. expect(b.fetched).toEqual([])
  160. expect(win.__ModuleLoader__).toBe(b.target)
  161. expect(b.target.mode).toBe('live')
  162. })
  163. it('prefetch loads and registers but does not run the factory', async () => {
  164. const ran: string[] = []
  165. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  166. await b.loader.prefetch('a')
  167. expect(b.fetched).toEqual([APPLICATION_URL])
  168. expect(ran).toEqual([])
  169. expect(b.loader.loadCache.has('a')).toBe(false)
  170. })
  171. it('import materializes once and memoizes the exports', async () => {
  172. const ran: string[] = []
  173. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  174. const first = await b.loader.import('a', '', {})
  175. const second = await b.loader.import('a', '', {})
  176. expect(first).toBe(second)
  177. expect((first as { marker: string }).marker).toBe('a')
  178. expect(ran).toEqual(['a'])
  179. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  180. })
  181. it('import without prefetch loads, registers, and materializes in one call', async () => {
  182. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  183. const exports = await b.loader.import('a', '', {})
  184. expect((exports as { marker: string }).marker).toBe('direct')
  185. expect(b.fetched).toHaveLength(1)
  186. })
  187. it('registers declared dynamic requests before materializing their consumer', async () => {
  188. const b = bench([
  189. row('consumer', { external: ['provider/client', 'react'] }),
  190. row('provider'),
  191. ], {
  192. consumer: req => ({ provider: req('provider/client'), react: req('react') }),
  193. provider: () => ({ marker: 'provider' }),
  194. }, { seed: { react: { marker: 'react' } } })
  195. const exports = await b.loader.import('consumer', '', {}) as {
  196. provider: { marker: string }
  197. react: { marker: string }
  198. }
  199. expect(b.fetched).toEqual([APPLICATION_URL])
  200. expect(exports.provider.marker).toBe('provider')
  201. expect(exports.react.marker).toBe('react')
  202. })
  203. it('registers injected package factories before materializing a consumer', async () => {
  204. const b = bench([
  205. row('consumer', { inject: ['provider'] }),
  206. row('provider', { inject: ['consumer'] }),
  207. ], {
  208. consumer: req => ({ provider: req('provider/client') }),
  209. provider: () => ({ marker: 'provider' }),
  210. })
  211. const exports = await b.loader.import('consumer', '', {}) as { provider: { marker: string } }
  212. expect(b.fetched).toEqual([APPLICATION_URL])
  213. expect(exports.provider.marker).toBe('provider')
  214. })
  215. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  216. const ran: string[] = []
  217. const url = APPLICATION_URL
  218. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  219. const first = b.loader.import('a', '', {})
  220. const second = b.loader.import('a', '', {})
  221. const third = b.loader.prefetch('a')
  222. b.gates.get(url)?.()
  223. const [s1, s2] = await Promise.all([first, second, third])
  224. expect(s1).toBe(s2)
  225. expect(b.fetched).toEqual([url])
  226. expect(ran).toEqual(['a'])
  227. })
  228. it('prefetch after registration is a no-op without invalidate', async () => {
  229. const b = bench([row('a')], { a: () => ({}) })
  230. await b.loader.prefetch('a')
  231. await b.loader.prefetch('a')
  232. expect(b.fetched).toHaveLength(1)
  233. })
  234. it('loads a package-local dynamic chunk only when its factory requests it', async () => {
  235. const b = bench([row('a')], {
  236. a: req => ({ load: () => req.async('./client.terminal.js') }),
  237. }, {
  238. chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
  239. })
  240. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<{ marker: string }> }
  241. expect(b.fetched).toEqual([APPLICATION_URL])
  242. const first = await entry.load()
  243. const second = await entry.load()
  244. expect(first).toBe(second)
  245. expect(first).toEqual({ marker: 'terminal' })
  246. expect(b.fetched).toEqual([APPLICATION_URL, chunkReference('a', 'client.terminal.js')])
  247. })
  248. it('loads a package-local chunk with the revision that invalidated its entry', async () => {
  249. const b = bench([row('a')], {
  250. a: req => ({ load: () => req.async('./client.terminal.js') }),
  251. }, {
  252. chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
  253. })
  254. const first = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  255. await first.load()
  256. b.loader.invalidate('a', 'rebuilt')
  257. const second = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  258. await second.load()
  259. expect(b.fetched).toEqual([
  260. APPLICATION_URL,
  261. chunkReference('a', 'client.terminal.js'),
  262. comboReference(['a'], 'rebuilt'),
  263. chunkReference('a', 'client.terminal.js', 'rebuilt'),
  264. ])
  265. })
  266. it('answers a bare asynchronous request through the ordinary module import path', async () => {
  267. const b = bench([row('a'), row('b')], {
  268. a: req => ({ load: () => req.async('b') }),
  269. b: () => ({ marker: 'b' }),
  270. })
  271. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  272. await expect(entry.load()).resolves.toEqual({ marker: 'b' })
  273. })
  274. it('materializes a parser-preloaded chunk without another transport', async () => {
  275. const b = bench([row('a')], {
  276. a: req => ({ load: () => req.async('./client.preloaded.js') }),
  277. }, {
  278. pending: [{ id: 'a', chunk: 'client.preloaded.js', factory: () => ({ marker: 'preloaded' }) }],
  279. })
  280. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  281. await expect(entry.load()).resolves.toEqual({ marker: 'preloaded' })
  282. expect(b.fetched).toEqual([APPLICATION_URL])
  283. })
  284. it('shares one in-flight package-local chunk transport', async () => {
  285. const url = chunkReference('a', 'client.terminal.js')
  286. const b = bench([row('a')], {
  287. a: req => ({ load: () => req.async('./client.terminal.js') }),
  288. }, {
  289. gated: [url],
  290. chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
  291. })
  292. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  293. const first = entry.load()
  294. const second = entry.load()
  295. expect(b.gates.has(url)).toBe(true)
  296. b.gates.get(url)?.()
  297. const [left, right] = await Promise.all([first, second])
  298. expect(left).toBe(right)
  299. expect(b.fetched.filter(fetched => fetched === url)).toHaveLength(1)
  300. })
  301. it('uses a pending replacement revision for a stale entry closure', async () => {
  302. const b = bench([row('a')], {
  303. a: req => ({ load: () => req.async('./client.terminal.js') }),
  304. }, {
  305. chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
  306. })
  307. const stale = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  308. b.loader.invalidate('a', 'rebuilt')
  309. await stale.load()
  310. expect(b.fetched.at(-1)).toBe(chunkReference('a', 'client.terminal.js', 'rebuilt'))
  311. })
  312. it('discards a chunk that arrives after its owner generation was invalidated', async () => {
  313. const staleUrl = chunkReference('a', 'client.terminal.js')
  314. const b = bench([row('a')], {
  315. a: req => ({ load: () => req.async('./client.terminal.js') }),
  316. }, {
  317. gated: [staleUrl],
  318. chunks: { 'a/client.terminal.js': () => ({ marker: 'terminal' }) },
  319. })
  320. const staleEntry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  321. const staleLoad = staleEntry.load()
  322. expect(b.gates.has(staleUrl)).toBe(true)
  323. b.loader.invalidate('a', 'rebuilt')
  324. await b.loader.import('a', '', {})
  325. b.gates.get(staleUrl)?.()
  326. await expect(staleLoad).resolves.toEqual({ marker: 'terminal' })
  327. expect(b.fetched).toContain(chunkReference('a', 'client.terminal.js', 'rebuilt'))
  328. })
  329. })
  330. describe('bundle arrival recovery', () => {
  331. const single = (id: string): string => comboReference([id], '0')
  332. it('retries a batch once after a transport failure and shares the retry across its rows', async () => {
  333. const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
  334. transportFailures: { [APPLICATION_URL]: 1 },
  335. })
  336. const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
  337. expect(a).toEqual({ a: 1 })
  338. expect(c).toEqual({ b: 2 })
  339. expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL])
  340. })
  341. it('falls back to each missing row\'s one-resource URL when the batch keeps failing, without re-fetching the batch per row', async () => {
  342. const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
  343. transportFailures: { [APPLICATION_URL]: 5 },
  344. })
  345. const [a, c] = await Promise.all([b.loader.import('a', '', {}), b.loader.import('b', '', {})])
  346. expect(a).toEqual({ a: 1 })
  347. expect(c).toEqual({ b: 2 })
  348. expect(b.fetched.filter(url => url === APPLICATION_URL)).toHaveLength(2)
  349. expect(b.fetched.slice(2).sort()).toEqual([single('a'), single('b')].sort())
  350. expect(b.loader.importError('a')).toBeUndefined()
  351. })
  352. it('does not re-execute a batch that loaded without registering; the missing row loads alone', async () => {
  353. const b = bench([row('a')], { a: () => ({ a: 1 }) }, { registerOnly: { [APPLICATION_URL]: [] } })
  354. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  355. expect(b.fetched).toEqual([APPLICATION_URL, single('a')])
  356. })
  357. it('after a partially registering batch, loads only the missing row and never duplicates the registered one', async () => {
  358. const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
  359. registerOnly: { [APPLICATION_URL]: ['a'] },
  360. })
  361. expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
  362. expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
  363. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  364. expect(b.fetched).toHaveLength(2)
  365. })
  366. it('never re-executes a batch that already ran, even when its first importer was one of the rows it did register', async () => {
  367. const b = bench([row('a'), row('b')], { a: () => ({ a: 1 }), b: () => ({ b: 2 }) }, {
  368. registerOnly: { [APPLICATION_URL]: ['a'] },
  369. })
  370. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  371. expect(b.fetched).toEqual([APPLICATION_URL])
  372. expect(await b.loader.import('b', '', {})).toEqual({ b: 2 })
  373. expect(b.fetched).toEqual([APPLICATION_URL, single('b')])
  374. })
  375. it('reports every attempt when the one-resource fallback fails too', async () => {
  376. const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
  377. transportFailures: { [APPLICATION_URL]: 2, [single('a')]: 1 },
  378. })
  379. const failure: unknown = await b.loader.import('a', '', {}).then(() => undefined, (error: unknown) => error)
  380. if (!(failure instanceof Error)) throw new Error('import resolved')
  381. expect(failure.message).toContain('could not load "a"')
  382. const batchAttempts = failure.message.split(`${APPLICATION_URL}: client-modules: bundle script`).length - 1
  383. expect(batchAttempts).toBe(2)
  384. expect(failure.message).toContain(`${single('a')}: client-modules: bundle script`)
  385. expect(b.fetched).toEqual([APPLICATION_URL, APPLICATION_URL, single('a')])
  386. })
  387. it('a one-resource URL that fails stays retryable on the next import instead of being remembered as a failed batch', async () => {
  388. const reloadUrl = comboReference(['a'], '1')
  389. const b = bench([row('a')], { a: () => ({ a: 1 }) }, { transportFailures: { [reloadUrl]: 2 } })
  390. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  391. b.loader.invalidate('a', '1')
  392. await expect(b.loader.import('a', '', {})).rejects.toThrow('could not load "a"')
  393. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  394. expect(b.fetched).toEqual([APPLICATION_URL, reloadUrl, reloadUrl, reloadUrl])
  395. })
  396. })
  397. describe('import error record', () => {
  398. it('records the transport failure of a row and clears it once the row imports', async () => {
  399. const b = bench([row('a')], { a: () => ({ a: 1 }) }, {
  400. transportFailures: { [APPLICATION_URL]: 2, [comboReference(['a'], '0')]: 1 },
  401. })
  402. await expect(b.loader.import('a', '', {})).rejects.toThrow()
  403. expect(b.loader.importError('a')?.message).toContain('could not load "a"')
  404. expect(b.loader.importError('a/client')).toBe(b.loader.importError('a'))
  405. expect(await b.loader.import('a', '', {})).toEqual({ a: 1 })
  406. expect(b.loader.importError('a')).toBeUndefined()
  407. })
  408. it('records a factory that throws during materialization, which no arrival record could see', async () => {
  409. const b = bench([row('a')], { a: () => { throw new Error('factory exploded') } })
  410. await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
  411. expect(b.loader.importError('a')?.message).toBe('factory exploded')
  412. })
  413. it('names the failed dependency in the consumer\'s record so a cascade reads as a chain', async () => {
  414. const b = bench([row('dep'), row('consumer', { inject: ['dep'] })], { dep: () => ({}), consumer: () => ({}) }, {
  415. registerOnly: { [APPLICATION_URL]: ['consumer'] },
  416. transportFailures: { [comboReference(['dep'], '0')]: 1 },
  417. })
  418. await expect(b.loader.import('consumer', '', {})).rejects.toThrow(
  419. '"consumer" not loaded because dependency "dep" failed: client-modules: could not load "dep"',
  420. )
  421. expect(b.loader.importError('consumer')?.message).toContain('dependency "dep" failed')
  422. expect(b.loader.importError('dep')).toBeUndefined()
  423. expect(b.loader.importError('consumer')?.cause).toBeInstanceOf(Error)
  424. })
  425. it('records a non-Error thrown by a factory as an Error carrying its text', async () => {
  426. const b = bench([row('a')], { a: () => { throw 'factory rejected a string' } })
  427. await expect(b.loader.import('a', '', {})).rejects.toBe('factory rejected a string')
  428. expect(b.loader.importError('a')).toBeInstanceOf(Error)
  429. expect(b.loader.importError('a')?.message).toBe('factory rejected a string')
  430. })
  431. it('records a prefetch failure and invalidate clears the record', async () => {
  432. const b = bench([row('a')], { a: null })
  433. await expect(b.loader.prefetch('a')).rejects.toThrow('without registering "a"')
  434. expect(b.loader.importError('a')).toBeDefined()
  435. b.loader.invalidate('a')
  436. expect(b.loader.importError('a')).toBeUndefined()
  437. })
  438. it('has no record for a row that never failed or is unknown', () => {
  439. const b = bench([row('a')], { a: () => ({}) })
  440. expect(b.loader.importError('a')).toBeUndefined()
  441. expect(b.loader.importError('nope')).toBeUndefined()
  442. })
  443. })
  444. describe('require resolution', () => {
  445. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  446. const order: string[] = []
  447. const b = bench([row('a'), row('b')], {
  448. a: (req) => {
  449. order.push('a')
  450. const dep = req('b/client') as { helper: string }
  451. return { got: dep.helper }
  452. },
  453. b: () => { order.push('b'); return { helper: 'from-b' } },
  454. })
  455. await b.loader.prefetch('a')
  456. await b.loader.prefetch('b')
  457. const exports = await b.loader.import('a', '', {})
  458. expect((exports as { got: string }).got).toBe('from-b')
  459. expect(order).toEqual(['a', 'b'])
  460. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  461. expect(b.loader.loadCache.has('b')).toBe(true)
  462. })
  463. it('require prefers the platform seed word over the module table', async () => {
  464. const react = { marker: 'react' }
  465. const b = bench([row('a')], {
  466. a: req => ({ dep: req('react') }),
  467. }, { seed: { react } })
  468. const exports = await b.loader.import('a', '', {})
  469. expect((exports as { dep: unknown }).dep).toBe(react)
  470. expect(await b.loader.import('react', '', {})).toBe(react)
  471. expect(b.loader.loadCache.has('react')).toBe(false)
  472. })
  473. it('require answers an already-materialized module from the cache', async () => {
  474. let built = 0
  475. const b = bench([row('a'), row('c')], {
  476. a: req => ({ dep: req('c') }),
  477. c: () => { built += 1; return { marker: 'c' } },
  478. })
  479. const c = await b.loader.import('c', '', {})
  480. const a = await b.loader.import('a', '', {})
  481. expect((a as { dep: unknown }).dep).toBe(c)
  482. expect(built).toBe(1)
  483. })
  484. it('a require that misses the module table is loud', async () => {
  485. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  486. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  487. })
  488. it('a require cycle is fatal', async () => {
  489. const b = bench([row('a'), row('b')], {
  490. a: req => ({ dep: req('b') }),
  491. b: req => ({ dep: req('a') }),
  492. })
  493. await b.loader.prefetch('b')
  494. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  495. })
  496. })
  497. describe('bootstrap module', () => {
  498. it('caches the materialized modules exports under the package id and /client alias', async () => {
  499. const b = bench([
  500. row('consumer', { external: [`${MODULES_ID}/client`] }),
  501. row(MODULES_ID),
  502. ], {
  503. consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
  504. })
  505. await b.loader.prefetch(MODULES_ID)
  506. const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
  507. expect(exports.dep).toBe(bootstrapExports)
  508. expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
  509. expect(b.fetched).toEqual([APPLICATION_URL])
  510. })
  511. it('publishes the module system attached to its own Loader', () => {
  512. const a = bench([])
  513. const b = bench([])
  514. const ctxA = new Context()
  515. const ctxB = new Context()
  516. ctxA.reflect.provide('loader', { internal: a.loader })
  517. ctxB.reflect.provide('loader', { internal: b.loader })
  518. apply(ctxA)
  519. apply(ctxB)
  520. expect(ctxA.modules).toBe(a.loader)
  521. expect(ctxB.modules).toBe(b.loader)
  522. })
  523. it('rejects a second queued registration for the bootstrap id', () => {
  524. expect(() => bench([], {}, {
  525. pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
  526. })).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
  527. })
  528. })
  529. describe('failure modes', () => {
  530. it('duplicate factory registration is loud', () => {
  531. bench([])
  532. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  533. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  534. .toThrow('duplicate factory registration for "x"')
  535. })
  536. it('rejects malformed and duplicate chunk registrations', () => {
  537. const b = bench([])
  538. expect(() => { b.target.load({ id: 'a', chunk: '../bad.js', factory: () => ({}) }) })
  539. .toThrow('invalid package-local chunk "../bad.js"')
  540. b.target.load({ id: 'a', chunk: 'client.terminal.js', factory: () => ({}) })
  541. expect(() => { b.target.load({ id: 'a', chunk: 'client.terminal.js', factory: () => ({}) }) })
  542. .toThrow('duplicate factory registration for "a/client.terminal.js"')
  543. })
  544. it('rejects malformed relative chunk requests', async () => {
  545. const b = bench([row('a')], {
  546. a: req => ({ load: () => req.async('./terminal.js') }),
  547. })
  548. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  549. await expect(entry.load()).rejects.toThrow('invalid relative chunk request "./terminal.js"')
  550. })
  551. it('rejects a chunk request from a manually registered owner outside the boot graph', async () => {
  552. const b = bench([])
  553. b.target.load({
  554. id: 'orphan',
  555. factory: req => ({ load: () => req.async('./client.terminal.js') }),
  556. })
  557. const entry = await b.loader.import('orphan', '', {}) as { load: () => Promise<unknown> }
  558. await expect(entry.load()).rejects.toThrow('chunk owner "orphan" is not a boot graph entry')
  559. })
  560. it('rejects a graph row whose one-resource URL cannot address sibling chunks', async () => {
  561. const b = bench([row('a', { url: 'plugins/a/client.js?rev=0' })], {
  562. a: req => ({ load: () => req.async('./client.terminal.js') }),
  563. })
  564. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  565. await expect(entry.load()).rejects.toThrow('cannot resolve chunk "client.terminal.js"')
  566. })
  567. it('rejects a chunk script that does not register its generated id', async () => {
  568. const b = bench([row('a')], {
  569. a: req => ({ load: () => req.async('./client.missing.js') }),
  570. })
  571. const entry = await b.loader.import('a', '', {}) as { load: () => Promise<unknown> }
  572. await expect(entry.load()).rejects.toThrow('loaded without registering "a/client.missing.js"')
  573. })
  574. it('a bundle that never registers its id is loud', async () => {
  575. const b = bench([row('a')], { a: null })
  576. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  577. })
  578. it('an unknown import specifier is loud', async () => {
  579. const b = bench([])
  580. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  581. })
  582. it('an unknown prefetch id is loud', async () => {
  583. const b = bench([])
  584. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  585. })
  586. it('a duplicate graph entry is loud at construction', () => {
  587. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  588. })
  589. it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
  590. const b = bench([
  591. row('a', { external: ['b'] }),
  592. row('b', { external: ['a'] }),
  593. ])
  594. await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
  595. })
  596. it('double boot is loud', () => {
  597. const b = bench([])
  598. const options: ClientModuleCreateOptions = {
  599. boot: { rev: 'graph', entries: [], batches: [] },
  600. staticModules: {},
  601. }
  602. expect(() => b.target.create(options)).toThrow('create called after module-system boot')
  603. })
  604. })
  605. describe('boot manifest wire', () => {
  606. it('normalizes absent shared-module fields and carries the declared ones', () => {
  607. const manifest = parseBootManifest({
  608. rev: 'graph',
  609. entries: [
  610. { id: 'a', url: 'plugins/a/client.js', rev: '1', inject: ['b'] },
  611. { id: 'b', url: 'plugins/b/client.js', rev: '2', external: ['react'] },
  612. ],
  613. batches: [{ phase: 'application', url: 'batch.js', rev: 'batch', entries: ['a', 'b'] }],
  614. })
  615. expect(manifest.modules).toEqual([
  616. { id: 'a', url: 'plugins/a/client.js', initialUrl: 'batch.js', rev: '1', inject: ['b'], external: [] },
  617. { id: 'b', url: 'plugins/b/client.js', initialUrl: 'batch.js', rev: '2', inject: [], external: ['react'] },
  618. ])
  619. })
  620. it('rejects a non-array external', () => {
  621. expect(() => parseBootManifest({
  622. rev: 'graph',
  623. entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
  624. batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a'] }],
  625. })).toThrow('client-modules: boot manifest entry "a" external must be a string array')
  626. })
  627. it('requires the batch table', () => {
  628. expect(() => parseBootManifest({ rev: 'graph', entries: [] }))
  629. .toThrow('client-modules: boot manifest batches must be an array')
  630. })
  631. it('carries an optional Host release and rejects a malformed one', () => {
  632. const wire = { rev: 'graph', entries: [], batches: [] }
  633. expect(parseBootManifest(wire)).not.toHaveProperty('release')
  634. expect(parseBootManifest({ ...wire, release: { version: '1.0.0' } }).release).toEqual({ version: '1.0.0' })
  635. // Members outside the identity are dropped so equality compares only version and commit.
  636. expect(parseBootManifest({ ...wire, release: { version: '1.0.0', commit: 'abc1234', label: 'x' } }).release)
  637. .toEqual({ version: '1.0.0', commit: 'abc1234' })
  638. for (const release of ['1.0.0', null, {}, { version: 1 }, { version: '1.0.0', commit: 7 }]) {
  639. expect(() => parseBootManifest({ ...wire, release }))
  640. .toThrow('client-modules: boot manifest release must carry a string version and an optional string commit')
  641. // Release comparison reads no further than the release and reports an unreadable one as absent.
  642. expect(readRelease({ release })).toBeUndefined()
  643. }
  644. expect(readRelease({ release: { version: '1.0.0', commit: 'abc1234', label: 'x' }, entries: 'another format' }))
  645. .toEqual({ version: '1.0.0', commit: 'abc1234' })
  646. expect(readRelease(null)).toBeUndefined()
  647. })
  648. it('rejects malformed batch phases', () => {
  649. const entry = { id: 'a', url: '/a.js', rev: '1' }
  650. expect(() => parseBootManifest({ rev: 'graph', entries: [entry], batches: [null] }))
  651. .toThrow('client-modules: boot manifest batch is not an object')
  652. expect(() => parseBootManifest({
  653. rev: 'graph', entries: [entry], batches: [{ phase: 'idle', url: '/b.js', rev: 'b', entries: ['a'] }],
  654. })).toThrow('boot manifest batch phase must be "bootstrap" or "application"')
  655. })
  656. it('rejects duplicate batch URLs', () => {
  657. expect(() => parseBootManifest({
  658. rev: 'graph',
  659. entries: [
  660. { id: 'a', url: '/a.js', rev: '1' },
  661. { id: 'b', url: '/b.js', rev: '2' },
  662. ],
  663. batches: [
  664. { phase: 'application', url: '/combo.js', rev: '1', entries: ['a'] },
  665. { phase: 'application', url: '/combo.js', rev: '2', entries: ['b'] },
  666. ],
  667. })).toThrow('boot manifest carries duplicate batch URL "/combo.js"')
  668. })
  669. it('allows several batches in one scheduling phase', () => {
  670. const manifest = parseBootManifest({
  671. rev: 'graph',
  672. entries: [
  673. { id: 'a', url: '/a.js', rev: '1' },
  674. { id: 'b', url: '/b.js', rev: '2' },
  675. ],
  676. batches: [
  677. { phase: 'application', url: '/b.js', rev: '1', entries: ['a'] },
  678. { phase: 'application', url: '/c.js', rev: '2', entries: ['b'] },
  679. ],
  680. })
  681. expect(manifest.modules.map(row => row.initialUrl)).toEqual(['/b.js', '/c.js'])
  682. })
  683. it('requires complete batch fields and non-empty entries', () => {
  684. const entry = { id: 'a', url: '/a.js', rev: '1' }
  685. expect(() => parseBootManifest({
  686. rev: 'graph', entries: [entry], batches: [{ phase: 'application', entries: ['a'] }],
  687. })).toThrow('boot manifest application batch must carry string url/rev')
  688. expect(() => parseBootManifest({
  689. rev: 'graph', entries: [entry], batches: [{ phase: 'application', url: '/b.js', rev: 'b', entries: [] }],
  690. })).toThrow('boot manifest application batch entries must be a non-empty string array')
  691. })
  692. it('requires a one-to-one batch assignment over graph entries', () => {
  693. const entries = [
  694. { id: 'a', url: '/a.js', rev: '1' },
  695. { id: 'b', url: '/b.js', rev: '2' },
  696. ]
  697. expect(() => parseBootManifest({
  698. rev: 'graph',
  699. entries,
  700. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['ghost'] }],
  701. })).toThrow('boot manifest application batch names unknown entry "ghost"')
  702. expect(() => parseBootManifest({
  703. rev: 'graph',
  704. entries,
  705. batches: [
  706. { phase: 'bootstrap', url: '/boot.js', rev: 'boot', entries: ['a'] },
  707. { phase: 'application', url: '/batch.js', rev: 'app', entries: ['a', 'b'] },
  708. ],
  709. })).toThrow('boot manifest entry "a" belongs to more than one batch')
  710. expect(() => parseBootManifest({
  711. rev: 'graph',
  712. entries,
  713. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['a'] }],
  714. })).toThrow('boot manifest entry "b" belongs to no initial-load batch')
  715. })
  716. })
  717. describe('HMR reset', () => {
  718. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  719. let generation = 0
  720. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  721. const first = await b.loader.import('a', '', {})
  722. b.loader.invalidate('a', '1')
  723. expect(b.loader.loadCache.has('a')).toBe(false)
  724. await b.loader.prefetch('a')
  725. const second = await b.loader.import('a', '', {})
  726. expect(b.fetched).toEqual([APPLICATION_URL, comboReference(['a'], '1')])
  727. expect((first as { generation: number }).generation).toBe(1)
  728. expect((second as { generation: number }).generation).toBe(2)
  729. })
  730. it('preserves an absolute combo endpoint when applying the rebuilt revision', async () => {
  731. const b = bench([
  732. row('a', { url: 'https://plugins.example.test/plugins/??a/client.js&rev=0' }),
  733. ], { a: () => ({}) })
  734. await b.loader.import('a', '', {})
  735. b.loader.invalidate('a', 'next')
  736. await b.loader.prefetch('a')
  737. expect(b.fetched.at(-1)).toBe('https://plugins.example.test/plugins/??a/client.js&rev=next')
  738. })
  739. it('preserves a protocol-relative combo endpoint when applying the rebuilt revision', async () => {
  740. const b = bench([
  741. row('a', { url: '//plugins.example.test/plugins/??a/client.js&rev=0' }),
  742. ], { a: () => ({}) })
  743. await b.loader.import('a', '', {})
  744. b.loader.invalidate('a', 'next')
  745. await b.loader.prefetch('a')
  746. expect(b.fetched.at(-1)).toBe('//plugins.example.test/plugins/??a/client.js&rev=next')
  747. })
  748. it('uses the current plugin revision when a graph-row invalidation omits an override', async () => {
  749. const b = bench([row('a')], { a: () => ({}) })
  750. await b.loader.import('a', '', {})
  751. b.loader.invalidate('a')
  752. await b.loader.prefetch('a')
  753. expect(b.fetched).toEqual([APPLICATION_URL, comboReference(['a'], '0')])
  754. })
  755. })
  756. describe('style claiming', () => {
  757. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  758. const foreign = document.createElement('style')
  759. foreign.setAttribute('data-plugin', 'other')
  760. document.head.appendChild(foreign)
  761. const b = bench([row('a')], {
  762. a: () => {
  763. document.head.appendChild(document.createElement('style'))
  764. const tagged = document.createElement('style')
  765. tagged.setAttribute('data-plugin', 'a')
  766. tagged.setAttribute('data-plugin-css', 'sheet-1')
  767. document.head.appendChild(tagged)
  768. return {}
  769. },
  770. })
  771. await b.loader.import('a', '', {})
  772. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  773. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  774. expect(foreign.getAttribute('data-plugin')).toBe('other')
  775. })
  776. it('leaves untagged style tags inserted before materialization unclaimed', async () => {
  777. const earlier = document.createElement('style')
  778. document.head.appendChild(earlier)
  779. const b = bench([row('a')], { a: () => ({}) })
  780. await b.loader.import('a', '', {})
  781. removeOwnedStyles('a')
  782. expect(earlier.isConnected).toBe(true)
  783. expect(earlier.hasAttribute('data-plugin')).toBe(false)
  784. })
  785. it('assigns an untagged style to the factory that inserted it before a nested require', async () => {
  786. const outer = document.createElement('style')
  787. const b = bench([row('b'), row('a', { external: ['b'] })], {
  788. a: (require) => {
  789. document.head.appendChild(outer)
  790. require('b')
  791. return {}
  792. },
  793. b: () => ({}),
  794. })
  795. await b.loader.import('a', '', {})
  796. expect(outer.getAttribute('data-plugin')).toBe('a')
  797. })
  798. it('removes untagged styles inserted by a factory that throws', async () => {
  799. const leaked = document.createElement('style')
  800. const b = bench([row('a')], { a: () => { document.head.appendChild(leaked); throw new Error('factory exploded') } })
  801. await expect(b.loader.import('a', '', {})).rejects.toThrow('factory exploded')
  802. expect(leaked.isConnected).toBe(false)
  803. })
  804. it('materialization without a document skips the style inventory', async () => {
  805. const b = bench([row('a')], { a: () => ({}) })
  806. vi.stubGlobal('document', undefined)
  807. try {
  808. await b.loader.import('a', '', {})
  809. removeOwnedStyles('a')
  810. } finally {
  811. vi.unstubAllGlobals()
  812. }
  813. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  814. })
  815. })
  816. describe('default transport seam', () => {
  817. it('loads through an external classic script and removes the settled node', async () => {
  818. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  819. const script = nodes[0]
  820. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  821. expect(script.async).toBe(true)
  822. expect(script.getAttribute('src')).toBe(APPLICATION_URL)
  823. queueMicrotask(() => {
  824. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  825. script.dispatchEvent(new Event('load'))
  826. })
  827. })
  828. const b = bench([row('dee')], {}, { defaultTransport: true })
  829. const exports = await b.loader.import('dee', '', {})
  830. expect((exports as { marker: string }).marker).toBe('via-script')
  831. expect(append).toHaveBeenCalledOnce()
  832. expect([...document.querySelectorAll('script')]).toEqual([])
  833. })
  834. it('a script load failure is loud and removes the node', async () => {
  835. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  836. const script = nodes[0]
  837. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  838. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  839. })
  840. const b = bench([row('dee')], {}, { defaultTransport: true })
  841. await expect(b.loader.prefetch('dee')).rejects.toThrow(
  842. `bundle script ${APPLICATION_URL} failed to load`,
  843. )
  844. expect([...document.querySelectorAll('script')]).toEqual([])
  845. })
  846. })
  847. it('rejects invalid revision URLs and keeps bootstrap exports pinned under invalidation', () => {
  848. const b = bench([row(MODULES_ID), row('a', { url: '/unrevisioned' })])
  849. b.loader.invalidate(MODULES_ID)
  850. expect(b.loader.loadCache.get(MODULES_ID)?.exports).toBe(bootstrapExports)
  851. expect(() =>{ b.loader.invalidate('a', 'next') }).toThrow('has no revision')
  852. })
  853. it('prefetch skips platform requests, cached dependencies and absent optional inject rows', async () => {
  854. const b = bench([
  855. row('a'),
  856. row('b', { external: ['platform', 'a/client'], inject: ['missing'] }),
  857. ], { a: () => ({}), b: () => ({}) }, { seed: { platform: {} } })
  858. await b.loader.import('a', '', {})
  859. await b.loader.import('b', '', {})
  860. expect(b.fetched).toEqual([APPLICATION_URL])
  861. })
  862. it('rejects a wire request with no dynamic row or platform supplier at materialization', async () => {
  863. const b = bench([row('a', { external: ['missing'] })], { a: require => ({ value: require('missing') }) })
  864. await expect(b.loader.import('a', '', {})).rejects.toThrow('missed the module table')
  865. })