@trytilde/ontology 0.0.0-stage → 3.1.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/dist/mod.d.ts ADDED
@@ -0,0 +1,1132 @@
1
+ /**
2
+ * `@trytilde/ontology`: an ontology project in TypeScript, the single source for
3
+ *
4
+ * - **models**: dbt-style ducktail models (`source`, `model`, `cdcCurrent`, `sqlFile`), compiled
5
+ * to `manifest.json`, which ducktail executes;
6
+ * - **nouns**: object types with typed properties over models, links, entity resolution;
7
+ * - **transactional views**: a portion of the graph materialised per key in a celld SQLite
8
+ * cell for hot transactional work (`transactionalView`);
9
+ * - **verbs**: `action` (txWrite) and `read` (txRead in a view, or `read` against the lake),
10
+ * with zod input and output and declared `edits` and `reads` (enforced). Handlers call
11
+ * third parties with plain `fetch` or SDKs; `ctx.deferredFetch` sends a request durably after
12
+ * the action commits, with credentials from a `connection` slot (a third-party account the
13
+ * environment binds, never visible to handlers) or an `auth` resolver over declared `secrets`;
14
+ * - **realtime views**: `realtime` reads whose results are pushed to subscribers when they
15
+ * change (per view instance in its cell, or across cells from the lake);
16
+ * - **policies**: Cedar (`policy`, `cedar`...``), enforced by the runtime on every invocation.
17
+ *
18
+ * Definitions are pure builders. `tilde deploy` evaluates `<root>/ontology.ts` once on the client
19
+ * (`tilde-ontology-build ir`, this package's `cli.ts`) into the IR that Tilde validates and
20
+ * compiles, and bundles it into the version's handler module (`tilde-ontology-build worker`).
21
+ *
22
+ * ```ts
23
+ * import { z } from "zod";
24
+ * import { action, cdcCurrent, model, object, ontology, source, sql, t, transactionalView } from "@trytilde/ontology";
25
+ *
26
+ * const customersRaw = source("app", "public_customers");
27
+ * const customersNow = model({ name: "app_customers", schema: "current", ...cdcCurrent(customersRaw) });
28
+ * const crmCustomers = model({ name: "crm_customers", schema: "cells", materialized: "cell", uniqueKey: "customer_id",
29
+ * columns: { customer_id: t.string(), name: t.string() },
30
+ * sql: ({ ref }) => sql`SELECT payload->>'id' AS customer_id, payload->>'name' AS name FROM ${ref(customersNow)}` });
31
+ * export const Customer = object("Customer", { id: "customer", key: "customerId", source: crmCustomers,
32
+ * properties: { customerId: t.string().map(sql`customer_id`), name: t.string().map(sql`name`),
33
+ * notes: t.string().optional().owned() } });
34
+ * export const CustomerView = transactionalView("Customer", { key: "customer_id", tables: { customers: crmCustomers } });
35
+ * export const setNotes = action("setNotes", {
36
+ * view: CustomerView, kind: "txWrite", input: z.object({ notes: z.string() }), output: z.null(),
37
+ * edits: [Customer.notes], reads: [Customer],
38
+ * handler: ({ input, view, ctx }) => { ctx.update(Customer, view.key, { notes: input.notes }); return null; },
39
+ * });
40
+ * export default ontology({ objects: [Customer], views: [CustomerView], actions: [setNotes] });
41
+ * ```
42
+ */
43
+ import { z } from "zod";
44
+ import { type PolledKind, type PolledProvider, type PolledStreams, type WebhookEvents } from "./catalog.ts";
45
+ export type { PipelineKind, PolledKind, PolledProvider, PolledStreams, WebhookEvents, WebhookProvider } from "./catalog.ts";
46
+ export type Json = null | boolean | number | string | Json[] | {
47
+ [key: string]: Json;
48
+ };
49
+ export type SqlParam = string | number | boolean | null;
50
+ export type Key = string | number;
51
+ /** Where an ontology's data lives: `cell` (the default: SQLite cells for views, DuckLake for the
52
+ * lake) or `postgres` (one Postgres schema for everything; see CONTEXT.md, "Postgres storage"). */
53
+ export type Storage = "cell" | "postgres";
54
+ /** The SQL dialect models and handler SQL are written in: DuckDB for `cell` storage, Postgres
55
+ * for `postgres`; ClickHouse for the models of a ClickHouse destination. */
56
+ export type Dialect = "duckdb" | "postgres" | "clickhouse";
57
+ /** The kind of a named destination models can materialize to besides the storage. */
58
+ export type DestinationKind = "clickhouse";
59
+ /** A SQL text fragment (in the storage's dialect). */
60
+ export interface Sql {
61
+ readonly sql: string;
62
+ }
63
+ /** Tagged template for SQL. Only other `sql` fragments (including `ref(...)` etc.) can be interpolated. */
64
+ export declare function sql(strings: TemplateStringsArray, ...parts: Sql[]): Sql;
65
+ /** A property or column type. Immutable: every modifier returns a new value. */
66
+ export declare class Prop<T, Owned extends boolean = false, Optional extends boolean = false> {
67
+ readonly type: string;
68
+ readonly spec: {
69
+ optional?: boolean;
70
+ owned?: boolean;
71
+ map?: string;
72
+ default?: Json;
73
+ id?: string;
74
+ description?: string;
75
+ loc?: string | null;
76
+ };
77
+ readonly __t: T;
78
+ readonly __owned: Owned;
79
+ readonly __optional: Optional;
80
+ constructor(type: string, spec?: {
81
+ optional?: boolean;
82
+ owned?: boolean;
83
+ map?: string;
84
+ default?: Json;
85
+ id?: string;
86
+ description?: string;
87
+ loc?: string | null;
88
+ });
89
+ private with;
90
+ /** Nullable. */
91
+ optional(): Prop<T, Owned, true>;
92
+ /** Owned by the ontology: edited by actions (in the cell edit log), never mapped from a source. */
93
+ owned(): Prop<T, true, Optional>;
94
+ /** Mapping: a SQL expression over the object's source model columns. */
95
+ map(expr: Sql): Prop<T, Owned, Optional>;
96
+ /** Value of an owned property before any edit. */
97
+ default(value: T & Json): Prop<T, Owned, Optional>;
98
+ /** Stable physical column id (pin it when renaming the property). */
99
+ id(id: string): Prop<T, Owned, Optional>;
100
+ describe(description: string): Prop<T, Owned, Optional>;
101
+ }
102
+ export declare const t: {
103
+ string: () => Prop<string, false, false>;
104
+ /** An integer within ±2^53 (larger values: `t.string()`). As a key or ref target, a string. */
105
+ int: () => Prop<number, false, false>;
106
+ float: () => Prop<number, false, false>;
107
+ bool: () => Prop<boolean, false, false>;
108
+ /** RFC 3339 text. */
109
+ timestamp: () => Prop<string, false, false>;
110
+ /** `YYYY-MM-DD`. */
111
+ date: () => Prop<string, false, false>;
112
+ /** Exact decimal text (a number in SQL inside cells, up to 15 digits). */
113
+ decimal: (precision: number, scale: number) => Prop<string, false, false>;
114
+ enum: <const V extends string[]>(...values: V) => Prop<V[number], false, false>;
115
+ array: <T>(of: Prop<T>) => Prop<T[], false, false>;
116
+ /** Reference to another object type: its key, which handlers always see as a string. */
117
+ ref: (object: string) => Prop<string, false, false>;
118
+ };
119
+ type ValueOf<P> = P extends Prop<infer T, boolean, infer O> ? (O extends true ? T | null : T) : never;
120
+ type Props = Record<string, Prop<unknown, boolean, boolean>>;
121
+ export type Row<P extends Props> = {
122
+ [K in keyof P]: ValueOf<P[K]>;
123
+ };
124
+ /**
125
+ * An object as handlers see it: like `Row`, except that the key is always a string (cells keep
126
+ * keys and refs as text, whatever their type, so they never lose digits or change form).
127
+ */
128
+ export type ObjectRow<P extends Props, K extends keyof P> = {
129
+ [F in keyof P]: F extends K ? string : ValueOf<P[F]>;
130
+ };
131
+ type OwnedKeys<P extends Props> = {
132
+ [K in keyof P]: P[K] extends Prop<unknown, true, boolean> ? K : never;
133
+ }[keyof P] & string;
134
+ /** A ducktail raw stream: `lake.raw.<pipeline>__<stream>`. */
135
+ export declare class SourceDef {
136
+ readonly pipeline: string;
137
+ readonly stream: string;
138
+ readonly loc: string | null;
139
+ readonly kind = "source";
140
+ readonly id: string;
141
+ readonly table: string;
142
+ constructor(pipeline: string, stream: string, loc: string | null);
143
+ }
144
+ /**
145
+ * A source: `source(pipeline, stream)` names one raw stream of a pipeline declared elsewhere;
146
+ * `source(name, { pipeline })` declares the pipeline that feeds the streams (`linear.poll`,
147
+ * `github.webhook`, `postgres.cdc`, ...; see Pipelines) and answers its streams as sources
148
+ * (`.stream("issues")`, typed by the pipeline's streams). List declared pipelines in
149
+ * `ontology({ pipelines })`.
150
+ */
151
+ export declare function source(pipeline: string, stream: string): SourceDef;
152
+ export declare function source<const S extends string>(name: string, spec: {
153
+ pipeline: Pipeline<S>;
154
+ }): PipelineSource<S>;
155
+ /**
156
+ * A custom stream: records that enter the environment through Tilde's Ingress
157
+ * (`IngressService.WriteRecords`, by API keys, people and agents with `write_streams` on the
158
+ * project, or the environment's own worker), each validated against `schema` and keyed by `key`
159
+ * (a string or number property: a newer record of a key replaces the older). They land in
160
+ * `lake.raw.ingress__<name>`: read it with `src()` and `changes()` like any source (the payload
161
+ * is the record). List streams in `ontology({ streams })`.
162
+ */
163
+ export declare class StreamDef extends SourceDef {
164
+ readonly schema: z.ZodType;
165
+ readonly key: string;
166
+ readonly reference: readonly unknown[];
167
+ constructor(name: string, schema: z.ZodType, key: string, reference: readonly unknown[], loc: string | null);
168
+ }
169
+ /**
170
+ * `reference`: static records the project ships with the stream (a solution's tenant
171
+ * configuration, say). The build validates them against `schema` and compiles them into the
172
+ * version; every rollout of the version loads them into the environment through Ingress, so a
173
+ * redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
174
+ * list is not deleted).
175
+ */
176
+ export declare function stream(name: string, options: {
177
+ schema: z.ZodType;
178
+ key: string;
179
+ reference?: readonly unknown[];
180
+ }): StreamDef;
181
+ /** The SQL builder context of a model: evaluated twice, once per `isIncremental`. */
182
+ export interface ModelSqlCtx {
183
+ /** `lake.<schema>.<name>` of another model (a dependency), or an object type's table: the
184
+ * object as the ontology has it, one row per key with a column per property id, owned values
185
+ * included (the generated model `<object id>`; eventually consistent, behind the actions'
186
+ * commits by a ducktail run). This is how a model reads owned state. */
187
+ ref(model: ModelDef | AnyObject): Sql;
188
+ /** `lake.raw.<pipeline>__<stream>` of a source (a dependency). */
189
+ src(source: SourceDef): Sql;
190
+ /** Rows changed in the run's window (ducktail's `changes()`), with `_change_type` and
191
+ * `_snapshot_id`; in a full run, the upstream's full state, all `insert`. Only over sources
192
+ * and incremental or cell models. */
193
+ changes(of: ModelDef | SourceDef | AnyObject): Sql;
194
+ /** True in the incremental run of an incremental or cell model. */
195
+ isIncremental: boolean;
196
+ /** The dialect the SQL must be written in (from the ontology's `storage`). */
197
+ dialect: Dialect;
198
+ /** The model's own table (`{{this}}`); only valid in incremental SQL and hooks. */
199
+ self: Sql;
200
+ /** A microbatch model's current batch, `[batchStart, batchEnd)` as timestamptz values. */
201
+ batchStart: Sql;
202
+ batchEnd: Sql;
203
+ }
204
+ export type ModelSql = (ctx: ModelSqlCtx) => Sql;
205
+ /** Raw SQL in a file, with the placeholders `{{ ref('model') }}`, `{{ src('pipeline', 'stream') }}`,
206
+ * `{{ changes(ref('model')) }}`, `{{ changes(src(...)) }}`, `{{ this }}` and
207
+ * `{% if is_incremental() %} ... {% else %} ... {% endif %}`. Placeholders are substituted as
208
+ * text, also inside comments and string literals: keep `{{`/`{%` out of those. */
209
+ export interface SqlFile {
210
+ readonly kind: "sqlFile";
211
+ readonly path: string;
212
+ readonly loc: string | null;
213
+ }
214
+ export declare function sqlFile(path: string): SqlFile;
215
+ export type ModelTest = {
216
+ kind: "unique";
217
+ column: string;
218
+ } | {
219
+ kind: "not_null";
220
+ column: string;
221
+ } | {
222
+ kind: "accepted_values";
223
+ column: string;
224
+ values: Json[];
225
+ } | {
226
+ kind: "relationships";
227
+ column: string;
228
+ to: ModelDef;
229
+ field: string;
230
+ };
231
+ export declare const tests: {
232
+ unique: (column: string) => ModelTest;
233
+ notNull: (column: string) => ModelTest;
234
+ acceptedValues: (column: string, values: Json[]) => ModelTest;
235
+ relationships: (column: string, to: ModelDef, field: string) => ModelTest;
236
+ };
237
+ /** dbt's config vocabulary, so models written for dbt transfer. */
238
+ /** Statements run inside a model's transaction before / after its write (not on views). */
239
+ export interface ModelHooks {
240
+ full?: ModelSql[];
241
+ incremental?: ModelSql[];
242
+ }
243
+ /**
244
+ * An index on a model's table (Postgres storage; ducktail creates and reconciles it).
245
+ * `columns` are index elements as Postgres writes them: a column (optionally with `DESC`,
246
+ * `NULLS FIRST` or an operator class) or an expression (a function call as is, anything else
247
+ * in parentheses).
248
+ */
249
+ export interface ModelIndex {
250
+ columns: string[];
251
+ unique?: boolean;
252
+ method?: "btree" | "gin" | "gist" | "hash" | "brin";
253
+ }
254
+ export interface ModelSpec<C extends Props> {
255
+ name: string;
256
+ schema?: string;
257
+ materialized: "view" | "table" | "incremental" | "cell" | "microbatch";
258
+ /** `microbatch` models (Postgres storage): built batch by batch of `eventTime` from `begin`
259
+ * (a date, an RFC 3339 time or a duration before now; default: ducktail's `[backfill] start`),
260
+ * each batch replaced as a whole; the SQL filters its inputs with `batchStart` / `batchEnd`. */
261
+ microbatch?: {
262
+ eventTime: string;
263
+ begin?: string;
264
+ batchSize: "hour" | "day" | "month";
265
+ lookback?: number;
266
+ };
267
+ preHooks?: ModelHooks;
268
+ postHooks?: ModelHooks;
269
+ uniqueKey?: string | string[];
270
+ incrementalStrategy?: "append" | "delete+insert" | "merge";
271
+ clusterBy?: string[];
272
+ fullRefresh?: boolean;
273
+ tests?: ModelTest[];
274
+ /** Postgres storage, tables only (not views). `uniqueKey` is always indexed. */
275
+ indexes?: ModelIndex[];
276
+ /** A destination of the ontology's `destinations` the model materializes to instead of the
277
+ * storage (Postgres storage only). Its SQL is then that destination's dialect (ClickHouse),
278
+ * and it reads models and sources of the storage through copies ducktail keeps there. A
279
+ * view, table or incremental model without hooks, tests or indexes; object types cannot be
280
+ * backed by it. */
281
+ destination?: string;
282
+ description?: string;
283
+ /** Column types: type `view.tables` rows in handlers and the cell's SQLite affinity. */
284
+ columns?: C;
285
+ sql: ModelSql | SqlFile;
286
+ }
287
+ export declare class ModelDef<C extends Props = Props> {
288
+ readonly spec: ModelSpec<C>;
289
+ readonly loc: string | null;
290
+ readonly kind = "model";
291
+ readonly id: string;
292
+ /** Set by the transactional view a cell model belongs to (one view only: a second is a build error). */
293
+ cell: {
294
+ view: string;
295
+ partitionBy: string;
296
+ } | null;
297
+ constructor(spec: ModelSpec<C>, loc: string | null);
298
+ }
299
+ export declare function model<C extends Props = Props>(spec: ModelSpec<C>): ModelDef<C>;
300
+ /**
301
+ * ducktail's `cdc_current`, verbatim from its README ("Current state from CDC"): the latest
302
+ * row per `_key` of a CDC stream (`_key, _pos, _seq, _source_ts, payload, _deleted`), applying
303
+ * deletes, honouring truncates and snapshot restarts (`t` rows: an incremental pre-hook clears
304
+ * the target) and carrying unchanged TOAST columns forward. Spread it into a model:
305
+ * `model({ name: "app_users", schema: "current", ...cdcCurrent(source("app", "users")) })`.
306
+ */
307
+ export declare function cdcCurrent(of: SourceDef): {
308
+ materialized: "incremental";
309
+ uniqueKey: string;
310
+ incrementalStrategy: "delete+insert";
311
+ sql: ({ changes, isIncremental, self, dialect }: ModelSqlCtx) => Sql;
312
+ preHooks: {
313
+ incremental: (({ changes, self }: ModelSqlCtx) => Sql)[];
314
+ };
315
+ };
316
+ /** A reference to one property of an object type (`Customer.notes`). */
317
+ export interface PropRef<O extends string = string, F extends string = string, P = Prop<unknown, boolean, boolean>> {
318
+ readonly kind: "prop";
319
+ readonly object: O;
320
+ readonly property: F;
321
+ readonly prop: P;
322
+ }
323
+ type ObjectInternals<N extends string, P extends Props, K extends keyof P & string> = {
324
+ readonly $kind: "object";
325
+ readonly $name: N;
326
+ readonly $spec: {
327
+ id: string;
328
+ key: K;
329
+ description?: string;
330
+ source?: ModelDef;
331
+ properties: P;
332
+ history?: boolean;
333
+ historyAt?: string;
334
+ replicas?: string[];
335
+ };
336
+ readonly $loc: string | null;
337
+ /** Type-level only: the object row handlers see. */
338
+ readonly $row: ObjectRow<P, K>;
339
+ readonly $owned: OwnedKeys<P>;
340
+ };
341
+ /** Any object type, for parameters that take one (precise types come from `ObjectDef`). */
342
+ export interface AnyObject {
343
+ readonly $kind: "object";
344
+ readonly $name: string;
345
+ readonly $spec: {
346
+ id: string;
347
+ key: string;
348
+ description?: string;
349
+ source?: ModelDef;
350
+ properties: Props;
351
+ history?: boolean;
352
+ historyAt?: string;
353
+ replicas?: string[];
354
+ };
355
+ readonly $loc: string | null;
356
+ readonly $row: any;
357
+ readonly $owned: string;
358
+ }
359
+ /** An object type, with one `PropRef` per property (`Customer.notes`). Internals are `$`-prefixed. */
360
+ export type ObjectDef<N extends string = string, P extends Props = Props, K extends keyof P & string = keyof P & string> = ObjectInternals<N, P, K> & {
361
+ readonly [F in keyof P & string]: PropRef<N, F, P[F]>;
362
+ };
363
+ /**
364
+ * An object type. Objects without a `source` are owned by the ontology (created by actions).
365
+ * `history: true` keeps every change of its properties in `lake.ontology.<id>__changes` from
366
+ * then on (read it with `history(Object)`); `historyAt` names a source-owned timestamp
367
+ * property that dates source-side changes (else the time the lake saw them).
368
+ *
369
+ * With Postgres storage, an object whose `source` materializes to a ClickHouse destination is
370
+ * read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
371
+ * history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
372
+ * object's table in that destination, so SQL there can join it.
373
+ */
374
+ export declare function object<const N extends string, P extends Props, const K extends keyof P & string>(name: N, spec: {
375
+ id: string;
376
+ key: K;
377
+ description?: string;
378
+ source?: ModelDef;
379
+ properties: P;
380
+ history?: boolean;
381
+ historyAt?: keyof P & string;
382
+ replicas?: string[];
383
+ }): ObjectDef<N, P, K>;
384
+ /** An object type's change history (`history: true`): the relation `lake.ontology.<id>__changes`,
385
+ * which a view-less read declares in its `reads`, and Cedar's `Model::"<id>__changes"` (what
386
+ * `query` is decided on). */
387
+ export interface HistoryRef {
388
+ readonly kind: "history";
389
+ readonly object: string;
390
+ readonly model: string;
391
+ }
392
+ export declare function history(object: AnyObject): HistoryRef;
393
+ export interface LinkDef {
394
+ readonly kind: "link";
395
+ readonly name: string;
396
+ readonly ir: Record<string, unknown>;
397
+ readonly source: ModelDef | null;
398
+ }
399
+ /** A link type: 1:1 / 1:N via a ref property on `to`, or N:M with its own model. */
400
+ export declare function link(name: string, spec: {
401
+ id: string;
402
+ from: AnyObject;
403
+ to: AnyObject;
404
+ cardinality: "one_to_one" | "one_to_many";
405
+ via: string;
406
+ } | {
407
+ id: string;
408
+ from: AnyObject;
409
+ to: AnyObject;
410
+ cardinality: "many_to_many";
411
+ source: ModelDef;
412
+ map: {
413
+ from: Sql;
414
+ to: Sql;
415
+ };
416
+ }): LinkDef;
417
+ export type Normalizer = "exact" | "text" | "email" | "domain" | "phone";
418
+ /** One member type of an entity resolution: feature name -> SQL over its properties. */
419
+ export declare function member(object: AnyObject, features: Record<string, Sql>): {
420
+ object: string;
421
+ features: {
422
+ [k: string]: string;
423
+ };
424
+ };
425
+ /** Entity resolution across object types (deterministic rules, fuzzy candidates). */
426
+ export declare function resolution(name: string, spec: {
427
+ id: string;
428
+ features: Record<string, Normalizer>;
429
+ members: ReturnType<typeof member>[];
430
+ rules: {
431
+ name: string;
432
+ on: string[];
433
+ }[];
434
+ fuzzy?: {
435
+ on: string;
436
+ threshold: number;
437
+ block?: string;
438
+ };
439
+ }): {
440
+ fuzzy: {
441
+ on: string;
442
+ threshold: number;
443
+ block?: string;
444
+ } | null;
445
+ loc: string | null;
446
+ id: string;
447
+ features: Record<string, Normalizer>;
448
+ members: ReturnType<typeof member>[];
449
+ rules: {
450
+ name: string;
451
+ on: string[];
452
+ }[];
453
+ name: string;
454
+ };
455
+ /**
456
+ * A transactional view: a portion of the ontology graph materialised per key in one celld
457
+ * SQLite cell (`<view id>:<key>`) for hot transactional work. Its `tables` are ducktail cell
458
+ * models, each partitioned by the `key` column; the root table is the one keyed by `key`.
459
+ * `dependsOn` lists the objects and links the view serves; the build warns where it disagrees
460
+ * with what the models' lineage shows. For ontology-owned objects (no source) it is what makes
461
+ * them members: an ontology-owned object belongs to the view that lists it.
462
+ */
463
+ export declare class ViewDef<T extends Record<string, ModelDef> = Record<string, ModelDef>> {
464
+ readonly name: string;
465
+ readonly spec: {
466
+ key: string;
467
+ tables: T;
468
+ dependsOn?: {
469
+ objects?: AnyObject[];
470
+ links?: LinkDef[];
471
+ };
472
+ };
473
+ readonly loc: string | null;
474
+ readonly kind = "view";
475
+ readonly id: string;
476
+ constructor(name: string, spec: {
477
+ key: string;
478
+ tables: T;
479
+ dependsOn?: {
480
+ objects?: AnyObject[];
481
+ links?: LinkDef[];
482
+ };
483
+ }, loc: string | null);
484
+ }
485
+ export declare function transactionalView<const T extends Record<string, ModelDef>>(name: string, spec: {
486
+ key: string;
487
+ tables: T;
488
+ dependsOn?: {
489
+ objects?: AnyObject[];
490
+ links?: LinkDef[];
491
+ };
492
+ }): ViewDef<T>;
493
+ type TableRow<M> = M extends ModelDef<infer C> ? (Props extends C ? Record<string, Json> : Row<C>) : never;
494
+ /** A transactional view instance as handlers see it. Reads are limited to the declared `reads`. */
495
+ export interface ViewHandle<V extends ViewDef> {
496
+ /** The view key (the cell key). */
497
+ readonly key: string;
498
+ /** Rows of the view's tables (as hydrated from ducktail). */
499
+ readonly tables: {
500
+ readonly [K in keyof V["spec"]["tables"]]: TableRow<V["spec"]["tables"][K]>[];
501
+ };
502
+ /** One object of this view by key (with this cell's own edits), or null. */
503
+ get<O extends AnyObject>(object: O, key: string): O["$row"] | null;
504
+ /** Every object of a type in this view. */
505
+ all<O extends AnyObject>(object: O): O["$row"][];
506
+ }
507
+ /**
508
+ * A per-deployment value handlers read from `ctx.secrets` (secrets: celld secrets /
509
+ * `.dev.vars`) or `ctx.settings` (plain settings: celld vars, with a default). Secrets are
510
+ * visible to handlers (they call third parties with them) but never stored: `ctx.deferredFetch`
511
+ * refuses requests carrying them; deferred requests get credentials from `auth` resolvers.
512
+ */
513
+ export interface EnvDef {
514
+ readonly kind: "secret" | "setting";
515
+ readonly default: string | null;
516
+ }
517
+ export declare const secret: () => EnvDef;
518
+ export declare const setting: (defaultValue?: string) => EnvDef;
519
+ /**
520
+ * A connection slot: a third-party account the project needs (`connection("linear")`), which
521
+ * each environment binds to one of its organization's Tilde connections of that provider (and
522
+ * type, when given). Name it as a request's `auth` (`deferredFetch(url, init, { auth: linear })`,
523
+ * a read's `ctx.authHeaders(linear)`): the runtime gets the account's current credentials from
524
+ * the control plane when the request is sent (fresh, refreshed tokens; cached briefly) and sets
525
+ * them as headers. Handlers never see them. Pipelines name the same slot (`linear.poll({ slot })`).
526
+ * Declare slots with `defineSlots` and `ontology({ slots })` (or `connection()` and `connections`).
527
+ */
528
+ export interface ConnectionDef {
529
+ readonly kind: "connection";
530
+ /** The slot's name (snake_case), unique among slots and `auth` resolvers. */
531
+ readonly name: string;
532
+ /** The Tilde connection provider (`linear`, `github`, `sentry`, `aws`, ...). */
533
+ readonly provider: string;
534
+ /** One of the provider's connection types (`api_key`, `oauth`, ...); null accepts any. */
535
+ readonly type: string | null;
536
+ readonly loc: string | null;
537
+ }
538
+ /** A connection slot; `provider` defaults to the slot's name. */
539
+ export declare function connection(name: string, options?: {
540
+ provider?: string;
541
+ type?: string;
542
+ }): ConnectionDef;
543
+ /** A slot as `slot()` makes it, named by `defineSlots`. */
544
+ export interface SlotSpec<P extends string = string> {
545
+ readonly kind: "slot";
546
+ readonly provider: P;
547
+ readonly type: string | null;
548
+ readonly loc: string | null;
549
+ }
550
+ /** A declared connection slot whose provider is `P` (`defineSlots`). */
551
+ export interface Slot<P extends string = string> extends ConnectionDef {
552
+ readonly provider: P;
553
+ }
554
+ /** A connection slot of a Tilde connection provider (and optionally one of its types), named by
555
+ * its key in `defineSlots`. */
556
+ export declare function slot<const P extends string>(provider: P, options?: {
557
+ type?: string;
558
+ }): SlotSpec<P>;
559
+ /**
560
+ * The connection slots the ontology needs, by name: `defineSlots({ linear: slot("linear"),
561
+ * github: slot("github") })`. Pipelines and requests name them as `slots.linear` (a pipeline
562
+ * helper takes only a slot of its provider), each environment binds them to its organization's
563
+ * connections, and `ontology({ slots })` declares them.
564
+ */
565
+ export declare function defineSlots<const S extends Record<string, SlotSpec>>(slots: S): {
566
+ readonly [K in keyof S]: Slot<S[K]["provider"]>;
567
+ };
568
+ /** A declared raw secret (`defineSecrets`), which pipelines take where ducktail wants a secret. */
569
+ export interface SecretRef<N extends string = string> {
570
+ readonly kind: "secretRef";
571
+ readonly name: N;
572
+ readonly loc: string | null;
573
+ }
574
+ /**
575
+ * The raw secrets the ontology's pipelines need, by name: `defineSecrets({ PG_PASSWORD:
576
+ * secret() })`, used as `postgres.cdc({ password: secrets.PG_PASSWORD, ... })` and declared with
577
+ * `ontology({ secrets })`. Each environment supplies them (bound to its team's Tilde secrets, or
578
+ * set on the environment); their values never enter the version. Handlers do not see them (that
579
+ * is `env`).
580
+ */
581
+ export declare function defineSecrets<const S extends Record<string, EnvDef>>(secrets: S): {
582
+ readonly [K in keyof S & string]: SecretRef<K>;
583
+ };
584
+ /** A ducktail duration: `500ms`, `60s`, `5m`, `6h`, `90d`. */
585
+ export type Duration = `${number}${"ms" | "s" | "m" | "h" | "d"}`;
586
+ /** Text with secrets in it (a Postgres connection string): each becomes the environment's. */
587
+ export interface SecretText {
588
+ readonly kind: "secretText";
589
+ readonly parts: readonly (string | SecretRef)[];
590
+ }
591
+ /** A value of a pipeline's ducktail config; a `SecretRef` becomes the environment's secret. */
592
+ export type PipelineValue = string | number | boolean | SecretRef | SecretText | readonly PipelineValue[] | {
593
+ readonly [key: string]: PipelineValue | undefined;
594
+ };
595
+ /**
596
+ * What feeds a source's raw streams (`lake.raw.<source>__<stream>`): one ducktail pipeline of
597
+ * `type`, optionally through a connection slot, with its streams and ducktail's own config keys
598
+ * (`options`, snake_case as ducktail's README writes them). Made by the helpers below; the build
599
+ * compiles it into the version and the environment's rollout gives it to ducktail.
600
+ */
601
+ export declare class Pipeline<S extends string = string> {
602
+ readonly type: string;
603
+ readonly slot: ConnectionDef | null;
604
+ readonly streams: readonly S[];
605
+ readonly options: {
606
+ readonly [key: string]: PipelineValue | undefined;
607
+ };
608
+ readonly loc: string | null;
609
+ /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
610
+ readonly name: string | null;
611
+ readonly kind = "pipeline";
612
+ constructor(type: string, slot: ConnectionDef | null, streams: readonly S[], options: {
613
+ readonly [key: string]: PipelineValue | undefined;
614
+ }, loc: string | null,
615
+ /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
616
+ name?: string | null);
617
+ /** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
618
+ untypedStreams<const X extends string>(...names: X[]): Pipeline<S | X>;
619
+ }
620
+ /** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
621
+ export declare class WebhookPipeline<S extends string = string, E extends string = string> extends Pipeline<S> {
622
+ /** More routes, for event names this SDK's catalog does not know. */
623
+ untypedEvents(routes: {
624
+ readonly [event: string]: NoInfer<S>;
625
+ }): WebhookPipeline<S, E>;
626
+ }
627
+ /** A declared source: a pipeline under its name, whose streams are sources. */
628
+ export declare class PipelineSource<S extends string = string> {
629
+ readonly name: string;
630
+ readonly pipeline: Pipeline<S>;
631
+ readonly loc: string | null;
632
+ readonly kind = "pipelineSource";
633
+ constructor(name: string, pipeline: Pipeline<S>, loc: string | null);
634
+ /** One of the pipeline's streams: `lake.raw.<name>__<stream>`. */
635
+ stream(stream: S): SourceDef;
636
+ }
637
+ /** Polled options every polled kind takes. */
638
+ interface PollOptions<St extends string> {
639
+ /** The streams to poll (default: all of the kind's). */
640
+ streams?: readonly St[];
641
+ interval?: Duration;
642
+ /** Where the first sweep starts: a date, an RFC 3339 time or a duration before now. */
643
+ backfill?: {
644
+ start: string;
645
+ };
646
+ requestTimeout?: Duration;
647
+ }
648
+ /** A provider webhook's routing: event name -> stream, the rest to `fallback`. */
649
+ interface WebhookOptions<P extends keyof WebhookEvents, S extends string> {
650
+ slot: Slot<P>;
651
+ /** The pipeline's streams. */
652
+ streams: readonly S[];
653
+ /** Event -> stream; events not listed go to `fallback` (without one, ducktail answers 422). */
654
+ route: {
655
+ readonly [E in WebhookEvents[P]]?: NoInfer<S>;
656
+ };
657
+ fallback?: NoInfer<S>;
658
+ }
659
+ /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
660
+ export declare const linear: {
661
+ poll: <const St extends PolledStreams["linear"] = "teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">(o: PollOptions<St> & {
662
+ slot: Slot<"linear">;
663
+ pageSize?: number;
664
+ /** A stream's GraphQL selection, replacing the built-in one. */
665
+ fields?: { readonly [K in PolledStreams["linear"]]?: string; };
666
+ endpoint?: string;
667
+ }) => Pipeline<St>;
668
+ webhook: <const S extends string>(o: WebhookOptions<"linear", S>) => WebhookPipeline<S, "Attachment" | "AuditEntry" | "Comment" | "Customer" | "CustomerNeed" | "Cycle" | "Document" | "Initiative" | "InitiativeUpdate" | "Issue" | "IssueLabel" | "IssueSLA" | "OAuthApp" | "Project" | "ProjectUpdate" | "Reaction" | "User">;
669
+ };
670
+ /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
671
+ export declare const sentry: {
672
+ poll: <const St extends PolledStreams["sentry"] = "projects" | "issues">(o: PollOptions<St> & {
673
+ slot: Slot<"sentry">;
674
+ organization: string;
675
+ /** Project slugs whose issues are polled. */
676
+ projects?: readonly string[];
677
+ /** `https://sentry.io` (default), a regional host or self-hosted Sentry. */
678
+ baseUrl?: string;
679
+ query?: string;
680
+ fullSweepInterval?: Duration;
681
+ }) => Pipeline<St>;
682
+ webhook: <const S extends string>(o: WebhookOptions<"sentry", S>) => WebhookPipeline<S, "installation" | "comment" | "error" | "event_alert" | "issue" | "metric_alert" | "seer">;
683
+ };
684
+ /** GitHub: the connection's webhooks (a GitHub App's), with an optional backfill of history. */
685
+ export declare const github: {
686
+ webhook: <const S extends string>(o: WebhookOptions<"github", S> & {
687
+ /** On the pipeline's first run, fetch the repositories' history as the webhook delivers it. */
688
+ backfill?: {
689
+ repositories: readonly string[];
690
+ start?: string;
691
+ baseUrl?: string;
692
+ pageSize?: number;
693
+ };
694
+ }) => WebhookPipeline<S, "issues" | "check_run" | "check_suite" | "code_scanning_alert" | "create" | "delete" | "dependabot_alert" | "deployment" | "deployment_status" | "discussion" | "discussion_comment" | "fork" | "installation" | "installation_repositories" | "issue_comment" | "label" | "member" | "merge_group" | "milestone" | "ping" | "pull_request" | "pull_request_review" | "pull_request_review_comment" | "pull_request_review_thread" | "push" | "release" | "repository" | "secret_scanning_alert" | "status" | "workflow_job" | "workflow_run">;
695
+ };
696
+ /** A CloudWatch metric (`AWS/RDS` `CPUUtilization` ...). */
697
+ export interface CloudwatchMetric {
698
+ namespace: string;
699
+ name: string;
700
+ dimensions?: {
701
+ readonly [name: string]: string;
702
+ };
703
+ /** `Average`, `Sum`, `Minimum`, `Maximum`, `SampleCount` or a percentile like `p95`. */
704
+ stat: string;
705
+ }
706
+ /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
707
+ export declare const cloudwatch: {
708
+ poll: <const St extends PolledStreams["cloudwatch"] = "ecs_clusters" | "ecs_services" | "load_balancers" | "target_groups" | "target_health" | "metric_data" | "alarms" | "alarm_history">(o: PollOptions<St> & {
709
+ slot: Slot<PolledProvider["cloudwatch"]>;
710
+ region: string;
711
+ discoveryInterval?: Duration;
712
+ period?: Duration;
713
+ delay?: Duration;
714
+ /** ECS clusters to discover (default: all); not with `accounts`. */
715
+ clusters?: readonly string[];
716
+ /** Several accounts through the one connection, by a name of your choosing. */
717
+ accounts?: {
718
+ readonly [name: string]: {
719
+ id: string;
720
+ clusters?: readonly string[];
721
+ metrics?: readonly CloudwatchMetric[];
722
+ };
723
+ };
724
+ discoverMetrics?: boolean;
725
+ metrics?: readonly CloudwatchMetric[];
726
+ endpoint?: string;
727
+ }) => Pipeline<St>;
728
+ };
729
+ /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
730
+ * `options` are ducktail's keys for it (README, "Polled sources"). */
731
+ export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch">, const St extends PolledStreams[K] = PolledStreams[K]>(kind: K, o: PollOptions<St> & {
732
+ slot: Slot<PolledProvider[K]>;
733
+ options?: {
734
+ readonly [key: string]: PipelineValue | undefined;
735
+ };
736
+ }): Pipeline<St>;
737
+ /** Postgres logical replication of tables (streams `<schema>_<table>`). */
738
+ export declare const postgres: {
739
+ cdc: <const T extends string>(o: {
740
+ host: string;
741
+ port?: number;
742
+ user: string;
743
+ password: SecretRef;
744
+ database: string;
745
+ sslmode?: "disable" | "prefer" | "require" | "verify-ca" | "verify-full";
746
+ /** `schema.table` names. */
747
+ tables: readonly T[];
748
+ /** The replication slot (default `ducktail_<source>`). */
749
+ replicationSlot?: string;
750
+ publication?: string;
751
+ snapshotWorkers?: number;
752
+ }) => Pipeline<string>;
753
+ };
754
+ /** Kafka topics (streams: the topic names, lower-cased, other characters `_`). */
755
+ export declare const kafka: {
756
+ consume: <const T extends string>(o: {
757
+ brokers: readonly string[];
758
+ topics: readonly T[];
759
+ start?: "earliest" | "latest";
760
+ format?: "json" | "text";
761
+ tls?: {
762
+ caFile?: string;
763
+ verify?: boolean;
764
+ };
765
+ sasl?: {
766
+ mechanism: "PLAIN" | "SCRAM-SHA-256" | "SCRAM-SHA-512";
767
+ username: string;
768
+ password: SecretRef;
769
+ };
770
+ }) => Pipeline<string>;
771
+ };
772
+ /**
773
+ * A webhook pipeline of the solution's own, which Tilde delivers to (records written through
774
+ * Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>`, or one URL routed by
775
+ * a header.
776
+ */
777
+ export declare function webhook<const S extends string>(o: {
778
+ streams: readonly S[];
779
+ /** The header whose value keys deliveries (`_key = {"id": ...}`). */
780
+ keyHeader?: string;
781
+ route?: {
782
+ header: string;
783
+ streams: {
784
+ readonly [value: string]: NoInfer<S>;
785
+ };
786
+ fallback?: NoInfer<S>;
787
+ };
788
+ }): Pipeline<S>;
789
+ /** The tables Tilde's registry events deliver (`tilde.events`). */
790
+ export type RegistryStream = "public_chat_threads" | "public_chat_runs" | "public_chat_tasks" | "public_chat_invocations" | "public_inference_requests" | "public_chat_messages" | "public_chat_participants" | "public_chat_channel_identities";
791
+ /** Tilde itself. */
792
+ export declare const tilde: {
793
+ /**
794
+ * The organization's registry events (threads, runs, tasks, invocations, inference usage,
795
+ * messages...), pushed by Tilde to environments that turn them on: only the streams listed
796
+ * are delivered. The source must be named `tilde`.
797
+ */
798
+ events: <const S extends RegistryStream>(o: {
799
+ streams: readonly S[];
800
+ }) => Pipeline<S>;
801
+ };
802
+ /** Options of `ctx.deferredFetch`. */
803
+ export interface DeferredOptions {
804
+ /** Stable across retries; default `<invocation>:<n>`. Sent as `Idempotency-Key` unless the request has one. */
805
+ idempotencyKey?: string;
806
+ /** Expected new values of source-owned properties, shown until the source confirms them. */
807
+ pending?: {
808
+ object: AnyObject;
809
+ key: string;
810
+ values: Record<string, Json>;
811
+ };
812
+ /** Headers resolved when the request is sent (fresh credentials on every attempt): a
813
+ * connection slot's or an `auth` resolver's. The outbox stores only the name. */
814
+ auth?: AuthDef | ConnectionDef;
815
+ /** An action of the same view to run once the request is delivered (2xx), with the
816
+ * response as its input (`deferredResponse`); declare it in the action's `continuations`. */
817
+ then?: HandlerDef;
818
+ }
819
+ /**
820
+ * Credentials for a third party derived from static secrets when a request is sent, e.g. an
821
+ * OAuth2 client-credentials exchange. The result is cached (per isolate) until `ttlSeconds`
822
+ * (less a tenth, at most 30 s); without `ttlSeconds` it is not cached, resolved for every
823
+ * attempt. A 401 or 403 from the third party drops the cached result. Runs in the outbox
824
+ * sender (never inside a handler's transaction) and for reads' `ctx.authHeaders` (live calls;
825
+ * actions do not get it, see `TxCtx`).
826
+ */
827
+ export interface AuthDef {
828
+ readonly kind: "auth";
829
+ readonly name: string;
830
+ readonly resolve: (env: {
831
+ secrets: Readonly<Record<string, string>>;
832
+ settings: Readonly<Record<string, string>>;
833
+ fetch: typeof fetch;
834
+ }) => Promise<{
835
+ headers: Record<string, string>;
836
+ ttlSeconds?: number;
837
+ }>;
838
+ readonly loc: string | null;
839
+ }
840
+ export declare function auth(name: string, resolve: AuthDef["resolve"]): AuthDef;
841
+ /** The input a continuation (`DeferredOptions.then`) receives: extend it to type `body`. */
842
+ export declare const deferredResponse: z.ZodObject<{
843
+ status: z.ZodNumber;
844
+ body: z.ZodUnknown;
845
+ callId: z.ZodString;
846
+ invocationId: z.ZodString;
847
+ }, z.core.$strip>;
848
+ /**
849
+ * Record a request to send after the action commits (retried, in order per origin, with an
850
+ * idempotency key) and answer a synthetic 202 at once. Fetch-compatible: pass it to an SDK as
851
+ * its fetch. Live calls are just `fetch`.
852
+ */
853
+ export type DeferredFetch = (input: string | URL | Request, init?: RequestInit, options?: DeferredOptions) => Promise<Response>;
854
+ /** Thrown by `ctx.fail` / `ctx.require`: a business failure (nothing is written). */
855
+ export declare class ActionError extends Error {
856
+ constructor(message: string);
857
+ }
858
+ /** Tag an output field with the ontology property it carries (field masking). The field is
859
+ * nullable: a caller who may not `readField` the property gets null there (and the lake
860
+ * already reads it as NULL), so the output schema and client types say so. */
861
+ export declare function prop<R extends PropRef>(ref: R): z.ZodType<ValueOf<R["prop"]> | null>;
862
+ export interface LakeCtx {
863
+ /** Analytics SQL over the lake (the eventually consistent ontology): only the object views
864
+ * and models the read declares; the read scopes its own rows (from `ctx.principal`). */
865
+ query<R = Record<string, Json>>(sql: string, ...params: Json[]): Promise<R[]>;
866
+ /** A ClickHouse destination (Postgres storage): `query` runs ClickHouse SQL over the declared
867
+ * objects and models that live there (or are copied there), masked like `query`; parameters
868
+ * are `$1`, `$2`, ... (typed from their values: compare timestamps through
869
+ * `parseDateTime64BestEffort($1)`). Never joins across stores: look rows up by key. */
870
+ destination(name: string): {
871
+ query<R = Record<string, Json>>(sql: string, ...params: Json[]): Promise<R[]>;
872
+ };
873
+ }
874
+ /** Who is asking, from the verified token: the subject, the actors acting for it (current
875
+ * actor first) and the subject's attributes. */
876
+ export interface Principal {
877
+ readonly sub: string;
878
+ readonly act: readonly string[];
879
+ readonly attrs: Readonly<Record<string, string>>;
880
+ }
881
+ /** A handler as `ListActions` / `ctx.availableActions` reports it for a caller. */
882
+ export interface AvailableAction {
883
+ name: string;
884
+ kind: "txWrite" | "txRead" | "read";
885
+ /** `conditional`: allowed when `condition` holds (a residual over the input). */
886
+ decision: "allowed" | "conditional" | "approval_required" | "denied";
887
+ condition: string | null;
888
+ policyIds: string[];
889
+ inputSchema: Json;
890
+ outputSchema: Json;
891
+ }
892
+ /** A view-less read's ctx: the lake, limited to the relations its `reads` declare. */
893
+ export interface LakeReadCtx extends BaseCtx {
894
+ readonly lake: LakeCtx;
895
+ }
896
+ export interface BaseCtx {
897
+ /** Who is asking (read-only). A view-less read is responsible for scoping its own rows. */
898
+ readonly principal: Principal;
899
+ /** The project's declared secrets (`env` with `secret()`), by name. */
900
+ readonly secrets: Readonly<Record<string, string>>;
901
+ /** The project's declared settings (`env` with `setting()`), by name. */
902
+ readonly settings: Readonly<Record<string, string>>;
903
+ /** Headers from an `auth` resolver, for live calls (cached like the outbox's). A connection's
904
+ * credentials are never handed to handlers: send with `fetch`. */
905
+ authHeaders(auth: AuthDef): Promise<Record<string, string>>;
906
+ /** `fetch`, with the headers of a connection slot or an `auth` resolver set by the runtime
907
+ * (replacing the request's): the handler gets the response, never the credentials. A 401 or
908
+ * 403 drops the cached credentials. */
909
+ fetch(input: string | URL | Request, init?: RequestInit, options?: {
910
+ auth?: AuthDef | ConnectionDef;
911
+ }): Promise<Response>;
912
+ /** Fail with `message` unless `condition` holds (a precondition). To narrow a value, use
913
+ * `if (!x) return ctx.fail(...)` (assertion signatures do not survive destructuring). */
914
+ require(condition: unknown, message: string): void;
915
+ fail(message: string): never;
916
+ }
917
+ export interface ReadCtx extends BaseCtx {
918
+ /**
919
+ * Read-only SQL over the cell's SQLite database: object views by API name and the view's
920
+ * tables by model name, limited to the declared `reads`. Synchronous, so `cell` storage
921
+ * only: with `postgres` storage it fails; use `query`.
922
+ */
923
+ sql<R = Record<string, Json>>(query: string, ...params: SqlParam[]): R[];
924
+ /**
925
+ * `sql`, asynchronous, in the storage's dialect (SQLite with `?` in a cell, Postgres with
926
+ * `$1` in `postgres` storage, where it sees this view instance's committed rows: the
927
+ * handler's own staged edits are not in it).
928
+ */
929
+ query<R = Record<string, Json>>(query: string, ...params: SqlParam[]): Promise<R[]>;
930
+ /** What the caller may invoke on this view instance (the same policies and evaluator as
931
+ * invocation; advisory). */
932
+ availableActions(options?: {
933
+ kinds?: AvailableAction["kind"][];
934
+ includeDenied?: boolean;
935
+ }): AvailableAction[];
936
+ }
937
+ /** An action's ctx. No `authHeaders` or `fetch`: credentials an action could read could end up
938
+ * in a deferred request and be stored, and its calls to third parties are deferred; deferred
939
+ * requests name their slot or resolver (`{ auth }`). */
940
+ export interface TxCtx extends Omit<ReadCtx, "authHeaders" | "fetch"> {
941
+ readonly invocationId: string;
942
+ readonly deferredFetch: DeferredFetch;
943
+ /** Create an ontology-owned object; the cell generates and returns its key. */
944
+ create<O extends AnyObject>(object: O, values: Partial<Omit<O["$row"], O["$spec"]["key"]>>): string;
945
+ /** Change owned properties (written to the edit log and shipped to ducktail). */
946
+ update<O extends AnyObject>(object: O, key: string, values: Partial<Pick<O["$row"], O["$owned"]>>): void;
947
+ delete(object: AnyObject, key: string): void;
948
+ }
949
+ type Readable = AnyObject | PropRef | ModelDef | HistoryRef;
950
+ type Editable = AnyObject | PropRef;
951
+ /** What a lake-scoped realtime view watches: object types (their lake tables), models and histories. */
952
+ type Watchable = AnyObject | ModelDef | HistoryRef;
953
+ export interface HandlerDef<N extends string = string, I extends z.ZodType = z.ZodType, O extends z.ZodType = z.ZodType, InView extends boolean = boolean> {
954
+ /** Type-level only: whether it runs in a view instance (and so takes a key). */
955
+ readonly $inView?: InView;
956
+ readonly kind: "action" | "read" | "realtime";
957
+ readonly name: N;
958
+ readonly ir: Record<string, unknown>;
959
+ readonly input: I;
960
+ readonly output: O;
961
+ readonly idempotency?: (input: any) => string;
962
+ readonly handler: (args: any) => unknown;
963
+ }
964
+ /** A transactional write in one view instance. `edits` and `reads` are hard limits. */
965
+ export declare function action<const N extends string, V extends ViewDef, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
966
+ description?: string;
967
+ view: V;
968
+ kind: "txWrite";
969
+ /** Through the generated contract (proto3) an array or record the caller left out arrives
970
+ * as `[]` or `{}`, also when optional: treat empty as absent (true of every handler's input). */
971
+ input: I;
972
+ output: O;
973
+ edits: Editable[];
974
+ reads: Readable[];
975
+ /** A key: a repeat with the same key by the same principal replays the first outcome. */
976
+ idempotency?: (input: z.infer<I>) => string;
977
+ /** Actions its deferred requests may continue with (`then`): a hard limit, checked at build time. */
978
+ continuations?: HandlerDef[];
979
+ /** Source-owned properties its deferred requests may show pending values for: a hard limit. */
980
+ pending?: PropRef[];
981
+ handler: (args: {
982
+ input: z.infer<I>;
983
+ view: ViewHandle<V>;
984
+ ctx: TxCtx;
985
+ }) => z.input<O> | Promise<z.input<O>>;
986
+ }): HandlerDef<N, I, O, true>;
987
+ /** A read: `txRead` in one view instance (in its cell), or `read` against the lake (no view). */
988
+ export declare function read<const N extends string, V extends ViewDef, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
989
+ description?: string;
990
+ view: V;
991
+ kind: "txRead";
992
+ input: I;
993
+ output: O;
994
+ reads: Readable[];
995
+ handler: (args: {
996
+ input: z.infer<I>;
997
+ view: ViewHandle<V>;
998
+ ctx: ReadCtx;
999
+ }) => z.input<O> | Promise<z.input<O>>;
1000
+ }): HandlerDef<N, I, O, true>;
1001
+ export declare function read<const N extends string, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
1002
+ description?: string;
1003
+ kind: "read";
1004
+ input: I;
1005
+ output: O;
1006
+ reads: Readable[];
1007
+ handler: (args: {
1008
+ input: z.infer<I>;
1009
+ ctx: LakeReadCtx;
1010
+ }) => z.input<O> | Promise<z.input<O>>;
1011
+ }): HandlerDef<N, I, O, false>;
1012
+ /**
1013
+ * A realtime view: a read whose result is pushed to its subscribers (a server-streaming RPC of
1014
+ * the generated contract) on subscription and then whenever it changes. Two kinds:
1015
+ *
1016
+ * - **cell-scoped** (`view`): subscribers attach to one view instance (the request's key); the
1017
+ * handler runs like a txRead, in the cell, as the subscriber (Cedar and field masking
1018
+ * included), after every commit of that cell (actions, approvals, ducktail pushes and
1019
+ * pulls). Only a changed result is pushed.
1020
+ * - **lake-scoped** (`watch`): no view, for grids and lists across cells; the handler runs like
1021
+ * a view-less read, in the worker against `ctx.lake`, again whenever the lake snapshot of a
1022
+ * watched object, model or history advances (polled every `REALTIME_POLL_S`). Everything it
1023
+ * watches must also be in its `reads`.
1024
+ */
1025
+ export declare function realtime<const N extends string, V extends ViewDef, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
1026
+ description?: string;
1027
+ view: V;
1028
+ input: I;
1029
+ output: O;
1030
+ reads: Readable[];
1031
+ handler: (args: {
1032
+ input: z.infer<I>;
1033
+ view: ViewHandle<V>;
1034
+ ctx: ReadCtx;
1035
+ }) => z.input<O> | Promise<z.input<O>>;
1036
+ }): HandlerDef<N, I, O, true>;
1037
+ export declare function realtime<const N extends string, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
1038
+ description?: string;
1039
+ watch: Watchable[];
1040
+ input: I;
1041
+ output: O;
1042
+ reads: Readable[];
1043
+ handler: (args: {
1044
+ input: z.infer<I>;
1045
+ ctx: LakeReadCtx;
1046
+ }) => z.input<O> | Promise<z.input<O>>;
1047
+ }): HandlerDef<N, I, O, false>;
1048
+ /** Cedar policy text, built with `cedar`...``. */
1049
+ export interface CedarText {
1050
+ readonly kind: "cedar";
1051
+ readonly text: string;
1052
+ }
1053
+ type CedarPart = CedarText | HandlerDef | ViewDef | AnyObject | PropRef | HistoryRef | string | number | boolean;
1054
+ /** The Cedar action of a handler: `followUpInvoice` -> `FollowUpInvoice`. */
1055
+ export declare const cedarActionId: (name: string) => string;
1056
+ /**
1057
+ * Cedar with typed interpolation: a handler becomes its action (`Action::"FollowUpInvoice"`),
1058
+ * a transactional view its entity type (`Customer`, for `resource is ${CustomerView}`), an
1059
+ * object type `ObjectType::"Customer"`, a property `Property::"Customer.email"`, a history
1060
+ * `Model::"customer__changes"`, a string a Cedar string literal, a number or boolean itself.
1061
+ */
1062
+ export declare function cedar(strings: TemplateStringsArray, ...parts: CedarPart[]): CedarText;
1063
+ /** The runtime's own Cedar actions and the lake resource. */
1064
+ export declare const readField: CedarText;
1065
+ export declare const query: CedarText;
1066
+ /** Every approve action (`action in ${approve}`): approving any parked invocation. */
1067
+ export declare const approve: CedarText;
1068
+ /** Approving a parked invocation of one action, with `context.input` typed like the action's
1069
+ * (`action == ${approveOf(followUpInvoice)}`). */
1070
+ export declare function approveOf(action: HandlerDef): CedarText;
1071
+ export declare const lake: CedarText;
1072
+ /** Who may open a space: `permit(principal in ${group("sales")}, action == ${openSpace}, resource == ${space("pipeline")});`. */
1073
+ export declare const openSpace: CedarText;
1074
+ /** A space of the project (`spaces/<id>/`), a Cedar resource. */
1075
+ export declare function space(id: string): CedarText;
1076
+ /** A group: the token's subject is in each group its `groups` attribute lists (comma-separated). */
1077
+ export declare function group(name: string): CedarText;
1078
+ export interface PolicyDef {
1079
+ readonly kind: "policy";
1080
+ readonly id: string;
1081
+ readonly text: string;
1082
+ readonly loc: string | null;
1083
+ }
1084
+ /** One Cedar policy (exactly one `permit` or `forbid`), validated against the generated schema at build time. */
1085
+ export declare function policy(id: string, text: CedarText): PolicyDef;
1086
+ export interface OntologySpec {
1087
+ /** Models not reachable from objects, links or views (reachable ones are found). */
1088
+ models?: ModelDef[];
1089
+ objects?: AnyObject[];
1090
+ links?: LinkDef[];
1091
+ resolutions?: ReturnType<typeof resolution>[];
1092
+ views?: ViewDef[];
1093
+ actions?: HandlerDef[];
1094
+ reads?: HandlerDef[];
1095
+ /** Realtime views (`realtime`): reads pushed to subscribers whenever their result changes. */
1096
+ realtime?: HandlerDef[];
1097
+ /** Per-deployment secrets and settings handlers read (`ctx.secrets`, `ctx.settings`). */
1098
+ env?: Record<string, EnvDef>;
1099
+ policies?: PolicyDef[];
1100
+ /** Credential resolvers for deferred (and live) requests. */
1101
+ auths?: AuthDef[];
1102
+ /** Third-party accounts each environment binds (`connection`), for deferred (and live)
1103
+ * requests and pipelines. Prefer `slots` (`defineSlots`). */
1104
+ connections?: ConnectionDef[];
1105
+ /** Custom streams records are written to through Tilde's Ingress (`stream`). */
1106
+ streams?: StreamDef[];
1107
+ /** Connection slots (`defineSlots`): third-party accounts each environment binds. */
1108
+ slots?: {
1109
+ readonly [name: string]: ConnectionDef;
1110
+ };
1111
+ /** Raw secrets the pipelines take (`defineSecrets`), supplied by each environment. */
1112
+ secrets?: {
1113
+ readonly [name: string]: SecretRef;
1114
+ };
1115
+ /** The pipelines that feed the sources (`source(name, { pipeline })`). Once there is one,
1116
+ * every source read must have one, and the rollout builds ducktail's config from them. */
1117
+ pipelines?: PipelineSource[];
1118
+ /** Where the data lives (default `cell`); it also decides the dialect of every SQL text. */
1119
+ storage?: Storage;
1120
+ /** Named places models can materialize to besides the storage (`model({ destination })`),
1121
+ * e.g. `{ events: "clickhouse" }` for append-heavy logs and events. Postgres storage only. */
1122
+ destinations?: Record<string, DestinationKind>;
1123
+ }
1124
+ export interface Ontology extends Required<OntologySpec> {
1125
+ readonly kind: "ontology";
1126
+ }
1127
+ /** The default export of `<root>/ontology.ts`. */
1128
+ export declare function ontology<const S extends OntologySpec>(spec: S): Ontology & S;
1129
+ /** Read a project file at build time (the build runner provides it; sandboxed to the root). */
1130
+ export type ReadFile = (path: string) => string;
1131
+ /** The JSON IR consumed by the Rust core. Locations are made relative to `root`. */
1132
+ export declare function toIR(o: Ontology, root: string, readFile: ReadFile): Json;