gen-persistence-catalog.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /**
  2. * Generate `docs/persistence-catalog.md` from every `SessionEventMap` merge and
  3. * the owning event-envelope types. This is the durable-record vocabulary, not
  4. * the live Cordis bus. Event declarations must be unique, explicitly typed,
  5. * documented, inheritance-free, and free of Cordis-only `@mode` tags; every
  6. * surface-union member must resolve to one. `--check` verifies the artifact.
  7. */
  8. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  9. import { resolve, sep } from 'node:path'
  10. import ts from 'typescript'
  11. import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  12. import { githubSlug } from './verify-md-links.ts'
  13. const root = resolve(import.meta.dirname, '..')
  14. const OUT = 'docs/persistence-catalog.md'
  15. const OUT_RUNTIME_TYPES = 'packages/core/session/src/known-event-types.ts'
  16. /** The fenced-block info string for generated declaration blocks (skipped by
  17. * doc-typecheck, since their imported types are not standalone-compilable). */
  18. const FENCE = 'ts persistence-catalog'
  19. /** The package that owns the durable event vocabulary. */
  20. const SESSION_PACKAGE = '@deepseek-ai/dsh-session'
  21. /** The type-only module that plugin declaration merges augment. */
  22. const SESSION_TYPES_MODULE = '@deepseek-ai/dsh-session/types'
  23. /** Event-envelope declarations rendered before the per-event vocabulary. */
  24. const EVENT_ENVELOPE_TYPE_NAMES = [
  25. 'SessionEventType',
  26. 'SurfaceEventType',
  27. 'SurfaceOp',
  28. 'SessionEvent',
  29. ] as const
  30. type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number]
  31. /** Primary subsystems page for linked payload types. */
  32. const LINK_MAP: Record<string, string> = {
  33. CallId: 'core.md',
  34. ContentBlock: 'core.md',
  35. MessageSource: 'core.md',
  36. ScheduleChange: 'schedule.md',
  37. StreamChunk: 'llm-streaming.md',
  38. TokenUsage: 'llm-streaming.md',
  39. TodoItem: 'session.md',
  40. TurnTrigger: 'session.md',
  41. TurnEndReason: 'session.md',
  42. SessionTitleEventData: 'session-title.md',
  43. SessionTitleLlmRequestEventData: 'session-title.md',
  44. SessionTitleModelProvenance: 'session-title.md',
  45. SessionTitleProviderId: 'session-title.md',
  46. SessionTitleSource: 'session-title.md',
  47. }
  48. /** One log event, extracted from a `SessionEventMap` declaration. */
  49. export interface LogEventEntry {
  50. /** Scoped name, e.g. `turn/start`. */
  51. name: string
  52. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  53. scope: string
  54. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  55. payload: string
  56. /** Source member declaration and complete JSDoc, dedented from its container. */
  57. declaration: string
  58. /** Description prose (the member's JSDoc), one line per paragraph. */
  59. doc: string
  60. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  61. source: string
  62. }
  63. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  64. export interface AnnotatedLogEventEntry extends LogEventEntry {
  65. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  66. surface: boolean
  67. }
  68. /** One owning event-envelope declaration pasted into the generated catalog. */
  69. export interface EventEnvelopeTypeEntry {
  70. /** Exported declaration name. */
  71. name: EventEnvelopeTypeName
  72. /** Verbatim type declaration, including its complete leading JSDoc. */
  73. declaration: string
  74. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  75. source: string
  76. }
  77. const printer = ts.createPrinter({ removeComments: true })
  78. /**
  79. * Render a member type on one line through the TypeScript printer, which adds
  80. * semicolon separators. Drop its trailing semicolon before `}` to match the
  81. * repository's inline-literal style.
  82. */
  83. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  84. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  85. .replace(/\s+/g, ' ')
  86. .replace(/;\s*\}/g, ' }')
  87. .trim()
  88. }
  89. /**
  90. * Copy a declaration from its leading JSDoc through its closing token while
  91. * removing only the indentation imposed by its containing interface/module.
  92. */
  93. function declarationText(text: string, sf: ts.SourceFile, node: ts.Node): string {
  94. const raw = rawJsDoc(text, node)
  95. const nodeStart = node.getStart(sf)
  96. const start = raw ? text.lastIndexOf(raw, nodeStart) : nodeStart
  97. const { line } = sf.getLineAndCharacterOfPosition(start)
  98. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  99. const indent = text.slice(lineStart, start)
  100. return text.slice(lineStart, node.end)
  101. .split('\n')
  102. .map(lineText => lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText)
  103. .join('\n')
  104. .trimEnd()
  105. }
  106. /**
  107. * Every `interface SessionEventMap` declaration in a source file: the owning
  108. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  109. * merge inside a `declare module '@deepseek-ai/dsh-session/types'` block. Both forms
  110. * declare members of the SAME merged interface, so both are catalogued
  111. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  112. * it actually lives in the owning package — an unrelated local interface that
  113. * happens to share the name must not be catalogued as the on-disk vocabulary.
  114. */
  115. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  116. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  117. for (const stmt of sf.statements) {
  118. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  119. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_TYPES_MODULE
  120. && stmt.body && ts.isModuleBlock(stmt.body)) {
  121. for (const inner of stmt.body.statements) {
  122. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  123. }
  124. }
  125. }
  126. return decls
  127. }
  128. /**
  129. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  130. * from that package's manifest — or null when the manifest is missing or
  131. * unparseable (the caller treats null as "ownership unverifiable").
  132. */
  133. function packageNameFor(rel: string, scanRoot: string): string | null {
  134. const dir = rel.split('/').slice(0, 3).join('/')
  135. try {
  136. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  137. return typeof manifest.name === 'string' ? manifest.name : null
  138. } catch {
  139. // Missing or malformed package.json — every real workspace package has one,
  140. // so this only arises in stripped-down fixture trees; either way ownership
  141. // cannot be verified and the caller reports the declaration.
  142. return null
  143. }
  144. }
  145. /**
  146. * Collect every `SessionEventMap` merge, rejecting inherited, non-literal,
  147. * untyped, undocumented, duplicate, or incorrectly owned members in one report.
  148. */
  149. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  150. const entries: LogEventEntry[] = []
  151. const violations: string[] = []
  152. const seen = new Map<string, string>()
  153. let owningDecl: string | null = null
  154. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  155. const abs = resolve(scanRoot, rel)
  156. const text = readFileSync(abs, 'utf8')
  157. if (!text.includes('SessionEventMap')) continue
  158. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  159. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  160. const declSrc = pointer(rel, sf, decl)
  161. if (topLevel) {
  162. // The top-level form has one home: the single exported declaration in
  163. // the owning package. Same-named interfaces elsewhere are different
  164. // types and must not enter the on-disk catalog.
  165. const pkg = packageNameFor(rel, scanRoot)
  166. if (pkg !== SESSION_PACKAGE) {
  167. 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}'.`)
  168. continue
  169. }
  170. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  171. if (!exported) {
  172. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  173. continue
  174. }
  175. if (owningDecl) {
  176. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  177. continue
  178. }
  179. owningDecl = declSrc
  180. }
  181. if (decl.heritageClauses?.length) {
  182. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  183. }
  184. for (const member of decl.members) {
  185. const src = pointer(rel, sf, member)
  186. if (!ts.isPropertySignature(member) || !member.type) {
  187. // A method-form or type-less member still joins `keyof SessionEventMap`,
  188. // so skipping it silently would be exactly the undocumented-event hole
  189. // this catalog exists to close.
  190. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  191. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  192. continue
  193. }
  194. if (!ts.isStringLiteral(member.name)) {
  195. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  196. continue
  197. }
  198. const name = member.name.text
  199. const where = `log event '${name}' (${src})`
  200. const prior = seen.get(name)
  201. if (prior) {
  202. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  203. continue
  204. }
  205. seen.set(name, src)
  206. const payload = payloadText(member.type, sf)
  207. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  208. if (hasMode) {
  209. 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.`)
  210. }
  211. if (!doc) {
  212. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  213. }
  214. const declaration = declarationText(text, sf, member)
  215. entries.push({ name, scope: name.split('/')[0] ?? name, payload, declaration, doc, source: src })
  216. }
  217. }
  218. }
  219. reportViolations('gen-persistence-catalog', violations)
  220. return entries
  221. }
  222. /**
  223. * Collect the exported declarations that compose the persisted event envelope,
  224. * preserving their source JSDoc and declaration text.
  225. */
  226. export function collectEventEnvelopeTypes(scanRoot: string = root): EventEnvelopeTypeEntry[] {
  227. const found = new Map<EventEnvelopeTypeName, EventEnvelopeTypeEntry>()
  228. const violations: string[] = []
  229. const wanted = new Set<string>(EVENT_ENVELOPE_TYPE_NAMES)
  230. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  231. const abs = resolve(scanRoot, rel)
  232. const text = readFileSync(abs, 'utf8')
  233. if (!EVENT_ENVELOPE_TYPE_NAMES.some(name => text.includes(name))) continue
  234. if (packageNameFor(rel, scanRoot) !== SESSION_PACKAGE) continue
  235. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  236. for (const stmt of sf.statements) {
  237. if (!ts.isTypeAliasDeclaration(stmt) || !wanted.has(stmt.name.text)) continue
  238. const name = stmt.name.text as EventEnvelopeTypeName
  239. const src = pointer(rel, sf, stmt)
  240. const where = `event-envelope type '${name}' (${src})`
  241. const prior = found.get(name)
  242. if (prior) {
  243. violations.push(`${where} is already declared at ${prior.source}; the persisted envelope type has exactly one owner.`)
  244. continue
  245. }
  246. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) {
  247. violations.push(`${where} is not exported.`)
  248. }
  249. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, stmt))
  250. if (hasMode) violations.push(`${where} carries an @mode tag, but a persisted type has no dispatch mode.`)
  251. if (!doc) violations.push(`${where} has no description prose. The full JSDoc is part of the generated catalog.`)
  252. found.set(name, { name, declaration: declarationText(text, sf, stmt), source: src })
  253. }
  254. }
  255. const missing = EVENT_ENVELOPE_TYPE_NAMES.filter(name => !found.has(name))
  256. if (missing.length > 0) {
  257. violations.push(`missing event-envelope declaration(s): ${missing.join(', ')}.`)
  258. }
  259. reportViolations('gen-persistence-catalog', violations)
  260. return EVENT_ENVELOPE_TYPE_NAMES.map((name) => {
  261. const entry = found.get(name)
  262. if (!entry) throw new Error(`gen-persistence-catalog: missing checked event-envelope declaration '${name}'.`)
  263. return entry
  264. })
  265. }
  266. /**
  267. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  268. * types — from source. Hard-errors when the alias is missing, declared more
  269. * than once, or contains a non-string-literal member: the badge derivation
  270. * relies on the union being a closed set of literal event names.
  271. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  272. */
  273. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  274. const found: { names: string[]; source: string }[] = []
  275. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  276. const abs = resolve(scanRoot, rel)
  277. const text = readFileSync(abs, 'utf8')
  278. if (!text.includes('SurfaceEventType')) continue
  279. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  280. for (const stmt of sf.statements) {
  281. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  282. const src = pointer(rel, sf, stmt)
  283. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  284. const names: string[] = []
  285. for (const m of members) {
  286. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  287. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  288. }
  289. found.push({ names, source: src })
  290. }
  291. }
  292. const only = found[0]
  293. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  294. 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.`)
  295. return only.names
  296. }
  297. /**
  298. * Attach the surface/log-only badge to each event. Hard-errors when a
  299. * `SurfaceEventType` union member names no collected event — a stale union
  300. * member would otherwise silently badge nothing.
  301. */
  302. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  303. const names = new Set(events.map(e => e.name))
  304. const stale = surfaceTypes.filter(t => !names.has(t))
  305. if (stale.length > 0) {
  306. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  307. }
  308. const surface = new Set(surfaceTypes)
  309. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  310. }
  311. /** Render the cross-link "Types:" line for a payload, or '' if none apply. */
  312. function typeLinks(payload: string): string {
  313. const seen = new Set<string>()
  314. for (const name of Object.keys(LINK_MAP)) {
  315. if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
  316. }
  317. if (seen.size === 0) return ''
  318. const links = [...seen].sort().map(n => `[${n}](subsystems/${LINK_MAP[n]})`)
  319. return `Types: ${links.join(' · ')}`
  320. }
  321. /** Render one log event entry. */
  322. function renderEvent(e: AnnotatedLogEventEntry): string[] {
  323. const heading = `${e.name} — ${e.surface ? 'surface' : 'log-only'}`
  324. const out = [`<a id="${githubSlug(heading)}"></a>`, '', `#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, '']
  325. out.push('```' + FENCE, e.declaration, '```', '')
  326. const links = typeLinks(e.payload)
  327. if (links) out.push(links, '')
  328. out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '')
  329. return out
  330. }
  331. /** Render the full catalog (pure, deterministic given the collected inputs). */
  332. export function render(events: AnnotatedLogEventEntry[], envelopeTypes: EventEnvelopeTypeEntry[]): string {
  333. const lines: string[] = [
  334. '<!-- Generated by scripts/gen-persistence-catalog.ts — do not edit by hand.',
  335. ' Run `pnpm run gen-persistence-catalog` to regenerate. -->',
  336. '',
  337. '# Session Persistence Event Catalog',
  338. '',
  339. 'Every event type that can appear in a session\'s durable event log: the complete persisted `SessionEvent` envelope and each member of the merge-extensible `SessionEventMap` — the owning vocabulary in `@deepseek-ai/dsh-session` plus every plugin declaration merge into `@deepseek-ai/dsh-session/types` in this repo — with source JSDoc, full payload declaration, surface badge, and declaration site. It complements [session.md](subsystems/session.md) (surface ordering and the `deriveMessages()` projection), [persistence.md](subsystems/persistence.md) (how the log is made durable), and the generated region of [session.md](subsystems/session.md#cordis-surface) (the live bus wiring — a log event is NOT a cordis event; it reaches listeners via the single `session/event` emit).',
  340. '',
  341. 'This file is GENERATED from source (`scripts/gen-persistence-catalog.ts`) and verified fresh by `pnpm run verify-persistence-catalog` (part of `doc-sync`) — do not edit it by hand. Declaration blocks retain the source declaration and nested property JSDoc, removing only the indentation imposed by a containing interface/module, and use a `ts persistence-catalog` fence (skipped by doc-typecheck because declarations reference types from their owning modules). Type names in a payload link to the page that documents them. See [the persistence-log-catalog Agent Note](../.agents/notes/archived/process/2026-07-04-persistence-log-catalog.md).',
  342. '',
  343. 'The envelope declarations below compose each event\'s `type`, monotonic `seq`, epoch-ms `time`, `data`, the optional `ignorable` unknown-type skip marker, and the conditional `surfaceOp`/`sourceEventSeqs` fields. **surface** marks a `SurfaceEventType` member: it produces an LLM message and declares how it joins the surface list. **log-only** marks everything else: a durable, replayable record with no derived-history contribution. Every payload is JSON-serializable (enforced at `Session.append`), and the whole format is pinned at `SESSION_FORMAT_VERSION = 0` — pre-release, no compatibility implied ([the version stance](subsystems/persistence.md)). Scope: the packages in this repo; a downstream plugin can merge further event types, which are outside this catalog by construction.',
  344. '',
  345. '## Event envelope',
  346. '',
  347. '```' + FENCE,
  348. envelopeTypes.map(entry => entry.declaration).join('\n\n'),
  349. '```',
  350. '',
  351. `Sources: ${envelopeTypes.map(entry => `[\`${entry.source}\`](../${entry.source.split(':')[0]})`).join(' · ')}`,
  352. '',
  353. '## Events',
  354. '',
  355. ]
  356. const scopes = [...new Set(events.map(e => e.scope))].sort()
  357. for (const scope of scopes) {
  358. lines.push(`### \`${scope}/*\``, '')
  359. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  360. lines.push(...renderEvent(e))
  361. }
  362. }
  363. return lines.join('\n')
  364. }
  365. /**
  366. * Render the runtime known-vocabulary module: every event type the packages in
  367. * this repo can write, as a generated `ReadonlySet` the read path checks
  368. * unknown-type refusal against (`SessionEvent.ignorable` contract).
  369. */
  370. export function renderKnownEventTypes(events: AnnotatedLogEventEntry[]): string {
  371. const names = [...new Set(events.map(e => e.name))].sort()
  372. return [
  373. '/**',
  374. ' * GENERATED by `scripts/gen-persistence-catalog.ts` — do not edit by hand; run',
  375. ' * `pnpm run gen-persistence-catalog` to regenerate (verified fresh by',
  376. ' * `pnpm run verify-persistence-catalog`, part of `doc-sync`).',
  377. ' * @module @deepseek-ai/dsh-session/known-event-types',
  378. ' */',
  379. '',
  380. '/**',
  381. ' * Every `SessionEventMap` member declared in this repository — the event',
  382. ' * vocabulary this build understands. The persistence read path refuses to',
  383. ' * interpret a log containing a type outside this set unless the event',
  384. ' * carries the envelope\'s `ignorable` marker (see `SessionEvent.ignorable`',
  385. ' * in `./types.ts`): such a log was likely written by a newer harness, and',
  386. ' * silently skipping a required event would reconstruct a wrong session.',
  387. ' * Downstream (out-of-repo) plugin events are outside this list by',
  388. ' * construction; a registration surface for them is deferred until such a',
  389. ' * consumer exists.',
  390. ' */',
  391. 'export const KNOWN_SESSION_EVENT_TYPES: ReadonlySet<string> = new Set([',
  392. ...names.map(name => ` '${name}',`),
  393. '])',
  394. '',
  395. ].join('\n')
  396. }
  397. /** One generated artifact: repo-relative target and its freshly-rendered content. */
  398. interface GeneratedArtifact {
  399. readonly out: string
  400. readonly content: string
  401. }
  402. /** CLI entry: default writes the artifacts, `--check` fails if a committed copy
  403. * is stale. Guarded behind an entry-point check so importing this module for
  404. * tests neither regenerates the committed files nor calls process.exit. */
  405. function main(): void {
  406. const events = annotateSurface(collectLogEvents(), collectSurfaceEventTypes())
  407. const artifacts: GeneratedArtifact[] = [
  408. { out: OUT, content: render(events, collectEventEnvelopeTypes()) },
  409. { out: OUT_RUNTIME_TYPES, content: renderKnownEventTypes(events) },
  410. ]
  411. if (process.argv.includes('--check')) {
  412. const stale = artifacts.filter((artifact) => {
  413. let committed: string | null = null
  414. try {
  415. committed = readFileSync(resolve(root, artifact.out), 'utf8')
  416. } catch {
  417. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  418. // file is not a state this repo produces. Either way the remedy is the
  419. // same — regenerate — so treat a read failure as "stale".
  420. committed = null
  421. }
  422. return committed !== artifact.content
  423. })
  424. if (stale.length === 0) {
  425. console.log(`gen-persistence-catalog: ${artifacts.map(a => a.out).join(', ')} are up to date.`)
  426. process.exit(0)
  427. }
  428. console.error(`gen-persistence-catalog: ${stale.map(a => a.out).join(', ')} stale. Run \`pnpm run gen-persistence-catalog\` and commit the result.`)
  429. process.exit(1)
  430. }
  431. for (const artifact of artifacts) {
  432. writeFileSync(resolve(root, artifact.out), artifact.content)
  433. console.log(`gen-persistence-catalog: wrote ${artifact.out}.`)
  434. }
  435. }
  436. // Run only when invoked as a script, not when imported by a test.
  437. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  438. main()
  439. }