gen-persistence-catalog.ts 23 KB

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