loader.client.spec.ts 22 KB

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