jsdoc.ts 9.5 KB

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