@cosmicdrift/kumiko-samples 0.411.0 → 0.413.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 (182) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +13 -13
  3. package/packages/bundled-features/src/admin-shell/feature.ts +1 -1
  4. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +64 -3
  5. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +13 -130
  6. package/packages/bundled-features/src/agent-tools/api-docs/anchors.ts +60 -0
  7. package/packages/bundled-features/src/agent-tools/api-docs/check.ts +25 -0
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +140 -0
  9. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +175 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/curl.ts +28 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/error-table.ts +45 -0
  12. package/packages/bundled-features/src/agent-tools/api-docs/examples.ts +43 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +179 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/index-json.ts +29 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +21 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/list-parameters.ts +38 -0
  17. package/packages/bundled-features/src/agent-tools/api-docs/markdown.ts +70 -0
  18. package/packages/bundled-features/src/agent-tools/api-docs/menu-path.ts +82 -0
  19. package/packages/bundled-features/src/agent-tools/api-docs/model.ts +83 -0
  20. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +58 -0
  21. package/packages/bundled-features/src/agent-tools/api-docs/render-events.ts +76 -0
  22. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +216 -0
  23. package/packages/bundled-features/src/agent-tools/api-docs/render-overview.ts +86 -0
  24. package/packages/bundled-features/src/agent-tools/api-docs/render-reference.ts +79 -0
  25. package/packages/bundled-features/src/agent-tools/api-docs/render-tokens.ts +136 -0
  26. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +167 -0
  27. package/packages/bundled-features/src/agent-tools/api-docs/section-ids.ts +28 -0
  28. package/packages/bundled-features/src/agent-tools/api-docs/system-only.ts +11 -0
  29. package/packages/bundled-features/src/agent-tools/api-docs/texts/de.ts +166 -0
  30. package/packages/bundled-features/src/agent-tools/api-docs/texts/en.ts +159 -0
  31. package/packages/bundled-features/src/agent-tools/api-docs/texts/es.ts +162 -0
  32. package/packages/bundled-features/src/agent-tools/api-docs/texts/fr.ts +169 -0
  33. package/packages/bundled-features/src/agent-tools/api-docs/texts/index.ts +67 -0
  34. package/packages/bundled-features/src/agent-tools/api-docs/texts/it.ts +165 -0
  35. package/packages/bundled-features/src/agent-tools/api-docs/texts/types.ts +130 -0
  36. package/packages/bundled-features/src/agent-tools/api-docs/ui-writes.ts +81 -0
  37. package/packages/bundled-features/src/agent-tools/changes.json +24 -0
  38. package/packages/bundled-features/src/agent-tools/handler-schema.ts +45 -0
  39. package/packages/bundled-features/src/agent-tools/index.ts +24 -0
  40. package/packages/bundled-features/src/agent-tools/labels.ts +181 -0
  41. package/packages/bundled-features/src/auth-email-password/boot-rules.ts +9 -0
  42. package/packages/bundled-features/src/auth-email-password/feature.ts +6 -19
  43. package/packages/bundled-features/src/auth-email-password/validate-options.ts +20 -0
  44. package/packages/bundled-features/src/billing-foundation/boot-rules.ts +26 -0
  45. package/packages/bundled-features/src/billing-foundation/validate-options.ts +59 -46
  46. package/packages/bundled-features/src/cap-overview/boot-rules.ts +14 -0
  47. package/packages/bundled-features/src/cap-overview/feature.ts +12 -5
  48. package/packages/bundled-features/src/documents/boot-rules.ts +14 -0
  49. package/packages/bundled-features/src/documents/feature.ts +8 -4
  50. package/packages/bundled-features/src/file-derivatives/boot-rules.ts +9 -0
  51. package/packages/bundled-features/src/file-derivatives/feature.ts +6 -3
  52. package/packages/bundled-features/src/folders/boot-rules.ts +9 -0
  53. package/packages/bundled-features/src/folders/feature.ts +6 -3
  54. package/packages/bundled-features/src/helpdesk/boot-rules.ts +9 -0
  55. package/packages/bundled-features/src/{contact → helpdesk}/challenge.ts +2 -2
  56. package/packages/bundled-features/src/{contact → helpdesk}/changes.json +6 -0
  57. package/packages/bundled-features/src/{contact/client/contact-client-source.ts → helpdesk/client/helpdesk-client-source.ts} +4 -4
  58. package/packages/bundled-features/src/helpdesk/client/helpdesk-website-client.ts +29 -0
  59. package/packages/bundled-features/src/helpdesk/client/index.ts +9 -0
  60. package/packages/bundled-features/src/{contact → helpdesk}/entity.ts +35 -31
  61. package/packages/bundled-features/src/{contact → helpdesk}/feature.ts +56 -52
  62. package/packages/bundled-features/src/{contact → helpdesk}/handlers/attempts.ts +3 -3
  63. package/packages/bundled-features/src/{contact → helpdesk}/handlers/challenge.query.ts +10 -10
  64. package/packages/bundled-features/src/{contact → helpdesk}/handlers/forward-request.write.ts +25 -23
  65. package/packages/bundled-features/src/{contact → helpdesk}/handlers/mark-done.write.ts +11 -11
  66. package/packages/bundled-features/src/{contact → helpdesk}/handlers/notify-reporter-in-app.write.ts +14 -14
  67. package/packages/bundled-features/src/{contact → helpdesk}/handlers/open-count.query.ts +4 -4
  68. package/packages/bundled-features/src/{contact → helpdesk}/handlers/open-count.ts +2 -2
  69. package/packages/bundled-features/src/{contact → helpdesk}/handlers/replies.query.ts +6 -6
  70. package/packages/bundled-features/src/{contact → helpdesk}/handlers/reply.write.ts +30 -30
  71. package/packages/bundled-features/src/{contact → helpdesk}/handlers/report.write.ts +29 -29
  72. package/packages/bundled-features/src/{contact → helpdesk}/handlers/request-delivery.query.ts +40 -40
  73. package/packages/bundled-features/src/{contact → helpdesk}/handlers/request-detail.query.ts +15 -15
  74. package/packages/bundled-features/src/{contact → helpdesk}/handlers/request-list.query.ts +2 -2
  75. package/packages/bundled-features/src/{contact → helpdesk}/handlers/send-reply-mail.write.ts +24 -24
  76. package/packages/bundled-features/src/{contact → helpdesk}/handlers/send-test.write.ts +18 -14
  77. package/packages/bundled-features/src/{contact → helpdesk}/handlers/submit.write.ts +32 -31
  78. package/packages/bundled-features/src/{contact → helpdesk}/handlers/take-over-uploads.ts +5 -5
  79. package/packages/bundled-features/src/{contact → helpdesk}/i18n.ts +78 -75
  80. package/packages/bundled-features/src/helpdesk/index.ts +29 -0
  81. package/packages/bundled-features/src/{contact → helpdesk}/lib.ts +32 -28
  82. package/packages/bundled-features/src/{contact → helpdesk}/mail.ts +56 -56
  83. package/packages/bundled-features/src/{contact → helpdesk}/options.ts +18 -16
  84. package/packages/bundled-features/src/helpdesk/panels.ts +28 -0
  85. package/packages/bundled-features/src/{contact → helpdesk}/payloads.ts +33 -33
  86. package/packages/bundled-features/src/{contact → helpdesk}/screens.ts +104 -104
  87. package/packages/bundled-features/src/{contact → helpdesk}/subject.ts +3 -3
  88. package/packages/bundled-features/src/{contact → helpdesk}/user-data-hooks.ts +17 -17
  89. package/packages/bundled-features/src/helpdesk/web/constants.ts +160 -0
  90. package/packages/bundled-features/src/helpdesk/web/index.ts +29 -0
  91. package/packages/bundled-features/src/host-routing/boot-rules.ts +27 -0
  92. package/packages/bundled-features/src/host-routing/validate-options.ts +36 -27
  93. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  94. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +99 -71
  95. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +2 -2
  96. package/packages/bundled-features/src/jobs/boot-rules.ts +9 -0
  97. package/packages/bundled-features/src/jobs/feature.ts +9 -4
  98. package/packages/bundled-features/src/legal-pages/boot-rules.ts +19 -0
  99. package/packages/bundled-features/src/legal-pages/feature.ts +6 -3
  100. package/packages/bundled-features/src/legal-pages/lib/validate-routes.ts +11 -5
  101. package/packages/bundled-features/src/metrics/boot-rules.ts +15 -0
  102. package/packages/bundled-features/src/metrics/validate.ts +8 -2
  103. package/packages/bundled-features/src/notes-history/boot-rules.ts +9 -0
  104. package/packages/bundled-features/src/notes-history/feature.ts +6 -3
  105. package/packages/bundled-features/src/personal-access-tokens/boot-rules.ts +9 -0
  106. package/packages/bundled-features/src/personal-access-tokens/changes.json +6 -0
  107. package/packages/bundled-features/src/personal-access-tokens/feature.ts +5 -2
  108. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +7 -2
  109. package/packages/bundled-features/src/personal-access-tokens/i18n.ts +6 -1
  110. package/packages/bundled-features/src/personal-access-tokens/index.ts +37 -2
  111. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +31 -0
  112. package/packages/bundled-features/src/personal-access-tokens/screens.ts +9 -1
  113. package/packages/bundled-features/src/personal-access-tokens/web/constants.ts +1 -0
  114. package/packages/bundled-features/src/personal-access-tokens/web/scopes.ts +14 -0
  115. package/packages/bundled-features/src/presence/boot-rules.ts +9 -0
  116. package/packages/bundled-features/src/presence/options.ts +5 -1
  117. package/packages/bundled-features/src/readiness/boot-rules.ts +14 -0
  118. package/packages/bundled-features/src/readiness/probe-boot-check.ts +8 -6
  119. package/packages/bundled-features/src/shared/assert-no-where-rule-in-ownership-write.ts +6 -4
  120. package/packages/bundled-features/src/shared/boot-rules.ts +9 -0
  121. package/packages/bundled-features/src/subscription-mollie/boot-rules.ts +19 -0
  122. package/packages/bundled-features/src/subscription-mollie/feature.ts +18 -10
  123. package/packages/bundled-features/src/tags/boot-rules.ts +9 -0
  124. package/packages/bundled-features/src/tags/feature.ts +6 -3
  125. package/packages/bundled-features/src/template-resolver/boot-rules.ts +19 -0
  126. package/packages/bundled-features/src/template-resolver/feature.ts +14 -10
  127. package/packages/bundled-features/src/tenant/boot-rules.ts +9 -0
  128. package/packages/bundled-features/src/tenant/feature.ts +5 -3
  129. package/samples/apps/marketing-demo/README.md +1 -1
  130. package/samples/apps/marketing-demo/playwright.config.ts +1 -1
  131. package/samples/apps/marketing-demo/src/app/client.tsx +3 -3
  132. package/samples/apps/marketing-demo/src/app/seed-data.ts +1 -1
  133. package/samples/apps/marketing-demo/src/app/seed.ts +4 -4
  134. package/samples/apps/marketing-demo/src/app/server.ts +3 -3
  135. package/samples/apps/marketing-demo/src/features/{helpdesk → ticketing}/feature.ts +15 -12
  136. package/samples/apps/marketing-demo/src/features/ticketing/i18n.ts +100 -0
  137. package/samples/apps/marketing-demo/src/features/{helpdesk → ticketing}/schema/ticket.ts +4 -4
  138. package/samples/apps/marketing-demo/src/features/ticketing/web/index.ts +7 -0
  139. package/samples/apps/use-all-bundled/feature-manifest.json +67 -67
  140. package/samples/apps/use-all-bundled/kumiko/migrations/0064_helpdesk-rename.rebuild.json +4 -0
  141. package/samples/apps/use-all-bundled/package.json +1 -1
  142. package/samples/apps/use-all-bundled/src/app/client.tsx +1 -1
  143. package/samples/apps/use-all-bundled/src/app/screens-feature.ts +10 -10
  144. package/samples/apps/use-all-bundled/src/run-config.ts +6 -6
  145. package/samples/recipes/api-docs/README.md +52 -0
  146. package/samples/recipes/api-docs/api-docs/de/events.md +62 -0
  147. package/samples/recipes/api-docs/api-docs/de/overview.md +100 -0
  148. package/samples/recipes/api-docs/api-docs/de/reference/tickets.md +305 -0
  149. package/samples/recipes/api-docs/api-docs/de/tokens.md +66 -0
  150. package/samples/recipes/api-docs/api-docs/en/events.md +62 -0
  151. package/samples/recipes/api-docs/api-docs/en/overview.md +100 -0
  152. package/samples/recipes/api-docs/api-docs/en/reference/tickets.md +305 -0
  153. package/samples/recipes/api-docs/api-docs/en/tokens.md +66 -0
  154. package/samples/recipes/api-docs/api-docs/index.json +371 -0
  155. package/samples/recipes/api-docs/api-docs/openapi.json +982 -0
  156. package/samples/recipes/api-docs/api-examples/ticket-close.json +21 -0
  157. package/samples/recipes/api-docs/api-examples/ticket-create.json +42 -0
  158. package/samples/recipes/api-docs/api-examples/ticket-detail.json +28 -0
  159. package/samples/recipes/api-docs/api-examples/ticket-list.json +31 -0
  160. package/samples/recipes/api-docs/api-examples/ticket-update.json +54 -0
  161. package/samples/recipes/api-docs/api-examples/webhooks/ticket-closed.json +8 -0
  162. package/samples/recipes/api-docs/api-examples/webhooks/ticket-created.json +10 -0
  163. package/samples/recipes/api-docs/kumiko.config.ts +33 -0
  164. package/samples/recipes/api-docs/package.json +14 -0
  165. package/samples/recipes/api-docs/src/feature.ts +218 -0
  166. package/samples/recipes/api-docs/tsconfig.json +22 -0
  167. package/samples/recipes/golden-path/src/feature.ts +1 -1
  168. package/samples/recipes/{contact → helpdesk}/README.md +16 -16
  169. package/samples/recipes/{contact → helpdesk}/package.json +2 -2
  170. package/samples/recipes/{contact → helpdesk}/src/feature.ts +6 -6
  171. package/packages/bundled-features/src/contact/client/contact-website-client.ts +0 -29
  172. package/packages/bundled-features/src/contact/client/index.ts +0 -9
  173. package/packages/bundled-features/src/contact/index.ts +0 -29
  174. package/packages/bundled-features/src/contact/panels.ts +0 -28
  175. package/packages/bundled-features/src/contact/web/constants.ts +0 -160
  176. package/packages/bundled-features/src/contact/web/index.ts +0 -29
  177. package/samples/apps/marketing-demo/src/features/helpdesk/i18n.ts +0 -100
  178. package/samples/apps/marketing-demo/src/features/helpdesk/web/index.ts +0 -7
  179. /package/packages/bundled-features/src/{contact → helpdesk}/handlers/access.ts +0 -0
  180. /package/packages/bundled-features/src/{contact → helpdesk}/pow.ts +0 -0
  181. /package/packages/bundled-features/src/{contact → helpdesk}/user-agent.ts +0 -0
  182. /package/samples/apps/marketing-demo/src/features/{helpdesk → ticketing}/schema/index.ts +0 -0
@@ -0,0 +1,175 @@
1
+ import { patAllows } from "@cosmicdrift/kumiko-framework/api";
2
+ import type {
3
+ FeatureDefinition,
4
+ QueryHandlerDef,
5
+ WriteHandlerDef,
6
+ } from "@cosmicdrift/kumiko-framework/engine";
7
+ import {
8
+ handlerDescriptionKey,
9
+ handlerFieldLabelKey,
10
+ handlerTitleKey,
11
+ } from "@cosmicdrift/kumiko-framework/engine";
12
+ import {
13
+ expandScopes,
14
+ type PatScopeConfig,
15
+ patRateLimitFromFeature,
16
+ patScopesFromFeature,
17
+ } from "../../personal-access-tokens/index.ts";
18
+ import { handlerInputJsonSchema } from "../handler-schema.ts";
19
+ import { compareIds, entityFieldLabels, localizedLabels, pickLabel } from "../labels.ts";
20
+ import type { RegistryManifestView } from "../types.ts";
21
+ import { collectApiDocsEvents } from "./collect-events.ts";
22
+ import type { ApiExampleFile, WebhookExampleFile } from "./examples.ts";
23
+ import { patCreateLabel, patMenuPath } from "./menu-path.ts";
24
+ import type {
25
+ ApiDocsGrantLevel,
26
+ ApiDocsHandler,
27
+ ApiDocsModel,
28
+ ApiDocsScope,
29
+ ApiDocsScopeHandler,
30
+ LocalizedText,
31
+ } from "./model.ts";
32
+ import { fieldRows } from "./schema-fields.ts";
33
+ import { isSystemOnlyHandler } from "./system-only.ts";
34
+
35
+ export function findPatFeature(registry: RegistryManifestView): FeatureDefinition | undefined {
36
+ return [...registry.features.values()].find(
37
+ (feature) => patScopesFromFeature(feature) !== undefined,
38
+ );
39
+ }
40
+
41
+ type AnyHandlerDef = QueryHandlerDef | WriteHandlerDef;
42
+
43
+ function nonEmpty(value: string | undefined): string | undefined {
44
+ return value !== undefined && value !== "" ? value : undefined;
45
+ }
46
+
47
+ function perLocale(
48
+ locales: readonly string[],
49
+ resolve: (locale: string) => string | undefined,
50
+ ): LocalizedText {
51
+ return Object.fromEntries(
52
+ locales.flatMap((locale) => {
53
+ const text = resolve(locale);
54
+ return text === undefined ? [] : [[locale, text]];
55
+ }),
56
+ );
57
+ }
58
+
59
+ function buildHandler(
60
+ registry: RegistryManifestView,
61
+ qn: string,
62
+ def: AnyHandlerDef,
63
+ kind: "query" | "write",
64
+ locales: readonly string[],
65
+ examples: ReadonlyMap<string, ApiExampleFile>,
66
+ ): ApiDocsHandler {
67
+ const translations = registry.getAllTranslations();
68
+ const titleLabels = localizedLabels(translations, handlerTitleKey(qn));
69
+ const descriptionLabels = localizedLabels(translations, handlerDescriptionKey(qn));
70
+ const fallbackDescription = nonEmpty(def.description);
71
+ const inputSchema = handlerInputJsonSchema(def);
72
+ const entity = registry.getHandlerEntity(qn);
73
+ const fieldLabels = Object.fromEntries(
74
+ fieldRows(inputSchema).map(({ name: field }) => {
75
+ const own = localizedLabels(translations, handlerFieldLabelKey(qn, field));
76
+ const labels =
77
+ Object.keys(own).length > 0 || entity === undefined
78
+ ? own
79
+ : entityFieldLabels(translations, entity, field);
80
+ return [field, perLocale(locales, (locale) => pickLabel(labels, locale))];
81
+ }),
82
+ );
83
+ return {
84
+ qn,
85
+ kind,
86
+ title: perLocale(
87
+ locales,
88
+ (locale) => pickLabel(titleLabels, locale) ?? fallbackDescription ?? qn,
89
+ ),
90
+ description: perLocale(
91
+ locales,
92
+ (locale) => nonEmpty(descriptionLabels[locale]) ?? fallbackDescription,
93
+ ),
94
+ inputSchema,
95
+ excludedFields: "excludedFields" in def && def.excludedFields ? [...def.excludedFields] : [],
96
+ fieldLabels,
97
+ example: examples.get(qn),
98
+ };
99
+ }
100
+
101
+ function scopeHandlers(
102
+ domain: string,
103
+ scopes: PatScopeConfig,
104
+ qns: readonly string[],
105
+ ): readonly ApiDocsScopeHandler[] {
106
+ const readQns = expandScopes(scopes, [`${domain}:read`]);
107
+ const writeQns = expandScopes(scopes, [`${domain}:write`]);
108
+ return qns.flatMap((qn) => {
109
+ const grant: ApiDocsGrantLevel | undefined = patAllows(readQns, qn)
110
+ ? "read"
111
+ : patAllows(writeQns, qn)
112
+ ? "write"
113
+ : undefined;
114
+ return grant === undefined ? [] : [{ qn, grant }];
115
+ });
116
+ }
117
+
118
+ /** Registry and PAT scope catalog to a locale-resolved model. Only handlers that
119
+ * some scope reaches are collected, so nothing outside the scopes can leak into the docs. */
120
+ export function collectApiDocsModel(
121
+ registry: RegistryManifestView,
122
+ options: {
123
+ readonly locales: readonly string[];
124
+ readonly examples: ReadonlyMap<string, ApiExampleFile>;
125
+ readonly webhookExamples: ReadonlyMap<string, WebhookExampleFile>;
126
+ },
127
+ ): { readonly model: ApiDocsModel; readonly patFeature: FeatureDefinition } | undefined {
128
+ const patFeature = findPatFeature(registry);
129
+ const scopeConfig = patFeature === undefined ? undefined : patScopesFromFeature(patFeature);
130
+ if (patFeature === undefined || scopeConfig === undefined) return undefined;
131
+
132
+ const kinds = new Map<string, { kind: "query" | "write"; def: AnyHandlerDef }>();
133
+ for (const [qn, def] of registry.getAllQueryHandlers()) {
134
+ if (!isSystemOnlyHandler(def)) kinds.set(qn, { kind: "query", def });
135
+ }
136
+ for (const [qn, def] of registry.getAllWriteHandlers()) {
137
+ if (!isSystemOnlyHandler(def)) kinds.set(qn, { kind: "write", def });
138
+ }
139
+ const allQns = [...kinds.keys()].sort(compareIds);
140
+
141
+ const scopes: ApiDocsScope[] = Object.keys(scopeConfig)
142
+ .sort(compareIds)
143
+ .map((domain) => ({
144
+ domain,
145
+ label: scopeConfig[domain]?.label ?? domain,
146
+ hasWriteLevel: (scopeConfig[domain]?.write?.length ?? 0) > 0,
147
+ handlers: scopeHandlers(domain, scopeConfig, allQns),
148
+ }));
149
+
150
+ const reachable = new Set(scopes.flatMap((scope) => scope.handlers.map((entry) => entry.qn)));
151
+ const handlers = allQns
152
+ .filter((qn) => reachable.has(qn))
153
+ .flatMap((qn) => {
154
+ const entry = kinds.get(qn);
155
+ return entry === undefined
156
+ ? []
157
+ : [buildHandler(registry, qn, entry.def, entry.kind, options.locales, options.examples)];
158
+ });
159
+
160
+ return {
161
+ patFeature,
162
+ model: {
163
+ scopes,
164
+ events: collectApiDocsEvents(registry, scopeConfig, {
165
+ locales: options.locales,
166
+ examples: options.webhookExamples,
167
+ }),
168
+ handlers,
169
+ menuPath: patMenuPath(registry, patFeature, options.locales),
170
+ createLabel: patCreateLabel(registry, patFeature, options.locales),
171
+ rateLimit: patRateLimitFromFeature(patFeature),
172
+ toggleable: patFeature.toggleableDefault !== undefined,
173
+ },
174
+ };
175
+ }
@@ -0,0 +1,28 @@
1
+ import type { ApiDocsHandler } from "./model.ts";
2
+ import { examplePayload } from "./schema-fields.ts";
3
+
4
+ export function endpointOf(handler: Pick<ApiDocsHandler, "kind">): "/api/query" | "/api/write" {
5
+ return handler.kind === "query" ? "/api/query" : "/api/write";
6
+ }
7
+
8
+ /** Recorded payload when there is one, else a value derived from the input schema. */
9
+ export function requestPayload(handler: ApiDocsHandler): unknown {
10
+ const recorded = handler.example?.request.body.payload;
11
+ if (recorded !== undefined) return recorded;
12
+ return handler.inputSchema === undefined ? {} : examplePayload(handler.inputSchema);
13
+ }
14
+
15
+ // Inside a single-quoted shell string the only character that needs care is the quote itself.
16
+ function shellSingleQuoted(text: string): string {
17
+ return `'${text.replaceAll("'", "'\\''")}'`;
18
+ }
19
+
20
+ export function curlExample(handler: ApiDocsHandler, baseUrl: string): string {
21
+ const body = JSON.stringify({ type: handler.qn, payload: requestPayload(handler) }, null, 2);
22
+ return [
23
+ `curl -X POST ${baseUrl}${endpointOf(handler)} \\`,
24
+ ` -H "Authorization: Bearer $API_TOKEN" \\`,
25
+ ` -H "Content-Type: application/json" \\`,
26
+ ` -d ${shellSingleQuoted(body)}`,
27
+ ].join("\n");
28
+ }
@@ -0,0 +1,45 @@
1
+ import { patAuthRejectHttpStatus } from "@cosmicdrift/kumiko-framework/api";
2
+ import { frameworkErrorHttpStatus } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { compareIds } from "../labels.ts";
4
+ import { codeSpan, table } from "./markdown.ts";
5
+ import type { ApiDocsTexts, DocumentedErrorCode } from "./texts/index.ts";
6
+
7
+ export type ErrorRow = { readonly code: DocumentedErrorCode; readonly status: number };
8
+
9
+ const statusTables: readonly Readonly<Record<string, number>>[] = [
10
+ frameworkErrorHttpStatus,
11
+ patAuthRejectHttpStatus,
12
+ ];
13
+
14
+ function isDocumentedErrorCode(
15
+ texts: Pick<ApiDocsTexts, "errorMeanings">,
16
+ code: string,
17
+ ): code is DocumentedErrorCode {
18
+ return Object.hasOwn(texts.errorMeanings, code);
19
+ }
20
+
21
+ /** Every code the API can answer with: the framework table plus the token rejections,
22
+ * sorted by status then code. A code in both tables with the same status appears once. */
23
+ export function documentedErrorRows(
24
+ texts: Pick<ApiDocsTexts, "errorMeanings">,
25
+ ): readonly ErrorRow[] {
26
+ const rows = new Map<string, ErrorRow>();
27
+ for (const statuses of statusTables) {
28
+ for (const [code, status] of Object.entries(statuses)) {
29
+ if (isDocumentedErrorCode(texts, code)) rows.set(`${status}/${code}`, { code, status });
30
+ }
31
+ }
32
+ return [...rows.values()].sort((a, b) => a.status - b.status || compareIds(a.code, b.code));
33
+ }
34
+
35
+ export function errorMeaningTable(texts: ApiDocsTexts, columns: string): string {
36
+ const [code, status, meaning] = columns.split(" | ");
37
+ return table(
38
+ [code ?? "", status ?? "", meaning ?? ""],
39
+ documentedErrorRows(texts).map((row) => [
40
+ codeSpan(row.code),
41
+ String(row.status),
42
+ texts.errorMeanings[row.code],
43
+ ]),
44
+ );
45
+ }
@@ -0,0 +1,43 @@
1
+ import {
2
+ type ApiExampleFile,
3
+ ApiExampleFileSchema,
4
+ type WebhookExampleFile,
5
+ WebhookExampleFileSchema,
6
+ } from "@cosmicdrift/kumiko-types/api-example";
7
+ import { compareIds } from "../labels.ts";
8
+
9
+ export {
10
+ type ApiExampleFile,
11
+ ApiExampleFileSchema,
12
+ type WebhookExampleFile,
13
+ WebhookExampleFileSchema,
14
+ };
15
+
16
+ export type NamedWebhookExample = { readonly fileName: string; readonly file: WebhookExampleFile };
17
+
18
+ /** Same tie-break as `examplesByHandler`: the first file name in code-point order wins. */
19
+ export function webhookExamplesByEvent(
20
+ examples: readonly NamedWebhookExample[],
21
+ ): ReadonlyMap<string, WebhookExampleFile> {
22
+ const byEvent = new Map<string, WebhookExampleFile>();
23
+ const sorted = [...examples].sort((a, b) => compareIds(a.fileName, b.fileName));
24
+ for (const { file } of sorted) if (!byEvent.has(file.event)) byEvent.set(file.event, file);
25
+ return byEvent;
26
+ }
27
+
28
+ export type NamedApiExample = { readonly fileName: string; readonly file: ApiExampleFile };
29
+
30
+ /** A recording belongs to the handler named by `request.body.type`; when several
31
+ * recordings name the same handler the first file name in code-point order wins,
32
+ * so the choice never depends on directory listing order. */
33
+ export function examplesByHandler(
34
+ examples: readonly NamedApiExample[],
35
+ ): ReadonlyMap<string, ApiExampleFile> {
36
+ const byHandler = new Map<string, ApiExampleFile>();
37
+ const sorted = [...examples].sort((a, b) => compareIds(a.fileName, b.fileName));
38
+ for (const { file } of sorted) {
39
+ const handlerQn = file.request.body.type;
40
+ if (handlerQn !== undefined && !byHandler.has(handlerQn)) byHandler.set(handlerQn, file);
41
+ }
42
+ return byHandler;
43
+ }
@@ -0,0 +1,179 @@
1
+ import { findApiDocHandlerGaps, findDescriptionTranslationGaps } from "../agent-doc-lint.ts";
2
+ import type { RegistryManifestView } from "../types.ts";
3
+ import { anchorsForPage, slugify } from "./anchors.ts";
4
+ import { collectApiDocsModel } from "./collect.ts";
5
+ import {
6
+ examplesByHandler,
7
+ type NamedApiExample,
8
+ type NamedWebhookExample,
9
+ webhookExamplesByEvent,
10
+ } from "./examples.ts";
11
+ import { type ApiDocsPageEntry, INDEX_FILE, renderIndexJson } from "./index-json.ts";
12
+ import type { RenderedPage } from "./markdown.ts";
13
+ import type { ApiDocsSource, ResolvedApiDocsConfig } from "./model.ts";
14
+ import { type ApiDocsProblem, sortApiDocsProblems } from "./problems.ts";
15
+ import { renderEventsPage } from "./render-events.ts";
16
+ import { renderOpenApi } from "./render-openapi.ts";
17
+ import { renderOverview } from "./render-overview.ts";
18
+ import { renderReferencePage } from "./render-reference.ts";
19
+ import { renderTokens } from "./render-tokens.ts";
20
+ import { isApiDocsLocale, resolveApiDocsTexts } from "./texts/index.ts";
21
+ import { uiWriteProblems } from "./ui-writes.ts";
22
+
23
+ export const OPENAPI_FILE = "openapi.json";
24
+
25
+ const OVERVIEW_ORDER = 1;
26
+ const TOKENS_ORDER = 2;
27
+ const REFERENCE_ORDER_START = 10;
28
+
29
+ export type ApiDocsInput = {
30
+ readonly registry: RegistryManifestView;
31
+ readonly config: ResolvedApiDocsConfig;
32
+ readonly source: ApiDocsSource;
33
+ readonly examples: readonly NamedApiExample[];
34
+ readonly webhookExamples?: readonly NamedWebhookExample[];
35
+ };
36
+
37
+ export type ApiDocsResult = {
38
+ readonly files: ReadonlyMap<string, string>;
39
+ readonly problems: readonly ApiDocsProblem[];
40
+ };
41
+
42
+ /** Pure: registry in, files and problems out. No I/O, clock or environment, so the
43
+ * same input always yields byte-identical files. */
44
+ export function generateApiDocs(input: ApiDocsInput): ApiDocsResult {
45
+ const { registry, config } = input;
46
+ const { locales } = config;
47
+ if (locales.length === 0) throw new Error("apiDocs needs at least one locale.");
48
+ const unsupported = locales.filter((locale) => !isApiDocsLocale(locale));
49
+ if (unsupported.length > 0) {
50
+ throw new Error(`Unsupported apiDocs locales: ${unsupported.join(", ")}.`);
51
+ }
52
+
53
+ const collected = collectApiDocsModel(registry, {
54
+ locales,
55
+ examples: examplesByHandler(input.examples),
56
+ webhookExamples: webhookExamplesByEvent(input.webhookExamples ?? []),
57
+ });
58
+ if (collected === undefined) {
59
+ return { files: new Map(), problems: [{ kind: "patFeatureMissing" }] };
60
+ }
61
+ const { model } = collected;
62
+ const problems: ApiDocsProblem[] = [];
63
+ const files = new Map<string, string>();
64
+ const pages: ApiDocsPageEntry[] = [];
65
+ const handlersByQn = new Map(model.handlers.map((handler) => [handler.qn, handler]));
66
+
67
+ const addPage = (
68
+ path: string,
69
+ locale: string,
70
+ kind: ApiDocsPageEntry["kind"],
71
+ order: number,
72
+ page: RenderedPage,
73
+ scope?: string,
74
+ ): void => {
75
+ files.set(path, page.content);
76
+ pages.push({
77
+ path,
78
+ locale,
79
+ kind,
80
+ order,
81
+ title: page.title,
82
+ description: page.description,
83
+ ...(scope !== undefined && { scope }),
84
+ anchors: page.anchors,
85
+ });
86
+ };
87
+
88
+ for (const locale of locales) {
89
+ if (!isApiDocsLocale(locale)) continue;
90
+ const resolved = resolveApiDocsTexts(locale, config.texts?.[locale]);
91
+ problems.push(...resolved.problems);
92
+ const { texts } = resolved;
93
+ addPage(
94
+ `${locale}/overview.md`,
95
+ locale,
96
+ "overview",
97
+ OVERVIEW_ORDER,
98
+ renderOverview({ handlers: model.handlers, texts, baseUrl: config.baseUrl }),
99
+ );
100
+ addPage(
101
+ `${locale}/tokens.md`,
102
+ locale,
103
+ "tokens",
104
+ TOKENS_ORDER,
105
+ renderTokens({
106
+ model,
107
+ locale,
108
+ texts,
109
+ baseUrl: config.baseUrl,
110
+ appName: config.appName,
111
+ planNote: config.planNote?.[locale],
112
+ }),
113
+ );
114
+ model.scopes.forEach((scope, index) => {
115
+ addPage(
116
+ `${locale}/reference/${slugify(scope.domain)}.md`,
117
+ locale,
118
+ "reference",
119
+ REFERENCE_ORDER_START + index,
120
+ renderReferencePage({
121
+ scope,
122
+ handlers: handlersByQn,
123
+ anchors: anchorsForPage(scope.handlers.map((entry) => entry.qn)),
124
+ locale,
125
+ texts,
126
+ baseUrl: config.baseUrl,
127
+ }),
128
+ scope.domain,
129
+ );
130
+ });
131
+ if (model.events.length > 0) {
132
+ const deliveryText = config.webhookDelivery?.[locale];
133
+ if (deliveryText === undefined) problems.push({ kind: "webhookDeliveryTextMissing", locale });
134
+ addPage(
135
+ `${locale}/events.md`,
136
+ locale,
137
+ "events",
138
+ REFERENCE_ORDER_START + model.scopes.length,
139
+ renderEventsPage({ events: model.events, locale, texts, deliveryText }),
140
+ );
141
+ }
142
+ }
143
+
144
+ files.set(
145
+ OPENAPI_FILE,
146
+ renderOpenApi({
147
+ model,
148
+ source: input.source,
149
+ baseUrl: config.baseUrl,
150
+ appName: config.appName,
151
+ descriptionLocale: locales.includes("en") ? "en" : (locales[0] ?? "en"),
152
+ }),
153
+ );
154
+ files.set(INDEX_FILE, renderIndexJson(input.source, locales, pages));
155
+
156
+ const handlerQns = model.handlers.map((handler) => handler.qn);
157
+ problems.push(
158
+ ...findApiDocHandlerGaps([...registry.features.values()], new Set(handlerQns)).map(
159
+ (gap): ApiDocsProblem => ({ kind: "docGap", gap }),
160
+ ),
161
+ ...findDescriptionTranslationGaps(registry, { handlerQns, locales }).flatMap(
162
+ (gap): ApiDocsProblem[] =>
163
+ gap.locale === undefined
164
+ ? []
165
+ : [{ kind: "descriptionTranslationMissing", qn: gap.qn, locale: gap.locale }],
166
+ ),
167
+ ...uiWriteProblems(registry, model, config.uiOnlyWrites ?? []),
168
+ ...model.events.flatMap((event) =>
169
+ event.untranslatedLocales.map(
170
+ (locale): ApiDocsProblem => ({
171
+ kind: "webhookEventWithoutDescriptionTranslation",
172
+ qn: event.qn,
173
+ locale,
174
+ }),
175
+ ),
176
+ ),
177
+ );
178
+ return { files, problems: sortApiDocsProblems(problems) };
179
+ }
@@ -0,0 +1,29 @@
1
+ import { compareIds } from "../labels.ts";
2
+ import type { PageAnchor } from "./markdown.ts";
3
+ import type { ApiDocsSource } from "./model.ts";
4
+
5
+ export type ApiDocsPageKind = "overview" | "tokens" | "reference" | "events";
6
+
7
+ export type ApiDocsPageEntry = {
8
+ readonly path: string;
9
+ readonly locale: string;
10
+ readonly kind: ApiDocsPageKind;
11
+ readonly order: number;
12
+ readonly title: string;
13
+ readonly description: string;
14
+ readonly scope?: string;
15
+ readonly anchors: readonly PageAnchor[];
16
+ };
17
+
18
+ export const INDEX_FILE = "index.json";
19
+
20
+ export function renderIndexJson(
21
+ source: ApiDocsSource,
22
+ locales: readonly string[],
23
+ pages: readonly ApiDocsPageEntry[],
24
+ ): string {
25
+ const sorted = [...pages].sort(
26
+ (a, b) => compareIds(a.locale, b.locale) || a.order - b.order || compareIds(a.path, b.path),
27
+ );
28
+ return `${JSON.stringify({ source, locales, pages: sorted }, null, 2)}\n`;
29
+ }
@@ -0,0 +1,21 @@
1
+ export type { ApiDocsDiff } from "./check.ts";
2
+ export { diffApiDocsOutput } from "./check.ts";
3
+ export {
4
+ type ApiExampleFile,
5
+ ApiExampleFileSchema,
6
+ type NamedApiExample,
7
+ type NamedWebhookExample,
8
+ type WebhookExampleFile,
9
+ WebhookExampleFileSchema,
10
+ } from "./examples.ts";
11
+ export {
12
+ type ApiDocsInput,
13
+ type ApiDocsResult,
14
+ generateApiDocs,
15
+ OPENAPI_FILE,
16
+ } from "./generate.ts";
17
+ export { INDEX_FILE } from "./index-json.ts";
18
+ export type { ApiDocsSource, ResolvedApiDocsConfig } from "./model.ts";
19
+ export { type ApiDocsProblem, formatApiDocsProblem } from "./problems.ts";
20
+ export type { ApiDocsLocale, ApiDocsTexts } from "./texts/index.ts";
21
+ export { apiDocsLocales, formatApiDocsText, isApiDocsLocale } from "./texts/index.ts";
@@ -0,0 +1,38 @@
1
+ import {
2
+ DEFAULT_LIST_LIMIT,
3
+ entityListSchema,
4
+ MAX_LIST_LIMIT,
5
+ } from "@cosmicdrift/kumiko-framework/engine";
6
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
7
+ import * as z from "zod";
8
+ import { FILTER_OPS } from "../filter-ops.ts";
9
+ import { codeSpan } from "./markdown.ts";
10
+ import type { ApiDocsHandler } from "./model.ts";
11
+ import { type ApiDocsTexts, formatApiDocsText } from "./texts/index.ts";
12
+
13
+ export const LIST_INPUT_JSON_SCHEMA = z.toJSONSchema(entityListSchema, { io: "input" });
14
+
15
+ const LIST_PARAMETER_NAMES = Object.keys(LIST_INPUT_JSON_SCHEMA.properties ?? {}).sort();
16
+
17
+ export function listParameterText(texts: ApiDocsTexts, name: string): string | undefined {
18
+ const text = Object.entries(texts.listParameters).find(([key]) => key === name)?.[1];
19
+ return text === undefined
20
+ ? undefined
21
+ : formatApiDocsText(text, {
22
+ default: DEFAULT_LIST_LIMIT,
23
+ max: MAX_LIST_LIMIT,
24
+ ops: FILTER_OPS.map(codeSpan).join(", "),
25
+ });
26
+ }
27
+
28
+ /** True when the handler takes exactly the generated entity list input, so the shared
29
+ * list parameter texts describe its fields. */
30
+ export function takesEntityListInput(handler: ApiDocsHandler): boolean {
31
+ const properties = handler.inputSchema?.["properties"];
32
+ if (!isPlainObject(properties)) return false;
33
+ const names = Object.keys(properties).sort();
34
+ return (
35
+ names.length === LIST_PARAMETER_NAMES.length &&
36
+ names.every((name, index) => name === LIST_PARAMETER_NAMES[index])
37
+ );
38
+ }
@@ -0,0 +1,70 @@
1
+ const TABLE_CELL_BREAKS = /\s*[\r\n]+\s*/g;
2
+
3
+ export function escapeCell(text: string): string {
4
+ return text.replace(TABLE_CELL_BREAKS, " ").replace(/\|/g, "\\|");
5
+ }
6
+
7
+ export function table(header: readonly string[], rows: readonly (readonly string[])[]): string {
8
+ const line = (cells: readonly string[]) => `| ${cells.map(escapeCell).join(" | ")} |`;
9
+ return [line(header), line(header.map(() => "---")), ...rows.map(line)].join("\n");
10
+ }
11
+
12
+ /** Code span that survives backticks inside the text. */
13
+ export function codeSpan(text: string): string {
14
+ const longestRun = Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length));
15
+ const fence = "`".repeat(longestRun + 1);
16
+ return longestRun > 0 ? `${fence} ${text} ${fence}` : `${fence}${text}${fence}`;
17
+ }
18
+
19
+ export function fenced(language: string, body: string): string {
20
+ return [`\`\`\`${language}`, body, "```"].join("\n");
21
+ }
22
+
23
+ /** Only `title` and `description`: the markdown must stay valid for any static-site tooling. */
24
+ export function frontmatter(title: string, description: string): string {
25
+ return [
26
+ "---",
27
+ `title: ${JSON.stringify(title)}`,
28
+ `description: ${JSON.stringify(description)}`,
29
+ "---",
30
+ ].join("\n");
31
+ }
32
+
33
+ /** Blocks joined by blank lines; the file ends with exactly one newline. */
34
+ export function joinBlocks(blocks: readonly string[]): string {
35
+ return `${blocks.filter((block) => block !== "").join("\n\n")}\n`;
36
+ }
37
+
38
+ export type PageAnchor = {
39
+ readonly id: string;
40
+ /** The heading text exactly as rendered. */
41
+ readonly heading: string;
42
+ readonly level: 2 | 3;
43
+ readonly qn?: string;
44
+ };
45
+
46
+ export type RenderedPage = {
47
+ readonly title: string;
48
+ readonly description: string;
49
+ readonly content: string;
50
+ readonly anchors: readonly PageAnchor[];
51
+ };
52
+
53
+ /** Collects blocks and, for every heading, an anchor entry: the ids stay in index.json
54
+ * instead of the heading so they are the same in every language. */
55
+ export function pageBuilder(title: string, description: string) {
56
+ const blocks: string[] = [frontmatter(title, description)];
57
+ const anchors: PageAnchor[] = [];
58
+ return {
59
+ add(...more: readonly string[]): void {
60
+ blocks.push(...more);
61
+ },
62
+ section(id: string, heading: string, level: 2 | 3 = 2, qn?: string): void {
63
+ blocks.push(`${"#".repeat(level)} ${heading}`);
64
+ anchors.push({ id, heading, level, ...(qn !== undefined && { qn }) });
65
+ },
66
+ finish(): RenderedPage {
67
+ return { title, description, content: joinBlocks(blocks), anchors };
68
+ },
69
+ };
70
+ }