@cosmicdrift/kumiko-framework 0.158.2 → 0.160.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 (168) hide show
  1. package/package.json +7 -2
  2. package/src/__tests__/consumer-cli.integration.test.ts +110 -0
  3. package/src/api/__tests__/api.test.ts +65 -0
  4. package/src/api/__tests__/auth-routes-cookie.test.ts +17 -1
  5. package/src/api/__tests__/auth-routes-invalid-body-invite.test.ts +237 -0
  6. package/src/api/__tests__/auth-routes-mfa-verify.test.ts +1 -0
  7. package/src/api/__tests__/csrf-constants-sync.test.ts +20 -0
  8. package/src/api/__tests__/dispatcher-live.integration.test.ts +74 -0
  9. package/src/api/__tests__/jwt.test.ts +150 -1
  10. package/src/api/__tests__/login-rate-limiter-sweep.test.ts +41 -0
  11. package/src/api/__tests__/server-boot-guards.test.ts +71 -0
  12. package/src/api/__tests__/server-jwt-ttl.test.ts +58 -0
  13. package/src/api/api-constants.ts +5 -0
  14. package/src/api/auth-middleware.ts +48 -59
  15. package/src/api/auth-routes.ts +51 -17
  16. package/src/api/index.ts +3 -3
  17. package/src/api/jwt.ts +148 -7
  18. package/src/api/pii-leak-guard.ts +5 -2
  19. package/src/api/routes.ts +57 -0
  20. package/src/api/server.ts +19 -5
  21. package/src/bun-db/__tests__/select-many-retry.test.ts +79 -0
  22. package/src/bun-db/query.ts +46 -27
  23. package/src/consumer-cli.ts +87 -0
  24. package/src/crypto/__tests__/pii-field-encryption.test.ts +69 -13
  25. package/src/crypto/blind-index.ts +8 -4
  26. package/src/crypto/event-pii.ts +1 -0
  27. package/src/crypto/kms-adapter.ts +2 -118
  28. package/src/crypto/pii-field-encryption.ts +49 -15
  29. package/src/db/__tests__/build-filter-where.test.ts +34 -0
  30. package/src/db/__tests__/event-store-executor-context.pii-roundtrip.test.ts +67 -0
  31. package/src/db/__tests__/event-store-executor-write-verbs.integration.test.ts +396 -0
  32. package/src/db/__tests__/event-store-executor.integration.test.ts +5 -5
  33. package/src/db/blind-index-cleanup.ts +3 -1
  34. package/src/db/connection.ts +3 -11
  35. package/src/db/cursor.ts +1 -18
  36. package/src/db/dialect.ts +8 -19
  37. package/src/db/encryption.ts +2 -3
  38. package/src/db/entity-table-meta-types.ts +2 -0
  39. package/src/db/entity-table-meta.ts +16 -90
  40. package/src/db/event-store-executor.ts +4 -96
  41. package/src/db/queries/backfill-pii.ts +1 -0
  42. package/src/db/queries/event-consumer.ts +35 -2
  43. package/src/db/table-builder.ts +2 -19
  44. package/src/db/tenant-db.ts +6 -55
  45. package/src/engine/__tests__/boot-validator-boot-check.test.ts +99 -0
  46. package/src/engine/__tests__/boot-validator-gdpr-storage.test.ts +7 -233
  47. package/src/engine/__tests__/boot-validator.test.ts +46 -0
  48. package/src/engine/__tests__/codemod-pipeline.test.ts +139 -10
  49. package/src/engine/__tests__/define-roles.test.ts +21 -0
  50. package/src/engine/__tests__/engine.test.ts +28 -0
  51. package/src/engine/__tests__/event-type-map-augmentation.test.ts +24 -0
  52. package/src/engine/__tests__/registry-facade-sweep.test.ts +80 -0
  53. package/src/engine/__tests__/registry.test.ts +40 -0
  54. package/src/engine/__tests__/store-table.test.ts +12 -0
  55. package/src/engine/__tests__/tier-resolver-extension.test.ts +19 -1
  56. package/src/engine/boot-validator/action-wiring.ts +1 -1
  57. package/src/engine/boot-validator/boot-check.ts +21 -0
  58. package/src/engine/boot-validator/entity-handler.ts +10 -1
  59. package/src/engine/boot-validator/entity-list-screens.ts +1 -1
  60. package/src/engine/boot-validator/gdpr-storage.ts +0 -112
  61. package/src/engine/boot-validator/index.ts +3 -9
  62. package/src/engine/boot-validator/screens.ts +1 -1
  63. package/src/engine/define-feature.ts +2 -0
  64. package/src/engine/define-handler.ts +11 -91
  65. package/src/engine/entity-handlers.ts +15 -27
  66. package/src/engine/feature-ast/__tests__/canonical-form.test.ts +11 -1
  67. package/src/engine/feature-ast/__tests__/parse.test.ts +983 -3
  68. package/src/engine/feature-ast/__tests__/patch.test.ts +168 -0
  69. package/src/engine/feature-ast/__tests__/patcher.test.ts +7 -0
  70. package/src/engine/feature-ast/__tests__/render-roundtrip.test.ts +9 -0
  71. package/src/engine/feature-ast/extractors/handlers.ts +19 -2
  72. package/src/engine/feature-ast/extractors/index.ts +1 -0
  73. package/src/engine/feature-ast/index.ts +2 -0
  74. package/src/engine/feature-ast/parse.ts +3 -0
  75. package/src/engine/feature-ast/patch.ts +2 -0
  76. package/src/engine/feature-ast/patcher.ts +21 -0
  77. package/src/engine/feature-ast/patterns.ts +16 -0
  78. package/src/engine/feature-ast/render.ts +15 -0
  79. package/src/engine/feature-builder-state.ts +6 -0
  80. package/src/engine/feature-config-events-jobs.ts +1 -1
  81. package/src/engine/feature-entity-handlers.ts +36 -2
  82. package/src/engine/feature-ui-extensions.ts +5 -1
  83. package/src/engine/field-helpers.ts +31 -0
  84. package/src/engine/handler-helpers.ts +26 -0
  85. package/src/engine/hook-helpers.ts +14 -0
  86. package/src/engine/index.ts +5 -2
  87. package/src/engine/ownership.ts +22 -76
  88. package/src/engine/pattern-library/__tests__/library.test.ts +9 -0
  89. package/src/engine/pattern-library/library.ts +2 -0
  90. package/src/engine/pattern-library/mixed-schemas.ts +37 -0
  91. package/src/engine/registry-facade.ts +9 -0
  92. package/src/engine/registry-ingest.ts +10 -0
  93. package/src/engine/registry-state.ts +3 -0
  94. package/src/engine/registry-validate.ts +1 -1
  95. package/src/engine/screen-helpers.ts +54 -0
  96. package/src/engine/tier-resolver-extension.ts +3 -2
  97. package/src/engine/types/config.ts +2 -497
  98. package/src/engine/types/define-handler.ts +2 -0
  99. package/src/engine/types/entity-handlers.ts +2 -0
  100. package/src/engine/types/event-type-map.ts +1 -37
  101. package/src/engine/types/feature.ts +2 -976
  102. package/src/engine/types/fields.ts +2 -697
  103. package/src/engine/types/handlers.ts +2 -839
  104. package/src/engine/types/hooks.ts +2 -184
  105. package/src/engine/types/http-route.ts +1 -72
  106. package/src/engine/types/identifiers.ts +1 -47
  107. package/src/engine/types/index.ts +66 -33
  108. package/src/engine/types/nav.ts +2 -67
  109. package/src/engine/types/ownership.ts +2 -0
  110. package/src/engine/types/projection.ts +2 -165
  111. package/src/engine/types/relations.ts +1 -51
  112. package/src/engine/types/screen.ts +2 -793
  113. package/src/engine/types/step.ts +2 -334
  114. package/src/engine/types/target-ref.ts +1 -21
  115. package/src/engine/types/tree-node.ts +1 -129
  116. package/src/engine/types/workspace.ts +2 -42
  117. package/src/entrypoint/index.ts +2 -2
  118. package/src/errors/write-error-info.ts +6 -22
  119. package/src/event-store/__tests__/event-store.integration.test.ts +31 -0
  120. package/src/event-store/__tests__/unscoped-stream-primitives.guard.test.ts +43 -0
  121. package/src/event-store/errors.ts +2 -35
  122. package/src/event-store/event-store.ts +28 -51
  123. package/src/event-store/events-schema.ts +1 -10
  124. package/src/event-store/index.ts +3 -2
  125. package/src/event-store/snapshot.ts +11 -35
  126. package/src/event-store/types.ts +2 -0
  127. package/src/files/__tests__/in-memory-provider.contract.test.ts +4 -0
  128. package/src/files/file-handle.ts +2 -19
  129. package/src/files/provider-resolver.ts +3 -5
  130. package/src/files/types.ts +5 -54
  131. package/src/i18n/required-surface-keys.ts +1 -1
  132. package/src/jobs/__tests__/jobs.integration.test.ts +102 -1
  133. package/src/logging/types.ts +1 -7
  134. package/src/observability/types/index.ts +1 -29
  135. package/src/observability/types/metric.ts +1 -56
  136. package/src/observability/types/provider.ts +1 -32
  137. package/src/observability/types/span.ts +1 -58
  138. package/src/pipeline/__tests__/dispatcher.test.ts +134 -1
  139. package/src/pipeline/__tests__/event-dispatcher-delivery-max-attempts.test.ts +126 -0
  140. package/src/pipeline/__tests__/event-dispatcher-rearm.integration.test.ts +180 -0
  141. package/src/pipeline/__tests__/lifecycle-pipeline.test.ts +208 -0
  142. package/src/pipeline/dispatch-shared.ts +51 -3
  143. package/src/pipeline/dispatch-stream.ts +74 -0
  144. package/src/pipeline/dispatcher-utils.ts +1 -1
  145. package/src/pipeline/dispatcher.ts +7 -0
  146. package/src/pipeline/entity-cache.ts +2 -33
  147. package/src/pipeline/event-consumer-state.ts +28 -3
  148. package/src/pipeline/event-dispatcher-admin.ts +4 -0
  149. package/src/pipeline/event-dispatcher-delivery.ts +29 -3
  150. package/src/pipeline/event-dispatcher.ts +27 -1
  151. package/src/pipeline/multi-stream-apply-context.ts +4 -42
  152. package/src/pipeline/system-hooks.ts +7 -0
  153. package/src/rate-limit/resolver.ts +10 -30
  154. package/src/search/types.ts +1 -39
  155. package/src/secrets/__tests__/envelope-cipher.test.ts +2 -30
  156. package/src/secrets/__tests__/envelope.test.ts +1 -1
  157. package/src/secrets/envelope-cipher.ts +17 -45
  158. package/src/secrets/types.ts +2 -177
  159. package/src/stack/__tests__/event-collector.test.ts +42 -0
  160. package/src/testing/__tests__/late-bound.test.ts +25 -0
  161. package/src/testing/__tests__/wait-for.test.ts +53 -0
  162. package/src/testing/boot-validator-fixture.ts +1 -1
  163. package/src/testing/file-provider-contract.ts +84 -0
  164. package/src/testing/handler-context.ts +1 -1
  165. package/src/testing/index.ts +1 -0
  166. package/src/time/geo-tz.ts +1 -32
  167. package/src/time/tz-context.ts +9 -56
  168. package/src/ui-types/index.ts +7 -7
@@ -1,976 +1,2 @@
1
- import type { ZodType, z } from "zod";
2
- import type { EntityTableMeta } from "../../db/entity-table-meta";
3
- import type { QueryHandlerDefinition, WriteHandlerDefinition } from "../define-handler";
4
- import type { RegisterEntityCrudOptions } from "../entity-handlers";
5
- import type {
6
- ConfigKeyDefinition,
7
- ConfigKeyHandle,
8
- ConfigKeyType,
9
- ConfigSeedDef,
10
- ExtensionSelectorDef,
11
- JobDefinition,
12
- JobHandlerFn,
13
- NotificationDataFn,
14
- NotificationDefinition,
15
- NotificationRecipientFn,
16
- NotificationTemplateFn,
17
- ReferenceDataDef,
18
- RegistrarExtensionDef,
19
- RegistrarExtensionRegistration,
20
- TranslationKeys,
21
- TranslationsDef,
22
- } from "./config";
23
- import type { EntityDefinition } from "./fields";
24
- import type {
25
- AccessRule,
26
- AuthClaimsFn,
27
- AuthClaimsHookDef,
28
- ClaimKeyDefinition,
29
- ClaimKeyHandle,
30
- ClaimKeyType,
31
- DeclarativeEventMigration,
32
- EntityRef,
33
- EventDef,
34
- EventMigrationDef,
35
- EventPiiFields,
36
- EventUpcastFn,
37
- HandlerRef,
38
- NameOrRef,
39
- QualifiedEventName,
40
- QueryHandlerDef,
41
- QueryHandlerFn,
42
- RateLimitOption,
43
- WriteHandlerDef,
44
- WriteHandlerFn,
45
- } from "./handlers";
46
- import type {
47
- EntityHookMap,
48
- HookMap,
49
- HookPhase,
50
- OwnedFn,
51
- PostDeleteHookFn,
52
- PostQueryHookFn,
53
- PostSaveHookFn,
54
- PreDeleteHookFn,
55
- PreQueryHookFn,
56
- PreSaveHookFn,
57
- SearchPayloadContributorFn,
58
- ValidationHookFn,
59
- } from "./hooks";
60
- import type { HttpRouteDefinition } from "./http-route";
61
- import type { NavDefinition } from "./nav";
62
- import type {
63
- EntityProjectionExtension,
64
- MultiStreamProjectionDefinition,
65
- ProjectionDefinition,
66
- } from "./projection";
67
- import type { EntityRelations, RelationDefinition } from "./relations";
68
- import type { ScreenDefinition } from "./screen";
69
- import type { TreeActionDef, TreeActionsHandle } from "./tree-node";
70
- import type { WorkspaceDefinition } from "./workspace";
71
-
72
- // --- Metrics (declared by features via r.metric()) ---
73
-
74
- export type FeatureMetricType = "counter" | "histogram" | "gauge";
75
-
76
- // The user-facing short form written in a feature. The Framework prefixes it
77
- // with `kumiko_<featureName>_` to produce the fully-qualified Prometheus name.
78
- export type FeatureMetricDef = {
79
- readonly shortName: string;
80
- readonly type: FeatureMetricType;
81
- readonly description?: string;
82
- readonly labels?: readonly string[];
83
- readonly buckets?: readonly number[];
84
- readonly unit?: string;
85
- // When true, Framework auto-adds tenant_id to labels (ctx-driven). Default
86
- // false — cardinality multiplies by tenant count, so opt-in.
87
- readonly tenantLabel?: boolean;
88
- };
89
-
90
- export type MetricOptions = Omit<FeatureMetricDef, "shortName">;
91
-
92
- // --- Secret Keys (declared by features via r.secret()) ---
93
-
94
- // A feature-declared secret. The fully-qualified name is
95
- // `<featureName>:<shortName>` — the Framework prefixes. Ops see the
96
- // qualified name in list / audit; feature code reads it via
97
- // ctx.secrets.get(tenantId, SecretKeys.stripeKey) with the typed handle.
98
- export type SecretKeyDefinition = {
99
- // Short name inside the feature (e.g. "stripe.apiKey"). Qualified to
100
- // `<feature>:<shortName>` at registry-build time.
101
- readonly shortName: string;
102
- // Qualified name — `<feature>:<shortName>`. Set during registry build.
103
- readonly qualifiedName: string;
104
- // i18n label for TenantAdmin UI.
105
- readonly label: { readonly [locale: string]: string };
106
- // Optional redaction function. Takes the plaintext, returns the preview
107
- // shown in list handlers. Default is first-3-chars + bullets.
108
- readonly redact?: (plaintext: string) => string;
109
- // Short human hint shown in UI ("Find this in your Stripe dashboard ...").
110
- readonly hint?: { readonly [locale: string]: string };
111
- // Per-secret scope. v1 only "tenant" — user / system scopes ship in v2.
112
- readonly scope: "tenant";
113
- // Tenant must set this secret before the owning feature works. Surfaced
114
- // by readiness:query:status; keep in sync with the missing-secret throw
115
- // in the feature's build-fn.
116
- readonly required?: boolean;
117
- };
118
-
119
- export type SecretOptions = Omit<SecretKeyDefinition, "shortName" | "qualifiedName">;
120
-
121
- // Typed reference returned by r.secret(). Lets feature code pass a
122
- // strongly-named handle to ctx.secrets.get instead of retyping the
123
- // qualified string. Parallels ConfigKeyHandle from the config system.
124
- export type SecretKeyHandle = {
125
- readonly name: string;
126
- };
127
-
128
- // --- Store tables (declared by features via r.storeTable()) ---
129
- // Post-drizzle-cut: unified with the former r.unmanagedTable() — both
130
- // carried the same reason/audit contract, differing only in whether the
131
- // table value was a legacy Drizzle PgTable (storeTable) or the framework-
132
- // native EntityTableMeta (unmanagedTable, consumed by migrate-runner).
133
- // EntityTableMeta was the forward-compatible shape, so storeTable adopted it.
134
-
135
- /** Options accepted by `r.storeTable()`. The `reason` is required so the
136
- * bypass leaves an audit trail at the registration site — reviewers can
137
- * judge legitimacy without spelunking into history, and a future cleanup
138
- * pass can find candidates for migration to `r.entity()`. */
139
- export type StoreTableOptions = {
140
- /** Why this table needs to bypass the event-sourcing system. Examples:
141
- * "imported from pre-ES system, read-only", "external Stripe webhook
142
- * payload cache, write-only by webhook handler", "denormalised
143
- * projection of a non-Kumiko data source". */
144
- readonly reason: string;
145
- /** Direct-write stores skip the executor, so the executor's PII
146
- * encryption never runs for them — a feature whose meta carries
147
- * piiSubjectFields must encrypt those fields itself before every
148
- * insert/update and declare that here, or boot fails (#820). */
149
- readonly piiEncryptedOnWrite?: true;
150
- };
151
-
152
- /** Per-feature store-table registration. `meta` is the `EntityTableMeta`
153
- * (framework-native shape used by `migrate-runner`). Carries the
154
- * bypass-justification reason but knows nothing about the owning
155
- * feature — that's added when the registry aggregates entries
156
- * cross-feature into `StoreTableDef`. */
157
- export type StoreTableEntry = {
158
- readonly name: string;
159
- readonly meta: EntityTableMeta;
160
- readonly reason: string;
161
- readonly piiEncryptedOnWrite?: true;
162
- };
163
-
164
- /** Registry-aggregated store-table — the per-feature `StoreTableEntry` plus
165
- * the owning feature name. This is what `Registry.getAllStoreTables()`
166
- * exposes to readers (dev-server, ops UIs). */
167
- export type StoreTableDef = StoreTableEntry & {
168
- readonly featureName: string;
169
- };
170
-
171
- // --- UI-Hints (manifest-only, picker/scaffolder metadata) ---
172
-
173
- // Optional, declarative UI metadata declared via `r.uiHints({...})`. Surfaces
174
- // in feature-manifest.json under `feature.uiHints`. Consumers (the picker in
175
- // `create-kumiko-app`, the docs feature-reference) treat absent hints as
176
- // "no special treatment" — bare feature.name + feature.description still work.
177
- //
178
- // Keep this list lean. Anything that already has a home on the feature
179
- // (configKeys.scope/default/encrypted, secretKeys, requires, etc.) lives there.
180
- // Only add fields here that are genuinely UI-only.
181
- // "select"/"text" variants dropped (569/1) — no bundled feature uses anything
182
- // but "boolean" yet and the picker doesn't render them either; re-add once a
183
- // real feature needs them.
184
- export type UiHintOption = {
185
- readonly key: string;
186
- readonly label: string;
187
- readonly type: "boolean";
188
- readonly default: boolean;
189
- };
190
-
191
- export type UiHints = {
192
- // Picker-facing label ("Auth · Email + Password" instead of the bare
193
- // feature-name "auth-email-password").
194
- readonly displayLabel?: string;
195
- // Grouping for the picker. Free-form string; the picker sorts/groups by it.
196
- readonly category?: string;
197
- // Pre-checked in the picker when the user runs `bun create kumiko-app`.
198
- readonly recommended?: boolean;
199
- // Sub-options the picker asks about per-feature (e.g. "Password-Reset-Flow
200
- // on/off"). The scaffolder maps each key to a generator decision; the
201
- // framework doesn't act on them at runtime.
202
- readonly configurableOptions?: readonly UiHintOption[];
203
- };
204
-
205
- // --- Feature Definition (output of defineFeature) ---
206
-
207
- export type FeatureDefinition = {
208
- readonly name: string;
209
- // Docs-lead paragraph declared via r.describe(). Flows through the
210
- // manifest introspection into the generated feature-reference pages.
211
- readonly description?: string;
212
- readonly systemScope: boolean;
213
- // Set from the setup-callback return — typed via `defineFeature<TExports>`.
214
- // `undefined` for setups that return nothing.
215
- readonly exports?: unknown;
216
- readonly requires: readonly string[];
217
- readonly optionalRequires: readonly string[];
218
- // Read-side projection-tables this feature is allowed to write via
219
- // r.step.unsafeProjectionUpsert / unsafeProjectionDelete. Declared via
220
- // r.requires.projection("table_name"). Hard requirement — boot-error
221
- // if a step targets a non-listed table or one that's already an
222
- // r.entity-registered aggregate-table. See step-vocabulary.md Q10.
223
- readonly requiredProjections: ReadonlySet<string>;
224
- // Tier-2 step kinds opted-in via r.requires.step("webhook.send"). Q9.
225
- readonly requiredSteps: ReadonlySet<string>;
226
- // Declared via r.toggleable({ default }). Presence makes the feature
227
- // operator-switchable via the feature-toggles bundled feature; absence
228
- // means the feature is always-on (e.g. auth, tenant, user — core infra
229
- // that would brick the system if switchable).
230
- readonly toggleableDefault?: boolean;
231
- // Declarative UI metadata for picker/scaffolder tooling. Set via r.uiHints().
232
- // Pure manifest-side info — the framework runtime doesn't read it.
233
- readonly uiHints?: UiHints;
234
- // entities/hooks/entityHooks are optional: defineFeature always
235
- // materializes them, but hand-built definitions at system boundaries
236
- // (test fixtures, partial boots — see registry.test.ts "slot robustness")
237
- // omit them and the registry guards against that. Type follows runtime.
238
- readonly entities?: Readonly<Record<string, EntityDefinition>>;
239
- // Optional backing Drizzle table per entity, declared via the third arg of
240
- // `r.entity(name, def, { table })`. Source of truth for the physical DDL
241
- // when the table carries columns/indexes the field-DSL can't express
242
- // (e.g. secrets' envelope jsonb without default). `collectTableMetas` and
243
- // the registry's implicit-projection use this object instead of the
244
- // field-derived table, so generate + test-push + executor share ONE table.
245
- readonly entityTables?: Readonly<Record<string, unknown>>;
246
- readonly relations: Readonly<Record<string, EntityRelations>>;
247
- readonly writeHandlers: Readonly<Record<string, WriteHandlerDef>>;
248
- readonly queryHandlers: Readonly<Record<string, QueryHandlerDef>>;
249
- readonly translations: TranslationKeys;
250
- readonly hooks?: HookMap;
251
- readonly entityHooks?: EntityHookMap;
252
- // F3 search-payload-extension — per-entity contributors that add flat fields
253
- // to the search-index payload during indexing. Keyed by entityName. Wrapped
254
- // in OwnedFn for feature-toggle filtering (consistent with postQuery-Hooks).
255
- readonly searchPayloadExtensions?: Readonly<
256
- Record<string, readonly OwnedFn<SearchPayloadContributorFn>[]>
257
- >;
258
- readonly configKeys: Readonly<Record<string, ConfigKeyDefinition>>;
259
- readonly configSeeds: readonly ConfigSeedDef[];
260
- readonly jobs: Readonly<Record<string, JobDefinition>>;
261
- readonly registrarExtensions: Readonly<Record<string, RegistrarExtensionDef>>;
262
- readonly extensionUsages: readonly RegistrarExtensionRegistration[];
263
- readonly extensionSelectors: readonly ExtensionSelectorDef[];
264
- /**
265
- * Cross-feature API names this feature exposes via `r.exposesApi(name)`.
266
- * Pure Marker-Deklaration — die echte Implementation wird als
267
- * Query-/Write-Handler unter dem QN-Pattern registriert (z.B.
268
- * `compliance-profiles:query:effective-profile`). Boot-Validator prüft
269
- * dass jedes `r.usesApi(name)` einen passenden Exposer hier findet —
270
- * Tippfehler oder Drop-Refactorings werden zu Boot-Fail statt Runtime-Crash.
271
- */
272
- readonly exposedApis: ReadonlySet<string>;
273
- /**
274
- * Cross-feature API names this feature calls. Pflicht-Boot-Check:
275
- * jeder Eintrag muss in `exposedApis` irgendeines Features auftauchen
276
- * UND das Provider-Feature muss in requires/optionalRequires sein.
277
- */
278
- readonly usedApis: ReadonlySet<string>;
279
- readonly referenceData: readonly ReferenceDataDef[];
280
- readonly notifications: Readonly<Record<string, NotificationDefinition>>;
281
- readonly events: Readonly<Record<string, EventDef>>;
282
- // Event schema migrations declared via defineEvent's `migrations` option. Keyed by event
283
- // short-name; each entry carries the step transforms (fromVersion →
284
- // toVersion). The registry stitches these with the defineEvent-declared
285
- // current version and exposes a per-qualified-name upcaster chain.
286
- readonly eventMigrations: Readonly<Record<string, readonly EventMigrationDef[]>>;
287
- readonly configReads: readonly string[];
288
- // Handler → entity mapping inferred from the colon convention
289
- // ("entityName:verb") via tryMapEntity in defineFeature.
290
- readonly handlerEntityMappings: Readonly<Record<string, string>>;
291
- // Metrics declared via r.metric(). Short names — Framework prefixes on boot.
292
- readonly metrics: Readonly<Record<string, FeatureMetricDef>>;
293
- // Secret keys declared via r.secret(). Short names — Framework prefixes to
294
- // "<feature>:<short>" during registry build.
295
- readonly secretKeys: Readonly<Record<string, SecretKeyDefinition>>;
296
- // Projections declared via r.projection(). Keyed by projection name; executor
297
- // looks them up by source-entity at write-time.
298
- readonly projections: Readonly<Record<string, ProjectionDefinition>>;
299
- // Implicit-projection extensions declared via r.extendEntityProjection().
300
- // Keyed by entity name; merged into that entity's implicit projection at
301
- // registry build so rebuildProjection replays the extension's events.
302
- readonly entityProjectionExtensions?: Readonly<
303
- Record<string, readonly EntityProjectionExtension[]>
304
- >;
305
- // Multi-stream projections — cross-aggregate async read-models. Keyed by
306
- // short name; the dispatcher wraps each into an EventConsumer with its
307
- // own cursor.
308
- readonly multiStreamProjections: Readonly<Record<string, MultiStreamProjectionDefinition>>;
309
- // Auth-claims hooks declared via r.authClaims(). Executed at login (and
310
- // switch-tenant) time; their returned records are merged into
311
- // SessionUser.claims under the auto-prefix "<featureName>:<key>".
312
- readonly authClaimsHooks: readonly AuthClaimsFn[];
313
- // Declared claim keys via r.claimKey(). Shorts keyed by their JS-side
314
- // short name, qualified name qualified at registration time.
315
- readonly claimKeys: Readonly<Record<string, ClaimKeyDefinition>>;
316
- // Screen definitions declared via r.screen(). Keyed by the feature-local
317
- // short id; the registry qualifies to "<feature>:screen:<id>" on boot.
318
- // Pure data — ui-core + renderer packages interpret; engine only stores
319
- // and validates entity/field references against the feature's entities.
320
- readonly screens: Readonly<Record<string, ScreenDefinition>>;
321
- // Nav entries declared via r.nav(). Keyed by the feature-local short id;
322
- // registry qualifies to "<feature>:nav:<id>". Flat list — the renderer's
323
- // resolveNavigation assembles the tree from parent refs at mount time.
324
- readonly navs: Readonly<Record<string, NavDefinition>>;
325
- // Workspaces declared via r.workspace(). Keyed by feature-local short id;
326
- // registry qualifies to "<feature>:workspace:<id>". Pure UI metadata —
327
- // shellWorkspaces consumes the resolved per-workspace nav list at mount
328
- // time; engine validates roles + nav refs at boot.
329
- readonly workspaces: Readonly<Record<string, WorkspaceDefinition>>;
330
- // Tree-Actions-Map declared via r.treeActions(). At-most-one per feature
331
- // (only-once-guard at registration). Erased to `Record<string,
332
- // TreeActionDef>` for runtime registry-lookup (Visual-Tree-Component
333
- // dispatching, Pattern-AST consumers). The compile-time-typed surface
334
- // is the registrar's return value (TreeActionsHandle) which the
335
- // feature exports via setup-return — buildTarget consumes the handle,
336
- // not this slot. See visual-tree.md A5 + A7.
337
- readonly treeActions?: Readonly<Record<string, TreeActionDef>>;
338
- // HTTP-Routes declared via r.httpRoute(). Index is "METHOD path"
339
- // (z.B. "GET /feed.xml") — eindeutig pro Feature. Die App-Server-
340
- // Boot-Stage iteriert getAllHttpRoutes() und mountet jede Route auf
341
- // den Hono-app (außerhalb /api/*). Pattern symmetrisch zu queryHandlers/
342
- // writeHandlers — Routes leben mit dem Feature, nicht im Bootstrap.
343
- readonly httpRoutes: Readonly<Record<string, HttpRouteDefinition>>;
344
- // Store tables declared via r.storeTable() — bypass the event-sourcing
345
- // system. Keyed by feature-local short name (derived from
346
- // meta.tableName). The registry attaches featureName on aggregation,
347
- // lifting StoreTableEntry → StoreTableDef. `kumiko schema generate`
348
- // aggregates these alongside r.entity()-derived metas to build the
349
- // full schema.
350
- readonly storeTables: Readonly<Record<string, StoreTableEntry>>;
351
- // Optional Zod-schema for env-vars this feature reads at runtime.
352
- // Declared via `r.envSchema(z.object({...}))`. `composeEnvSchema` reads
353
- // this to build one app-wide schema for boot-validation + dry-run
354
- // rendering. Absence means the feature reads no env-vars (or hasn't
355
- // been migrated yet — Sprint-9 migration is add-only per phase).
356
- readonly envSchema?: z.ZodObject<z.ZodRawShape>;
357
- };
358
-
359
- // --- Feature Registrar (the "r" object in defineFeature) ---
360
-
361
- type RefOrRefs = NameOrRef | readonly NameOrRef[];
362
- // Entity-wide hook target — "all query/write handlers of this entity",
363
- // same reach r.entityHook() used to have. Only valid for postSave/
364
- // preDelete/postDelete/postQuery (the same 4 types entityHook covered);
365
- // hook() throws at registration time if used with validation/preSave/
366
- // preQuery.
367
- type HookTarget = RefOrRefs | { readonly allOf: NameOrRef };
368
-
369
- /**
370
- * `TFeature` is the literal feature-name from `defineFeature("foo", ...)` —
371
- * default-`string` keeps every existing usage zero-config. Strict-typed
372
- * features (apps that opt into the literal-name flavour) get propagated
373
- * through to `defineEvent` so the returned `EventDef.name` is a literal
374
- * `${CamelToKebab<TFeature>}:event:${CamelToKebab<TInner>}`. That literal
375
- * threads through `ctx.appendEvent({ type: eventDef.name, ... })`,
376
- * keeping strict-mode alive even when handlers route via `eventDef.name`
377
- * instead of hand-typed string literals.
378
- */
379
- /**
380
- * `r.requires` is a callable+namespace: existing call form takes feature
381
- * names (`r.requires("auth", "tenant")`), the `.projection` extension
382
- * declares read-side projection tables that this feature's pipeline
383
- * steps are allowed to write via `r.step.unsafeProjectionUpsert`.
384
- * Hard-required for any unsafeProjection-* step usage (see Q10).
385
- */
386
- export type RequiresApi = ((...featureNames: string[]) => void) &
387
- // Object-Form — the shape the feature-ast renderer (`render.ts`) emits
388
- // for Designer/AI-generated code. A single object argument with named
389
- // fields is easier to generate correctly than positional args whose
390
- // count/order vary per registrar method.
391
- ((options: { readonly features: readonly string[] }) => void) & {
392
- readonly projection: (tableName: string) => void;
393
- // Tier-2 step opt-in (Q9). Tier-1 implicit, Tier-2 must be declared.
394
- readonly step: (stepKind: string) => void;
395
- };
396
-
397
- export type FeatureRegistrar<TFeature extends string = string> = {
398
- systemScope(): void;
399
- // One-to-three-sentence docs-lead for the feature ("what it does + when
400
- // you need it"). At most once per feature; must be non-empty.
401
- describe(text: string): void;
402
- requires: RequiresApi;
403
- optionalRequires(...featureNames: string[]): void;
404
- optionalRequires(options: { readonly features: readonly string[] }): void;
405
- // Declare the feature as operator-togglable. `default` is the effective
406
- // state when no global-toggle row exists. Must be called at most once per
407
- // feature; calling on an always-on feature (e.g. auth/tenant/user) is a
408
- // bug — and one nothing catches at boot, so don't.
409
- toggleable(options: { default: boolean }): void;
410
- // Picker/scaffolder metadata — see UiHints. At most once per feature.
411
- uiHints(hints: UiHints): void;
412
-
413
- entity(
414
- name: string,
415
- definition: EntityDefinition,
416
- options?: { readonly table?: unknown },
417
- ): EntityRef;
418
- entity(definition: { readonly name: string } & EntityDefinition): EntityRef;
419
-
420
- // Shorthand for registerEntityCrud(r, ...), scoped to this registrar.
421
- crud(entityName: string, entity: EntityDefinition, options?: RegisterEntityCrudOptions): void;
422
-
423
- writeHandler<TName extends string, TSchema extends ZodType>(
424
- def: WriteHandlerDefinition<TName, TSchema>,
425
- ): HandlerRef;
426
- writeHandler<TSchema extends ZodType>(
427
- name: string,
428
- schema: TSchema,
429
- handler: WriteHandlerFn<z.infer<TSchema>>,
430
- options?: { access?: AccessRule; rateLimit?: RateLimitOption },
431
- ): HandlerRef;
432
-
433
- queryHandler<TName extends string, TSchema extends ZodType>(
434
- def: QueryHandlerDefinition<TName, TSchema>,
435
- ): HandlerRef;
436
- queryHandler<TSchema extends ZodType>(
437
- name: string,
438
- schema: TSchema,
439
- handler: QueryHandlerFn<z.infer<TSchema>>,
440
- options?: { access?: AccessRule; rateLimit?: RateLimitOption },
441
- ): HandlerRef;
442
-
443
- relation(entity: NameOrRef, relationName: string, definition: RelationDefinition): void;
444
- // TDef inferred from the literal — keeps the excess-property check
445
- // resolved against the matching RelationDefinition union member instead
446
- // of distributing across all three (which spuriously rejects valid
447
- // combinations when checked directly against the raw union).
448
- relation<TDef extends RelationDefinition>(
449
- definition: { readonly entity: NameOrRef; readonly name: string } & TDef,
450
- ): void;
451
-
452
- hook(type: "validation", target: RefOrRefs, fn: ValidationHookFn): void;
453
- hook(type: "preSave", target: RefOrRefs, fn: PreSaveHookFn): void;
454
- // postSave/preDelete/postDelete/postQuery accept `{ allOf: entityRef }` —
455
- // fires for every write/query handler of that entity, replacing the old
456
- // r.entityHook(type, entity, fn). postQuery's entity-wide form fires for
457
- // ALL query-handlers of the entity (e.g. customFields-bundle merging
458
- // custom-fields-jsonb into every read); no phase semantics there
459
- // (synchronous after handler-execute, before field-access-filter).
460
- hook(
461
- type: "postSave",
462
- target: HookTarget,
463
- fn: PostSaveHookFn,
464
- options?: { phase?: HookPhase },
465
- ): void;
466
- // preDelete always runs in-transaction (it guards the delete — there is no
467
- // meaningful "after" for a pre-hook). No phase option.
468
- hook(type: "preDelete", target: HookTarget, fn: PreDeleteHookFn): void;
469
- hook(
470
- type: "postDelete",
471
- target: HookTarget,
472
- fn: PostDeleteHookFn,
473
- options?: { phase?: HookPhase },
474
- ): void;
475
- hook(type: "preQuery", target: RefOrRefs, fn: PreQueryHookFn): void;
476
- hook(type: "postQuery", target: HookTarget, fn: PostQueryHookFn): void;
477
-
478
- // F3 — Search-Payload-Extension: contributor function adds flat fields to
479
- // an entity's search-index document. Fires synchronously during
480
- // buildSearchDocument indexing. Use-case: custom-fields-bundle merging
481
- // customFields-jsonb-keys flat into search-doc; tags-bundle projecting
482
- // tags-array as searchable. See `SearchPayloadContributorFn`.
483
- searchPayloadExtension(entity: NameOrRef, fn: SearchPayloadContributorFn): void;
484
-
485
- // Single-key form: bare handle, no wrapping record, no seeds (callers
486
- // needing seeds use the multi-key form below).
487
- config<T extends ConfigKeyType>(keyName: string, def: ConfigKeyDefinition<T>): ConfigKeyHandle<T>;
488
-
489
- // Multi-key form: returns a handle map keyed exactly like the input. Pass
490
- // any handle to `ctx.config(handle)` to get the value type narrowed by the
491
- // key's `type`. Optional `seeds` declare boot-time system-rows that are
492
- // written via the event-store executor — idempotent, skipped when the
493
- // stream already exists.
494
- config<TKeys extends Readonly<Record<string, ConfigKeyDefinition<ConfigKeyType>>>>(definition: {
495
- readonly keys: TKeys;
496
- readonly seeds?: Readonly<Record<string, ConfigSeedDef>>;
497
- }): { readonly [K in keyof TKeys]: ConfigKeyHandle<TKeys[K]["type"]> };
498
-
499
- job(name: string, options: Omit<JobDefinition, "name" | "handler">, handler: JobHandlerFn): void;
500
- job(definition: JobDefinition): void;
501
-
502
- notification(
503
- name: string,
504
- definition: {
505
- readonly trigger: { readonly on: NameOrRef };
506
- readonly recipient: NotificationRecipientFn;
507
- readonly data: NotificationDataFn;
508
- readonly templates?: Readonly<Record<string, NotificationTemplateFn>>;
509
- },
510
- ): void;
511
- notification(definition: {
512
- readonly name: string;
513
- readonly trigger: { readonly on: NameOrRef };
514
- readonly recipient: NotificationRecipientFn;
515
- readonly data: NotificationDataFn;
516
- readonly templates?: Readonly<Record<string, NotificationTemplateFn>>;
517
- }): void;
518
-
519
- translations(def: TranslationsDef): void;
520
-
521
- // Register an event payload shape. Returns the qualified def so callers
522
- // can pass `.name` to ctx.appendEvent without hand-building the
523
- // "<feature>:event:<short>" string.
524
- //
525
- // `options.version` declares the CURRENT schema generation. Defaults to 1
526
- // on first registration. When you bump the payload shape, add a step to
527
- // `options.migrations` covering N -> N+1 — the framework refuses to boot
528
- // if the chain from 1 to `version` has gaps. Migrations were formerly a
529
- // separate r.eventMigration() call; folded in here because an event and
530
- // its schema evolution are one lifecycle, not two registrar concepts
531
- // (#1082 step 8) — transforms are pure functions (old payload in, new
532
- // payload out) and run once per read, not once per event persisted, so
533
- // keep them cheap.
534
- //
535
- // `options.piiFields` declares PII payload fields encrypted under the DEK
536
- // of the user named by `subjectField` (crypto-shredding, #799). append()
537
- // enforces the catalog on every write path.
538
- defineEvent<const TInner extends string, TPayload>(
539
- name: TInner,
540
- schema: ZodType<TPayload>,
541
- options?: {
542
- readonly version?: number;
543
- readonly piiFields?: EventPiiFields;
544
- readonly migrations?: readonly {
545
- readonly fromVersion: number;
546
- readonly toVersion: number;
547
- readonly transform: EventUpcastFn | DeclarativeEventMigration;
548
- }[];
549
- },
550
- ): EventDef<TPayload, QualifiedEventName<TFeature, TInner>>;
551
-
552
- readsConfig(...qualifiedKeys: string[]): void;
553
- readsConfig(options: { readonly keys: readonly string[] }): void;
554
-
555
- referenceData(
556
- entity: NameOrRef,
557
- data: readonly Record<string, unknown>[],
558
- options?: { upsertKey?: string },
559
- ): void;
560
- referenceData(definition: {
561
- readonly entity: NameOrRef;
562
- readonly data: readonly Record<string, unknown>[];
563
- readonly upsertKey?: string;
564
- }): void;
565
-
566
- extendsRegistrar(name: string, def: RegistrarExtensionDef): void;
567
-
568
- useExtension(extensionName: string, entity: NameOrRef, options?: Record<string, unknown>): void;
569
- useExtension(
570
- definition: { readonly name: string; readonly entity: NameOrRef } & Record<string, unknown>,
571
- ): void;
572
-
573
- /**
574
- * Declares which config key selects the active provider under an
575
- * extension point — called by the point-owning foundation (e.g.
576
- * `r.extensionSelector("mailTransport", configKeys.provider)`).
577
- * Readiness gating counts a provider-feature's `required` keys and
578
- * secrets only while that provider is the selected one. Registry-build
579
- * fails on duplicate declarations per extension and on selector keys
580
- * that no mounted feature declares.
581
- */
582
- extensionSelector(extensionName: string, key: { readonly name: string } | string): void;
583
-
584
- /**
585
- * Marker-Deklaration: dieses Feature stellt eine Cross-Feature-API
586
- * unter dem genannten Namen bereit. Die eigentliche Implementation
587
- * wird separat als Query- oder Write-Handler unter dem QN-Pattern
588
- * registriert; `r.exposesApi` ist reine Boot-Check-Surface.
589
- *
590
- * Boot-Validator prüft, dass jedes `r.usesApi(name)` einen passenden
591
- * Exposer findet, dass das Exposer-Feature in requires/optionalRequires
592
- * gelisted ist und dass kein API-Name doppelt exposed wird.
593
- *
594
- * ```ts
595
- * defineFeature("compliance-profiles", (r) => {
596
- * r.exposesApi("compliance.forTenant");
597
- * r.queryHandler({
598
- * name: "compliance:query:for-tenant",
599
- * // ... echte Implementation
600
- * });
601
- * });
602
- * ```
603
- */
604
- exposesApi(apiName: string): void;
605
-
606
- /**
607
- * Declares that this feature calls a cross-feature API. Boot-Validator
608
- * checkt dass irgendein anderes Feature `r.exposesApi(apiName)` macht
609
- * und dass dieses Feature `r.requires/optionalRequires` darauf hat.
610
- *
611
- * ```ts
612
- * defineFeature("user-data-rights", (r) => {
613
- * r.requires("compliance-profiles");
614
- * r.usesApi("compliance.forTenant");
615
- * });
616
- * ```
617
- */
618
- usesApi(apiName: string): void;
619
-
620
- // Declare a metric. Short name (without kumiko_<feature>_ prefix) — Framework
621
- // qualifies it on boot. Validation (snake_case + typ-suffix) runs at boot.
622
- // Usage at runtime: ctx.metrics.inc("created_total", { status: "new" }).
623
- metric(shortName: string, options: MetricOptions): void;
624
- metric(definition: { readonly name: string } & MetricOptions): void;
625
-
626
- // Declare a secret key. Qualified name follows "<feature>:secret:<kebab>"
627
- // via the QN helper. Returns a typed handle so feature code can pass it
628
- // to ctx.secrets.get without retyping the qualified string — same
629
- // ergonomics as r.config's handle.
630
- secret(shortName: string, options: SecretOptions): SecretKeyHandle;
631
- secret(definition: { readonly name: string } & SecretOptions): SecretKeyHandle;
632
-
633
- // Register a projection driven by events of one or more source entities.
634
- // The runtime fires projection.apply[event.type] inside the event-store's
635
- // transaction, so projections stay consistent with the events that feed them.
636
- projection(definition: ProjectionDefinition): void;
637
-
638
- // Register a cross-aggregate async projection. The event-dispatcher owns
639
- // delivery via a dedicated cursor — at-least-once, strictly-ordered by
640
- // events.id. Handlers must be idempotent. Marten's MultiStreamProjection
641
- // equivalent: customer billing summaries, cross-feature audit views,
642
- // saga state machines where a single view spans many aggregate types.
643
- // Omit `table` for pure side-effect handlers (notifications, webhooks,
644
- // external-system sync) — the dispatcher still delivers at-least-once with
645
- // per-consumer ordering and dead-letter behaviour.
646
- multiStreamProjection(definition: MultiStreamProjectionDefinition): void;
647
-
648
- // Merge extra apply handlers (+ extra event sources) into an entity's
649
- // implicit projection so rebuildProjection replays event types a bundled
650
- // extension materializes into the HOST entity's table (custom-fields
651
- // pattern). Rebuild-only: the inline runner skips implicit projections —
652
- // live delivery stays with the extension's own MSP. The entity must be
653
- // declared via r.entity in the SAME feature; unknown entities and
654
- // apply-key collisions fail at registry build.
655
- extendEntityProjection(entityName: string, extension: EntityProjectionExtension): void;
656
-
657
- // Register a function that contributes claims into SessionUser.claims at
658
- // login time. Multiple features (and multiple calls within one feature)
659
- // are allowed; returns are merged. Keys are auto-prefixed with the feature
660
- // name ("<feature>:<key>") — cross-feature collisions are impossible by
661
- // construction. Same-feature duplicate keys follow last-wins.
662
- //
663
- // Hooks run in parallel. If one throws, the error is logged and that
664
- // feature's claims are simply missing from the merged record — login
665
- // still succeeds. This is a deliberate best-effort policy: identity-facts
666
- // are convenience, not access-gates (that's what `roles` + field-access
667
- // rules are for).
668
- authClaims(fn: AuthClaimsFn): void;
669
-
670
- // Declare a claim key. Qualified name follows "<feature>:<shortName>" —
671
- // NO kebab conversion (it would break the claim round-trip, unlike
672
- // r.secret / r.config). Returns a
673
- // typed handle so feature code can pass it to `readClaim(user, handle)`
674
- // without retyping the qualified string and with the right narrowed
675
- // return type.
676
- //
677
- // Declaring claim keys also turns on a runtime check: when the feature's
678
- // r.authClaims hooks return an inner-key not in the declared list, the
679
- // resolver logs a warning (the claim still lands in the JWT — declared
680
- // or not — so strict-mode isn't on; this is typo-drift protection).
681
- claimKey<T extends ClaimKeyType>(
682
- shortName: string,
683
- options: { readonly type: T },
684
- ): ClaimKeyHandle<T>;
685
- claimKey<T extends ClaimKeyType>(definition: {
686
- readonly name: string;
687
- readonly type: T;
688
- }): ClaimKeyHandle<T>;
689
-
690
- // Register a screen. The id is the feature-local short name (kebab-case);
691
- // the registry qualifies to "<feature>:screen:<id>". Boot-validation checks
692
- // that entity-bound screens reference a registered entity and that the
693
- // columns / form-field refs name real fields — cross-feature component-QN
694
- // validation (r.uiComponent) comes in M4/M5. Optional `nav` field is
695
- // sugar for a single nav entry pointing at this screen — equivalent to
696
- // a standalone r.nav({ id: <same id>, screen: "<feature>:screen:<id>", ... }).
697
- screen(definition: ScreenDefinition): void;
698
-
699
- // Register a nav entry. The id is the feature-local short name (kebab-case);
700
- // the registry qualifies to "<feature>:nav:<id>". Boot-validation checks
701
- // that `screen` and `parent` refs exist (cross-feature QNs allowed) and
702
- // that parent chains don't contain cycles.
703
- nav(definition: NavDefinition): void;
704
-
705
- // Register a workspace — a persona-/role-scoped UI surface. Pure UI
706
- // composition; the registry qualifies the short id to
707
- // "<feature>:workspace:<id>". Boot-validation checks that any nav refs
708
- // exist, that workspace ids referenced from r.nav() are real, and that
709
- // at most one workspace per app declares `default: true`.
710
- workspace(definition: WorkspaceDefinition): void;
711
-
712
- // Register an HTTP-route owned by this feature. The route is mounted
713
- // outside the dispatcher pipeline (= außerhalb /api/write|query|batch),
714
- // direkt an die app — Use-Case: RSS/Atom-Feeds, OG-Images, OpenAPI-Specs.
715
- // Duplicate "method path"-Combinations are rejected per feature at setup
716
- // time; there is no cross-feature check.
717
- // Symmetric to queryHandler/writeHandler — Routes leben mit dem Feature,
718
- // nicht im Bootstrap. Escape-hatch für nicht-feature-bound Routes
719
- // bleibt runProdApp.extraRoutes.
720
- httpRoute(definition: HttpRouteDefinition): void;
721
-
722
- // Declare an "unmanaged" framework-native table that bypasses the
723
- // event-sourcing system. Reserved for legacy-import, read-only caches,
724
- // write-only webhook payload buffers, or read-side projections of
725
- // event-streams (delivery-attempts, job-run-logs) where r.entity()'s
726
- // aggregate-lifecycle assumptions don't fit. The dev-server iterates
727
- // these alongside r.entity() projections at boot so the table exists
728
- // before the first query.
729
- //
730
- // EntityTableMeta carries the same column-shape that r.entity() builds,
731
- // minus the audit-trail + base-columns scaffolding. The `meta` argument
732
- // is the result of `defineUnmanagedTable(...)` / `buildEntityTableMeta(...)`
733
- // from `@cosmicdrift/kumiko-framework/db`.
734
- //
735
- // The required `reason` string is the marker that justifies the bypass —
736
- // a non-empty string is the contract. If you can't write a reason,
737
- // declare data via `r.entity()` instead.
738
- storeTable(meta: EntityTableMeta, options: StoreTableOptions): void;
739
-
740
- // Register the tree-actions schema for this feature — a map of
741
- // action-name → action-definition (with optional typed args). At-most-
742
- // one call per feature.
743
- //
744
- // Returns a TreeActionsHandle that the feature exports via setup-return
745
- // (Memory `[EventDef-Exports-Pattern]`). The handle carries the
746
- // literal-typed action-map that `buildTarget` consumes for compile-
747
- // time validation:
748
- //
749
- // const handle = r.treeActions({
750
- // edit: { args: { slug: "" as string } },
751
- // list: {},
752
- // });
753
- // return { handle };
754
- //
755
- // Without this typed return, the action-map collapses to
756
- // `Record<string, TreeActionDef>` at the buildTarget call-site and
757
- // every action becomes accept-anything-string. See visual-tree.md A5.
758
- //
759
- // The runtime FeatureDefinition.treeActions slot stores the same map
760
- // as erased Record (registry lookup, Pattern-AST consumers).
761
- treeActions<const TActions extends Record<string, TreeActionDef>>(
762
- actions: TActions,
763
- ): TreeActionsHandle<TFeature, TActions>;
764
-
765
- // Declare the Zod-schema for env-vars this feature reads at runtime.
766
- // At-most-one call per feature. composeEnvSchema reads it across all
767
- // features to build one app-wide schema, which runProdApp parses
768
- // process.env against at boot. App-Authors can also call
769
- // `KUMIKO_DRY_RUN_ENV=human|json|pulumi|k8s` to introspect the
770
- // required env-vars without booting.
771
- //
772
- // Convention: keys are SHOUTING_SNAKE_CASE env-var names. Per-var
773
- // metadata (Pulumi-config-key override, openssl-generator suggestion,
774
- // k8s-secret hints) goes into `.meta({ kumiko: { pulumi: {...} } })`
775
- // — see framework/env/index.ts for the meta-shape.
776
- envSchema(schema: z.ZodObject<z.ZodRawShape>): void;
777
- };
778
-
779
- // --- Registry (created from features) ---
780
-
781
- export type Registry = {
782
- readonly features: ReadonlyMap<string, FeatureDefinition>;
783
-
784
- getFeature(name: string): FeatureDefinition | undefined;
785
- getEntity(name: string): EntityDefinition | undefined;
786
- getAllEntities(): ReadonlyMap<string, EntityDefinition>;
787
- getWriteHandler(name: string): WriteHandlerDef | undefined;
788
- getQueryHandler(name: string): QueryHandlerDef | undefined;
789
- getAllQueryHandlers(): ReadonlyMap<string, QueryHandlerDef>;
790
- getSearchableFields(entityName: string): readonly string[];
791
- getSortableFields(entityName: string): readonly string[];
792
- getRelations(entityName: string): EntityRelations;
793
- getSearchIncludes(entityName: string): ReadonlyMap<string, readonly string[]>;
794
- getIncomingRelations(entityName: string): ReadonlyArray<{
795
- sourceEntity: string;
796
- relationName: string;
797
- relation: RelationDefinition;
798
- }>;
799
- // Hook getters — pass `effectiveFeatures` to drop hooks registered by
800
- // globally-disabled features. Omit the arg to get all hooks (legacy
801
- // callers + places where the feature-toggles feature isn't wired).
802
- getPreSaveHooks(name: string, effectiveFeatures?: ReadonlySet<string>): readonly PreSaveHookFn[];
803
- getPostSaveHooks(
804
- name: string,
805
- phase?: HookPhase,
806
- effectiveFeatures?: ReadonlySet<string>,
807
- ): readonly PostSaveHookFn[];
808
- getPreDeleteHooks(
809
- name: string,
810
- phase?: HookPhase,
811
- effectiveFeatures?: ReadonlySet<string>,
812
- ): readonly PreDeleteHookFn[];
813
- getPostDeleteHooks(
814
- name: string,
815
- phase?: HookPhase,
816
- effectiveFeatures?: ReadonlySet<string>,
817
- ): readonly PostDeleteHookFn[];
818
- getPreQueryHooks(
819
- name: string,
820
- effectiveFeatures?: ReadonlySet<string>,
821
- ): readonly PreQueryHookFn[];
822
- getPostQueryHooks(
823
- name: string,
824
- effectiveFeatures?: ReadonlySet<string>,
825
- ): readonly PostQueryHookFn[];
826
- getEntityPostSaveHooks(
827
- entityName: string,
828
- phase?: HookPhase,
829
- effectiveFeatures?: ReadonlySet<string>,
830
- ): readonly PostSaveHookFn[];
831
- getEntityPreDeleteHooks(
832
- entityName: string,
833
- phase?: HookPhase,
834
- effectiveFeatures?: ReadonlySet<string>,
835
- ): readonly PreDeleteHookFn[];
836
- getEntityPostDeleteHooks(
837
- entityName: string,
838
- phase?: HookPhase,
839
- effectiveFeatures?: ReadonlySet<string>,
840
- ): readonly PostDeleteHookFn[];
841
- getEntityPostQueryHooks(
842
- entityName: string,
843
- effectiveFeatures?: ReadonlySet<string>,
844
- ): readonly PostQueryHookFn[];
845
- // F3 — contributors for an entity's search-doc-payload, fired during
846
- // buildSearchDocument indexing. See `SearchPayloadContributorFn`.
847
- // `effectiveFeatures` filters out contributors owned by feature-toggle-
848
- // disabled features (parallel to other getters' filtering semantic).
849
- getSearchPayloadExtensions(
850
- entityName: string,
851
- effectiveFeatures?: ReadonlySet<string>,
852
- ): readonly SearchPayloadContributorFn[];
853
- getHandlerEntity(qualifiedHandler: string): string | undefined;
854
- isHandlerSystemScoped(qualifiedHandler: string): boolean;
855
- getHandlerFeature(qualifiedHandler: string): string | undefined;
856
- // True iff at least one registered handler declares a `rateLimit`
857
- // option. Pre-computed at registry-build so the boot path can skip
858
- // wiring the RateLimitResolver (and its Lua-script registration on
859
- // Redis) entirely when nobody opted in. Per-request cost stays zero
860
- // for apps that don't use the feature.
861
- hasRateLimitedHandler(): boolean;
862
- // All metrics from all features, keyed by fully-qualified name
863
- // (kumiko_<feature>_<shortName>). Consumed at boot to register them on the
864
- // active Meter.
865
- getAllMetrics(): ReadonlyMap<string, FeatureMetricDef & { readonly featureName: string }>;
866
- getAllTranslations(): TranslationKeys;
867
- getConfigKey(qualifiedKey: string): ConfigKeyDefinition | undefined;
868
- getAllConfigKeys(): ReadonlyMap<string, ConfigKeyDefinition>;
869
- getAllConfigSeeds(): readonly ConfigSeedDef[];
870
- // Feature-declared secrets, aggregated across all registered features.
871
- // Keyed by qualified name ("<feature>:<shortName>"). Used by the rotation
872
- // job (to iterate "known" secrets) and admin-UIs to list available keys.
873
- getAllSecretKeys(): ReadonlyMap<string, SecretKeyDefinition>;
874
- getSecretKey(qualifiedName: string): SecretKeyDefinition | undefined;
875
- getJob(qualifiedName: string): JobDefinition | undefined;
876
- getAllJobs(): ReadonlyMap<string, JobDefinition>;
877
- getEvent(qualifiedName: string): EventDef | undefined;
878
-
879
- // Upcaster chain per qualified event name. Entries describe the current
880
- // schema version and the step-wise transforms that upgrade older stored
881
- // payloads. Empty chain when an event has never been migrated (version=1).
882
- getEventUpcasters(): ReadonlyMap<
883
- string,
884
- { readonly currentVersion: number; readonly chain: ReadonlyMap<number, EventUpcastFn> }
885
- >;
886
- getExtension(name: string): RegistrarExtensionDef | undefined;
887
- getExtensionUsages(extensionName: string): readonly RegistrarExtensionRegistration[];
888
- // Extension point → selector config key, from r.extensionSelector calls.
889
- getAllExtensionSelectors(): ReadonlyMap<string, string>;
890
- getAllNotifications(): ReadonlyMap<string, NotificationDefinition>;
891
- getAllReferenceData(): readonly ReferenceDataDef[];
892
- // Look up projections by source-entity name. Empty list when no projection
893
- // feeds off the entity — event-store-executor uses this as the hot-path.
894
- getProjectionsForSource(entityName: string): readonly ProjectionDefinition[];
895
- getAllProjections(): ReadonlyMap<string, ProjectionDefinition>;
896
-
897
- // All r.storeTable() registrations across all features, keyed by
898
- // feature-local short name. The dev-server iterates this alongside
899
- // implicit projections at boot. Cross-feature uniqueness is enforced
900
- // at registry-build — duplicate names from different features fail
901
- // the boot, so callers can rely on a flat keyspace.
902
- getAllStoreTables(): ReadonlyMap<string, StoreTableDef>;
903
-
904
- // Multi-stream projections registered via r.multiStreamProjection().
905
- // Keyed by qualified name. The server wires each into the event-dispatcher
906
- // as its own EventConsumer with a dedicated cursor.
907
- getAllMultiStreamProjections(): ReadonlyMap<string, MultiStreamProjectionDefinition>;
908
- // The feature that registered the given MSP. Used by the event-dispatcher
909
- // to pause MSP-consumers whose owning feature is globally disabled.
910
- getMultiStreamProjectionFeature(qualifiedName: string): string | undefined;
911
-
912
- // All r.authClaims() hooks across all features, tagged with the declaring
913
- // feature name so the resolver can apply the auto-prefix. Pre-aggregated
914
- // at registry-build so the login hot path is a single Map read.
915
- getAuthClaimsHooks(): readonly AuthClaimsHookDef[];
916
-
917
- // Feature-declared claim keys, aggregated across all features. Keyed by
918
- // qualified name ("<feature>:<short>"). Ops-UI + Boot-Validator use this
919
- // to introspect what claims the app can produce.
920
- getAllClaimKeys(): ReadonlyMap<string, ClaimKeyDefinition>;
921
- getClaimKey(qualifiedName: string): ClaimKeyDefinition | undefined;
922
-
923
- // Screens declared via r.screen() across all features. Keyed by qualified
924
- // name ("<feature>:screen:<id>"). ui-core / renderer consume this to build
925
- // navigation + screen-tree at mount time.
926
- getAllScreens(): ReadonlyMap<string, ScreenDefinition>;
927
- getScreen(qualifiedName: string): ScreenDefinition | undefined;
928
- // The feature that registered the given screen. Consumed by the nav
929
- // resolver to gate a nav-entry whose screen belongs to a disabled feature.
930
- getScreenFeature(qualifiedName: string): string | undefined;
931
- // All entity-bound screens (entityList / entityEdit) that target the given
932
- // entity. Pre-grouped so ui-core's view-model builders don't re-filter
933
- // getAllScreens() on every render. Custom screens have no entity and are
934
- // never returned here — walk getAllScreens() for those.
935
- getScreensByEntity(entityName: string): readonly ScreenDefinition[];
936
-
937
- // Nav entries declared via r.nav() across all features. Keyed by qualified
938
- // name ("<feature>:nav:<id>"). Flat list — the renderer's resolveNavigation
939
- // assembles the tree from parent refs and gates by effective-features.
940
- getAllNavs(): ReadonlyMap<string, NavDefinition>;
941
- getNav(qualifiedName: string): NavDefinition | undefined;
942
- // The feature that registered the given nav entry. Used by the nav
943
- // resolver to drop entries whose owning feature is globally disabled.
944
- getNavFeature(qualifiedName: string): string | undefined;
945
- // Direct children of the given parent nav entry. Empty array when the
946
- // parent has no children. Pre-grouped for O(1) tree-walk — resolveNavigation
947
- // recurses with getNavsByParent(child.qn) instead of filtering getAllNavs().
948
- getNavsByParent(parentQualifiedName: string): readonly NavDefinition[];
949
- // Nav entries that declare no parent — the roots of the navigation tree.
950
- // resolveNavigation starts its walk here and descends via getNavsByParent.
951
- getTopLevelNavs(): readonly NavDefinition[];
952
-
953
- // Workspaces declared via r.workspace() across all features. Keyed by
954
- // qualified name ("<feature>:workspace:<id>"). The active web shell
955
- // (shellWorkspaces) consumes this to render the switcher.
956
- getAllWorkspaces(): ReadonlyMap<string, WorkspaceDefinition>;
957
- getWorkspace(qualifiedName: string): WorkspaceDefinition | undefined;
958
- // The feature that registered the workspace. Mirrors getNavFeature —
959
- // lets the resolver drop workspaces whose owning feature is disabled.
960
- getWorkspaceFeature(qualifiedName: string): string | undefined;
961
- // Resolved nav QNs that belong to the given workspace. Pre-computed at
962
- // boot from BOTH r.workspace.nav AND r.nav.workspaces — the shell
963
- // doesn't have to merge sources at render time.
964
- getWorkspaceNavs(workspaceQualifiedName: string): readonly string[];
965
- // The single workspace whose `default: true` is set, if any. Boot
966
- // validator rejects more than one. Apps without a default fall back to
967
- // the first workspace the user has access to.
968
- getDefaultWorkspace(): WorkspaceDefinition | undefined;
969
-
970
- // Tree-Actions-Map des Features. Returns the erased Record (compile-
971
- // time-typed handle wandert über setup-export, nicht hier). Die
972
- // Content-Tree-Nav nutzt das für Runtime-Action-Lookup beim Klick auf
973
- // einen TreeNode.target — der Resolver findet das Feature via
974
- // TargetRef.featureId und holt sich die zugehörige Action-Definition.
975
- getTreeActions(featureName: string): Readonly<Record<string, TreeActionDef>> | undefined;
976
- };
1
+ // Legacy path re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/feature";