loader.client.spec.ts 21 KB

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