loader.client.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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 a Loader whose internal is absent or not a client module system', () => {
  118. for (const internal of [undefined, { version: 'worker' }]) {
  119. const ctx = new Context()
  120. ctx.provide('loader', { internal } as never)
  121. expect(() => { apply(ctx) }).toThrow('the Loader has no client module system')
  122. }
  123. })
  124. })
  125. describe('lazy CJS arrival', () => {
  126. it('drains registrations queued by parser-blocking preload scripts into the same live facade', async () => {
  127. const b = bench([row('runtime')], {}, {
  128. pending: [{ id: 'runtime', factory: () => ({ marker: 'preloaded' }) }],
  129. })
  130. const exports = await b.loader.import('runtime', '', {})
  131. expect((exports as { marker: string }).marker).toBe('preloaded')
  132. expect(b.target.pendingQueue).toEqual([])
  133. expect(b.fetched).toEqual([])
  134. expect(win.__ModuleLoader__).toBe(b.target)
  135. expect(b.target.mode).toBe('live')
  136. })
  137. it('prefetch loads and registers but does not run the factory', async () => {
  138. const ran: string[] = []
  139. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  140. await b.loader.prefetch('a')
  141. expect(b.fetched).toEqual([APPLICATION_URL])
  142. expect(ran).toEqual([])
  143. expect(b.loader.loadCache.has('a')).toBe(false)
  144. })
  145. it('import materializes once and memoizes the exports', async () => {
  146. const ran: string[] = []
  147. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  148. const first = await b.loader.import('a', '', {})
  149. const second = await b.loader.import('a', '', {})
  150. expect(first).toBe(second)
  151. expect((first as { marker: string }).marker).toBe('a')
  152. expect(ran).toEqual(['a'])
  153. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  154. })
  155. it('import without prefetch loads, registers, and materializes in one call', async () => {
  156. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  157. const exports = await b.loader.import('a', '', {})
  158. expect((exports as { marker: string }).marker).toBe('direct')
  159. expect(b.fetched).toHaveLength(1)
  160. })
  161. it('registers declared dynamic requests before materializing their consumer', async () => {
  162. const b = bench([
  163. row('consumer', { external: ['provider/client', 'react'] }),
  164. row('provider'),
  165. ], {
  166. consumer: req => ({ provider: req('provider/client'), react: req('react') }),
  167. provider: () => ({ marker: 'provider' }),
  168. }, { seed: { react: { marker: 'react' } } })
  169. const exports = await b.loader.import('consumer', '', {}) as {
  170. provider: { marker: string }
  171. react: { marker: string }
  172. }
  173. expect(b.fetched).toEqual([APPLICATION_URL])
  174. expect(exports.provider.marker).toBe('provider')
  175. expect(exports.react.marker).toBe('react')
  176. })
  177. it('registers injected package factories before materializing a consumer', async () => {
  178. const b = bench([
  179. row('consumer', { inject: ['provider'] }),
  180. row('provider', { inject: ['consumer'] }),
  181. ], {
  182. consumer: req => ({ provider: req('provider/client') }),
  183. provider: () => ({ marker: 'provider' }),
  184. })
  185. const exports = await b.loader.import('consumer', '', {}) as { provider: { marker: string } }
  186. expect(b.fetched).toEqual([APPLICATION_URL])
  187. expect(exports.provider.marker).toBe('provider')
  188. })
  189. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  190. const ran: string[] = []
  191. const url = APPLICATION_URL
  192. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  193. const first = b.loader.import('a', '', {})
  194. const second = b.loader.import('a', '', {})
  195. const third = b.loader.prefetch('a')
  196. b.gates.get(url)?.()
  197. const [s1, s2] = await Promise.all([first, second, third])
  198. expect(s1).toBe(s2)
  199. expect(b.fetched).toEqual([url])
  200. expect(ran).toEqual(['a'])
  201. })
  202. it('prefetch after registration is a no-op without invalidate', async () => {
  203. const b = bench([row('a')], { a: () => ({}) })
  204. await b.loader.prefetch('a')
  205. await b.loader.prefetch('a')
  206. expect(b.fetched).toHaveLength(1)
  207. })
  208. })
  209. describe('require resolution', () => {
  210. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  211. const order: string[] = []
  212. const b = bench([row('a'), row('b')], {
  213. a: (req) => {
  214. order.push('a')
  215. const dep = req('b/client') as { helper: string }
  216. return { got: dep.helper }
  217. },
  218. b: () => { order.push('b'); return { helper: 'from-b' } },
  219. })
  220. await b.loader.prefetch('a')
  221. await b.loader.prefetch('b')
  222. const exports = await b.loader.import('a', '', {})
  223. expect((exports as { got: string }).got).toBe('from-b')
  224. expect(order).toEqual(['a', 'b'])
  225. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  226. expect(b.loader.loadCache.has('b')).toBe(true)
  227. })
  228. it('require prefers the platform seed word over the module table', async () => {
  229. const react = { marker: 'react' }
  230. const b = bench([row('a')], {
  231. a: req => ({ dep: req('react') }),
  232. }, { seed: { react } })
  233. const exports = await b.loader.import('a', '', {})
  234. expect((exports as { dep: unknown }).dep).toBe(react)
  235. expect(await b.loader.import('react', '', {})).toBe(react)
  236. expect(b.loader.loadCache.has('react')).toBe(false)
  237. })
  238. it('require answers an already-materialized module from the cache', async () => {
  239. let built = 0
  240. const b = bench([row('a'), row('c')], {
  241. a: req => ({ dep: req('c') }),
  242. c: () => { built += 1; return { marker: 'c' } },
  243. })
  244. const c = await b.loader.import('c', '', {})
  245. const a = await b.loader.import('a', '', {})
  246. expect((a as { dep: unknown }).dep).toBe(c)
  247. expect(built).toBe(1)
  248. })
  249. it('a require that misses the module table is loud', async () => {
  250. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  251. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  252. })
  253. it('a require cycle is fatal', async () => {
  254. const b = bench([row('a'), row('b')], {
  255. a: req => ({ dep: req('b') }),
  256. b: req => ({ dep: req('a') }),
  257. })
  258. await b.loader.prefetch('b')
  259. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  260. })
  261. })
  262. describe('bootstrap module', () => {
  263. it('caches the materialized modules exports under the package id and /client alias', async () => {
  264. const b = bench([
  265. row('consumer', { external: [`${MODULES_ID}/client`] }),
  266. row(MODULES_ID),
  267. ], {
  268. consumer: req => ({ dep: req(`${MODULES_ID}/client`) }),
  269. })
  270. await b.loader.prefetch(MODULES_ID)
  271. const exports = await b.loader.import('consumer', '', {}) as { dep: unknown }
  272. expect(exports.dep).toBe(bootstrapExports)
  273. expect(await b.loader.import(`${MODULES_ID}/client`, '', {})).toBe(bootstrapExports)
  274. expect(b.fetched).toEqual([APPLICATION_URL])
  275. })
  276. it('publishes the module system attached to its own Loader', () => {
  277. const a = bench([])
  278. const b = bench([])
  279. const ctxA = new Context()
  280. const ctxB = new Context()
  281. ctxA.reflect.provide('loader', { internal: a.loader })
  282. ctxB.reflect.provide('loader', { internal: b.loader })
  283. apply(ctxA)
  284. apply(ctxB)
  285. expect(ctxA.modules).toBe(a.loader)
  286. expect(ctxB.modules).toBe(b.loader)
  287. })
  288. it('rejects a second queued registration for the bootstrap id', () => {
  289. expect(() => bench([], {}, {
  290. pending: [{ id: `${MODULES_ID}/client`, factory: () => ({}) }],
  291. })).toThrow(`duplicate factory registration for "${MODULES_ID}/client"`)
  292. })
  293. })
  294. describe('failure modes', () => {
  295. it('duplicate factory registration is loud', () => {
  296. bench([])
  297. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  298. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  299. .toThrow('duplicate factory registration for "x"')
  300. })
  301. it('a bundle that never registers its id is loud', async () => {
  302. const b = bench([row('a')], { a: null })
  303. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  304. })
  305. it('an unknown import specifier is loud', async () => {
  306. const b = bench([])
  307. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  308. })
  309. it('an unknown prefetch id is loud', async () => {
  310. const b = bench([])
  311. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  312. })
  313. it('a duplicate graph entry is loud at construction', () => {
  314. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  315. })
  316. it('a module arrival cycle is loud even if a malformed host graph reaches the browser', async () => {
  317. const b = bench([
  318. row('a', { external: ['b'] }),
  319. row('b', { external: ['a'] }),
  320. ])
  321. await expect(b.loader.prefetch('a')).rejects.toThrow('module arrival cycle a -> b -> a')
  322. })
  323. it('double boot is loud', () => {
  324. const b = bench([])
  325. const options: ClientModuleCreateOptions = {
  326. boot: { rev: 'graph', entries: [], batches: [] },
  327. staticModules: {},
  328. }
  329. expect(() => b.target.create(options)).toThrow('create called after module-system boot')
  330. })
  331. })
  332. describe('boot manifest wire', () => {
  333. it('normalizes absent shared-module fields and carries the declared ones', () => {
  334. const manifest = parseBootManifest({
  335. rev: 'graph',
  336. entries: [
  337. { id: 'a', url: '/plugins/a/client.js', rev: '1', inject: ['b'] },
  338. { id: 'b', url: '/plugins/b/client.js', rev: '2', external: ['react'] },
  339. ],
  340. batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a', 'b'] }],
  341. })
  342. expect(manifest.modules).toEqual([
  343. { id: 'a', url: '/plugins/a/client.js', initialUrl: '/batch.js', rev: '1', inject: ['b'], external: [] },
  344. { id: 'b', url: '/plugins/b/client.js', initialUrl: '/batch.js', rev: '2', inject: [], external: ['react'] },
  345. ])
  346. })
  347. it('rejects a non-array external', () => {
  348. expect(() => parseBootManifest({
  349. rev: 'graph',
  350. entries: [{ id: 'a', url: '/a', rev: '1', external: 'react' }],
  351. batches: [{ phase: 'application', url: '/batch.js', rev: 'batch', entries: ['a'] }],
  352. })).toThrow('client-modules: boot manifest entry "a" external must be a string array')
  353. })
  354. it('requires the batch table', () => {
  355. expect(() => parseBootManifest({ rev: 'graph', entries: [] }))
  356. .toThrow('client-modules: boot manifest batches must be an array')
  357. })
  358. it('rejects malformed batch phases', () => {
  359. const entry = { id: 'a', url: '/a.js', rev: '1' }
  360. expect(() => parseBootManifest({ rev: 'graph', entries: [entry], batches: [null] }))
  361. .toThrow('client-modules: boot manifest batch is not an object')
  362. expect(() => parseBootManifest({
  363. rev: 'graph', entries: [entry], batches: [{ phase: 'idle', url: '/b.js', rev: 'b', entries: ['a'] }],
  364. })).toThrow('boot manifest batch phase must be "bootstrap" or "application"')
  365. })
  366. it('rejects duplicate batch URLs', () => {
  367. expect(() => parseBootManifest({
  368. rev: 'graph',
  369. entries: [
  370. { id: 'a', url: '/a.js', rev: '1' },
  371. { id: 'b', url: '/b.js', rev: '2' },
  372. ],
  373. batches: [
  374. { phase: 'application', url: '/combo.js', rev: '1', entries: ['a'] },
  375. { phase: 'application', url: '/combo.js', rev: '2', entries: ['b'] },
  376. ],
  377. })).toThrow('boot manifest carries duplicate batch URL "/combo.js"')
  378. })
  379. it('allows several batches in one scheduling phase', () => {
  380. const manifest = parseBootManifest({
  381. rev: 'graph',
  382. entries: [
  383. { id: 'a', url: '/a.js', rev: '1' },
  384. { id: 'b', url: '/b.js', rev: '2' },
  385. ],
  386. batches: [
  387. { phase: 'application', url: '/b.js', rev: '1', entries: ['a'] },
  388. { phase: 'application', url: '/c.js', rev: '2', entries: ['b'] },
  389. ],
  390. })
  391. expect(manifest.modules.map(row => row.initialUrl)).toEqual(['/b.js', '/c.js'])
  392. })
  393. it('requires complete batch fields and non-empty entries', () => {
  394. const entry = { id: 'a', url: '/a.js', rev: '1' }
  395. expect(() => parseBootManifest({
  396. rev: 'graph', entries: [entry], batches: [{ phase: 'application', entries: ['a'] }],
  397. })).toThrow('boot manifest application batch must carry string url/rev')
  398. expect(() => parseBootManifest({
  399. rev: 'graph', entries: [entry], batches: [{ phase: 'application', url: '/b.js', rev: 'b', entries: [] }],
  400. })).toThrow('boot manifest application batch entries must be a non-empty string array')
  401. })
  402. it('requires a one-to-one batch assignment over graph entries', () => {
  403. const entries = [
  404. { id: 'a', url: '/a.js', rev: '1' },
  405. { id: 'b', url: '/b.js', rev: '2' },
  406. ]
  407. expect(() => parseBootManifest({
  408. rev: 'graph',
  409. entries,
  410. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['ghost'] }],
  411. })).toThrow('boot manifest application batch names unknown entry "ghost"')
  412. expect(() => parseBootManifest({
  413. rev: 'graph',
  414. entries,
  415. batches: [
  416. { phase: 'bootstrap', url: '/boot.js', rev: 'boot', entries: ['a'] },
  417. { phase: 'application', url: '/batch.js', rev: 'app', entries: ['a', 'b'] },
  418. ],
  419. })).toThrow('boot manifest entry "a" belongs to more than one batch')
  420. expect(() => parseBootManifest({
  421. rev: 'graph',
  422. entries,
  423. batches: [{ phase: 'application', url: '/batch.js', rev: 'b', entries: ['a'] }],
  424. })).toThrow('boot manifest entry "b" belongs to no initial-load batch')
  425. })
  426. })
  427. describe('HMR reset', () => {
  428. it('invalidate drops the factory and record so the module reloads and re-registers', async () => {
  429. let generation = 0
  430. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  431. const first = await b.loader.import('a', '', {})
  432. b.loader.invalidate('a', '1')
  433. expect(b.loader.loadCache.has('a')).toBe(false)
  434. await b.loader.prefetch('a')
  435. const second = await b.loader.import('a', '', {})
  436. expect(b.fetched).toEqual([APPLICATION_URL, comboUrl(['a'], '1')])
  437. expect((first as { generation: number }).generation).toBe(1)
  438. expect((second as { generation: number }).generation).toBe(2)
  439. })
  440. it('preserves an absolute combo endpoint when applying the rebuilt revision', async () => {
  441. const b = bench([
  442. row('a', { url: 'https://plugins.example.test/plugins/??a/client.js&rev=0' }),
  443. ], { a: () => ({}) })
  444. await b.loader.import('a', '', {})
  445. b.loader.invalidate('a', 'next')
  446. await b.loader.prefetch('a')
  447. expect(b.fetched.at(-1)).toBe('https://plugins.example.test/plugins/??a/client.js&rev=next')
  448. })
  449. it('preserves a protocol-relative combo endpoint when applying the rebuilt revision', async () => {
  450. const b = bench([
  451. row('a', { url: '//plugins.example.test/plugins/??a/client.js&rev=0' }),
  452. ], { a: () => ({}) })
  453. await b.loader.import('a', '', {})
  454. b.loader.invalidate('a', 'next')
  455. await b.loader.prefetch('a')
  456. expect(b.fetched.at(-1)).toBe('//plugins.example.test/plugins/??a/client.js&rev=next')
  457. })
  458. it('uses the current plugin revision when a graph-row invalidation omits an override', async () => {
  459. const b = bench([row('a')], { a: () => ({}) })
  460. await b.loader.import('a', '', {})
  461. b.loader.invalidate('a')
  462. await b.loader.prefetch('a')
  463. expect(b.fetched).toEqual([APPLICATION_URL, comboUrl(['a'], '0')])
  464. })
  465. })
  466. describe('style claiming', () => {
  467. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  468. const foreign = document.createElement('style')
  469. foreign.setAttribute('data-plugin', 'other')
  470. document.head.appendChild(foreign)
  471. const b = bench([row('a')], {
  472. a: () => {
  473. document.head.appendChild(document.createElement('style'))
  474. const tagged = document.createElement('style')
  475. tagged.setAttribute('data-plugin', 'a')
  476. tagged.setAttribute('data-plugin-css', 'sheet-1')
  477. document.head.appendChild(tagged)
  478. return {}
  479. },
  480. })
  481. await b.loader.import('a', '', {})
  482. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  483. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  484. expect(foreign.getAttribute('data-plugin')).toBe('other')
  485. })
  486. it('materialization without a document skips the style inventory', async () => {
  487. const b = bench([row('a')], { a: () => ({}) })
  488. vi.stubGlobal('document', undefined)
  489. try {
  490. await b.loader.import('a', '', {})
  491. } finally {
  492. vi.unstubAllGlobals()
  493. }
  494. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  495. })
  496. })
  497. describe('default transport seam', () => {
  498. it('loads through an external classic script and removes the settled node', async () => {
  499. const append = vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  500. const script = nodes[0]
  501. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  502. expect(script.async).toBe(true)
  503. expect(script.getAttribute('src')).toBe(APPLICATION_URL)
  504. queueMicrotask(() => {
  505. win.__ModuleLoader__?.load({ id: 'dee', factory: () => ({ marker: 'via-script' }) })
  506. script.dispatchEvent(new Event('load'))
  507. })
  508. })
  509. const b = bench([row('dee')], {}, { defaultTransport: true })
  510. const exports = await b.loader.import('dee', '', {})
  511. expect((exports as { marker: string }).marker).toBe('via-script')
  512. expect(append).toHaveBeenCalledOnce()
  513. expect([...document.querySelectorAll('script')]).toEqual([])
  514. })
  515. it('a script load failure is loud and removes the node', async () => {
  516. vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
  517. const script = nodes[0]
  518. if (!(script instanceof HTMLScriptElement)) throw new Error('expected script node')
  519. queueMicrotask(() => { script.dispatchEvent(new Event('error')) })
  520. })
  521. const b = bench([row('dee')], {}, { defaultTransport: true })
  522. await expect(b.loader.prefetch('dee')).rejects.toThrow(
  523. `bundle script ${APPLICATION_URL} failed to load`,
  524. )
  525. expect([...document.querySelectorAll('script')]).toEqual([])
  526. })
  527. })