loader.client.spec.ts 30 KB

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