persistence-catalog-source.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /** Source discovery and declaration validation shared by persistence documentation and schemas. */
  2. import { globSync, readFileSync } from 'node:fs'
  3. import { resolve, sep } from 'node:path'
  4. import ts from 'typescript'
  5. import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  6. const root = resolve(import.meta.dirname, '..')
  7. /** The package that owns the durable event vocabulary. */
  8. const SESSION_PACKAGE = '@deepseek-ai/dsh-session'
  9. /** The type-only module that plugin declaration merges augment. */
  10. const SESSION_TYPES_MODULE = '@deepseek-ai/dsh-session/types'
  11. /** Event-envelope declarations rendered before the per-event vocabulary. */
  12. const EVENT_ENVELOPE_TYPE_NAMES = [
  13. 'SessionEventType',
  14. 'SurfaceEventType',
  15. 'SurfaceOp',
  16. 'SessionEvent',
  17. ] as const
  18. type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number]
  19. /** One log event, extracted from a `SessionEventMap` declaration. */
  20. export interface LogEventEntry {
  21. /** Scoped name, e.g. `turn/start`. */
  22. name: string
  23. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  24. scope: string
  25. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  26. payload: string
  27. /** Source member declaration and complete JSDoc, dedented from its container. */
  28. declaration: string
  29. /** Description prose (the member's JSDoc), one line per paragraph. */
  30. doc: string
  31. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  32. source: string
  33. }
  34. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  35. export interface AnnotatedLogEventEntry extends LogEventEntry {
  36. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  37. surface: boolean
  38. }
  39. /** One owning event-envelope declaration pasted into the generated catalog. */
  40. export interface EventEnvelopeTypeEntry {
  41. /** Exported declaration name. */
  42. name: EventEnvelopeTypeName
  43. /** Verbatim type declaration, including its complete leading JSDoc. */
  44. declaration: string
  45. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  46. source: string
  47. }
  48. const printer = ts.createPrinter({ removeComments: true })
  49. /**
  50. * Render a member type on one line through the TypeScript printer, which adds
  51. * semicolon separators. Drop its trailing semicolon before `}` to match the
  52. * repository's inline-literal style.
  53. */
  54. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  55. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  56. .replace(/\s+/g, ' ')
  57. .replace(/;\s*\}/g, ' }')
  58. .trim()
  59. }
  60. /**
  61. * Copy a declaration from its leading JSDoc through its closing token while
  62. * removing only the indentation imposed by its containing interface/module.
  63. */
  64. function declarationText(text: string, sf: ts.SourceFile, node: ts.Node): string {
  65. const raw = rawJsDoc(text, node)
  66. const nodeStart = node.getStart(sf)
  67. const start = raw ? text.lastIndexOf(raw, nodeStart) : nodeStart
  68. const { line } = sf.getLineAndCharacterOfPosition(start)
  69. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  70. const indent = text.slice(lineStart, start)
  71. return text.slice(lineStart, node.end)
  72. .split('\n')
  73. .map(lineText => lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText)
  74. .join('\n')
  75. .trimEnd()
  76. }
  77. /**
  78. * Every `interface SessionEventMap` declaration in a source file: the owning
  79. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  80. * merge inside a `declare module '@deepseek-ai/dsh-session/types'` block. Both forms
  81. * declare members of the SAME merged interface, so both are catalogued
  82. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  83. * it actually lives in the owning package — an unrelated local interface that
  84. * happens to share the name must not be catalogued as the on-disk vocabulary.
  85. */
  86. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  87. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  88. for (const stmt of sf.statements) {
  89. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  90. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_TYPES_MODULE
  91. && stmt.body && ts.isModuleBlock(stmt.body)) {
  92. for (const inner of stmt.body.statements) {
  93. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  94. }
  95. }
  96. }
  97. return decls
  98. }
  99. /**
  100. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  101. * from that package's manifest — or null when the manifest is missing or
  102. * unparseable (the caller treats null as "ownership unverifiable").
  103. */
  104. function packageNameFor(rel: string, scanRoot: string): string | null {
  105. const dir = rel.split('/').slice(0, 3).join('/')
  106. try {
  107. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  108. return typeof manifest.name === 'string' ? manifest.name : null
  109. } catch {
  110. // Missing or malformed package.json — every real workspace package has one,
  111. // so this only arises in stripped-down fixture trees; either way ownership
  112. // cannot be verified and the caller reports the declaration.
  113. return null
  114. }
  115. }
  116. /**
  117. * Collect every `SessionEventMap` merge, rejecting inherited, non-literal,
  118. * untyped, undocumented, duplicate, or incorrectly owned members in one report.
  119. */
  120. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  121. const entries: LogEventEntry[] = []
  122. const violations: string[] = []
  123. const seen = new Map<string, string>()
  124. let owningDecl: string | null = null
  125. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  126. const abs = resolve(scanRoot, rel)
  127. const text = readFileSync(abs, 'utf8')
  128. if (!text.includes('SessionEventMap')) continue
  129. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  130. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  131. const declSrc = pointer(rel, sf, decl)
  132. if (topLevel) {
  133. // The top-level form has one home: the single exported declaration in
  134. // the owning package. Same-named interfaces elsewhere are different
  135. // types and must not enter the on-disk catalog.
  136. const pkg = packageNameFor(rel, scanRoot)
  137. if (pkg !== SESSION_PACKAGE) {
  138. violations.push(`top-level interface SessionEventMap (${declSrc}) is outside ${SESSION_PACKAGE} (package ${pkg ?? 'unknown'}). Rename the interface, or contribute events via declare module '${SESSION_TYPES_MODULE}'.`)
  139. continue
  140. }
  141. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  142. if (!exported) {
  143. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  144. continue
  145. }
  146. if (owningDecl) {
  147. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  148. continue
  149. }
  150. owningDecl = declSrc
  151. }
  152. if (decl.heritageClauses?.length) {
  153. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  154. }
  155. for (const member of decl.members) {
  156. const src = pointer(rel, sf, member)
  157. if (!ts.isPropertySignature(member) || !member.type) {
  158. // A method-form or type-less member still joins `keyof SessionEventMap`,
  159. // so skipping it silently would be exactly the undocumented-event hole
  160. // this catalog exists to close.
  161. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  162. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  163. continue
  164. }
  165. if (!ts.isStringLiteral(member.name)) {
  166. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  167. continue
  168. }
  169. const name = member.name.text
  170. const where = `log event '${name}' (${src})`
  171. const prior = seen.get(name)
  172. if (prior) {
  173. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  174. continue
  175. }
  176. seen.set(name, src)
  177. const payload = payloadText(member.type, sf)
  178. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  179. if (hasMode) {
  180. violations.push(`${where} carries an @mode tag, but a log event has no dispatch mode (it is not a cordis bus event — it rides the 'session/event' emit). Remove the tag.`)
  181. }
  182. if (!doc) {
  183. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  184. }
  185. const declaration = declarationText(text, sf, member)
  186. entries.push({ name, scope: name.split('/')[0] ?? name, payload, declaration, doc, source: src })
  187. }
  188. }
  189. }
  190. reportViolations('gen-persistence-catalog', violations)
  191. return entries
  192. }
  193. /**
  194. * Collect the exported declarations that compose the persisted event envelope,
  195. * preserving their source JSDoc and declaration text.
  196. */
  197. export function collectEventEnvelopeTypes(scanRoot: string = root): EventEnvelopeTypeEntry[] {
  198. const found = new Map<EventEnvelopeTypeName, EventEnvelopeTypeEntry>()
  199. const violations: string[] = []
  200. const wanted = new Set<string>(EVENT_ENVELOPE_TYPE_NAMES)
  201. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  202. const abs = resolve(scanRoot, rel)
  203. const text = readFileSync(abs, 'utf8')
  204. if (!EVENT_ENVELOPE_TYPE_NAMES.some(name => text.includes(name))) continue
  205. if (packageNameFor(rel, scanRoot) !== SESSION_PACKAGE) continue
  206. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  207. for (const stmt of sf.statements) {
  208. if (!ts.isTypeAliasDeclaration(stmt) || !wanted.has(stmt.name.text)) continue
  209. const name = stmt.name.text as EventEnvelopeTypeName
  210. const src = pointer(rel, sf, stmt)
  211. const where = `event-envelope type '${name}' (${src})`
  212. const prior = found.get(name)
  213. if (prior) {
  214. violations.push(`${where} is already declared at ${prior.source}; the persisted envelope type has exactly one owner.`)
  215. continue
  216. }
  217. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) {
  218. violations.push(`${where} is not exported.`)
  219. }
  220. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, stmt))
  221. if (hasMode) violations.push(`${where} carries an @mode tag, but a persisted type has no dispatch mode.`)
  222. if (!doc) violations.push(`${where} has no description prose. The full JSDoc is part of the generated catalog.`)
  223. found.set(name, { name, declaration: declarationText(text, sf, stmt), source: src })
  224. }
  225. }
  226. const missing = EVENT_ENVELOPE_TYPE_NAMES.filter(name => !found.has(name))
  227. if (missing.length > 0) {
  228. violations.push(`missing event-envelope declaration(s): ${missing.join(', ')}.`)
  229. }
  230. reportViolations('gen-persistence-catalog', violations)
  231. return EVENT_ENVELOPE_TYPE_NAMES.map((name) => {
  232. const entry = found.get(name)
  233. if (!entry) throw new Error(`gen-persistence-catalog: missing checked event-envelope declaration '${name}'.`)
  234. return entry
  235. })
  236. }
  237. /**
  238. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  239. * types — from source. Hard-errors when the alias is missing, declared more
  240. * than once, or contains a non-string-literal member: the badge derivation
  241. * relies on the union being a closed set of literal event names.
  242. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  243. */
  244. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  245. const found: { names: string[]; source: string }[] = []
  246. for (const rel of globSync('packages/*/*/src/**/*.{ts,tsx}', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  247. const abs = resolve(scanRoot, rel)
  248. const text = readFileSync(abs, 'utf8')
  249. if (!text.includes('SurfaceEventType')) continue
  250. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  251. for (const stmt of sf.statements) {
  252. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  253. const src = pointer(rel, sf, stmt)
  254. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  255. const names: string[] = []
  256. for (const m of members) {
  257. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  258. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  259. }
  260. found.push({ names, source: src })
  261. }
  262. }
  263. const only = found[0]
  264. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  265. if (found.length > 1) throw new Error(`gen-persistence-catalog: SurfaceEventType is declared more than once (${found.map(f => f.source).join(', ')}); the surface subset has exactly one owner.`)
  266. return only.names
  267. }
  268. /**
  269. * Attach the surface/log-only badge to each event. Hard-errors when a
  270. * `SurfaceEventType` union member names no collected event — a stale union
  271. * member would otherwise silently badge nothing.
  272. */
  273. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  274. const names = new Set(events.map(e => e.name))
  275. const stale = surfaceTypes.filter(t => !names.has(t))
  276. if (stale.length > 0) {
  277. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  278. }
  279. const surface = new Set(surfaceTypes)
  280. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  281. }