web-plugins.spec.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { Context } from 'cordis'
  5. import { describe, expect, it } from 'vitest'
  6. import { createHostWebPluginRegistry, injectBootManifest } from '../src/index.ts'
  7. import type { LoaderEntryView, WebPluginRegistryDeps } from '../src/index.ts'
  8. /** Write a fake installed package (package.json + optional client bundle) and return its package.json path. */
  9. function makePkg(root: string, name: string, pkg: Record<string, unknown>, withBundle = true): string {
  10. const dir = join(root, name.replaceAll('/', '__'))
  11. mkdirSync(join(dir, 'lib'), { recursive: true })
  12. writeFileSync(join(dir, 'package.json'), JSON.stringify({ name, ...pkg }))
  13. if (withBundle) writeFileSync(join(dir, 'lib', 'client.js'), `// bundle of ${name}`)
  14. return join(dir, 'package.json')
  15. }
  16. const webDecl = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({
  17. dshClient: { inject: [], platform: 'web', ...extra },
  18. exports: { '.': './lib/index.js', './client': './lib/client.js' },
  19. })
  20. interface Fixture {
  21. deps: WebPluginRegistryDeps
  22. entries: LoaderEntryView[]
  23. errors: Error[]
  24. ctx: Context
  25. }
  26. function makeDeps(
  27. specs: { name: string; pkg: Record<string, unknown>; loaded?: boolean; disabled?: boolean; withBundle?: boolean }[],
  28. ): Fixture {
  29. const root = mkdtempSync(join(tmpdir(), 'dsh-webplugins-'))
  30. const paths = new Map<string, string>()
  31. const entries: LoaderEntryView[] = specs.map((spec) => {
  32. paths.set(spec.name, makePkg(root, spec.name, spec.pkg, spec.withBundle ?? true))
  33. return { options: { name: spec.name }, fiber: spec.loaded === false ? undefined : {}, disabled: spec.disabled ?? false }
  34. })
  35. const ctx = new Context()
  36. const errors: Error[] = []
  37. const deps: WebPluginRegistryDeps = {
  38. ctx,
  39. loader: { entries: () => entries },
  40. resolvePkgJson: (name) => {
  41. const path = paths.get(name)
  42. if (path === undefined) throw new Error(`unresolvable ${name}`)
  43. return path
  44. },
  45. onError: err => void errors.push(err),
  46. }
  47. return { deps, entries, errors, ctx }
  48. }
  49. describe('createHostWebPluginRegistry', () => {
  50. it('collects loaded web-declared plugins with url/inject/immediately and client paths', () => {
  51. const { deps } = makeDeps([
  52. { name: '@deepseek-ai/dsh-client-connection', pkg: webDecl({ immediately: true }) },
  53. { name: '@deepseek-ai/dsh-client-ui-layout', pkg: webDecl({ inject: ['@deepseek-ai/dsh-client-runtime'] }) },
  54. { name: '@deepseek-ai/dsh-agent', pkg: { exports: { '.': './lib/index.js' } } }, // no dshClient: skipped
  55. ])
  56. const registry = createHostWebPluginRegistry(deps)
  57. const rows = registry.snapshot()
  58. expect(rows).toEqual([
  59. {
  60. id: '@deepseek-ai/dsh-client-connection',
  61. url: '/plugins/@deepseek-ai/dsh-client-connection/client.js',
  62. inject: [],
  63. immediately: true,
  64. },
  65. {
  66. id: '@deepseek-ai/dsh-client-ui-layout',
  67. url: '/plugins/@deepseek-ai/dsh-client-ui-layout/client.js',
  68. inject: ['@deepseek-ai/dsh-client-runtime'],
  69. },
  70. ])
  71. expect(registry.clientPath('@deepseek-ai/dsh-client-connection')).toMatch(/lib[/\\]client\.js$/)
  72. expect(registry.clientPath('@deepseek-ai/dsh-agent')).toBeUndefined()
  73. registry.dispose()
  74. })
  75. it('skips entries that are unloaded, disabled, or declare another platform', () => {
  76. const { deps } = makeDeps([
  77. { name: 'not-loaded', pkg: webDecl(), loaded: false },
  78. { name: 'disabled', pkg: webDecl(), disabled: true },
  79. { name: 'electron-only', pkg: { dshClient: { platform: 'electron' }, exports: { './client': './lib/client.js' } } },
  80. ])
  81. const registry = createHostWebPluginRegistry(deps)
  82. expect(registry.snapshot()).toEqual([])
  83. registry.dispose()
  84. })
  85. it('fails loud at build time on a dshClient declaration without a "./client" export', () => {
  86. const { deps } = makeDeps([
  87. { name: 'broken', pkg: { dshClient: { platform: 'web' }, exports: { '.': './lib/index.js' } } },
  88. ])
  89. expect(() => createHostWebPluginRegistry(deps)).toThrow(/declares dshClient but exports no/)
  90. })
  91. it('fails loud on malformed declaration fields', () => {
  92. for (const dshClient of [42, { platform: 7 }, { platform: 'web', inject: 'nope' }, { platform: 'web', immediately: 'yes' }]) {
  93. const { deps } = makeDeps([{ name: 'bad', pkg: { dshClient, exports: { './client': './lib/client.js' } } }])
  94. expect(() => createHostWebPluginRegistry(deps)).toThrow(/dshClient/)
  95. }
  96. })
  97. it('rescans on internal/plugin (debounced) and keeps the old table when a rescan fails', async () => {
  98. const { deps, entries, errors, ctx } = makeDeps([
  99. { name: 'late-loader', pkg: webDecl(), loaded: false },
  100. ])
  101. const registry = createHostWebPluginRegistry(deps)
  102. expect(registry.snapshot()).toEqual([])
  103. // Entry finishes loading; a fiber lifecycle event triggers the debounced rescan.
  104. ;(entries[0] as { fiber?: unknown }).fiber = {}
  105. ctx.emit('internal/plugin', ctx.fiber)
  106. ctx.emit('internal/plugin', ctx.fiber) // debounce: two emissions, one rescan
  107. await Promise.resolve()
  108. expect(registry.snapshot().map(row => row.id)).toEqual(['late-loader'])
  109. // A failing rescan reports the error and keeps serving the previous table.
  110. entries.push({ options: { name: 'ghost' }, fiber: {}, disabled: false })
  111. ctx.emit('internal/plugin', ctx.fiber)
  112. await Promise.resolve()
  113. expect(errors).toHaveLength(1)
  114. expect(registry.snapshot().map(row => row.id)).toEqual(['late-loader'])
  115. // After dispose, further fiber events no longer rescan.
  116. registry.dispose()
  117. entries.pop()
  118. ctx.emit('internal/plugin', ctx.fiber)
  119. await Promise.resolve()
  120. expect(errors).toHaveLength(1)
  121. })
  122. })
  123. describe('injectBootManifest', () => {
  124. it('injects the manifest as the first script inside <head> and escapes </script> breakouts', () => {
  125. const html = '<html><head><script src="app.js"></script></head><body></body></html>'
  126. const out = injectBootManifest(html, [{ id: 'x</script><script>alert(1)', url: '/plugins/x/client.js', inject: [] }])
  127. expect(out.indexOf('window.__DSH_BOOT__')).toBeLessThan(out.indexOf('app.js'))
  128. expect(out).not.toContain('</script><script>alert(1)')
  129. expect(out).toContain('\\u003c/script')
  130. })
  131. it('prepends when the page has no <head>', () => {
  132. const out = injectBootManifest('<body>x</body>', [])
  133. expect(out.startsWith('<script>window.__DSH_BOOT__')).toBe(true)
  134. })
  135. })
  136. describe('clientExportOf shapes (through the registry build)', () => {
  137. it('accepts the conditional {types, default} export form', () => {
  138. const { deps } = makeDeps([{
  139. name: 'conditional',
  140. pkg: {
  141. dshClient: { platform: 'web' },
  142. exports: { './client': { types: './lib/types/client/index.d.ts', default: './lib/client.js' } },
  143. },
  144. }])
  145. const registry = createHostWebPluginRegistry(deps)
  146. expect(registry.clientPath('conditional')).toMatch(/lib[/\\]client\.js$/)
  147. registry.dispose()
  148. })
  149. it('rejects a conditional form without a string default, an array form, and a non-object exports field', () => {
  150. for (const exportsField of [
  151. { './client': { types: './x.d.ts' } },
  152. { './client': ['./a.js'] },
  153. ]) {
  154. const { deps } = makeDeps([{ name: 'bad-shape', pkg: { dshClient: { platform: 'web' }, exports: exportsField } }])
  155. expect(() => createHostWebPluginRegistry(deps)).toThrow(/unsupported shape/)
  156. }
  157. // Non-object exports: treated as "no ./client export" → the declares-but-no-bundle throw.
  158. const { deps } = makeDeps([{ name: 'no-exports', pkg: { dshClient: { platform: 'web' }, exports: './single.js' } }])
  159. expect(() => createHostWebPluginRegistry(deps)).toThrow(/declares dshClient but exports no/)
  160. })
  161. it('skips duplicate loader entries for the same package name (first wins)', () => {
  162. const { deps, entries } = makeDeps([{ name: 'dup-entry', pkg: webDecl() }])
  163. const first = entries[0] as LoaderEntryView
  164. entries.push({ options: { name: 'dup-entry' }, fiber: {}, disabled: false })
  165. void first
  166. const registry = createHostWebPluginRegistry(deps)
  167. expect(registry.snapshot().filter(r => r.id === 'dup-entry')).toHaveLength(1)
  168. registry.dispose()
  169. })
  170. it('rejects a null conditional form and wraps a non-Error rescan throw', async () => {
  171. // client: null → the object-form branch's null guard.
  172. const nulled = makeDeps([{ name: 'null-client', pkg: { dshClient: { platform: 'web' }, exports: { './client': null } } }])
  173. expect(() => createHostWebPluginRegistry(nulled.deps)).toThrow(/unsupported shape/)
  174. // Non-Error rescan throw: resolvePkgJson throws a string; onError must get a wrapped Error.
  175. const { deps, entries, errors, ctx } = makeDeps([{ name: 'ok-one', pkg: webDecl() }])
  176. const registry = createHostWebPluginRegistry(deps)
  177. entries.push({ options: { name: 'ghost-two' }, fiber: {}, disabled: false })
  178. const original = deps.resolvePkgJson
  179. deps.resolvePkgJson = (name) => {
  180. if (name === 'ghost-two') throw 'string failure'
  181. return original(name)
  182. }
  183. ctx.emit('internal/plugin', ctx.fiber)
  184. await Promise.resolve()
  185. expect(errors[0]).toBeInstanceOf(Error)
  186. expect(String(errors[0])).toContain('string failure')
  187. registry.dispose()
  188. })
  189. })