@metaobjectsdev/codegen-ts 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/README.md +1 -1
  2. package/dist/column-mapper.d.ts.map +1 -1
  3. package/dist/column-mapper.js +24 -8
  4. package/dist/column-mapper.js.map +1 -1
  5. package/dist/constants.d.ts +8 -0
  6. package/dist/constants.d.ts.map +1 -1
  7. package/dist/constants.js +16 -0
  8. package/dist/constants.js.map +1 -1
  9. package/dist/docs-paths.d.ts +58 -0
  10. package/dist/docs-paths.d.ts.map +1 -0
  11. package/dist/docs-paths.js +89 -0
  12. package/dist/docs-paths.js.map +1 -0
  13. package/dist/enum-import.d.ts +14 -0
  14. package/dist/enum-import.d.ts.map +1 -0
  15. package/dist/enum-import.js +35 -0
  16. package/dist/enum-import.js.map +1 -0
  17. package/dist/enum-shared.d.ts +32 -0
  18. package/dist/enum-shared.d.ts.map +1 -0
  19. package/dist/enum-shared.js +83 -0
  20. package/dist/enum-shared.js.map +1 -0
  21. package/dist/generator-registry.d.ts +22 -0
  22. package/dist/generator-registry.d.ts.map +1 -0
  23. package/dist/generator-registry.js +161 -0
  24. package/dist/generator-registry.js.map +1 -0
  25. package/dist/generator.d.ts +6 -0
  26. package/dist/generator.d.ts.map +1 -1
  27. package/dist/generator.js.map +1 -1
  28. package/dist/generators/api-doc-render.d.ts +17 -0
  29. package/dist/generators/api-doc-render.d.ts.map +1 -0
  30. package/dist/generators/api-doc-render.js +431 -0
  31. package/dist/generators/api-doc-render.js.map +1 -0
  32. package/dist/generators/api-docs-file.d.ts +21 -0
  33. package/dist/generators/api-docs-file.d.ts.map +1 -0
  34. package/dist/generators/api-docs-file.js +112 -0
  35. package/dist/generators/api-docs-file.js.map +1 -0
  36. package/dist/generators/api-field-shape.d.ts +39 -0
  37. package/dist/generators/api-field-shape.d.ts.map +1 -0
  38. package/dist/generators/api-field-shape.js +92 -0
  39. package/dist/generators/api-field-shape.js.map +1 -0
  40. package/dist/generators/api-label.d.ts +3 -0
  41. package/dist/generators/api-label.d.ts.map +1 -0
  42. package/dist/generators/api-label.js +8 -0
  43. package/dist/generators/api-label.js.map +1 -0
  44. package/dist/generators/api-model.d.ts +122 -0
  45. package/dist/generators/api-model.d.ts.map +1 -0
  46. package/dist/generators/api-model.js +809 -0
  47. package/dist/generators/api-model.js.map +1 -0
  48. package/dist/generators/docs-data-builder.d.ts +26 -4
  49. package/dist/generators/docs-data-builder.d.ts.map +1 -1
  50. package/dist/generators/docs-data-builder.js +436 -164
  51. package/dist/generators/docs-data-builder.js.map +1 -1
  52. package/dist/generators/docs-data.d.ts +136 -27
  53. package/dist/generators/docs-data.d.ts.map +1 -1
  54. package/dist/generators/docs-data.js +1 -1
  55. package/dist/generators/docs-data.js.map +1 -1
  56. package/dist/generators/docs-file.d.ts +19 -0
  57. package/dist/generators/docs-file.d.ts.map +1 -1
  58. package/dist/generators/docs-file.js +154 -27
  59. package/dist/generators/docs-file.js.map +1 -1
  60. package/dist/generators/entity-file.d.ts.map +1 -1
  61. package/dist/generators/entity-file.js +29 -14
  62. package/dist/generators/entity-file.js.map +1 -1
  63. package/dist/generators/extractor-file.d.ts.map +1 -1
  64. package/dist/generators/extractor-file.js +2 -1
  65. package/dist/generators/extractor-file.js.map +1 -1
  66. package/dist/generators/field-anchor.d.ts +7 -0
  67. package/dist/generators/field-anchor.d.ts.map +1 -0
  68. package/dist/generators/field-anchor.js +23 -0
  69. package/dist/generators/field-anchor.js.map +1 -0
  70. package/dist/generators/index.d.ts +8 -1
  71. package/dist/generators/index.d.ts.map +1 -1
  72. package/dist/generators/index.js +6 -0
  73. package/dist/generators/index.js.map +1 -1
  74. package/dist/generators/mermaid-er.d.ts +14 -0
  75. package/dist/generators/mermaid-er.d.ts.map +1 -1
  76. package/dist/generators/mermaid-er.js +14 -0
  77. package/dist/generators/mermaid-er.js.map +1 -1
  78. package/dist/generators/output-parser-file.d.ts.map +1 -1
  79. package/dist/generators/output-parser-file.js +3 -4
  80. package/dist/generators/output-parser-file.js.map +1 -1
  81. package/dist/generators/output-prompt-file.d.ts.map +1 -1
  82. package/dist/generators/output-prompt-file.js +2 -2
  83. package/dist/generators/output-prompt-file.js.map +1 -1
  84. package/dist/generators/prompt-render-file.d.ts.map +1 -1
  85. package/dist/generators/prompt-render-file.js +3 -4
  86. package/dist/generators/prompt-render-file.js.map +1 -1
  87. package/dist/generators/queries-file.d.ts.map +1 -1
  88. package/dist/generators/queries-file.js +8 -3
  89. package/dist/generators/queries-file.js.map +1 -1
  90. package/dist/generators/render-helper-file.d.ts.map +1 -1
  91. package/dist/generators/render-helper-file.js +2 -2
  92. package/dist/generators/render-helper-file.js.map +1 -1
  93. package/dist/generators/routes-file-hono.d.ts.map +1 -1
  94. package/dist/generators/routes-file-hono.js +5 -1
  95. package/dist/generators/routes-file-hono.js.map +1 -1
  96. package/dist/generators/routes-file.d.ts +3 -0
  97. package/dist/generators/routes-file.d.ts.map +1 -1
  98. package/dist/generators/routes-file.js +6 -1
  99. package/dist/generators/routes-file.js.map +1 -1
  100. package/dist/generators/template-doc-builder.d.ts +19 -0
  101. package/dist/generators/template-doc-builder.d.ts.map +1 -0
  102. package/dist/generators/template-doc-builder.js +220 -0
  103. package/dist/generators/template-doc-builder.js.map +1 -0
  104. package/dist/generators/template-doc-data.d.ts +62 -0
  105. package/dist/generators/template-doc-data.d.ts.map +1 -0
  106. package/dist/generators/template-doc-data.js +16 -0
  107. package/dist/generators/template-doc-data.js.map +1 -0
  108. package/dist/generators/template-payload-tree.d.ts +15 -0
  109. package/dist/generators/template-payload-tree.d.ts.map +1 -0
  110. package/dist/generators/template-payload-tree.js +61 -0
  111. package/dist/generators/template-payload-tree.js.map +1 -0
  112. package/dist/generators/template-source-annotate.d.ts +74 -0
  113. package/dist/generators/template-source-annotate.d.ts.map +1 -0
  114. package/dist/generators/template-source-annotate.js +184 -0
  115. package/dist/generators/template-source-annotate.js.map +1 -0
  116. package/dist/generators/template-source-render.d.ts +24 -0
  117. package/dist/generators/template-source-render.d.ts.map +1 -0
  118. package/dist/generators/template-source-render.js +175 -0
  119. package/dist/generators/template-source-render.js.map +1 -0
  120. package/dist/generators/trace-helper-file.d.ts +9 -0
  121. package/dist/generators/trace-helper-file.d.ts.map +1 -0
  122. package/dist/generators/trace-helper-file.js +196 -0
  123. package/dist/generators/trace-helper-file.js.map +1 -0
  124. package/dist/index.d.ts +29 -4
  125. package/dist/index.d.ts.map +1 -1
  126. package/dist/index.js +28 -2
  127. package/dist/index.js.map +1 -1
  128. package/dist/metaobjects-config.d.ts +75 -2
  129. package/dist/metaobjects-config.d.ts.map +1 -1
  130. package/dist/metaobjects-config.js +43 -0
  131. package/dist/metaobjects-config.js.map +1 -1
  132. package/dist/naming.d.ts +19 -0
  133. package/dist/naming.d.ts.map +1 -1
  134. package/dist/naming.js +41 -0
  135. package/dist/naming.js.map +1 -1
  136. package/dist/payload-codegen.d.ts.map +1 -1
  137. package/dist/payload-codegen.js +12 -4
  138. package/dist/payload-codegen.js.map +1 -1
  139. package/dist/projection/extract-view-spec.d.ts.map +1 -1
  140. package/dist/projection/extract-view-spec.js +51 -25
  141. package/dist/projection/extract-view-spec.js.map +1 -1
  142. package/dist/relation-resolver.d.ts +16 -0
  143. package/dist/relation-resolver.d.ts.map +1 -1
  144. package/dist/relation-resolver.js +82 -1
  145. package/dist/relation-resolver.js.map +1 -1
  146. package/dist/render-context.d.ts +4 -0
  147. package/dist/render-context.d.ts.map +1 -1
  148. package/dist/render-context.js.map +1 -1
  149. package/dist/render-engine/embedded-templates.generated.d.ts +2 -0
  150. package/dist/render-engine/embedded-templates.generated.d.ts.map +1 -0
  151. package/dist/render-engine/embedded-templates.generated.js +15 -0
  152. package/dist/render-engine/embedded-templates.generated.js.map +1 -0
  153. package/dist/render-engine/framework-provider.d.ts.map +1 -1
  154. package/dist/render-engine/framework-provider.js +26 -13
  155. package/dist/render-engine/framework-provider.js.map +1 -1
  156. package/dist/runner.d.ts.map +1 -1
  157. package/dist/runner.js +17 -0
  158. package/dist/runner.js.map +1 -1
  159. package/dist/templates/docs-file.d.ts +2 -6
  160. package/dist/templates/docs-file.d.ts.map +1 -1
  161. package/dist/templates/docs-file.js +2 -5
  162. package/dist/templates/docs-file.js.map +1 -1
  163. package/dist/templates/drizzle-schema.d.ts.map +1 -1
  164. package/dist/templates/drizzle-schema.js +30 -2
  165. package/dist/templates/drizzle-schema.js.map +1 -1
  166. package/dist/templates/entity-constants.d.ts +7 -0
  167. package/dist/templates/entity-constants.d.ts.map +1 -1
  168. package/dist/templates/entity-constants.js +1 -1
  169. package/dist/templates/entity-constants.js.map +1 -1
  170. package/dist/templates/entity-file.d.ts.map +1 -1
  171. package/dist/templates/entity-file.js +16 -5
  172. package/dist/templates/entity-file.js.map +1 -1
  173. package/dist/templates/enums-file.d.ts +11 -0
  174. package/dist/templates/enums-file.d.ts.map +1 -0
  175. package/dist/templates/enums-file.js +44 -0
  176. package/dist/templates/enums-file.js.map +1 -0
  177. package/dist/templates/extract-delegate-emitter.d.ts.map +1 -1
  178. package/dist/templates/extract-delegate-emitter.js +5 -7
  179. package/dist/templates/extract-delegate-emitter.js.map +1 -1
  180. package/dist/templates/extract-schema-emitter.d.ts.map +1 -1
  181. package/dist/templates/extract-schema-emitter.js +5 -1
  182. package/dist/templates/extract-schema-emitter.js.map +1 -1
  183. package/dist/templates/extractor.d.ts.map +1 -1
  184. package/dist/templates/extractor.js +56 -39
  185. package/dist/templates/extractor.js.map +1 -1
  186. package/dist/templates/field-meta.d.ts.map +1 -1
  187. package/dist/templates/field-meta.js +1 -5
  188. package/dist/templates/field-meta.js.map +1 -1
  189. package/dist/templates/filter-allowlist.d.ts +7 -2
  190. package/dist/templates/filter-allowlist.d.ts.map +1 -1
  191. package/dist/templates/filter-allowlist.js +17 -9
  192. package/dist/templates/filter-allowlist.js.map +1 -1
  193. package/dist/templates/filter-type.d.ts +7 -1
  194. package/dist/templates/filter-type.d.ts.map +1 -1
  195. package/dist/templates/filter-type.js +9 -5
  196. package/dist/templates/filter-type.js.map +1 -1
  197. package/dist/templates/find-templates.d.ts +4 -0
  198. package/dist/templates/find-templates.d.ts.map +1 -0
  199. package/dist/templates/find-templates.js +15 -0
  200. package/dist/templates/find-templates.js.map +1 -0
  201. package/dist/templates/fr010-field-mapping.d.ts +2 -0
  202. package/dist/templates/fr010-field-mapping.d.ts.map +1 -1
  203. package/dist/templates/fr010-field-mapping.js +10 -6
  204. package/dist/templates/fr010-field-mapping.js.map +1 -1
  205. package/dist/templates/inferred-types.d.ts +44 -7
  206. package/dist/templates/inferred-types.d.ts.map +1 -1
  207. package/dist/templates/inferred-types.js +107 -16
  208. package/dist/templates/inferred-types.js.map +1 -1
  209. package/dist/templates/mermaid-er.d.ts +35 -2
  210. package/dist/templates/mermaid-er.d.ts.map +1 -1
  211. package/dist/templates/mermaid-er.js +174 -7
  212. package/dist/templates/mermaid-er.js.map +1 -1
  213. package/dist/templates/output-parser.d.ts.map +1 -1
  214. package/dist/templates/output-parser.js +30 -79
  215. package/dist/templates/output-parser.js.map +1 -1
  216. package/dist/templates/output-prompt.d.ts.map +1 -1
  217. package/dist/templates/output-prompt.js +2 -2
  218. package/dist/templates/output-prompt.js.map +1 -1
  219. package/dist/templates/queries-file.d.ts.map +1 -1
  220. package/dist/templates/queries-file.js +112 -4
  221. package/dist/templates/queries-file.js.map +1 -1
  222. package/dist/templates/queries.d.ts +5 -0
  223. package/dist/templates/queries.d.ts.map +1 -1
  224. package/dist/templates/queries.js +7 -7
  225. package/dist/templates/queries.js.map +1 -1
  226. package/dist/templates/recover-schema-emitter.d.ts +8 -0
  227. package/dist/templates/recover-schema-emitter.d.ts.map +1 -0
  228. package/dist/templates/recover-schema-emitter.js +64 -0
  229. package/dist/templates/recover-schema-emitter.js.map +1 -0
  230. package/dist/templates/relations-block.js +10 -0
  231. package/dist/templates/relations-block.js.map +1 -1
  232. package/dist/templates/render-helper.d.ts.map +1 -1
  233. package/dist/templates/render-helper.js +4 -4
  234. package/dist/templates/render-helper.js.map +1 -1
  235. package/dist/templates/routes-file.d.ts.map +1 -1
  236. package/dist/templates/routes-file.js +183 -6
  237. package/dist/templates/routes-file.js.map +1 -1
  238. package/dist/templates/tph-discriminator.d.ts +56 -0
  239. package/dist/templates/tph-discriminator.d.ts.map +1 -0
  240. package/dist/templates/tph-discriminator.js +180 -0
  241. package/dist/templates/tph-discriminator.js.map +1 -0
  242. package/dist/templates/value-object-file.d.ts +2 -1
  243. package/dist/templates/value-object-file.d.ts.map +1 -1
  244. package/dist/templates/value-object-file.js +32 -4
  245. package/dist/templates/value-object-file.js.map +1 -1
  246. package/dist/templates/zod-validators.d.ts +64 -1
  247. package/dist/templates/zod-validators.d.ts.map +1 -1
  248. package/dist/templates/zod-validators.js +181 -8
  249. package/dist/templates/zod-validators.js.map +1 -1
  250. package/package.json +103 -34
  251. package/src/column-mapper.ts +25 -8
  252. package/src/constants.ts +18 -0
  253. package/src/docs-paths.ts +128 -0
  254. package/src/enum-import.ts +43 -0
  255. package/src/enum-shared.ts +95 -0
  256. package/src/generator-registry.ts +204 -0
  257. package/src/generator.ts +6 -0
  258. package/src/generators/api-doc-render.ts +572 -0
  259. package/src/generators/api-docs-file.ts +146 -0
  260. package/src/generators/api-field-shape.ts +114 -0
  261. package/src/generators/api-label.ts +7 -0
  262. package/src/generators/api-model.ts +1067 -0
  263. package/src/generators/docs-data-builder.ts +479 -185
  264. package/src/generators/docs-data.ts +139 -28
  265. package/src/generators/docs-file.ts +205 -39
  266. package/src/generators/entity-file.ts +31 -15
  267. package/src/generators/extractor-file.ts +2 -1
  268. package/src/generators/field-anchor.ts +24 -0
  269. package/src/generators/index.ts +8 -1
  270. package/src/generators/mermaid-er.ts +14 -0
  271. package/src/generators/output-parser-file.ts +3 -4
  272. package/src/generators/output-prompt-file.ts +2 -1
  273. package/src/generators/prompt-render-file.ts +3 -4
  274. package/src/generators/queries-file.ts +9 -3
  275. package/src/generators/render-helper-file.ts +2 -1
  276. package/src/generators/routes-file-hono.ts +5 -1
  277. package/src/generators/routes-file.ts +7 -1
  278. package/src/generators/template-doc-builder.ts +306 -0
  279. package/src/generators/template-doc-data.ts +85 -0
  280. package/src/generators/template-payload-tree.ts +71 -0
  281. package/src/generators/template-source-annotate.ts +290 -0
  282. package/src/generators/template-source-render.ts +203 -0
  283. package/src/generators/trace-helper-file.ts +301 -0
  284. package/src/index.ts +55 -4
  285. package/src/metaobjects-config.ts +117 -2
  286. package/src/naming.ts +48 -0
  287. package/src/payload-codegen.ts +14 -3
  288. package/src/projection/extract-view-spec.ts +49 -30
  289. package/src/relation-resolver.ts +103 -1
  290. package/src/render-context.ts +4 -0
  291. package/src/render-engine/embedded-templates.generated.ts +14 -0
  292. package/src/render-engine/framework-provider.ts +25 -11
  293. package/src/runner.ts +21 -0
  294. package/src/templates/docs-file.ts +2 -9
  295. package/src/templates/drizzle-schema.ts +31 -1
  296. package/src/templates/entity-constants.ts +1 -1
  297. package/src/templates/entity-file.ts +16 -5
  298. package/src/templates/enums-file.ts +50 -0
  299. package/src/templates/extract-delegate-emitter.ts +5 -6
  300. package/src/templates/extractor.ts +68 -38
  301. package/src/templates/field-meta.ts +0 -6
  302. package/src/templates/filter-allowlist.ts +17 -10
  303. package/src/templates/filter-type.ts +8 -6
  304. package/src/templates/find-templates.ts +15 -0
  305. package/src/templates/fr010-field-mapping.ts +10 -8
  306. package/src/templates/inferred-types.ts +108 -18
  307. package/src/templates/mermaid-er.ts +176 -8
  308. package/src/templates/output-parser.ts +30 -79
  309. package/src/templates/output-prompt.ts +2 -1
  310. package/src/templates/queries-file.ts +132 -3
  311. package/src/templates/queries.ts +15 -7
  312. package/src/templates/relations-block.ts +17 -0
  313. package/src/templates/render-helper.ts +4 -3
  314. package/src/templates/routes-file.ts +233 -6
  315. package/src/templates/tph-discriminator.ts +232 -0
  316. package/src/templates/value-object-file.ts +38 -4
  317. package/src/templates/zod-validators.ts +204 -7
  318. package/templates/api/agent-api.md.mustache +30 -0
  319. package/templates/api/entity-api.md.mustache +69 -0
  320. package/templates/api/index.md.mustache +21 -0
  321. package/templates/docs/entity-page.md.mustache +33 -21
  322. package/templates/docs/template-page.md.mustache +56 -0
  323. package/src/templates/extract-schema-emitter.ts +0 -111
@@ -0,0 +1,572 @@
1
+ // api-doc-render.ts — the two documentation FORMS that an ApiModel feeds:
2
+ // • a per-unit HUMAN reference page (renderEntityApiPage)
3
+ // • a consolidated HUMAN index (renderApiIndex)
4
+ // • a condensed AGENT/LLM form (renderAgentApi)
5
+ //
6
+ // ADR-0022 Part 3: one ApiModel, two forms — the human prose page and the
7
+ // token-frugal agent form derive from the SAME IR, never re-derived. Rendering
8
+ // goes through the SHARED `render()` Mustache engine against canonical templates
9
+ // under `templates/api/` (resolved via the framework/project provider chain —
10
+ // the same mechanism docs-file.ts uses), so adopters can override a template by
11
+ // dropping their own `templates/api/<ref>.mustache` into their project root.
12
+ //
13
+ // The view-models are pre-rendered here (mirroring docs-data-builder) so the
14
+ // Mustache templates stay logic-light: section grouping, symbol counts, and the
15
+ // collision-safe index hrefs (docPageHref) are computed in TS.
16
+
17
+ import { render } from "@metaobjectsdev/render";
18
+ import type { Provider } from "@metaobjectsdev/render";
19
+ import type { ApiModel, ApiUnitDoc, ApiSymbol, ApiSymbolKind, UnitExample } from "./api-model.js";
20
+ import { inlineShape, type FieldShape } from "./api-field-shape.js";
21
+ import { docPageHref, type DocPageNode } from "../docs-paths.js";
22
+ import type { OutputLayout } from "../import-path.js";
23
+ import { GENERATED_HEADER } from "../constants.js";
24
+
25
+ // Template refs (resolved as `templates/api/<ref-tail>.mustache`).
26
+ const ENTITY_PAGE_REF = "api/entity-api.md";
27
+ const INDEX_REF = "api/index.md";
28
+ const AGENT_REF = "api/agent-api.md";
29
+
30
+ const GENERATED_MARKER = `<!-- ${GENERATED_HEADER} — DO NOT EDIT. -->`;
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Relative-import RENDER prefix.
34
+ //
35
+ // An `ApiSymbol.importPath` is the generated module's path RELATIVE TO the
36
+ // codegen output dir (flat → `Product.queries`; package → the package-folded
37
+ // `acme/shop/Product.queries`). It is the DATA the accuracy gate verifies
38
+ // against the emitted file, so it stays a bare module path.
39
+ //
40
+ // The generated files import each OTHER with `./`-prefixed RELATIVE specifiers
41
+ // (`from "./Product"`), so a copy-paste consumer co-located in the generated
42
+ // output dir must do the same — a BARE specifier (`from "Product.queries"`)
43
+ // only resolves with a non-default `baseUrl` and otherwise fails TS2307. The
44
+ // renderers therefore `./`-prefix the importPath in every rendered `from "…"`
45
+ // (the human page, the agent group headers, AND the example import blocks),
46
+ // without touching the underlying importPath data. A consumer importing from
47
+ // elsewhere adjusts the prefix (stated once in the page's import note).
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /** The `./`-prefixed RELATIVE specifier for a documented module path (the form a
51
+ * co-located consumer copy-pastes). Already-relative paths pass through. */
52
+ function relSpecifier(importPath: string): string {
53
+ return importPath.startsWith("./") || importPath.startsWith("../")
54
+ ? importPath
55
+ : `./${importPath}`;
56
+ }
57
+
58
+ /** Rewrite the `from "<module>"` tail of an example `import { … } from "<module>";`
59
+ * line to the `./`-prefixed relative specifier — the example imports are
60
+ * pre-composed in the ApiModel (reusing each symbol's bare importPath), so the
61
+ * `./` prefix is applied at render time alongside the section/header imports. */
62
+ function relImportLine(line: string): string {
63
+ return line.replace(/(\bfrom\s+")([^"]+)(")/, (_m, pre, mod, post) => `${pre}${relSpecifier(mod)}${post}`);
64
+ }
65
+
66
+ // The human-facing section ORDER + HEADING per ApiSymbolKind. A unit's page
67
+ // renders only the kinds it actually carries, always in this canonical order
68
+ // (so two runs over the same model are byte-stable regardless of symbol order).
69
+ const KIND_ORDER: readonly ApiSymbolKind[] = [
70
+ "model",
71
+ "relation",
72
+ "data-access",
73
+ "callable",
74
+ "rest",
75
+ "rest-hono",
76
+ "validation",
77
+ "extractor",
78
+ "render",
79
+ "prompt",
80
+ ];
81
+ const KIND_HEADING: Record<ApiSymbolKind, string> = {
82
+ model: "Model",
83
+ relation: "Relations",
84
+ "data-access": "Data access",
85
+ callable: "Callable",
86
+ rest: "REST",
87
+ "rest-hono": "REST (Hono)",
88
+ validation: "Validation",
89
+ extractor: "Extractor",
90
+ render: "Render",
91
+ prompt: "Prompt",
92
+ };
93
+
94
+ /** A docs-page name for the index href helper. The API index lives at the docs
95
+ * ROOT, so its links to per-unit pages are computed via the same docPageHref
96
+ * used elsewhere (resolves in flat AND package layout). */
97
+ const INDEX_NODE: DocPageNode = { name: "index" };
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Setup preamble — how to obtain the runtime handles the documented signatures
101
+ // need (`db` / `provider` / `root`). This is PROSE (not gate-enforced), so every
102
+ // import + type here is grounded in the REAL runtime API:
103
+ // • `db` — the generated CRUD helpers take `db: Db`, a Drizzle alias
104
+ // (`NodePgDatabase` / `BaseSQLiteDatabase`, queries-file.ts);
105
+ // construction is adopter-specific ("pass any compatible
106
+ // Drizzle instance"), so we show the standard drizzle() call
107
+ // rather than invent a framework import.
108
+ // • `provider` — render<Name>(payload, provider: Provider); `Provider` +
109
+ // `InMemoryProvider` are exported from @metaobjectsdev/render.
110
+ // • `root` — extract<Name>(root: MetaRoot, …); `MetaRoot` is obtained from
111
+ // the loader shortcuts (`loadDirectory` / `loadString`) on
112
+ // @metaobjectsdev/metadata, whose LoadResult carries `.root`.
113
+ // ---------------------------------------------------------------------------
114
+
115
+ /** A setup row: the handle name, a one-line description, and a verified snippet.
116
+ * `snippetInline` is the same snippet flattened to a single line (`; `-joined)
117
+ * for the token-frugal agent form. */
118
+ interface SetupHandleVM {
119
+ handle: string;
120
+ note: string;
121
+ snippet: string;
122
+ snippetInline: string;
123
+ }
124
+
125
+ /** The full set of handles a unit's example may reference. The per-unit page
126
+ * shows only the handles that unit's example actually uses; the agent + index
127
+ * forms show the full set once. */
128
+ /** Build a setup row, deriving the single-line agent snippet from the block one
129
+ * (newlines → `; `, collapsing any blank lines / double semicolons). */
130
+ function setupHandle(handle: string, note: string, snippet: string): SetupHandleVM {
131
+ const snippetInline = snippet
132
+ .split("\n")
133
+ .map((l) => l.trim())
134
+ .filter((l) => l.length > 0)
135
+ .map((l) => (l.endsWith(";") ? l.slice(0, -1) : l))
136
+ .join("; ");
137
+ return { handle, note, snippet, snippetInline };
138
+ }
139
+
140
+ const SETUP_HANDLES: Record<"db" | "provider" | "root", SetupHandleVM> = {
141
+ db: setupHandle(
142
+ "db",
143
+ "your Drizzle connection — the generated queries take `db: Db` (a `NodePgDatabase` / `BaseSQLiteDatabase` alias). Construct one over your own driver and pass any compatible Drizzle instance:",
144
+ `import { drizzle } from "drizzle-orm/node-postgres";
145
+ import { Pool } from "pg";
146
+ const db = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }));`,
147
+ ),
148
+ provider: setupHandle(
149
+ "provider",
150
+ "the render `Provider` (resolves a template ref to text) — import it from `@metaobjectsdev/render`; `InMemoryProvider` is built in (or supply your own filesystem-backed `Provider`):",
151
+ `import { InMemoryProvider } from "@metaobjectsdev/render";
152
+ const provider = new InMemoryProvider({ "group/source": "Hello {{name}}" });`,
153
+ ),
154
+ root: setupHandle(
155
+ "root",
156
+ "the loaded `MetaRoot` `extract<Name>` parses against — load your metadata via `@metaobjectsdev/metadata` (the result carries `.root`):",
157
+ `import { loadDirectory } from "@metaobjectsdev/metadata";
158
+ const { root } = await loadDirectory("./metadata");`,
159
+ ),
160
+ };
161
+
162
+ /** Which handles a unit's example references (so the page shows only those). */
163
+ function setupHandlesFor(unit: ApiUnitDoc): SetupHandleVM[] {
164
+ const text = unit.example ? unit.example.body.join("\n") : "";
165
+ const out: SetupHandleVM[] = [];
166
+ if (/\bdb\b/.test(text)) out.push(SETUP_HANDLES.db);
167
+ if (/\bprovider\b/.test(text)) out.push(SETUP_HANDLES.provider);
168
+ if (/\broot\b/.test(text)) out.push(SETUP_HANDLES.root);
169
+ return out;
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Per-unit HUMAN page.
174
+ // ---------------------------------------------------------------------------
175
+
176
+ interface SectionVM {
177
+ heading: string;
178
+ symbols: SymbolVM[];
179
+ }
180
+ interface EntityPageVM {
181
+ generatedMarker: string;
182
+ node: string;
183
+ /** Relative href back to this entity's MODEL/metadata page, when the model
184
+ * surface is emitted alongside the api surface (cross-link). ABSENT otherwise
185
+ * → default api output byte-identical. */
186
+ modelPageHref?: string;
187
+ hasSetup: boolean;
188
+ setup: SetupHandleVM[];
189
+ unitExample?: string;
190
+ sections: SectionVM[];
191
+ }
192
+ interface FieldRowVM {
193
+ field: string;
194
+ type: string;
195
+ required: string;
196
+ notes: string;
197
+ }
198
+ interface SymbolVM {
199
+ signature: string;
200
+ usage: string;
201
+ /** The exact import an adopter writes to call this symbol (e.g.
202
+ * `import { findProductById } from "Product.queries"`). For REST it's the
203
+ * route-registrar import + a one-line mount note. */
204
+ importLine: string;
205
+ /** REST-only: the mount one-liner shown under the registrar import. */
206
+ mountNote?: string;
207
+ /** When/why the symbol throws — surfaced as a "Throws:" line. */
208
+ throws?: string;
209
+ example?: string;
210
+ /** Present iff the symbol carries a documented field shape — rendered as a
211
+ * Field / Type / Required / Notes table (mirroring the docs Constraints
212
+ * table) so a reader sees exactly what fields to pass / expect. */
213
+ hasFields?: boolean;
214
+ /** The field-table rows (one per documented field). */
215
+ fieldRows?: FieldRowVM[];
216
+ /** A short caption above the table naming what the shape is (e.g. "Fields",
217
+ * "Request body", "Returns"). */
218
+ fieldsCaption?: string;
219
+ }
220
+
221
+ /** A human-page caption for a symbol's field table, by kind + signature shape. */
222
+ function fieldsCaptionFor(s: ApiSymbol): string {
223
+ if (s.kind === "model") return "Fields";
224
+ if (s.kind === "validation") return "Accepted fields";
225
+ if (s.kind === "prompt") return "Payload";
226
+ if (s.kind === "extractor") return "Returns";
227
+ if (s.kind === "relation") return "Navigations";
228
+ if (s.kind === "callable") return "Returns";
229
+ if (s.kind === "rest" || s.kind === "rest-hono") {
230
+ return s.name.startsWith("GET ") ? "Response body" : "Request body";
231
+ }
232
+ // data-access: a create/update takes a body; reads return the model.
233
+ return s.name.startsWith("create") || s.name.startsWith("update") ? "Request body (data)" : "Returns";
234
+ }
235
+
236
+ /** Markdown-escape a cell whose text may contain a `|` (TS union types do). */
237
+ function mdCell(text: string): string {
238
+ return text.replace(/\|/g, "\\|");
239
+ }
240
+
241
+ /** Build the Field / Type / Required / Notes rows from a field shape. */
242
+ function fieldRows(fields: FieldShape[]): FieldRowVM[] {
243
+ return fields.map((f) => ({
244
+ field: f.name,
245
+ type: mdCell(f.type),
246
+ required: f.optional ? "" : "yes",
247
+ notes: f.note ?? "",
248
+ }));
249
+ }
250
+
251
+ /** The exact `import { … } from "<importPath>"` an adopter writes for a symbol.
252
+ * REST endpoints aren't importable functions — the import is the entity's route
253
+ * registrar (`<entity>Routes`) from the routes module; the symbol's `name` is a
254
+ * "METHOD /path", not an identifier, so we import the registrar instead. Import
255
+ * paths are RELATIVE to the adopter's generated-output dir (a note at the top of
256
+ * the page states this once). */
257
+ function importLineFor(s: ApiSymbol): string {
258
+ // REST + Hono endpoints aren't importable functions — import the route
259
+ // registrar named on the symbol instead of the "METHOD /path" name.
260
+ const isRouteKind = s.kind === "rest" || s.kind === "rest-hono";
261
+ const imported = isRouteKind ? s.registrar ?? s.name : s.name;
262
+ return `import { ${imported} } from "${relSpecifier(s.importPath)}"`;
263
+ }
264
+
265
+ /** Group a unit's symbols into ordered sections (one per present kind), each a
266
+ * list of {signature, usage, import, throws, example}. Empty kinds are omitted. */
267
+ function entityPageVM(unit: ApiUnitDoc): EntityPageVM {
268
+ const sections: SectionVM[] = [];
269
+ for (const kind of KIND_ORDER) {
270
+ const ofKind = unit.symbols.filter((s) => s.kind === kind);
271
+ if (ofKind.length === 0) continue;
272
+ sections.push({
273
+ heading: KIND_HEADING[kind],
274
+ symbols: ofKind.map(symbolVM),
275
+ });
276
+ }
277
+ const setup = setupHandlesFor(unit);
278
+ const vm: EntityPageVM = {
279
+ generatedMarker: GENERATED_MARKER,
280
+ node: unit.node,
281
+ hasSetup: setup.length > 0,
282
+ setup,
283
+ sections,
284
+ };
285
+ const ex = unitExampleBlock(unit.example);
286
+ if (ex !== undefined) vm.unitExample = ex;
287
+ return vm;
288
+ }
289
+
290
+ /** The full worked-example block for a unit (imports + body), as one ```ts body
291
+ * string. Undefined when the unit has no runnable example. */
292
+ function unitExampleBlock(example: UnitExample | undefined): string | undefined {
293
+ if (example === undefined) return undefined;
294
+ // The example imports are pre-composed in the ApiModel from the symbols' bare
295
+ // importPaths; `./`-prefix each at render time so the copy-paste block resolves.
296
+ const lines = example.imports.map(relImportLine);
297
+ if (example.imports.length > 0 && example.body.length > 0) lines.push("");
298
+ lines.push(...example.body);
299
+ return lines.join("\n");
300
+ }
301
+
302
+ function symbolVM(s: ApiSymbol): SymbolVM {
303
+ const vm: SymbolVM = { signature: s.signature, usage: s.usage, importLine: importLineFor(s) };
304
+ // REST: tell the agent how to actually wire the endpoints once imported.
305
+ if (s.kind === "rest" && s.registrar !== undefined) {
306
+ vm.mountNote = `\`await ${s.registrar}(fastify)\``;
307
+ }
308
+ // Hono: the registrar mounts onto the Hono app with a per-request deps object.
309
+ if (s.kind === "rest-hono" && s.registrar !== undefined) {
310
+ vm.mountNote = `\`${s.registrar}(app, { db })\``;
311
+ }
312
+ if (s.throws !== undefined) vm.throws = s.throws;
313
+ if (s.example !== undefined) vm.example = s.example;
314
+ // Field shape → a Field / Type / Required / Notes table (only when there is at
315
+ // least one field; a shape with no fields is omitted to keep the page clean).
316
+ if (s.fields !== undefined && s.fields.length > 0) {
317
+ vm.hasFields = true;
318
+ vm.fieldsCaption = fieldsCaptionFor(s);
319
+ vm.fieldRows = fieldRows(s.fields);
320
+ }
321
+ return vm;
322
+ }
323
+
324
+ /** Render ONE per-unit human reference page from an ApiUnitDoc, via the shared
325
+ * render() engine + the canonical `api/entity-api.md` template. `modelPageHref`
326
+ * (when given) cross-links the page back to the entity's model/metadata page. */
327
+ export function renderEntityApiPage(
328
+ unit: ApiUnitDoc,
329
+ provider: Provider,
330
+ modelPageHref?: string,
331
+ ): string {
332
+ const payload = entityPageVM(unit);
333
+ if (modelPageHref !== undefined) payload.modelPageHref = modelPageHref;
334
+ return render({
335
+ ref: ENTITY_PAGE_REF,
336
+ payload,
337
+ provider,
338
+ format: "markdown",
339
+ });
340
+ }
341
+
342
+ // ---------------------------------------------------------------------------
343
+ // Consolidated HUMAN index.
344
+ // ---------------------------------------------------------------------------
345
+
346
+ interface IndexRowVM {
347
+ node: string;
348
+ href: string;
349
+ summary: string;
350
+ symbolCount: number;
351
+ one: boolean;
352
+ }
353
+
354
+ /** Lowercase summary label per kind (keeps the proper-noun acronym "REST"
355
+ * intact rather than ".toLowerCase()"-ing it to "rest"). */
356
+ const KIND_SUMMARY_LABEL: Record<ApiSymbolKind, string> = {
357
+ model: "model",
358
+ relation: "relations",
359
+ "data-access": "data access",
360
+ callable: "callable",
361
+ rest: "REST",
362
+ "rest-hono": "REST (Hono)",
363
+ validation: "validation",
364
+ extractor: "extractor",
365
+ render: "render",
366
+ prompt: "prompt",
367
+ };
368
+
369
+ /** A one-line summary for a unit's index row: the count of each present kind,
370
+ * in canonical order (e.g. "model, 5 data access, 5 REST, 2 validation"). */
371
+ function unitSummary(unit: ApiUnitDoc): string {
372
+ const parts: string[] = [];
373
+ for (const kind of KIND_ORDER) {
374
+ const n = unit.symbols.filter((s) => s.kind === kind).length;
375
+ if (n === 0) continue;
376
+ const label = KIND_SUMMARY_LABEL[kind];
377
+ parts.push(n === 1 ? label : `${n} ${label}`);
378
+ }
379
+ return parts.length > 0 ? parts.join(", ") : "no public symbols";
380
+ }
381
+
382
+ function indexRow(layout: OutputLayout, unit: ApiUnitDoc): IndexRowVM {
383
+ // The per-unit page is placed by {name, effective package} (see Task-3
384
+ // emission); link to it via the same docPageHref used for doc pages so it
385
+ // resolves in BOTH layouts — flat (`./Product.md`) and package
386
+ // (`./acme/shop/Product.md`), folding under the package path.
387
+ const href = docPageHref(layout, INDEX_NODE, { name: unit.node, package: unit.package });
388
+ return {
389
+ node: unit.node,
390
+ href,
391
+ summary: unitSummary(unit),
392
+ symbolCount: unit.symbols.length,
393
+ one: unit.symbols.length === 1,
394
+ };
395
+ }
396
+
397
+ /** Render the consolidated human API index (links to each unit page, grouped
398
+ * entity vs template) via the shared render() engine + `api/index.md`. */
399
+ export function renderApiIndex(model: ApiModel, layout: OutputLayout, provider: Provider): string {
400
+ const byName = (a: ApiUnitDoc, b: ApiUnitDoc) => a.node.localeCompare(b.node);
401
+ const entities = model.units.filter((u) => u.nodeKind === "entity").sort(byName);
402
+ const templates = model.units.filter((u) => u.nodeKind === "template").sort(byName);
403
+
404
+ const payload = {
405
+ generatedMarker: GENERATED_MARKER,
406
+ title: "API Reference",
407
+ intro: "Generated public API surface, one page per entity and output template.",
408
+ hasEntities: entities.length > 0,
409
+ entities: entities.map((u) => indexRow(layout, u)),
410
+ hasTemplates: templates.length > 0,
411
+ templates: templates.map((u) => indexRow(layout, u)),
412
+ };
413
+ return render({ ref: INDEX_REF, payload, provider, format: "markdown" });
414
+ }
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // Condensed AGENT/LLM form.
418
+ // ---------------------------------------------------------------------------
419
+
420
+ interface AgentSymbolVM {
421
+ signature: string;
422
+ usage: string;
423
+ /** Compact `[throws: …]` marker appended after the usage, when the symbol
424
+ * throws — so an agent knows the failure mode without a prose page. */
425
+ throwsMarker?: string;
426
+ }
427
+ interface AgentGroupVM {
428
+ /** One `import { a, b, c } from "<module>"` header covering every symbol below
429
+ * it — the exact import for each, in a single token-frugal line. */
430
+ importHeader: string;
431
+ symbols: AgentSymbolVM[];
432
+ }
433
+ interface AgentUnitVM {
434
+ node: string;
435
+ groups: AgentGroupVM[];
436
+ /** ONE compact worked example for the unit — the concrete call site an agent
437
+ * benefits most from. The body statements only (imports are already in the
438
+ * group headers above). Undefined when the unit has no runnable example. */
439
+ example?: string;
440
+ }
441
+
442
+ /**
443
+ * The agent-form signature WITH the field shape inlined — so an LLM sees exactly
444
+ * what to pass / what it gets, not an opaque `unknown` / `ZodType` / type NAME.
445
+ * Token-frugal but complete. Shaping is per kind:
446
+ * • model → `interface <Name> <inlineShape>`;
447
+ * • data-access → swap the `data: unknown` param for `data: <inlineShape>`
448
+ * (create/update only; reads have no body shape);
449
+ * • validation → `<Name>InsertSchema: ZodType<<inlineShape>>`;
450
+ * • REST → append ` body: <inlineShape>` (write) / ` -> <inlineShape>`
451
+ * (GET response);
452
+ * • extractor → append ` // <Payload>: <inlineShape>`.
453
+ * Falls back to the bare signature when the symbol carries no field shape.
454
+ */
455
+ function agentSignature(s: ApiSymbol): string {
456
+ if (s.fields === undefined || s.fields.length === 0) return s.signature;
457
+ const shape = inlineShape(s.fields);
458
+ switch (s.kind) {
459
+ case "model":
460
+ return `interface ${s.name} ${shape}`;
461
+ case "data-access":
462
+ // create/update carry a `data: unknown` body param to specialize.
463
+ return s.signature.includes("data: unknown")
464
+ ? s.signature.replace("data: unknown", `data: ${shape}`)
465
+ : s.signature;
466
+ case "validation":
467
+ return s.signature.replace("ZodType", `ZodType<${shape}>`);
468
+ case "rest":
469
+ case "rest-hono":
470
+ return s.name.startsWith("GET ") ? `${s.signature} -> ${shape}` : `${s.signature} body: ${shape}`;
471
+ case "extractor":
472
+ case "prompt":
473
+ return `${s.signature} // ${s.returns ?? "payload"}: ${shape}`;
474
+ case "relation":
475
+ // The navigations ride in the shape; show them inline after the const decl.
476
+ return `const ${s.name} ${shape}`;
477
+ case "callable":
478
+ // Callable returns a typed row array; the model shape isn't its param, so
479
+ // keep the bare signature (its `args` shape is the @parameterRef VO, shown
480
+ // on that VO's own unit).
481
+ return s.signature;
482
+ default:
483
+ return s.signature;
484
+ }
485
+ }
486
+
487
+ /** Group a unit's symbols by their import MODULE (first-appearance order),
488
+ * emitting ONE `import { … } from "<module>"` header per module then the
489
+ * symbols under it. This is the token-frugal form that still tells the agent the
490
+ * exact import for EVERY symbol (one header amortized over N symbols, vs. an
491
+ * import line per symbol). REST endpoints aren't importable identifiers — they
492
+ * collapse under their entity's single route-registrar import (the registrar is
493
+ * the imported name; the endpoints list the verbs/paths it mounts). */
494
+ function agentGroups(unit: ApiUnitDoc): AgentGroupVM[] {
495
+ const order: string[] = [];
496
+ const byModule = new Map<string, { names: string[]; symbols: AgentSymbolVM[] }>();
497
+
498
+ for (const s of unit.symbols) {
499
+ let g = byModule.get(s.importPath);
500
+ if (!g) {
501
+ g = { names: [], symbols: [] };
502
+ byModule.set(s.importPath, g);
503
+ order.push(s.importPath);
504
+ }
505
+ // The identifier an adopter imports: the symbol name, or — for REST / Hono —
506
+ // the shared route registrar (deduped across the entity's endpoints).
507
+ const isRouteKind = s.kind === "rest" || s.kind === "rest-hono";
508
+ const imported = isRouteKind ? s.registrar ?? s.name : s.name;
509
+ if (!g.names.includes(imported)) g.names.push(imported);
510
+
511
+ const sym: AgentSymbolVM = { signature: agentSignature(s), usage: s.usage };
512
+ if (s.throws !== undefined) sym.throwsMarker = `[throws: ${s.throws}]`;
513
+ g.symbols.push(sym);
514
+ }
515
+
516
+ return order.map((mod) => {
517
+ const g = byModule.get(mod)!;
518
+ return {
519
+ importHeader: `import { ${g.names.join(", ")} } from "${relSpecifier(mod)}"`,
520
+ symbols: g.symbols,
521
+ };
522
+ });
523
+ }
524
+
525
+ /** Render the condensed agent/LLM form: per unit, symbols grouped under a single
526
+ * `import { … } from "<module>"` header then one compact `signature — usage`
527
+ * line each (with a `[throws: …]` marker when it throws), NO prose/examples
528
+ * (token budget). Units keep their ApiModel order; symbols keep their per-unit
529
+ * order (the canonical generator emission order). */
530
+ export function renderAgentApi(model: ApiModel, provider: Provider): string {
531
+ const units: AgentUnitVM[] = model.units
532
+ .filter((u) => u.symbols.length > 0)
533
+ .map((u) => {
534
+ const vm: AgentUnitVM = { node: u.node, groups: agentGroups(u) };
535
+ // The compact agent example: body statements only (the imports are already
536
+ // amortized into the group headers above the example).
537
+ if (u.example !== undefined && u.example.body.length > 0) {
538
+ vm.example = u.example.body.join("\n");
539
+ }
540
+ return vm;
541
+ });
542
+ // The handles ANY unit's example references — shown once at the top so an agent
543
+ // knows where db / provider / root come from before the call sites below.
544
+ const setup = setupHandlesForModel(model);
545
+ const payload = {
546
+ generatedMarker: GENERATED_MARKER,
547
+ title: "Agent API Reference",
548
+ // The ApiModel carries no package itself, so the model-only entry point uses
549
+ // a generic, self-contained project label. (A richer label off the loaded
550
+ // root's package can be layered in by the Task-3 emission entrypoint, which
551
+ // has the root.)
552
+ project: "this project",
553
+ // Import paths are RELATIVE to the adopter's generated-output dir.
554
+ importNote: "Imports are relative to your generated-output directory.",
555
+ hasSetup: setup.length > 0,
556
+ setup,
557
+ units,
558
+ };
559
+ return render({ ref: AGENT_REF, payload, provider, format: "markdown" });
560
+ }
561
+
562
+ /** The union of setup handles referenced by ANY unit's example, in canonical
563
+ * db→provider→root order (shown once at the top of the agent form). */
564
+ function setupHandlesForModel(model: ApiModel): SetupHandleVM[] {
565
+ const used = new Set<string>();
566
+ for (const u of model.units) {
567
+ for (const h of setupHandlesFor(u)) used.add(h.handle);
568
+ }
569
+ return (["db", "provider", "root"] as const)
570
+ .filter((h) => used.has(h))
571
+ .map((h) => SETUP_HANDLES[h]);
572
+ }