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