@cosmicdrift/kumiko-samples 0.411.0 → 0.412.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 (73) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -1
  3. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +64 -3
  4. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +13 -130
  5. package/packages/bundled-features/src/agent-tools/api-docs/anchors.ts +60 -0
  6. package/packages/bundled-features/src/agent-tools/api-docs/check.ts +25 -0
  7. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +140 -0
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +175 -0
  9. package/packages/bundled-features/src/agent-tools/api-docs/curl.ts +28 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/error-table.ts +45 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/examples.ts +43 -0
  12. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +179 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/index-json.ts +29 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +21 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/list-parameters.ts +38 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/markdown.ts +70 -0
  17. package/packages/bundled-features/src/agent-tools/api-docs/menu-path.ts +82 -0
  18. package/packages/bundled-features/src/agent-tools/api-docs/model.ts +83 -0
  19. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +58 -0
  20. package/packages/bundled-features/src/agent-tools/api-docs/render-events.ts +76 -0
  21. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +216 -0
  22. package/packages/bundled-features/src/agent-tools/api-docs/render-overview.ts +86 -0
  23. package/packages/bundled-features/src/agent-tools/api-docs/render-reference.ts +79 -0
  24. package/packages/bundled-features/src/agent-tools/api-docs/render-tokens.ts +136 -0
  25. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +167 -0
  26. package/packages/bundled-features/src/agent-tools/api-docs/section-ids.ts +28 -0
  27. package/packages/bundled-features/src/agent-tools/api-docs/system-only.ts +11 -0
  28. package/packages/bundled-features/src/agent-tools/api-docs/texts/de.ts +166 -0
  29. package/packages/bundled-features/src/agent-tools/api-docs/texts/en.ts +159 -0
  30. package/packages/bundled-features/src/agent-tools/api-docs/texts/es.ts +162 -0
  31. package/packages/bundled-features/src/agent-tools/api-docs/texts/fr.ts +169 -0
  32. package/packages/bundled-features/src/agent-tools/api-docs/texts/index.ts +67 -0
  33. package/packages/bundled-features/src/agent-tools/api-docs/texts/it.ts +165 -0
  34. package/packages/bundled-features/src/agent-tools/api-docs/texts/types.ts +130 -0
  35. package/packages/bundled-features/src/agent-tools/api-docs/ui-writes.ts +81 -0
  36. package/packages/bundled-features/src/agent-tools/changes.json +24 -0
  37. package/packages/bundled-features/src/agent-tools/handler-schema.ts +45 -0
  38. package/packages/bundled-features/src/agent-tools/index.ts +24 -0
  39. package/packages/bundled-features/src/agent-tools/labels.ts +181 -0
  40. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  41. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +99 -71
  42. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +2 -2
  43. package/packages/bundled-features/src/personal-access-tokens/changes.json +6 -0
  44. package/packages/bundled-features/src/personal-access-tokens/feature.ts +5 -2
  45. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +7 -2
  46. package/packages/bundled-features/src/personal-access-tokens/i18n.ts +6 -1
  47. package/packages/bundled-features/src/personal-access-tokens/index.ts +37 -2
  48. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +28 -0
  49. package/packages/bundled-features/src/personal-access-tokens/screens.ts +9 -1
  50. package/packages/bundled-features/src/personal-access-tokens/web/constants.ts +1 -0
  51. package/packages/bundled-features/src/personal-access-tokens/web/scopes.ts +14 -0
  52. package/samples/recipes/api-docs/README.md +52 -0
  53. package/samples/recipes/api-docs/api-docs/de/events.md +62 -0
  54. package/samples/recipes/api-docs/api-docs/de/overview.md +100 -0
  55. package/samples/recipes/api-docs/api-docs/de/reference/tickets.md +305 -0
  56. package/samples/recipes/api-docs/api-docs/de/tokens.md +66 -0
  57. package/samples/recipes/api-docs/api-docs/en/events.md +62 -0
  58. package/samples/recipes/api-docs/api-docs/en/overview.md +100 -0
  59. package/samples/recipes/api-docs/api-docs/en/reference/tickets.md +305 -0
  60. package/samples/recipes/api-docs/api-docs/en/tokens.md +66 -0
  61. package/samples/recipes/api-docs/api-docs/index.json +371 -0
  62. package/samples/recipes/api-docs/api-docs/openapi.json +982 -0
  63. package/samples/recipes/api-docs/api-examples/ticket-close.json +21 -0
  64. package/samples/recipes/api-docs/api-examples/ticket-create.json +42 -0
  65. package/samples/recipes/api-docs/api-examples/ticket-detail.json +28 -0
  66. package/samples/recipes/api-docs/api-examples/ticket-list.json +31 -0
  67. package/samples/recipes/api-docs/api-examples/ticket-update.json +54 -0
  68. package/samples/recipes/api-docs/api-examples/webhooks/ticket-closed.json +8 -0
  69. package/samples/recipes/api-docs/api-examples/webhooks/ticket-created.json +10 -0
  70. package/samples/recipes/api-docs/kumiko.config.ts +33 -0
  71. package/samples/recipes/api-docs/package.json +14 -0
  72. package/samples/recipes/api-docs/src/feature.ts +218 -0
  73. package/samples/recipes/api-docs/tsconfig.json +22 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.411.0",
3
+ "version": "0.412.0",
4
4
  "description": "Source trees of the Kumiko sample recipes, sample apps and bundled features in repo layout, for tooling such as few-shot corpus builds.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.411.0",
3
+ "version": "0.412.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "MIT",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -4,6 +4,7 @@ import type {
4
4
  WriteHandlerDef,
5
5
  } from "@cosmicdrift/kumiko-framework/engine";
6
6
  import {
7
+ handlerDescriptionKey,
7
8
  handlerFieldLabelKey,
8
9
  handlerTitleKey,
9
10
  isAgentVisibleScreen,
@@ -13,7 +14,9 @@ import {
13
14
  toKebab,
14
15
  } from "@cosmicdrift/kumiko-framework/engine";
15
16
  import * as z from "zod";
16
- import { systemOnlyPropertyNames } from "./agent-manifest.ts";
17
+ import { systemOnlyPropertyNames } from "./handler-schema.ts";
18
+ import { localizedLabels } from "./labels.ts";
19
+ import type { RegistryManifestView } from "./types.ts";
17
20
 
18
21
  export const AgentDocGapKinds = {
19
22
  handlerSchemaNotExpressible: "handler-schema-not-expressible",
@@ -21,6 +24,7 @@ export const AgentDocGapKinds = {
21
24
  customScreenWithoutDescription: "custom-screen-without-description",
22
25
  exposedEntityWithoutDescription: "exposed-entity-without-description",
23
26
  handlerWithoutTranslation: "handler-without-translation",
27
+ handlerWithoutDescriptionTranslation: "handler-without-description-translation",
24
28
  } as const;
25
29
 
26
30
  export type AgentDocGapKind = (typeof AgentDocGapKinds)[keyof typeof AgentDocGapKinds];
@@ -30,6 +34,7 @@ export type AgentDocGap = {
30
34
  readonly feature: string;
31
35
  readonly kind: AgentDocGapKind;
32
36
  readonly message: string;
37
+ readonly locale?: string;
33
38
  };
34
39
 
35
40
  // No shared screen-type union exists in the codebase to import (ScreenDefinition
@@ -39,6 +44,8 @@ const CUSTOM_SCREEN_TYPE = "custom";
39
44
 
40
45
  const ENTITY_QN_SEGMENT = "entity";
41
46
 
47
+ const DESCRIPTION_FALLBACK_LOCALE = "en";
48
+
42
49
  // QNs contain `:`, so localeCompare's ICU punctuation rules would make sort
43
50
  // order depend on runtime locale — compare by code point instead (same
44
51
  // reasoning as agent-manifest.ts's compareIds).
@@ -72,17 +79,21 @@ function handlerDocGaps(
72
79
  handlers: Readonly<Record<string, WriteHandlerDef | QueryHandlerDef>>,
73
80
  handlerQnType: typeof QnTypes.write | typeof QnTypes.query,
74
81
  handlerNoun: string,
82
+ // Set for the API docs: only these handlers are checked, and an agent opt-out
83
+ // doesn't excuse them because the docs show every handler a token reaches.
84
+ onlyQns?: ReadonlySet<string>,
75
85
  ): readonly AgentDocGap[] {
76
86
  const gaps: AgentDocGap[] = [];
77
87
  const handlerKind = handlerQnType === QnTypes.write ? "write" : "query";
78
88
  for (const [name, def] of Object.entries(handlers)) {
79
89
  const handlerQn = qn(toKebab(feature.name), handlerQnType, toKebab(name));
90
+ if (onlyQns !== undefined && !onlyQns.has(handlerQn)) continue;
80
91
  const isExposed = resolveAgentExposure(def, handlerKind).expose;
81
- if (isExposed) {
92
+ if (isExposed || onlyQns !== undefined) {
82
93
  const schemaGap = schemaNotExpressibleGap(feature, handlerQn, def, handlerNoun);
83
94
  if (schemaGap) gaps.push(schemaGap);
84
95
  }
85
- if (def.agent?.expose === false) continue;
96
+ if (onlyQns === undefined && def.agent?.expose === false) continue;
86
97
  if (def.description !== undefined && def.description.trim() !== "") continue;
87
98
  gaps.push({
88
99
  qn: handlerQn,
@@ -217,6 +228,30 @@ export function findAgentDocGaps(features: readonly FeatureDefinition[]): readon
217
228
  return [...gaps].sort((a, b) => compareByCodePoint(a.qn, b.qn));
218
229
  }
219
230
 
231
+ /** Description and schema gaps of exactly the handlers the API docs list. */
232
+ export function findApiDocHandlerGaps(
233
+ features: readonly FeatureDefinition[],
234
+ handlerQns: ReadonlySet<string>,
235
+ ): readonly AgentDocGap[] {
236
+ const gaps = features.flatMap((feature) => [
237
+ ...handlerDocGaps(
238
+ feature,
239
+ feature.writeHandlers ?? {},
240
+ QnTypes.write,
241
+ "write handler",
242
+ handlerQns,
243
+ ),
244
+ ...handlerDocGaps(
245
+ feature,
246
+ feature.queryHandlers ?? {},
247
+ QnTypes.query,
248
+ "query handler",
249
+ handlerQns,
250
+ ),
251
+ ]);
252
+ return [...gaps].sort((a, b) => compareByCodePoint(a.qn, b.qn));
253
+ }
254
+
220
255
  // Kept out of findAgentDocGaps on purpose: the published agent-manifest guard
221
256
  // fails on every gap that function returns, and these are advisory.
222
257
  export function findHandlerTranslationGaps(
@@ -227,6 +262,32 @@ export function findHandlerTranslationGaps(
227
262
  return [...gaps].sort((a, b) => compareByCodePoint(a.qn, b.qn));
228
263
  }
229
264
 
265
+ // "en" is skipped because the docs fall back to the handler's `description` for it.
266
+ // Advisory like findHandlerTranslationGaps: not part of findAgentDocGaps.
267
+ export function findDescriptionTranslationGaps(
268
+ registry: Pick<RegistryManifestView, "getAllTranslations">,
269
+ options: { readonly handlerQns: readonly string[]; readonly locales: readonly string[] },
270
+ ): readonly AgentDocGap[] {
271
+ const translations = registry.getAllTranslations();
272
+ const gaps: AgentDocGap[] = [];
273
+ for (const handlerQn of options.handlerQns) {
274
+ const labels = localizedLabels(translations, handlerDescriptionKey(handlerQn));
275
+ for (const locale of options.locales) {
276
+ if (locale === DESCRIPTION_FALLBACK_LOCALE || labels[locale] !== undefined) continue;
277
+ gaps.push({
278
+ qn: handlerQn,
279
+ feature: handlerQn.split(":")[0] ?? handlerQn,
280
+ kind: AgentDocGapKinds.handlerWithoutDescriptionTranslation,
281
+ locale,
282
+ message: `No \`${locale}\` translation under ${handlerDescriptionKey(handlerQn)}.`,
283
+ });
284
+ }
285
+ }
286
+ return [...gaps].sort(
287
+ (a, b) => compareByCodePoint(a.qn, b.qn) || compareByCodePoint(a.locale ?? "", b.locale ?? ""),
288
+ );
289
+ }
290
+
230
291
  export function formatAgentDocGap(gap: AgentDocGap): string {
231
292
  return `${gap.qn} — ${gap.message}`;
232
293
  }
@@ -6,7 +6,6 @@ import type {
6
6
  NavDefinition,
7
7
  QueryHandlerDef,
8
8
  ScreenDefinition,
9
- TranslationEntry,
10
9
  TranslationKeys,
11
10
  WorkspaceDefinition,
12
11
  WriteHandlerDef,
@@ -15,11 +14,15 @@ import {
15
14
  hasAccess,
16
15
  isAgentVisibleScreen,
17
16
  resolveAgentExposure,
18
- SYSTEM_ONLY_JSON_SCHEMA_KEY,
19
17
  } from "@cosmicdrift/kumiko-framework/engine";
20
- import { translationValueOtherText } from "@cosmicdrift/kumiko-framework/ui-types";
21
- import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
22
- import * as z from "zod";
18
+ import { handlerInputJsonSchema } from "./handler-schema.ts";
19
+ import {
20
+ compareIds,
21
+ entryAsLabels,
22
+ labelsForSuffix,
23
+ pickLabel,
24
+ screenTitleLabels,
25
+ } from "./labels.ts";
23
26
  import { recordManifestDenyQns } from "./manifest-deny-qns.ts";
24
27
  import { isExplicitlyAgentHidden } from "./tool-catalog.ts";
25
28
  import type {
@@ -35,23 +38,6 @@ import type {
35
38
  RegistryManifestView,
36
39
  } from "./types.ts";
37
40
 
38
- const FALLBACK_LOCALE = "en";
39
-
40
- /** Requested locale, then English, then the first remaining locale in code-point
41
- * order; `undefined` when the entry has no text at all (the key is then omitted). */
42
- function pickLabel(labels: Readonly<Record<string, string>>, locale: string): string | undefined {
43
- const nonEmpty = (value: string | undefined): string | undefined =>
44
- value !== undefined && value !== "" ? value : undefined;
45
- const firstLocale = Object.keys(labels)
46
- .sort(compareIds)
47
- .find((key) => nonEmpty(labels[key]));
48
- return (
49
- nonEmpty(labels[locale]) ??
50
- nonEmpty(labels[FALLBACK_LOCALE]) ??
51
- (firstLocale !== undefined ? labels[firstLocale] : undefined)
52
- );
53
- }
54
-
55
41
  function labelProp(
56
42
  labels: Readonly<Record<string, string>>,
57
43
  locale: string,
@@ -60,57 +46,6 @@ function labelProp(
60
46
  return label === undefined ? {} : { label };
61
47
  }
62
48
 
63
- /** The manifest surfaces one string per locale — a plural entry reads as its
64
- * CLDR `other` form since the manifest has no `count` to select a category. */
65
- function entryAsLabels(entry: TranslationEntry): Readonly<Record<string, string>> {
66
- return Object.fromEntries(
67
- Object.entries(entry).map(([locale, value]) => [locale, translationValueOtherText(value)]),
68
- );
69
- }
70
-
71
- const labelsIndexByTranslations = new WeakMap<
72
- TranslationKeys,
73
- Map<string, Readonly<Record<string, string>>>
74
- >();
75
-
76
- /** Every tail starting at a key boundary (`:` or `.`, with and without the
77
- * separator) maps to the labels of the first key that ends with it. */
78
- function buildSuffixIndex(
79
- translations: TranslationKeys,
80
- ): Map<string, Readonly<Record<string, string>>> {
81
- const index = new Map<string, Readonly<Record<string, string>>>();
82
- for (const [key, entry] of Object.entries(translations)) {
83
- const labels = entryAsLabels(entry);
84
- const addTail = (start: number): void => {
85
- const tail = key.slice(start);
86
- if (!index.has(tail)) index.set(tail, labels);
87
- };
88
- addTail(0);
89
- for (let position = 0; position < key.length; position++) {
90
- if (key[position] === ":" || key[position] === ".") {
91
- addTail(position);
92
- addTail(position + 1);
93
- }
94
- }
95
- }
96
- return index;
97
- }
98
-
99
- /** Translation keys carry a feature prefix the manifest can't reconstruct
100
- * (`showcase:entity:item:field:title`), so match on the suffix instead. The
101
- * suffix must start at a `:` or `.` boundary of the key. */
102
- function labelsForSuffix(
103
- translations: TranslationKeys,
104
- suffix: string,
105
- ): Readonly<Record<string, string>> {
106
- let index = labelsIndexByTranslations.get(translations);
107
- if (index === undefined) {
108
- index = buildSuffixIndex(translations);
109
- labelsIndexByTranslations.set(translations, index);
110
- }
111
- return index.get(suffix) ?? {};
112
- }
113
-
114
49
  /** Nav/screen/workspace gating is opt-in: no rule means visible to everyone
115
50
  * (NavDefinition.access). Handlers are the opposite — `hasAccess` is
116
51
  * default-deny there. */
@@ -118,12 +53,6 @@ function uiVisible(access: AccessRule | undefined, roles: readonly string[]): bo
118
53
  return access === undefined || hasAccess({ roles }, access);
119
54
  }
120
55
 
121
- // localeCompare depends on the runtime locale and ICU punctuation rules; qualified
122
- // names contain `:`, so compare by code point instead for deterministic ordering.
123
- function compareIds(a: string, b: string): number {
124
- return a < b ? -1 : a > b ? 1 : 0;
125
- }
126
-
127
56
  function dedupeSorted(values: readonly string[]): readonly string[] {
128
57
  return [...new Set(values)].sort(compareIds);
129
58
  }
@@ -240,35 +169,6 @@ function buildFeatures(
240
169
  return result;
241
170
  }
242
171
 
243
- // Agent dispatch never runs as a system identity, so properties the engine only
244
- // honors for system callers would be silently dropped — hide them from the tool.
245
- export function systemOnlyPropertyNames(jsonSchema: Record<string, unknown>): readonly string[] {
246
- const properties = jsonSchema["properties"];
247
- if (typeof properties !== "object" || properties === null) return [];
248
- return Object.entries(properties)
249
- .filter(
250
- ([, property]) => isPlainObject(property) && property[SYSTEM_ONLY_JSON_SCHEMA_KEY] === true,
251
- )
252
- .map(([name]) => name);
253
- }
254
-
255
- function withoutSystemOnlyProperties(
256
- jsonSchema: Record<string, unknown>,
257
- ): Readonly<Record<string, unknown>> {
258
- const properties = jsonSchema["properties"];
259
- if (typeof properties !== "object" || properties === null) return jsonSchema;
260
- const hidden = systemOnlyPropertyNames(jsonSchema);
261
- if (hidden.length === 0) return jsonSchema;
262
- const required = jsonSchema["required"];
263
- return {
264
- ...jsonSchema,
265
- properties: Object.fromEntries(
266
- Object.entries(properties).filter(([name]) => !hidden.includes(name)),
267
- ),
268
- ...(Array.isArray(required) && { required: required.filter((name) => !hidden.includes(name)) }),
269
- };
270
- }
271
-
272
172
  function buildHandlerEntry(
273
173
  qn: string,
274
174
  kind: "query" | "write",
@@ -287,15 +187,9 @@ function buildHandlerEntry(
287
187
  const description =
288
188
  def.description !== undefined && def.description !== "" ? def.description : undefined;
289
189
 
290
- let inputSchema: Readonly<Record<string, unknown>>;
291
- try {
292
- // A handler whose schema can't be expressed as JSON Schema (transforms,
293
- // z.instanceof, ...) is unusable for an agent tool call — leave it out
294
- // rather than ship a broken tool.
295
- inputSchema = withoutSystemOnlyProperties(z.toJSONSchema(def.schema, { io: "input" }));
296
- } catch {
297
- return undefined;
298
- }
190
+ // Left out rather than shipped as a broken tool when the schema isn't expressible.
191
+ const inputSchema = handlerInputJsonSchema(def);
192
+ if (inputSchema === undefined) return undefined;
299
193
 
300
194
  const entity = getHandlerEntity(qn);
301
195
  const excludedFields = "excludedFields" in def ? def.excludedFields : undefined;
@@ -447,11 +341,6 @@ function visibleEntityNamesOf(
447
341
  ]);
448
342
  }
449
343
 
450
- function lastSegment(qualifiedId: string): string {
451
- const idx = qualifiedId.lastIndexOf(":");
452
- return idx === -1 ? qualifiedId : qualifiedId.slice(idx + 1);
453
- }
454
-
455
344
  function detailIdParam(screen: ScreenDefinition): string {
456
345
  return screen.type === "projectionDetail" ? (screen.idParam ?? "id") : "id";
457
346
  }
@@ -459,15 +348,9 @@ function detailIdParam(screen: ScreenDefinition): string {
459
348
  function screenTitles(
460
349
  translations: TranslationKeys,
461
350
  screenId: string,
462
- shortId: string,
463
351
  locale: string,
464
352
  ): { readonly title?: string } {
465
- const title = pickLabel(
466
- entryAsLabels(
467
- translations[`${screenId}.title`] ?? translations[`screen:${shortId}.title`] ?? {},
468
- ),
469
- locale,
470
- );
353
+ const title = pickLabel(screenTitleLabels(translations, screenId), locale);
471
354
  return title === undefined ? {} : { title };
472
355
  }
473
356
 
@@ -480,7 +363,7 @@ function buildScreenEntry(
480
363
  return {
481
364
  id: screen.id,
482
365
  type: screen.type,
483
- ...screenTitles(translations, screen.id, lastSegment(screen.id), locale),
366
+ ...screenTitles(translations, screen.id, locale),
484
367
  // `screen.description` may be a raw i18n key (`registry.getAllTranslations()`
485
368
  // double-prefixes it, see build-app-schema.ts:77-81) — match on suffix like
486
369
  // `labelsForSuffix` does for entity/field labels, else fall back to the
@@ -0,0 +1,60 @@
1
+ const QN_TYPE_SEGMENTS = new Set(["query", "write"]);
2
+ const HEADING_SEPARATOR = ": ";
3
+
4
+ /** `helpdesk:write:ticket:close` becomes ["ticket", "close"]: the feature prefix and
5
+ * the `query`/`write` kind are noise inside a page that already names both. */
6
+ function tailSegments(qn: string): readonly string[] {
7
+ const segments = qn.split(":");
8
+ const rest = segments.slice(1);
9
+ return rest[0] !== undefined && QN_TYPE_SEGMENTS.has(rest[0]) ? rest.slice(1) : rest;
10
+ }
11
+
12
+ export function handlerHeading(qn: string): string {
13
+ return tailSegments(qn).join(HEADING_SEPARATOR);
14
+ }
15
+
16
+ function fullHeading(qn: string): string {
17
+ return qn.split(":").join(HEADING_SEPARATOR);
18
+ }
19
+
20
+ /** GitHub-style slug: lower case, punctuation dropped, spaces to hyphens. */
21
+ export function slugify(heading: string): string {
22
+ return heading
23
+ .toLowerCase()
24
+ .replace(/[^\p{L}\p{N}\p{M}\s_-]/gu, "")
25
+ .replace(/\s/g, "-");
26
+ }
27
+
28
+ export type HandlerAnchor = {
29
+ readonly qn: string;
30
+ readonly heading: string;
31
+ readonly anchor: string;
32
+ };
33
+
34
+ /** Events are headed by their wire name. Declared (`feature:name`) and entity (`entity.verb`) names can
35
+ * slug alike once punctuation is dropped, so repeats get GitHub's `-1`, `-2` suffix in QN order. */
36
+ export function eventAnchors(qns: readonly string[]): readonly HandlerAnchor[] {
37
+ const used = new Set<string>();
38
+ return qns.map((qn) => {
39
+ const base = slugify(qn);
40
+ let anchor = base;
41
+ for (let repeat = 1; used.has(anchor); repeat++) anchor = `${base}-${repeat}`;
42
+ used.add(anchor);
43
+ return { qn, heading: qn, anchor };
44
+ });
45
+ }
46
+
47
+ /** Short headings, except when two handlers of one page would get the same slug:
48
+ * both then switch to the full QN form, which is unique by construction. */
49
+ export function anchorsForPage(qns: readonly string[]): readonly HandlerAnchor[] {
50
+ const shortSlugCount = new Map<string, number>();
51
+ for (const qn of qns) {
52
+ const slug = slugify(handlerHeading(qn));
53
+ shortSlugCount.set(slug, (shortSlugCount.get(slug) ?? 0) + 1);
54
+ }
55
+ return qns.map((qn) => {
56
+ const isCollision = (shortSlugCount.get(slugify(handlerHeading(qn))) ?? 0) > 1;
57
+ const heading = isCollision ? fullHeading(qn) : handlerHeading(qn);
58
+ return { qn, heading, anchor: slugify(heading) };
59
+ });
60
+ }
@@ -0,0 +1,25 @@
1
+ export type ApiDocsDiff = {
2
+ readonly missing: readonly string[];
3
+ readonly changed: readonly string[];
4
+ readonly extra: readonly string[];
5
+ };
6
+
7
+ const byCodePoint = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
8
+
9
+ /** `expected` is what the generator produces, `actual` what is on disk. */
10
+ export function diffApiDocsOutput(
11
+ expected: ReadonlyMap<string, string>,
12
+ actual: ReadonlyMap<string, string>,
13
+ ): ApiDocsDiff {
14
+ const missing = [...expected.keys()].filter((path) => !actual.has(path));
15
+ const changed = [...expected].filter(([path, content]) => {
16
+ const onDisk = actual.get(path);
17
+ return onDisk !== undefined && onDisk !== content;
18
+ });
19
+ const extra = [...actual.keys()].filter((path) => !expected.has(path));
20
+ return {
21
+ missing: missing.sort(byCodePoint),
22
+ changed: changed.map(([path]) => path).sort(byCodePoint),
23
+ extra: extra.sort(byCodePoint),
24
+ };
25
+ }
@@ -0,0 +1,140 @@
1
+ import {
2
+ createWebhookContractResolver,
3
+ type WebhookEventContract,
4
+ webhookEventDescriptionKey,
5
+ webhookEventFieldKey,
6
+ } from "@cosmicdrift/kumiko-framework/engine";
7
+ import * as z from "zod";
8
+ import type { PatScopeConfig } from "../../personal-access-tokens/index.ts";
9
+ import {
10
+ compareIds,
11
+ entityFieldLabels,
12
+ localizedLabels,
13
+ localizedLabelsForSuffix,
14
+ pickLabel,
15
+ } from "../labels.ts";
16
+ import type { RegistryManifestView } from "../types.ts";
17
+ import type { WebhookExampleFile } from "./examples.ts";
18
+ import type { ApiDocsEvent, LocalizedText } from "./model.ts";
19
+ import { fieldRows } from "./schema-fields.ts";
20
+
21
+ const SOURCE_LOCALE = "en";
22
+
23
+ function nonEmpty(value: string | undefined): string | undefined {
24
+ return value !== undefined && value !== "" ? value : undefined;
25
+ }
26
+
27
+ function perLocale(locales: readonly string[], resolve: (locale: string) => string): LocalizedText {
28
+ return Object.fromEntries(locales.map((locale) => [locale, resolve(locale)]));
29
+ }
30
+
31
+ /** `undefined` when the payload cannot be expressed as JSON Schema (transforms, instanceof, ...). */
32
+ function payloadJsonSchema(contract: WebhookEventContract): Record<string, unknown> | undefined {
33
+ try {
34
+ return z.toJSONSchema(contract.payload, { io: "output" });
35
+ } catch {
36
+ // skip: a payload without a JSON Schema form is documented without a field table
37
+ return undefined;
38
+ }
39
+ }
40
+
41
+ /** Declared contracts read `<feature>:webhook:<name>:field:<path>`, derived ones the entity's
42
+ * field labels. A row without a label keeps the schema description (`.describe()`). */
43
+ function fieldLabelsByRow(
44
+ translations: ReturnType<RegistryManifestView["getAllTranslations"]>,
45
+ contract: WebhookEventContract,
46
+ payloadSchema: Record<string, unknown> | undefined,
47
+ locales: readonly string[],
48
+ ): Readonly<Record<string, LocalizedText>> {
49
+ const { entity } = contract;
50
+ return Object.fromEntries(
51
+ fieldRows(payloadSchema).flatMap(({ name }) => {
52
+ const labels =
53
+ entity === undefined
54
+ ? localizedLabels(translations, webhookEventFieldKey(contract.qn, name))
55
+ : entityFieldLabels(translations, entity, name);
56
+ const resolved = Object.fromEntries(
57
+ locales.flatMap((locale) => {
58
+ // A declared field falls back to its English `.describe()`, never to another locale.
59
+ const label =
60
+ entity === undefined
61
+ ? (nonEmpty(labels[locale]) ?? nonEmpty(labels[SOURCE_LOCALE]))
62
+ : pickLabel(labels, locale);
63
+ return label === undefined ? [] : [[locale, label]];
64
+ }),
65
+ );
66
+ return [[name, resolved]];
67
+ }),
68
+ );
69
+ }
70
+
71
+ function buildEvent(
72
+ registry: RegistryManifestView,
73
+ contract: WebhookEventContract,
74
+ domains: readonly string[],
75
+ options: { locales: readonly string[]; examples: ReadonlyMap<string, WebhookExampleFile> },
76
+ ): ApiDocsEvent {
77
+ const translations = registry.getAllTranslations();
78
+ const { locales } = options;
79
+ const declared = contract.origin === "declared";
80
+ const descriptionLabels = declared
81
+ ? localizedLabels(translations, webhookEventDescriptionKey(contract.qn))
82
+ : {};
83
+ const entityLabels =
84
+ contract.entity === undefined
85
+ ? {}
86
+ : localizedLabelsForSuffix(translations, `:entity:${contract.entity}`);
87
+ const payloadSchema = payloadJsonSchema(contract);
88
+ return {
89
+ qn: contract.qn,
90
+ wireName: contract.wireName,
91
+ origin: contract.origin,
92
+ ...(contract.entity !== undefined && { entity: contract.entity }),
93
+ ...(contract.verb !== undefined && { verb: contract.verb }),
94
+ version: contract.version,
95
+ description: perLocale(
96
+ locales,
97
+ (locale) =>
98
+ nonEmpty(descriptionLabels[locale]) ??
99
+ nonEmpty(descriptionLabels[SOURCE_LOCALE]) ??
100
+ contract.description,
101
+ ),
102
+ entityLabel: perLocale(
103
+ locales,
104
+ (locale) => pickLabel(entityLabels, locale) ?? contract.entity ?? contract.qn,
105
+ ),
106
+ untranslatedLocales: declared
107
+ ? locales.filter(
108
+ (locale) => locale !== SOURCE_LOCALE && nonEmpty(descriptionLabels[locale]) === undefined,
109
+ )
110
+ : [],
111
+ fieldLabels: fieldLabelsByRow(translations, contract, payloadSchema, locales),
112
+ payloadSchema,
113
+ domains,
114
+ example: options.examples.get(contract.qn),
115
+ };
116
+ }
117
+
118
+ /** Events some scope lists, deduplicated and sorted by QN. An entry without a contract is
119
+ * skipped: the token feature's boot check already refuses to start with one. */
120
+ export function collectApiDocsEvents(
121
+ registry: RegistryManifestView,
122
+ scopes: PatScopeConfig,
123
+ options: { locales: readonly string[]; examples: ReadonlyMap<string, WebhookExampleFile> },
124
+ ): readonly ApiDocsEvent[] {
125
+ const domainsByEvent = new Map<string, string[]>();
126
+ for (const domain of Object.keys(scopes).sort(compareIds)) {
127
+ for (const qn of scopes[domain]?.events ?? []) {
128
+ const domains = domainsByEvent.get(qn) ?? [];
129
+ if (!domains.includes(domain)) domains.push(domain);
130
+ domainsByEvent.set(qn, domains);
131
+ }
132
+ }
133
+ const resolver = createWebhookContractResolver([...registry.features.values()]);
134
+ return [...domainsByEvent.keys()].sort(compareIds).flatMap((qn) => {
135
+ const contract = resolver.get(qn);
136
+ return contract === undefined
137
+ ? []
138
+ : [buildEvent(registry, contract, domainsByEvent.get(qn) ?? [], options)];
139
+ });
140
+ }