loader.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // @vitest-environment jsdom
  2. /**
  3. * ClientModuleLoaderImpl behavior: lazy CJS arrival (bundle execution only
  4. * registers the factory), materialization on first import/require with
  5. * memoization and recursive self-sequencing, the resolution branch order,
  6. * shared in-flight arrival, invalidate-refetch (HMR), style claiming, the
  7. * default transport seams, and the loud failure modes (duplicate
  8. * registration, cycles, table misses, double boot).
  9. */
  10. import { afterEach, describe, expect, it, vi } from 'vitest'
  11. import {
  12. ClientModuleLoaderImpl, createClientModuleLoader,
  13. type ClientModuleLoader, type ClientPluginHandoff, type DshWindow, type WebBootEntry,
  14. } from '../src/index.ts'
  15. const win = globalThis as DshWindow
  16. type Factory = ClientPluginHandoff['factory']
  17. afterEach(() => {
  18. vi.unstubAllGlobals()
  19. delete win.__ModuleLoader__
  20. delete (document as unknown as Record<string, unknown>).__realmBridge
  21. for (const el of document.querySelectorAll('style, script')) el.remove()
  22. })
  23. const row = (id: string): WebBootEntry => ({ id, url: `/plugins/${id}/client.js?rev=0` })
  24. interface Bench {
  25. loader: ClientModuleLoader
  26. fetched: string[]
  27. gates: Map<string, () => void>
  28. }
  29. /**
  30. * Loader over scripted bundles: fetch resolves to the row url (optionally
  31. * gated on a release callback); execute registers the scripted factory
  32. * through the window sink (`null` scripts a bundle that never calls load).
  33. */
  34. function bench(
  35. entries: WebBootEntry[],
  36. bundles: Record<string, Factory | null> = {},
  37. opts: { seed?: Record<string, unknown>; gated?: string[] } = {},
  38. ): Bench {
  39. const fetched: string[] = []
  40. const gates = new Map<string, () => void>()
  41. const loader = createClientModuleLoader({
  42. graph: { rev: 'test', entries },
  43. staticModules: opts.seed ?? {},
  44. fetchBundle: (url) => {
  45. fetched.push(url)
  46. if (opts.gated?.includes(url) === true) {
  47. return new Promise((resolve) => { gates.set(url, () => { resolve(url) }) })
  48. }
  49. return Promise.resolve(url)
  50. },
  51. executeBundle: (code) => {
  52. const id = /\/plugins\/(.+)\/client\.js/.exec(code)?.[1]
  53. const factory = id === undefined ? undefined : bundles[id]
  54. if (factory == null || id === undefined) return
  55. win.__ModuleLoader__?.load({ id, factory })
  56. },
  57. })
  58. return { loader, fetched, gates }
  59. }
  60. describe('lazy CJS arrival', () => {
  61. it('prefetch fetches and executes but does not run the factory', async () => {
  62. const ran: string[] = []
  63. const b = bench([row('a')], { a: () => { ran.push('a'); return {} } })
  64. await b.loader.prefetch('a')
  65. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  66. expect(ran).toEqual([])
  67. expect(b.loader.loadCache.size).toBe(0)
  68. })
  69. it('import materializes once and memoizes the export surface', async () => {
  70. const ran: string[] = []
  71. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } })
  72. const first = await b.loader.import('a', '', {})
  73. const second = await b.loader.import('a', '', {})
  74. expect(first).toBe(second)
  75. expect((first as { marker: string }).marker).toBe('a')
  76. expect(ran).toEqual(['a'])
  77. expect(b.loader.loadCache.get('a')?.id).toBe('a')
  78. })
  79. it('import without prefetch fetches, executes, and materializes in one call', async () => {
  80. const b = bench([row('a')], { a: () => ({ marker: 'direct' }) })
  81. const surface = await b.loader.import('a', '', {})
  82. expect((surface as { marker: string }).marker).toBe('direct')
  83. expect(b.fetched).toHaveLength(1)
  84. })
  85. it('concurrent callers share one in-flight arrival and materialize once', async () => {
  86. const ran: string[] = []
  87. const url = '/plugins/a/client.js?rev=0'
  88. const b = bench([row('a')], { a: () => { ran.push('a'); return { marker: 'a' } } }, { gated: [url] })
  89. const first = b.loader.import('a', '', {})
  90. const second = b.loader.import('a', '', {})
  91. const third = b.loader.prefetch('a')
  92. b.gates.get(url)?.()
  93. const [s1, s2] = await Promise.all([first, second, third])
  94. expect(s1).toBe(s2)
  95. expect(b.fetched).toEqual([url])
  96. expect(ran).toEqual(['a'])
  97. })
  98. it('prefetch after registration is a no-op without invalidate', async () => {
  99. const b = bench([row('a')], { a: () => ({}) })
  100. await b.loader.prefetch('a')
  101. await b.loader.prefetch('a')
  102. expect(b.fetched).toHaveLength(1)
  103. })
  104. })
  105. describe('require resolution', () => {
  106. it('a factory requiring a registered-but-unmaterialized module materializes it recursively', async () => {
  107. const order: string[] = []
  108. const b = bench([row('a'), row('b')], {
  109. a: (req) => {
  110. order.push('a')
  111. const dep = req('b/client') as { helper: string }
  112. return { got: dep.helper }
  113. },
  114. b: () => { order.push('b'); return { helper: 'from-b' } },
  115. })
  116. await b.loader.prefetch('a')
  117. await b.loader.prefetch('b')
  118. const surface = await b.loader.import('a', '', {})
  119. expect((surface as { got: string }).got).toBe('from-b')
  120. expect(order).toEqual(['a', 'b'])
  121. expect(b.loader.loadCache.get('a')?.edges.has('b/client')).toBe(true)
  122. expect(b.loader.loadCache.has('b')).toBe(true)
  123. })
  124. it('require prefers the platform seed word over the module table', async () => {
  125. const react = { marker: 'react' }
  126. const b = bench([row('a')], {
  127. a: req => ({ dep: req('react') }),
  128. }, { seed: { react } })
  129. const surface = await b.loader.import('a', '', {})
  130. expect((surface as { dep: unknown }).dep).toBe(react)
  131. expect(await b.loader.import('react', '', {})).toBe(react)
  132. expect(b.loader.loadCache.has('react')).toBe(false)
  133. })
  134. it('require answers an already-materialized module from the cache', async () => {
  135. let built = 0
  136. const b = bench([row('a'), row('c')], {
  137. a: req => ({ dep: req('c') }),
  138. c: () => { built += 1; return { marker: 'c' } },
  139. })
  140. const c = await b.loader.import('c', '', {})
  141. const a = await b.loader.import('a', '', {})
  142. expect((a as { dep: unknown }).dep).toBe(c)
  143. expect(built).toBe(1)
  144. })
  145. it('a require that misses the module table is loud', async () => {
  146. const b = bench([row('a')], { a: req => ({ dep: req('ghost') }) })
  147. await expect(b.loader.import('a', '', {})).rejects.toThrow('require("ghost") missed the module table')
  148. })
  149. it('a require cycle is fatal', async () => {
  150. const b = bench([row('a'), row('b')], {
  151. a: req => ({ dep: req('b') }),
  152. b: req => ({ dep: req('a') }),
  153. })
  154. await b.loader.prefetch('b')
  155. await expect(b.loader.import('a', '', {})).rejects.toThrow('require cycle through "a"')
  156. })
  157. })
  158. describe('static registry', () => {
  159. it('serves shell-own modules to import and require without any fetch', async () => {
  160. const shell = { marker: 'app-shell' }
  161. const b = bench([row('a'), { id: 'app-shell' }], {
  162. a: req => ({ dep: req('app-shell') }),
  163. })
  164. b.loader.registerStatic('app-shell', shell)
  165. await b.loader.prefetch('app-shell')
  166. expect(await b.loader.import('app-shell', '', {})).toBe(shell)
  167. expect(b.loader.loadCache.get('app-shell')?.styles).toEqual([])
  168. expect((await b.loader.import('a', '', {}) as { dep: unknown }).dep).toBe(shell)
  169. expect(b.fetched).toEqual(['/plugins/a/client.js?rev=0'])
  170. })
  171. it('duplicate static registration is loud', () => {
  172. const b = bench([])
  173. b.loader.registerStatic('app-shell', {})
  174. expect(() => { b.loader.registerStatic('app-shell', {}) }).toThrow('registered twice')
  175. })
  176. })
  177. describe('failure modes', () => {
  178. it('duplicate factory registration is loud', () => {
  179. bench([])
  180. win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) })
  181. expect(() => win.__ModuleLoader__?.load({ id: 'x', factory: () => ({}) }))
  182. .toThrow('duplicate factory registration for "x"')
  183. })
  184. it('a bundle that never registers its id is loud', async () => {
  185. const b = bench([row('a')], { a: null })
  186. await expect(b.loader.import('a', '', {})).rejects.toThrow('without registering "a"')
  187. })
  188. it('an unknown import specifier is loud', async () => {
  189. const b = bench([])
  190. await expect(b.loader.import('nope', '', {})).rejects.toThrow('cannot resolve "nope"')
  191. })
  192. it('an unknown prefetch id is loud', async () => {
  193. const b = bench([])
  194. await expect(b.loader.prefetch('nope')).rejects.toThrow('prefetch("nope") — not a graph entry')
  195. })
  196. it('a graph row with no url and no static registration is loud', async () => {
  197. const b = bench([{ id: 'ghost' }])
  198. await expect(b.loader.import('ghost', '', {})).rejects.toThrow('no bundle url and no static registration')
  199. })
  200. it('a duplicate graph entry is loud at construction', () => {
  201. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  202. })
  203. it('double boot is loud', () => {
  204. bench([])
  205. expect(() => new ClientModuleLoaderImpl({ graph: { rev: 't', entries: [] }, staticModules: {} }))
  206. .toThrow('already installed (double boot?)')
  207. })
  208. })
  209. describe('HMR reset', () => {
  210. it('invalidate drops the factory and record so the module refetches and re-registers', async () => {
  211. let generation = 0
  212. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  213. const first = await b.loader.import('a', '', {})
  214. b.loader.invalidate('a')
  215. expect(b.loader.loadCache.has('a')).toBe(false)
  216. await b.loader.prefetch('a')
  217. const second = await b.loader.import('a', '', {})
  218. expect(b.fetched).toHaveLength(2)
  219. expect((first as { generation: number }).generation).toBe(1)
  220. expect((second as { generation: number }).generation).toBe(2)
  221. })
  222. })
  223. describe('style claiming', () => {
  224. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  225. const foreign = document.createElement('style')
  226. foreign.setAttribute('data-plugin', 'other')
  227. document.head.appendChild(foreign)
  228. const b = bench([row('a')], {
  229. a: () => {
  230. document.head.appendChild(document.createElement('style'))
  231. const tagged = document.createElement('style')
  232. tagged.setAttribute('data-plugin', 'a')
  233. tagged.setAttribute('data-plugin-css', 'sheet-1')
  234. document.head.appendChild(tagged)
  235. return {}
  236. },
  237. })
  238. await b.loader.import('a', '', {})
  239. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  240. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  241. expect(foreign.getAttribute('data-plugin')).toBe('other')
  242. })
  243. it('materialization without a document skips the style inventory', async () => {
  244. const b = bench([row('a')], { a: () => ({}) })
  245. vi.stubGlobal('document', undefined)
  246. try {
  247. await b.loader.import('a', '', {})
  248. } finally {
  249. vi.unstubAllGlobals()
  250. }
  251. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  252. })
  253. })
  254. describe('default transport seams', () => {
  255. it('fetches same-origin and executes through an inline script tag', async () => {
  256. // In a browser the loader's globalThis IS the page window; vitest's jsdom
  257. // evaluates <script> in a separate realm that shares only the document,
  258. // so the fixture bundle restores the sink from a document bridge before
  259. // using the normal calling convention.
  260. const code = 'window.__ModuleLoader__ = document.__realmBridge;\n'
  261. + 'window.__ModuleLoader__.load({ id: "dee", factory: function () { return { marker: "via-script" } } })'
  262. vi.stubGlobal('fetch', async () => ({ ok: true, text: async () => code }))
  263. const loader = createClientModuleLoader({ graph: { rev: 't', entries: [row('dee')] }, staticModules: {} })
  264. ;(document as unknown as Record<string, unknown>).__realmBridge = win.__ModuleLoader__
  265. const surface = await loader.import('dee', '', {})
  266. expect((surface as { marker: string }).marker).toBe('via-script')
  267. // The script node is removed right after its synchronous execution —
  268. // repeated HMR rebuilds must not accumulate dead script nodes.
  269. expect([...document.querySelectorAll('script')]).toEqual([])
  270. })
  271. it('a non-ok bundle response is loud with the status', async () => {
  272. vi.stubGlobal('fetch', async () => ({ ok: false, status: 404 }))
  273. const loader = createClientModuleLoader({ graph: { rev: 't', entries: [row('dee')] }, staticModules: {} })
  274. await expect(loader.prefetch('dee')).rejects.toThrow('answered 404')
  275. })
  276. })