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