jsdoc.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * Shared JSDoc parsing and completeness-check helpers for the documentation
  3. * gates: the cordis catalog generator (`scripts/gen-cordis-catalog.ts` — the
  4. * events + `ctx.<key>` service surface), the plugin config catalog generator
  5. * (`scripts/gen-config-catalog.ts`, which renders the parsed prose), and the
  6. * export-surface gate (`scripts/verify-export-jsdoc.ts` — every module-level
  7. * export). One home for the mechanics so "documented" means the same thing on
  8. * every gated surface: description prose ends at the first block tag; every
  9. * checkable parameter needs a non-empty `@param`; a non-void ANNOTATED return
  10. * needs a non-empty `@returns`; a stale `@param` naming no real parameter
  11. * errors.
  12. */
  13. import ts from 'typescript'
  14. /** Repo-relative source pointer `file:line` for a node's first character. */
  15. export function pointer(rel: string, sf: ts.SourceFile, node: ts.Node): string {
  16. const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf))
  17. return `${rel}:${line + 1}`
  18. }
  19. /** The raw `/** … *​/` JSDoc block immediately preceding a node, or '' if none. */
  20. export function rawJsDoc(text: string, node: ts.Node): string {
  21. const ranges = ts.getLeadingCommentRanges(text, node.getFullStart()) ?? []
  22. const jsdoc = ranges.filter(r => text.slice(r.pos, r.pos + 3) === '/**').at(-1)
  23. return jsdoc ? text.slice(jsdoc.pos, jsdoc.end) : ''
  24. }
  25. /** A dispatch mode, rendered as the badge after an event name in the catalog. */
  26. export type Mode = 'emit' | 'waterfall' | 'parallel' | 'serial'
  27. /**
  28. * Parse a raw JSDoc block into description prose + the `@mode` tag (when
  29. * present). Output obeys the repo's markdown conventions so the generated
  30. * catalog passes verify-md-wrap: each prose paragraph collapses to ONE physical
  31. * line, and a `-` bullet list is preserved with each item on its own single
  32. * line (continuation lines folded in). `{@link Foo}` unwraps to `Foo`.
  33. * Description prose ends at the FIRST block tag (standard JSDoc semantics):
  34. * tag lines and their continuation lines are never prose, so `@param` /
  35. * `@returns` blocks are invisible to the rendered catalog.
  36. * @param raw - the raw comment text including the JSDoc delimiters.
  37. * @returns the collapsed description prose plus the parsed `@mode` (or null).
  38. */
  39. export function parseJsDoc(raw: string): { doc: string; mode: Mode | null } {
  40. const inner = raw
  41. .replace(/^\/\*\*/, '')
  42. .replace(/\*\/$/, '')
  43. .split('\n')
  44. .map(l => l.replace(/^\s*\*?\s?/, '').replace(/\s+$/, ''))
  45. let mode: Mode | null = null
  46. let inTags = false
  47. const blocks: string[] = []
  48. let para: string[] = []
  49. let list: string[] = []
  50. let item: string[] = []
  51. const join = (parts: string[]): string => parts.join(' ').replace(/\s+/g, ' ').trim()
  52. const flushItem = (): void => {
  53. if (item.length) list.push(join(item))
  54. item = []
  55. }
  56. const flushList = (): void => {
  57. flushItem()
  58. if (list.length) blocks.push(list.join('\n')) // one block, items on own lines
  59. list = []
  60. }
  61. const flushPara = (): void => {
  62. flushList()
  63. if (para.length) blocks.push(join(para))
  64. para = []
  65. }
  66. for (const line of inner) {
  67. const m = /^@mode\s+(emit|waterfall|parallel|serial)\s*$/.exec(line)
  68. if (m) { mode = m[1] as Mode; flushPara(); inTags = true; continue }
  69. if (line.startsWith('@')) { flushPara(); inTags = true; continue }
  70. if (inTags) continue // block-tag territory: continuations are never prose
  71. if (line.trim() === '') { flushPara(); continue }
  72. if (/^-\s+/.test(line)) {
  73. // A list item starts: a pending paragraph (e.g. an intro line directly
  74. // above the list, no blank between) flushes FIRST so it renders above.
  75. flushItem()
  76. if (para.length) { blocks.push(join(para)); para = [] }
  77. item.push(line)
  78. continue
  79. }
  80. if (item.length) { item.push(line); continue } // continuation of current item
  81. para.push(line)
  82. }
  83. flushPara()
  84. const doc = blocks.join('\n\n').replace(/\{@link\s+([^}]+)\}/g, '$1').trim()
  85. return { doc, mode }
  86. }
  87. /**
  88. * Parse the block tags of a raw JSDoc comment for the completeness checks:
  89. * every `@param name — description` entry plus the `@returns` description.
  90. * Standard JSDoc block-tag semantics — a tag's description runs across
  91. * continuation lines until the next tag or a blank line, and the `-`/`—`
  92. * separator after a param name is optional. `[name]` optional-brackets unwrap
  93. * to `name`. Rendering never sees these: parseJsDoc stops prose at the first
  94. * block tag.
  95. * @param raw - the raw comment text including the JSDoc delimiters.
  96. * @returns the `@param` name→description map plus the `@returns` description
  97. * (null when the tag is absent, '' when present but empty).
  98. */
  99. export function parseTags(raw: string): { params: Map<string, string>; returns: string | null } {
  100. const inner = raw
  101. .replace(/^\/\*\*/, '')
  102. .replace(/\*\/$/, '')
  103. .split('\n')
  104. .map(l => l.replace(/^\s*\*?\s?/, '').replace(/\s+$/, ''))
  105. const params = new Map<string, string>()
  106. let returns: string | null = null
  107. let sink: ((text: string) => void) | null = null
  108. for (const line of inner) {
  109. const param = /^@param\s+(\[?[\w$]+\]?)\s*(?:[-—–]\s*)?(.*)$/.exec(line)
  110. if (param) {
  111. const name = (param[1] ?? '').replace(/^\[|\]$/g, '')
  112. let acc = param[2] ?? ''
  113. params.set(name, acc)
  114. sink = (t) => { acc = acc ? `${acc} ${t}` : t; params.set(name, acc) }
  115. continue
  116. }
  117. const ret = /^@returns?(?:\s+[-—–]?\s*(.*))?$/.exec(line)
  118. if (ret) {
  119. let acc = ret[1] ?? ''
  120. returns = acc
  121. sink = (t) => { acc = acc ? `${acc} ${t}` : t; returns = acc }
  122. continue
  123. }
  124. if (line.startsWith('@') || line.trim() === '') { sink = null; continue }
  125. sink?.(line.trim())
  126. }
  127. return { params, returns }
  128. }
  129. /**
  130. * Check the `@param` half of the completeness contract for one function-like
  131. * declaration: every checkable parameter carries a non-empty `@param`, and no
  132. * `@param` is stale. A binding-pattern parameter is a violation (it has no name
  133. * for `@param` to match); an exempt parameter may be documented but its absence
  134. * is never checked. Violations append to `violations` in place.
  135. * @param where - the offender label violations open with, e.g. `event 'x' (file:1)`.
  136. * @param surface - the surface noun for the binding-pattern message ("event", "service", "export").
  137. * @param parameters - the declaration's parameter list.
  138. * @param tags - the parsed `@param` name→description map from parseTags.
  139. * @param sf - the source file (for rendering a binding pattern's text).
  140. * @param isExempt - which parameters need no `@param` (e.g. `this`, a waterfall's trailing `next`).
  141. * @param violations - the aggregate list violations append to.
  142. */
  143. export function checkParams(
  144. where: string,
  145. surface: string,
  146. parameters: readonly ts.ParameterDeclaration[],
  147. tags: Map<string, string>,
  148. sf: ts.SourceFile,
  149. isExempt: (p: ts.ParameterDeclaration) => boolean,
  150. violations: string[],
  151. ): void {
  152. for (const p of parameters) {
  153. if (!ts.isIdentifier(p.name)) {
  154. violations.push(`${where}: parameter '${p.name.getText(sf)}' is a binding pattern; the ${surface} surface needs simple identifier parameters so @param can name them.`)
  155. continue
  156. }
  157. if (isExempt(p)) continue
  158. const desc = tags.get(p.name.text)
  159. if (desc === undefined) violations.push(`${where} is missing @param ${p.name.text}.`)
  160. else if (!desc.trim()) violations.push(`${where}: @param ${p.name.text} has an empty description.`)
  161. }
  162. for (const tag of tags.keys()) {
  163. if (!parameters.some(p => ts.isIdentifier(p.name) && p.name.text === tag)) {
  164. violations.push(`${where}: @param ${tag} does not match any parameter (stale tag?).`)
  165. }
  166. }
  167. }
  168. /**
  169. * Check the `@returns` half of the completeness contract: a non-`void` /
  170. * `Promise<void>` return needs a non-empty `@returns`, and the return type must
  171. * be ANNOTATED — a pure-AST walk cannot classify an inferred return. On a void
  172. * declaration `@returns` stays optional (resolution timing can be worth
  173. * documenting), never required. Violations append to `violations` in place.
  174. * @param where - the offender label violations open with.
  175. * @param typeNode - the declared return type annotation, or undefined when inferred.
  176. * @param returns - the parsed `@returns` description from parseTags (null when absent).
  177. * @param sf - the source file (for rendering the annotation's text).
  178. * @param violations - the aggregate list violations append to.
  179. */
  180. export function checkReturns(
  181. where: string,
  182. typeNode: ts.TypeNode | undefined,
  183. returns: string | null,
  184. sf: ts.SourceFile,
  185. violations: string[],
  186. ): void {
  187. if (typeNode === undefined) {
  188. violations.push(`${where} has no return type annotation; annotate it explicitly so the gate can classify the result.`)
  189. return
  190. }
  191. const rt = typeNode.getText(sf).replace(/\s+/g, ' ')
  192. if (/^(void|Promise<void>)$/.test(rt)) return
  193. if (returns === null) violations.push(`${where} is missing @returns (return type: ${rt}).`)
  194. else if (!returns.trim()) violations.push(`${where}: @returns has an empty description.`)
  195. }
  196. /**
  197. * Throw one aggregate error for every completeness violation a walk collected.
  198. * Aggregation (vs failing fast) is deliberate: a remediation pass sees the
  199. * whole list at once instead of replaying the gate once per offender.
  200. * @param gate - the reporting gate's name, prefixed to the error message.
  201. * @param violations - the collected violation lines; no-op when empty.
  202. */
  203. export function reportViolations(gate: string, violations: string[]): void {
  204. if (violations.length === 0) return
  205. throw new Error(
  206. `${gate}: ${violations.length} JSDoc completeness violation(s) (see AGENTS.md):\n`
  207. + violations.map(v => ` ${v}`).join('\n'),
  208. )
  209. }