loader.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // @vitest-environment jsdom
  2. /**
  3. * ClientModuleSystem 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. ClientModuleSystem,
  13. type BootModuleRow, type ClientModuleLoader, type ClientPluginHandoff, type DshWindow,
  14. } from '../src/client/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): BootModuleRow => ({ id, url: `/plugins/${id}/client.js?rev=0`, 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: BootModuleRow[],
  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 = new ClientModuleSystem({
  42. modules: 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')], {
  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 duplicate graph entry is loud at construction', () => {
  197. expect(() => bench([row('a'), row('a')])).toThrow('duplicate graph entry "a"')
  198. })
  199. it('double boot is loud', () => {
  200. bench([])
  201. expect(() => new ClientModuleSystem({ modules: [], staticModules: {} }))
  202. .toThrow('already installed (double boot?)')
  203. })
  204. })
  205. describe('HMR reset', () => {
  206. it('invalidate drops the factory and record so the module refetches and re-registers', async () => {
  207. let generation = 0
  208. const b = bench([row('a')], { a: () => ({ generation: ++generation }) })
  209. const first = await b.loader.import('a', '', {})
  210. b.loader.invalidate('a')
  211. expect(b.loader.loadCache.has('a')).toBe(false)
  212. await b.loader.prefetch('a')
  213. const second = await b.loader.import('a', '', {})
  214. expect(b.fetched).toHaveLength(2)
  215. expect((first as { generation: number }).generation).toBe(1)
  216. expect((second as { generation: number }).generation).toBe(2)
  217. })
  218. })
  219. describe('style claiming', () => {
  220. it('claims untagged style tags for the materializing plugin and inventories owned css ids', async () => {
  221. const foreign = document.createElement('style')
  222. foreign.setAttribute('data-plugin', 'other')
  223. document.head.appendChild(foreign)
  224. const b = bench([row('a')], {
  225. a: () => {
  226. document.head.appendChild(document.createElement('style'))
  227. const tagged = document.createElement('style')
  228. tagged.setAttribute('data-plugin', 'a')
  229. tagged.setAttribute('data-plugin-css', 'sheet-1')
  230. document.head.appendChild(tagged)
  231. return {}
  232. },
  233. })
  234. await b.loader.import('a', '', {})
  235. expect(b.loader.loadCache.get('a')?.styles).toEqual(['a', 'sheet-1'])
  236. expect(document.querySelectorAll('style[data-plugin="a"]')).toHaveLength(2)
  237. expect(foreign.getAttribute('data-plugin')).toBe('other')
  238. })
  239. it('materialization without a document skips the style inventory', async () => {
  240. const b = bench([row('a')], { a: () => ({}) })
  241. vi.stubGlobal('document', undefined)
  242. try {
  243. await b.loader.import('a', '', {})
  244. } finally {
  245. vi.unstubAllGlobals()
  246. }
  247. expect(b.loader.loadCache.get('a')?.styles).toEqual([])
  248. })
  249. })
  250. describe('default transport seams', () => {
  251. it('fetches same-origin and executes through an inline script tag', async () => {
  252. // In a browser the loader's globalThis IS the page window; vitest's jsdom
  253. // evaluates <script> in a separate realm that shares only the document,
  254. // so the fixture bundle restores the sink from a document bridge before
  255. // using the normal calling convention.
  256. const code = 'window.__ModuleLoader__ = document.__realmBridge;\n'
  257. + 'window.__ModuleLoader__.load({ id: "dee", factory: function () { return { marker: "via-script" } } })'
  258. vi.stubGlobal('fetch', async () => ({ ok: true, text: async () => code }))
  259. const loader: ClientModuleLoader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} })
  260. ;(document as unknown as Record<string, unknown>).__realmBridge = win.__ModuleLoader__
  261. const surface = await loader.import('dee', '', {})
  262. expect((surface as { marker: string }).marker).toBe('via-script')
  263. // The script node is removed right after its synchronous execution —
  264. // repeated HMR rebuilds must not accumulate dead script nodes.
  265. expect([...document.querySelectorAll('script')]).toEqual([])
  266. })
  267. it('a non-ok bundle response is loud with the status', async () => {
  268. vi.stubGlobal('fetch', async () => ({ ok: false, status: 404 }))
  269. const loader = new ClientModuleSystem({ modules: [row('dee')], staticModules: {} })
  270. await expect(loader.prefetch('dee')).rejects.toThrow('answered 404')
  271. })
  272. })