@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,497 +1,2 @@
1
- import type { ZodType } from "zod";
2
- import type { DbConnection } from "../../db/connection";
3
- import type { TenantDb } from "../../db/tenant-db";
4
- import type { ConcurrencyMode, ConfigScope } from "../constants";
5
- import type { FieldDefinition } from "./fields";
6
- import type { AppContext } from "./handlers";
7
- import type {
8
- PostDeleteHookFn,
9
- PostSaveHookFn,
10
- PreDeleteHookFn,
11
- PreQueryHookFn,
12
- PreSaveHookFn,
13
- } from "./hooks";
14
- import type { TenantId } from "./identifiers";
15
-
16
- // --- Config ---
17
-
18
- export type ConfigKeyAccess = {
19
- readonly read: readonly string[];
20
- readonly write: readonly string[];
21
- };
22
-
23
- export type ConfigKeyType = "text" | "number" | "boolean" | "select";
24
-
25
- export type ConfigValue<T extends ConfigKeyType> = T extends "number"
26
- ? number
27
- : T extends "boolean"
28
- ? boolean
29
- : T extends "text" | "select"
30
- ? string
31
- : never;
32
-
33
- // Bounds for numeric config keys. Enforced as hard-reject (not silent-clamp)
34
- // in set.write.ts: a tenant-admin setting a value outside [min, max] gets a
35
- // 400 "out_of_bounds" — silent clamping would be a UX trap ("I entered 9999,
36
- // it saved as 1000, why?"). Per-Request helpers MAY clamp — that's a
37
- // different call site where the caller often can't control the exact value.
38
- // Only meaningful for type="number"; boot-validator rejects on other types.
39
- export type ConfigBounds = {
40
- readonly min?: number;
41
- readonly max?: number;
42
- };
43
-
44
- // Ctx a `computed` key-resolver gets. Mirrors what the resolver itself has:
45
- // tenantId + userId for scope-aware lookups, db for ad-hoc queries (e.g.
46
- // "read the current subscription plan for this tenant"). Intentionally
47
- // narrow — giving it the full AppContext would leak deps like `redis`
48
- // into declaration-level code that shouldn't need them.
49
- export type ConfigComputedContext = {
50
- readonly tenantId: TenantId;
51
- readonly userId: string;
52
- readonly db: DbConnection | TenantDb;
53
- };
54
-
55
- // Computed-value resolver. Called when no scope-row AND no app-boot-override
56
- // exist for this key — sits one step above keyDef.default.
57
- //
58
- // Use-case: plan-based limits ("Pro tenants get maxUploadSizeMB=100"). The
59
- // feature declares *how* to compute the value, the handler stays neutral:
60
- // const max = await ctx.config(handle); // resolver calls computed
61
- //
62
- // Row wins over computed: a tenant-admin that sets a specific value
63
- // overrides the plan-default. If you want "plan is a hard policy", reject
64
- // set on the handler-side — don't try to invert the cascade.
65
- export type ConfigComputedFn<T extends ConfigKeyType = ConfigKeyType> = (
66
- ctx: ConfigComputedContext,
67
- ) => Promise<ConfigValue<T>>;
68
-
69
- // Storage-Backing eines provisionierten Config-Keys. "config" (Default) =
70
- // config_values-Projektion mit voller Cascade (user→tenant→system→app→default).
71
- // "secrets" = read_tenant_secrets (flach pro (tenant,key), AES-GCM-Envelope mit
72
- // Rotation/Audit, KEINE Cascade) — nur sinnvoll für scope:system ohne
73
- // Tenant-Override. Die backing×scope-Matrix erzwingt der boot-validator.
74
- export type ConfigBacking = "config" | "secrets";
75
-
76
- // Minimal read surface the config resolver needs to dispatch a
77
- // backing="secrets" key to the secrets store, without coupling the engine
78
- // types to the full SecretsContext. The app's `ctx.secrets` (a SecretsContext)
79
- // is structurally assignable. Threaded per-call (not at resolver construction)
80
- // because the resolver is framework-auto-created while `ctx.secrets` is
81
- // app-provided — only the request context sees both.
82
- export type ConfigSecretsReader = {
83
- get(tenantId: TenantId, key: string): Promise<{ readonly reveal: () => string } | undefined>;
84
- };
85
-
86
- export type ConfigKeyDefinition<T extends ConfigKeyType = ConfigKeyType> = {
87
- readonly type: T;
88
- readonly default?: ConfigValue<T>;
89
- readonly scope: ConfigScope;
90
- readonly access: ConfigKeyAccess;
91
- readonly encrypted?: boolean;
92
- /** User/admin may legitimately see the value — unlike `encrypted`
93
- * (shared master-key cipher), this is the subject-KMS: the value is
94
- * encrypted under the DEK of the scope actually written to (tenant-row
95
- * → tenant subject, user-row → user subject). Only on `type: "text"`,
96
- * `scope !== "system"` (no subject there), and mutually exclusive with
97
- * `encrypted` (kumiko-platform#231/#459). */
98
- readonly piiEncrypted?: boolean;
99
- readonly options?: readonly string[];
100
- readonly bounds?: ConfigBounds;
101
- // Per-key string-pattern validation for type="text". The value must match
102
- // the regex at write time — set.write hard-rejects a mismatch with
103
- // ValidationError("invalid_format"), same posture as bounds. Stored as a
104
- // serializable {regex, flags} pair (not a RegExp/predicate) so it survives
105
- // JSON like `bounds`/`options` (feature-manifest, docgen) and compiles per
106
- // write via new RegExp. Keep patterns anchored + length-bounded: the value
107
- // is tenant-supplied (untrusted), an unbounded catastrophic-backtracking
108
- // regex applied to it would be a ReDoS vector.
109
- readonly pattern?: { readonly regex: string; readonly flags?: string };
110
- readonly computed?: ConfigComputedFn<T>;
111
- // Per-Request opt-in. Default false — resolveConfigOrParam wirft für
112
- // Keys ohne diese Marke, auch wenn der Caller paramValue übergibt. Das
113
- // zwingt Feature-Devs zur expliziten Entscheidung "dieser Key darf pro
114
- // Request überschrieben werden" — statt versehentlich zu erlauben dass
115
- // ein Query-Param jede beliebige Tenant-Config umgeht.
116
- //
117
- // Nicht kombinierbar mit type="text" (Boot-Reject) — Text-Werte sind
118
- // immer gesperrt wegen XSS/SQL/Shell-Risiko, selbst mit Opt-in.
119
- // Nicht kombinierbar mit encrypted (Boot-Reject) — encrypted Keys
120
- // werden nicht transient aus Query-Strings heraus gelesen.
121
- readonly allowPerRequest?: boolean;
122
- // Tenant must supply a real value before the owning feature works — for
123
- // text keys an empty/whitespace value counts as unset. Surfaced by
124
- // config:query:readiness; keep in sync with the feature's requireNonEmpty
125
- // calls in its build-fn.
126
- readonly required?: boolean;
127
-
128
- // --- Provisioning-Metadata (optional auf createTenant/System/UserConfig) ---
129
- // ENV-Var-Name, dessen Wert beim Boot als app-override-Default dieses Keys
130
- // gebrückt wird. Reiner Fallback — überschreibt keinen gesetzten Row.
131
- readonly env?: string;
132
- // false → der geerbte system-row-Wert wird für Tenant-Admins redigiert
133
- // (cascade.query + values.query): der Tenant sieht weder den Wert noch dass
134
- // er gesetzt ist, nur den eigenen Override. Greift quell-basiert auf jeden
135
- // Wert aus der system-row — nicht scope-gebunden; typischer Fall ist ein
136
- // scope:tenant Key, dessen Plattform-Default in der system-row liegt (SMTP-
137
- // Creds). Default true = transparente Cascade.
138
- readonly inheritedToTenant?: boolean;
139
- // "config" (Default, volle Cascade) oder "secrets" (flach pro (tenant,key)).
140
- readonly backing?: ConfigBacking;
141
- // Markiert den Key als user-facing Einstellung: der Self-Populating
142
- // Settings-Hub leitet daraus automatisch Screen+Nav-Eintrag ab (kein
143
- // manuelles r.screen/r.nav). Fehlt `mask`, gilt der Key als internes
144
- // Plumbing (ENV-provisioniert/computed) und erscheint NICHT im Hub.
145
- readonly mask?: ConfigMask;
146
- // Überschreibt, unter welchem Settings-Hub-Namespace/Screen dieser Key
147
- // gruppiert wird (Default: das deklarierende Feature). Erlaubt einem
148
- // Feature, seine Keys unter einem fremden oder geteilten Namespace zu
149
- // bündeln (z.B. viele flache Migrations-Flags unter "tenant-settings"),
150
- // ohne dass das Ziel-Feature sie kennt. Rührt NICHT an qualifiziertem
151
- // Namen, Storage, Seeds oder App-Overrides — nur reine UI-Gruppierung.
152
- // Muss kebab-case sein (Boot-Validierung).
153
- readonly group?: string;
154
- };
155
-
156
- // Label-Träger für den Settings-Hub. `title` ist ein i18n-Key (kein Literal —
157
- // Guard), `icon` ein Icon-Registry-Key für den Nav-Eintrag, `order` die
158
- // Sortier-Gewichtung innerhalb seiner Audience-Gruppe.
159
- export type ConfigMask = {
160
- readonly title: string;
161
- readonly icon?: string;
162
- readonly order?: number;
163
- };
164
-
165
- export type ConfigDefinition = {
166
- readonly keys: Readonly<Record<string, ConfigKeyDefinition>>;
167
- };
168
-
169
- export type ConfigKeyHandle<T extends ConfigKeyType = ConfigKeyType> = {
170
- readonly name: string;
171
- readonly type: T;
172
- };
173
-
174
- export type ConfigAccessor = {
175
- (qualifiedKey: string): Promise<string | number | boolean | undefined>;
176
- <T extends ConfigKeyType>(handle: ConfigKeyHandle<T>): Promise<ConfigValue<T> | undefined>;
177
- };
178
-
179
- export type ConfigAccessorFactory = (deps: {
180
- readonly user: { readonly id: string; readonly tenantId: TenantId };
181
- readonly db: DbConnection | TenantDb;
182
- // Present when the app wired `extraContext.secrets`. Lets the internal
183
- // `ctx.config.get` read a backing="secrets" key transparently from the
184
- // secrets store; absent → a backing="secrets" read throws loud.
185
- readonly secrets?: ConfigSecretsReader;
186
- }) => ConfigAccessor;
187
-
188
- // Row shape returned by ConfigResolver.getAll — just enough for the
189
- // values.query handler to project. Stored as `unknown` value because the
190
- // resolver hands raw JSON strings; deserialization is the resolver's job.
191
- //
192
- // Post-ES the config_values projection PK is a UUID (event-store aggregate
193
- // id) and tenantId is non-null (system-scope rows carry SYSTEM_TENANT_ID).
194
- // The shape stays backward-compatible for read callers: they only touch
195
- // `value` and `key`.
196
- export type ConfigStoredRow = {
197
- readonly id: string;
198
- readonly key: string;
199
- readonly value: string | null;
200
- readonly tenantId: string;
201
- readonly userId: string | null;
202
- };
203
-
204
- // Extended row returned by ConfigResolver.getAllWithSource — includes the
205
- // resolution source so the UI can display where each value came from.
206
- export type ConfigStoredRowWithSource = ConfigStoredRow & {
207
- readonly source: ConfigValueSource;
208
- };
209
-
210
- // Which layer of the cascade actually produced a value. Emitted only by
211
- // `getWithSource` — regular `get` hides this to keep the hot-path simple.
212
- // Use-case: Ops-debugging ("warum ist mein Wert 50 und nicht 100?") without
213
- // poking through six scope-row-lookups by hand.
214
- export type ConfigValueSource =
215
- | "user-row" // user-scoped row (only for scope:user keys)
216
- | "tenant-row" // tenant-scoped row
217
- | "system-row" // system-scoped row (tenantId = SYSTEM_TENANT_ID, userId = null)
218
- | "app-override" // from createConfigResolver({ appOverrides })
219
- | "computed" // computed resolver in the key declaration
220
- | "default" // keyDef.default
221
- | "missing"; // no row, no override, no computed, no default
222
-
223
- export type ConfigValueWithSource = {
224
- readonly value: string | number | boolean | undefined;
225
- readonly source: ConfigValueSource;
226
- };
227
-
228
- /// Full cascade for a single config key — every level the resolver
229
- /// walks through, with the winning level marked.
230
- export type ConfigCascadeLevel = {
231
- readonly label: string;
232
- readonly value: string | number | boolean | undefined;
233
- readonly source: ConfigValueSource;
234
- readonly isActive: boolean;
235
- readonly hasValue: boolean;
236
- };
237
-
238
- export type ConfigCascade = {
239
- readonly value: string | number | boolean | undefined;
240
- readonly source: ConfigValueSource;
241
- readonly levels: readonly ConfigCascadeLevel[];
242
- };
243
-
244
- // Minimal contract handlers (set/reset/values.query) call against the
245
- // resolver. Lives in the framework so SharedContextFields.configResolver
246
- // can drop the `unknown` cast — the concrete implementation in
247
- // bundled-features/config/resolver.ts implements this shape.
248
- // Read-only contract: writes flow through the config feature's
249
- // write-handlers (set / reset), which append events + let the event-store-
250
- // executor materialise the projection. The resolver is purely a read
251
- // cascade (user → tenant → system → app-override → computed → default).
252
- export type ConfigResolver = {
253
- get(
254
- qualifiedKey: string,
255
- keyDef: ConfigKeyDefinition,
256
- tenantId: TenantId,
257
- userId: string,
258
- db: DbConnection | TenantDb,
259
- secretsReader?: ConfigSecretsReader,
260
- ): Promise<string | number | boolean | undefined>;
261
-
262
- // Same cascade as get() but also reports which layer produced the value.
263
- // Intended for Ops/Support tooling — never call this from hot-path
264
- // handlers (it builds the source tag even when the caller doesn't look
265
- // at it). Row-lookup count is identical to get(); the extra work is a
266
- // small branch tag.
267
- getWithSource(
268
- qualifiedKey: string,
269
- keyDef: ConfigKeyDefinition,
270
- tenantId: TenantId,
271
- userId: string,
272
- db: DbConnection | TenantDb,
273
- secretsReader?: ConfigSecretsReader,
274
- ): Promise<ConfigValueWithSource>;
275
-
276
- getAll(
277
- tenantId: TenantId,
278
- userId: string,
279
- db: DbConnection | TenantDb,
280
- ): Promise<ReadonlyMap<string, ConfigStoredRow>>;
281
-
282
- // Like getAll() but also reports the resolution source for each key.
283
- // Use when the caller needs to display the cascade origin (e.g. the
284
- // values.query handler serves the UI's hierarchy badge). Hot-path
285
- // callers should prefer getAll() for the narrower return type.
286
- getAllWithSource(
287
- tenantId: TenantId,
288
- userId: string,
289
- db: DbConnection | TenantDb,
290
- ): Promise<ReadonlyMap<string, ConfigStoredRowWithSource>>;
291
-
292
- // Returns ALL cascade levels for a single key — not just the winner.
293
- // Each level shows its value (or undefined if not set) and whether it
294
- // is the active/winning level. Levels are ordered by specificity
295
- // descending (most specific first).
296
- getCascade(
297
- qualifiedKey: string,
298
- keyDef: ConfigKeyDefinition,
299
- tenantId: TenantId,
300
- userId: string,
301
- db: DbConnection | TenantDb,
302
- secretsReader?: ConfigSecretsReader,
303
- ): Promise<ConfigCascade>;
304
-
305
- // Batch variant: resolves cascades for N keys in one DB round-trip.
306
- // keyDefs must contain definitions for every key in the keys array.
307
- // Returns a map of qualifiedKey → ConfigCascade. backing="secrets" keys
308
- // resolve their system rung from the secrets store via secretsReader
309
- // (one read each — they are system-only and rare).
310
- getCascadeBatch(
311
- keys: readonly string[],
312
- keyDefs: ReadonlyMap<string, ConfigKeyDefinition>,
313
- tenantId: TenantId,
314
- userId: string,
315
- db: DbConnection | TenantDb,
316
- secretsReader?: ConfigSecretsReader,
317
- ): Promise<ReadonlyMap<string, ConfigCascade>>;
318
- };
319
-
320
- // --- Process-Placement (runIn) ---
321
-
322
- // Which deploy-shape a consumer / job is allowed to run in. Filtered at
323
- // entrypoint boot: createApiEntrypoint picks up "api"|"both", createWorker
324
- // Entrypoint picks up "worker"|"both", createAllInOneEntrypoint takes
325
- // everything. Default is "worker" for every async consumer/job — that's the
326
- // sensible prod default (API instances stay request-focused, heavy async
327
- // work lives on the worker fleet). Opt into "api" only for latency-
328
- // sensitive or in-memory-stateful consumers (e.g. later: SSE per-instance
329
- // push in Welle 2.7).
330
- //
331
- // Feature-hooks (r.hook preSave/postSave/…) intentionally have no runIn —
332
- // they run in-TX in whatever process handles the command. Splitting them
333
- // would break atomicity. If you want async work, use r.job or
334
- // r.multiStreamProjection.
335
- export type RunIn = "api" | "worker" | "both";
336
-
337
- // Jobs are queue-delivered via BullMQ with one dedicated queue per lane
338
- // ("kumiko-jobs-api" vs "kumiko-jobs-worker") and one dedicated event-
339
- // enqueuer consumer per lane. "both" would mean "dispatch to both queues",
340
- // which over-delivers the job; the Marten-style cursor/queue fan-out is not
341
- // free. Restrict at the type level so the boot-validator never has to
342
- // report it.
343
- export type JobRunIn = Exclude<RunIn, "both">;
344
-
345
- // --- Jobs ---
346
-
347
- export type JobHandlerFn = (payload: Record<string, unknown>, context: AppContext) => Promise<void>;
348
-
349
- export type JobTrigger =
350
- // `on` akzeptiert ein einzelnes Handler-Ref ODER eine Liste. Multi-
351
- // Trigger-Form ist DRY für Fanout-Patterns: ein Job-Body, mehrere
352
- // Trigger (z.B. webhook-fanout: incident.open / incident.update /
353
- // maintenance.start) statt N r.job-Calls mit demselben Handler-Body.
354
- // Im Handler-payload landet `_triggerName: string` damit der Code
355
- // weiß, welcher Trigger gefeuert hat.
356
- | { readonly on: import("./handlers").NameOrRef | readonly import("./handlers").NameOrRef[] }
357
- | { readonly cron: string }
358
- | { readonly manual: true };
359
-
360
- export type JobDefinition = {
361
- readonly name: string;
362
- readonly handler: JobHandlerFn;
363
- readonly trigger: JobTrigger;
364
- readonly concurrency?: ConcurrencyMode | undefined;
365
- readonly maxPerTenant?: number | undefined;
366
- readonly debounceMs?: number | undefined;
367
- readonly retries?: number | undefined;
368
- readonly backoff?: "fixed" | "exponential" | undefined;
369
- readonly timeout?: number | undefined;
370
- readonly schema?: ZodType | undefined;
371
- readonly runOnBoot?: boolean | undefined;
372
- readonly perTenant?: boolean | undefined;
373
- // Which deploy-lane runs this job. Default "worker". Set "api" only for
374
- // short CPU-light handlers (token cleanup, in-process cache warmup) that
375
- // don't justify a separate worker container — long/CPU-heavy jobs on the
376
- // API lane will starve request handlers.
377
- readonly runIn?: JobRunIn | undefined;
378
- };
379
-
380
- // --- Notifications ---
381
-
382
- export type NotificationRecipientFn = (
383
- result: import("./hooks").SaveContext,
384
- ) => string | readonly string[] | { readonly tenant: string } | null;
385
-
386
- export type NotificationDataFn = (result: import("./hooks").SaveContext) => Record<string, unknown>;
387
-
388
- // Per-channel template function: transforms raw notification data into channel-specific format.
389
- // Example: inApp gets { title, body }, email gets { subject, sections }.
390
- export type NotificationTemplateFn = (data: Record<string, unknown>) => Record<string, unknown>;
391
-
392
- export type NotificationDefinition = {
393
- readonly name: string;
394
- readonly trigger: { readonly on: string };
395
- readonly recipient: NotificationRecipientFn;
396
- readonly data: NotificationDataFn;
397
- readonly templates: Readonly<Record<string, NotificationTemplateFn>> | undefined;
398
- };
399
-
400
- // --- Translations ---
401
-
402
- export type TranslationEntry = Readonly<Record<string, string>>;
403
- export type TranslationKeys = Readonly<Record<string, TranslationEntry>>;
404
-
405
- export type TranslationsDef = {
406
- readonly keys: TranslationKeys;
407
- };
408
-
409
- // --- Registrar Extensions ---
410
-
411
- export type RegistrarExtensionHooks = {
412
- readonly preSave?: PreSaveHookFn;
413
- readonly postSave?: PostSaveHookFn;
414
- readonly preDelete?: PreDeleteHookFn;
415
- readonly postDelete?: PostDeleteHookFn;
416
- readonly preQuery?: PreQueryHookFn;
417
- };
418
-
419
- export type UiExtensionDef = {
420
- readonly editSection?: string;
421
- readonly listColumns?: string;
422
- readonly filters?: string;
423
- };
424
-
425
- export type RegistrarExtensionDef = {
426
- readonly onRegister?: (entityName: string, options?: Record<string, unknown>) => void;
427
- readonly extendSchema?: (entityName: string) => Record<string, FieldDefinition>;
428
- readonly hooks?: RegistrarExtensionHooks;
429
- readonly extendSearch?: (entityName: string) => Record<string, unknown>;
430
- readonly uiExtension?: UiExtensionDef;
431
- };
432
-
433
- export type RegistrarExtensionRegistration = {
434
- readonly extensionName: string;
435
- readonly entityName: string;
436
- readonly options?: Record<string, unknown> | undefined;
437
- // Owning feature — annotated by the registry at merge time so consumers
438
- // (readiness gating) can map a registration back to the feature's keys.
439
- readonly featureName?: string;
440
- };
441
-
442
- // Declared by the extension-point-owning foundation via r.extensionSelector:
443
- // "which provider under <extensionName> is active is chosen by <qualifiedKey>".
444
- // Readiness counts a provider-feature's required keys only when selected.
445
- export type ExtensionSelectorDef = {
446
- readonly extensionName: string;
447
- readonly qualifiedKey: string;
448
- };
449
-
450
- // --- Reference Data ---
451
-
452
- export type ReferenceDataDef = {
453
- readonly entityName: string;
454
- readonly data: readonly Record<string, unknown>[];
455
- readonly upsertKey?: string | undefined;
456
- };
457
-
458
- // --- Config Seeding ---
459
-
460
- // A deploy-time default for a config key, written via the event-store
461
- // executor at boot. Idempotent — if the stream already exists the executor
462
- // returns version_conflict and seedConfigValues counts it as skipped.
463
- // See config-seeding.md.
464
- //
465
- // `scope` is optional on the factory-output: createSeed leaves it unset
466
- // (define-feature derives it from keyDef.scope). createSystemSeed /
467
- // createTenantSeed / createUserSeed always set it explicitly.
468
- //
469
- // `tenantId` / `userId` semantics:
470
- // - system scope: both stay undefined (row stored under SYSTEM_TENANT_ID).
471
- // - tenant scope: tenantId optional (undefined → fallback row under
472
- // SYSTEM_TENANT_ID, visible to all tenants via resolver cascade).
473
- // - user scope: BOTH tenantId AND userId required, otherwise the resolver
474
- // can never match the row (user-scope cascade looks up the user's actual
475
- // tenantId, not SYSTEM_TENANT_ID).
476
- export type ConfigSeedDef = {
477
- readonly key: string; // fully-qualified config key name (set by define-feature)
478
- readonly value: string | number | boolean;
479
- readonly scope?: ConfigScope;
480
- readonly tenantId?: string;
481
- readonly userId?: string;
482
- };
483
-
484
- // Factory types for ergonomic seed creation in r.config({ seeds }).
485
-
486
- export type CreateSeedOptions = {
487
- readonly value: string | number | boolean;
488
- };
489
-
490
- export type CreateTenantSeedOptions = {
491
- readonly tenantId?: string;
492
- };
493
-
494
- export type CreateUserSeedOptions = {
495
- readonly tenantId: string;
496
- readonly userId: string;
497
- };
1
+ // Legacy path re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/config";
@@ -0,0 +1,2 @@
1
+ // Legacy path — re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/define-handler";
@@ -0,0 +1,2 @@
1
+ // Legacy path — re-exported for callers still importing this module directly.
2
+ export * from "@cosmicdrift/kumiko-types/entity-handlers";
@@ -1,37 +1 @@
1
- // Cross-Feature Compile-Time-Type-Map.
2
- //
3
- // Zweck: ctx.appendEvent / ctx.queryProjection / dispatcher.write gegen ein
4
- // statisch bekanntes Schema-Bild prüfen, statt erst zur Boot- oder Runtime
5
- // (zod-validate) zu scheitern. Designer/AI-Layer profitiert dadurch sofort:
6
- // Autocomplete kennt alle Event-Typen aller geladenen Features, payload-
7
- // Shape-Mismatches werden im Editor angezeigt, nicht erst beim Boot.
8
- //
9
- // Befüllung erfolgt per Feature über `declare module "@cosmicdrift/kumiko-framework/engine"`
10
- // — entweder hand-geschrieben (für stabile Frameworks-Internals) oder vom
11
- // Codegen-Skript erzeugt (für apps/bundled-features). Empty defaults sind
12
- // kein Bug: ein Feature ohne Augmentation ist runtime-pluggable und nutzt
13
- // die Fallback-Overload mit `unknown` payload.
14
- //
15
- // Pattern für hand-geschriebene Augmentation am File-Top:
16
- //
17
- // declare module "@cosmicdrift/kumiko-framework/engine" {
18
- // interface KumikoEventTypeMap {
19
- // "users:user.created": z.infer<typeof userCreatedSchema>;
20
- // }
21
- // }
22
-
23
- // MUST be `interface` (not `type`): only interfaces support TS declaration-
24
- // merging. Apps/features extend these via `declare module "@cosmicdrift/kumiko-framework/engine"`
25
- // blocks. A `type X = {}` alias would silently break that augmentation channel.
26
-
27
- // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging marker — augmented per feature
28
- export interface KumikoEventTypeMap {}
29
-
30
- // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging marker
31
- export interface KumikoEntityTypeMap {}
32
-
33
- // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging marker
34
- export interface KumikoHandlerPayloadMap {}
35
-
36
- // biome-ignore lint/suspicious/noEmptyInterface: declaration-merging marker
37
- export interface KumikoHandlerResultMap {}
1
+ export * from "@cosmicdrift/kumiko-types/event-type-map";