verify-type-equiv.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /**
  2. * Doc-sync gate: verify every ` ```ts type-equiv ` block in the docs is a
  3. * VERBATIM copy of the source type definition it documents.
  4. *
  5. * The core-data-structures docs paste real type definitions so a reader sees
  6. * the exact shape. A paste drifts the moment source changes — this script is
  7. * the drift guard. For each block it extracts the documented symbol's
  8. * declaration from source via the TypeScript compiler API, whitespace-
  9. * normalizes both the source text and the block, and asserts they are equal.
  10. *
  11. * Provenance lives in a central manifest (`scripts/type-equiv.manifest.json`),
  12. * NOT in the doc prose: each entry names `{ doc, symbol, source }`. The script
  13. * enforces a 1:1 correspondence — every type-equiv block in the docs has
  14. * exactly one manifest entry (keyed by doc + declared symbol), and every
  15. * manifest entry resolves to exactly one block. An orphan on either side fails,
  16. * so a block can never be silently unchecked and an entry can never rot.
  17. *
  18. * doc-typecheck.ts recognizes the same ` ```ts type-equiv ` fence and skips it
  19. * (it is not standalone-compilable and is not counted in the opt-out ratio);
  20. * the two scripts share the fence, this one owns the verification.
  21. *
  22. * Run: `tsx scripts/verify-type-equiv.ts`.
  23. */
  24. import { globSync, readFileSync, existsSync } from 'node:fs'
  25. import { resolve } from 'node:path'
  26. import ts from 'typescript'
  27. const root = resolve(import.meta.dirname, '..')
  28. /**
  29. * Markdown globs scanned for ` ```ts type-equiv ` blocks — the SAME scope
  30. * doc-typecheck uses. Scanning every doc (not only the docs the manifest names)
  31. * is what makes the 1:1 guarantee real in both directions: a type-equiv block
  32. * added to a doc with NO manifest entry is still discovered here and reported as
  33. * an orphan, instead of being silently skipped.
  34. */
  35. const MARKDOWN_GLOBS = ['README.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
  36. /** One manifest entry: a documented type-equiv block and its source symbol. */
  37. interface ManifestEntry {
  38. /** Doc file (repo-relative) containing the ` ```ts type-equiv ` block. */
  39. doc: string
  40. /** The declared symbol the block must match (e.g. `SessionEvent`). */
  41. symbol: string
  42. /** Source file (repo-relative) that exports the symbol. */
  43. source: string
  44. }
  45. /** One extracted ` ```ts type-equiv ` block. */
  46. interface EquivBlock {
  47. doc: string
  48. /** 1-based line of the opening fence (for diagnostics). */
  49. line: number
  50. /** Symbol name parsed from the block's declaration. */
  51. symbol: string
  52. /** Block body (the pasted declaration). */
  53. code: string
  54. }
  55. /** Collapse a declaration to its structural form for comparison: drop comments
  56. * (block + line), then collapse all whitespace runs to single spaces. This lets
  57. * a doc block show a CLEAN definition (without source's verbose inline JSDoc)
  58. * while still guaranteeing the field shapes match — drift in a field name or
  59. * type fails; a reworded inline comment does not. Adequate for our own type
  60. * source (no string literal contains `//` or `/* *​/`); not a general tokenizer. */
  61. function normalize(code: string): string {
  62. return code
  63. .replace(/\/\*[\s\S]*?\*\//g, '')
  64. .replace(/(^|[^:])\/\/.*$/gm, '$1')
  65. .replace(/\s+/g, ' ')
  66. .trim()
  67. }
  68. /** Strip a leading `export ` / `export default ` modifier — the doc block shows
  69. * the bare declaration, the source carries the export modifier. */
  70. function stripExport(code: string): string {
  71. return code.replace(/^export\s+(default\s+)?/, '')
  72. }
  73. /** Parse the declared symbol name from a type-equiv block body. */
  74. function blockSymbol(code: string): string | null {
  75. const m = /(?:export\s+(?:default\s+)?)?(?:abstract\s+)?(?:interface|type|class|enum)\s+([A-Za-z0-9_]+)/.exec(code)
  76. return m?.[1] ?? null
  77. }
  78. /** Extract every ` ```ts type-equiv ` block from one Markdown file. */
  79. function extractEquivBlocks(docRel: string): EquivBlock[] {
  80. const text = readFileSync(resolve(root, docRel), 'utf8')
  81. const lines = text.split('\n')
  82. const blocks: EquivBlock[] = []
  83. let open: { line: number; body: string[] } | null = null
  84. for (let i = 0; i < lines.length; i++) {
  85. const raw = lines[i] ?? ''
  86. const fence = /^```(\s*)(\S.*)?$/.exec(raw)
  87. if (!fence) {
  88. if (open) open.body.push(raw)
  89. continue
  90. }
  91. if (open) {
  92. const code = open.body.join('\n')
  93. const symbol = blockSymbol(code)
  94. if (!symbol) {
  95. throw new Error(`verify-type-equiv: ${docRel}:${open.line} — type-equiv block has no parseable interface/type/class declaration`)
  96. }
  97. blocks.push({ doc: docRel, line: open.line, symbol, code })
  98. open = null
  99. continue
  100. }
  101. if ((fence[2] ?? '').trim() === 'ts type-equiv') open = { line: i + 1, body: [] }
  102. }
  103. if (open) throw new Error(`verify-type-equiv: ${docRel}:${open.line} — unterminated type-equiv block`)
  104. return blocks
  105. }
  106. /** The declaration text of `symbol` in `sourceRel`, with `export` stripped, or
  107. * null when the symbol is not declared there. Uses the TS parser so it spans
  108. * interfaces, type aliases (including mapped/generic ones), classes, and enums
  109. * uniformly, and excludes the leading JSDoc (getStart skips leading trivia)
  110. * while keeping inline member comments. */
  111. function sourceDeclaration(sourceRel: string, symbol: string): string | null {
  112. const abs = resolve(root, sourceRel)
  113. const text = readFileSync(abs, 'utf8')
  114. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, /* setParentNodes */ true)
  115. for (const stmt of sf.statements) {
  116. const named =
  117. ts.isInterfaceDeclaration(stmt) || ts.isTypeAliasDeclaration(stmt)
  118. || ts.isClassDeclaration(stmt) || ts.isEnumDeclaration(stmt)
  119. if (named && stmt.name?.text === symbol) {
  120. return stripExport(stmt.getText(sf))
  121. }
  122. }
  123. return null
  124. }
  125. const manifestRaw = readFileSync(resolve(root, 'scripts/type-equiv.manifest.json'), 'utf8')
  126. const manifest = JSON.parse(manifestRaw) as { entries: ManifestEntry[] }
  127. const entries = manifest.entries
  128. // Key a block/entry by doc + symbol (a symbol may be documented in more than one
  129. // doc, but at most once per doc).
  130. const keyOf = (x: { doc: string; symbol: string }): string => `${x.doc}::${x.symbol}`
  131. // Collect every type-equiv block across ALL docs in scope — not only the docs
  132. // the manifest names — so a block in an unmanifested doc is found and reported
  133. // as an orphan rather than silently skipped.
  134. const docSet = new Set<string>()
  135. for (const pattern of MARKDOWN_GLOBS) {
  136. for (const match of globSync(pattern, { cwd: root })) docSet.add(match)
  137. }
  138. const blocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks)
  139. const errors: string[] = []
  140. // A manifest entry naming a doc that does not exist (or is outside the scanned
  141. // scope, so no block could ever match it) is an error in its own right.
  142. for (const d of [...new Set(entries.map(e => e.doc))]) {
  143. if (!existsSync(resolve(root, d))) errors.push(`manifest references ${d}, which does not exist`)
  144. else if (!docSet.has(d)) errors.push(`manifest references ${d}, which is outside the scanned markdown scope (${MARKDOWN_GLOBS.join(', ')})`)
  145. }
  146. // Duplicate-block guard: the same symbol twice in one doc is ambiguous.
  147. const blockByKey = new Map<string, EquivBlock>()
  148. for (const b of blocks) {
  149. const k = keyOf(b)
  150. const prior = blockByKey.get(k)
  151. if (prior) {
  152. errors.push(`duplicate type-equiv block for ${b.symbol} in ${b.doc} (lines ${prior.line} and ${b.line})`)
  153. continue
  154. }
  155. blockByKey.set(k, b)
  156. }
  157. // Duplicate-entry guard in the manifest.
  158. const entryByKey = new Map<string, ManifestEntry>()
  159. for (const e of entries) {
  160. const k = keyOf(e)
  161. if (entryByKey.has(k)) {
  162. errors.push(`duplicate manifest entry for ${e.symbol} in ${e.doc}`)
  163. continue
  164. }
  165. entryByKey.set(k, e)
  166. }
  167. // 1:1 correspondence: orphan blocks (no entry) and orphan entries (no block).
  168. for (const b of blocks) {
  169. if (!entryByKey.has(keyOf(b))) {
  170. errors.push(`type-equiv block ${b.symbol} (${b.doc}:${b.line}) has no manifest entry — add one to scripts/type-equiv.manifest.json`)
  171. }
  172. }
  173. for (const e of entries) {
  174. if (!blockByKey.has(keyOf(e))) {
  175. errors.push(`manifest entry ${e.symbol} (${e.doc}) has no matching type-equiv block — remove it or add the block`)
  176. }
  177. }
  178. // Verbatim check: each matched block must equal its source declaration.
  179. let verified = 0
  180. for (const e of entries) {
  181. const b = blockByKey.get(keyOf(e))
  182. if (!b) continue // already reported as an orphan entry
  183. const decl = sourceDeclaration(e.source, e.symbol)
  184. if (decl === null) {
  185. errors.push(`symbol ${e.symbol} not found in ${e.source} (manifest entry for ${e.doc})`)
  186. continue
  187. }
  188. if (normalize(decl) !== normalize(stripExport(b.code))) {
  189. errors.push(
  190. `DRIFT: ${e.doc}:${b.line} — type-equiv block for ${e.symbol} does not match ${e.source}.\n`
  191. + ` source: ${normalize(decl)}\n`
  192. + ` doc: ${normalize(stripExport(b.code))}`,
  193. )
  194. continue
  195. }
  196. verified++
  197. }
  198. if (errors.length === 0) {
  199. console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source (1:1 with manifest).`)
  200. process.exit(0)
  201. }
  202. console.error('verify-type-equiv: type-equiv verification failed:')
  203. for (const e of errors) console.error(` ${e}`)
  204. console.error(`\n(checked ${blocks.length} block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s); manifest at scripts/type-equiv.manifest.json)`)
  205. process.exit(1)