@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.js ADDED
@@ -0,0 +1,1083 @@
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 { webhookHeaders } from "./catalog.js";
45
+ // ---------------------------------------------------------------------------- locations
46
+ /** `file.ts:line:col` of the user code that called a builder (for error messages). */
47
+ function callSite() {
48
+ const stack = new Error().stack?.split("\n") ?? [];
49
+ for (const frame of stack.slice(1)) {
50
+ // `file://` URLs, or absolute paths where a source map gave the frame its source.
51
+ const m = frame.match(/((?:file:\/\/)?\/[^\s()]+):(\d+):(\d+)/);
52
+ const file = m && (m[1].startsWith("/") ? `file://${m[1]}` : m[1]);
53
+ if (m && file && !file.includes("/ts/sdk/") && !file.includes("/node_modules/") && !file.includes("/.tilde/"))
54
+ return `${file}:${m[2]}:${m[3]}`;
55
+ }
56
+ return null;
57
+ }
58
+ /** Tagged template for SQL. Only other `sql` fragments (including `ref(...)` etc.) can be interpolated. */
59
+ export function sql(strings, ...parts) {
60
+ let out = strings[0];
61
+ parts.forEach((p, i) => {
62
+ if (typeof p !== "object" || p === null || typeof p.sql !== "string") {
63
+ throw new Error("sql``: only sql`` fragments can be interpolated");
64
+ }
65
+ out += p.sql + strings[i + 1];
66
+ });
67
+ return { sql: out };
68
+ }
69
+ // ---------------------------------------------------------------------------- types
70
+ /** A property or column type. Immutable: every modifier returns a new value. */
71
+ export class Prop {
72
+ type;
73
+ spec;
74
+ constructor(type, spec = {}) {
75
+ this.type = type;
76
+ this.spec = spec;
77
+ }
78
+ // deno-lint-ignore no-explicit-any
79
+ with(extra) {
80
+ return new Prop(this.type, { ...this.spec, ...extra, loc: this.spec.loc ?? callSite() });
81
+ }
82
+ /** Nullable. */
83
+ optional() {
84
+ return this.with({ optional: true });
85
+ }
86
+ /** Owned by the ontology: edited by actions (in the cell edit log), never mapped from a source. */
87
+ owned() {
88
+ return this.with({ owned: true });
89
+ }
90
+ /** Mapping: a SQL expression over the object's source model columns. */
91
+ map(expr) {
92
+ return this.with({ map: expr.sql });
93
+ }
94
+ /** Value of an owned property before any edit. */
95
+ default(value) {
96
+ return this.with({ default: value });
97
+ }
98
+ /** Stable physical column id (pin it when renaming the property). */
99
+ id(id) {
100
+ return this.with({ id });
101
+ }
102
+ describe(description) {
103
+ return this.with({ description });
104
+ }
105
+ }
106
+ const scalar = (type) => new Prop(type, { loc: callSite() });
107
+ export const t = {
108
+ string: () => scalar("string"),
109
+ /** An integer within ±2^53 (larger values: `t.string()`). As a key or ref target, a string. */
110
+ int: () => scalar("int"),
111
+ float: () => scalar("float"),
112
+ bool: () => scalar("bool"),
113
+ /** RFC 3339 text. */
114
+ timestamp: () => scalar("timestamp"),
115
+ /** `YYYY-MM-DD`. */
116
+ date: () => scalar("date"),
117
+ /** Exact decimal text (a number in SQL inside cells, up to 15 digits). */
118
+ decimal: (precision, scale) => scalar(`decimal(${precision},${scale})`),
119
+ enum: (...values) => scalar(`enum(${values.join(",")})`),
120
+ array: (of) => new Prop(`array<${of.type}>`, { loc: callSite() }),
121
+ /** Reference to another object type: its key, which handlers always see as a string. */
122
+ ref: (object) => scalar(`ref<${object}>`),
123
+ };
124
+ /** The zod schema of a property type (keys and refs as strings, decimals as text). */
125
+ function zodOf(p) {
126
+ const base = (type) => {
127
+ if (type === "string" || type.startsWith("ref<") || type === "timestamp" || type === "date")
128
+ return z.string();
129
+ if (type === "int")
130
+ return z.number().int();
131
+ if (type === "float")
132
+ return z.number();
133
+ if (type === "bool")
134
+ return z.boolean();
135
+ if (type.startsWith("decimal("))
136
+ return z.string().regex(/^-?\d+(\.\d+)?$/, "a decimal number as text");
137
+ if (type.startsWith("enum("))
138
+ return z.enum(type.slice(5, -1).split(","));
139
+ const m = type.match(/^array<(.+)>$/);
140
+ if (m)
141
+ return z.array(base(m[1]));
142
+ return z.unknown();
143
+ };
144
+ const s = base(p.type);
145
+ return p.spec.optional ? s.nullable() : s;
146
+ }
147
+ // ---------------------------------------------------------------------------- sources and models
148
+ /** A ducktail raw stream: `lake.raw.<pipeline>__<stream>`. */
149
+ export class SourceDef {
150
+ pipeline;
151
+ stream;
152
+ loc;
153
+ kind = "source";
154
+ id;
155
+ table;
156
+ constructor(pipeline, stream, loc) {
157
+ this.pipeline = pipeline;
158
+ this.stream = stream;
159
+ this.loc = loc;
160
+ this.id = `src:${pipeline}.${stream}`;
161
+ this.table = `lake.raw.${pipeline}__${stream}`;
162
+ }
163
+ }
164
+ export function source(name, spec) {
165
+ if (typeof spec === "string")
166
+ return new SourceDef(name, spec, callSite());
167
+ if (spec.pipeline.name !== null && spec.pipeline.name !== name) {
168
+ throw new Error(`${callSite() ?? ""} this pipeline is named \`${spec.pipeline.name}\`: source("${spec.pipeline.name}", { pipeline })`);
169
+ }
170
+ return new PipelineSource(name, spec.pipeline, callSite());
171
+ }
172
+ /**
173
+ * A custom stream: records that enter the environment through Tilde's Ingress
174
+ * (`IngressService.WriteRecords`, by API keys, people and agents with `write_streams` on the
175
+ * project, or the environment's own worker), each validated against `schema` and keyed by `key`
176
+ * (a string or number property: a newer record of a key replaces the older). They land in
177
+ * `lake.raw.ingress__<name>`: read it with `src()` and `changes()` like any source (the payload
178
+ * is the record). List streams in `ontology({ streams })`.
179
+ */
180
+ export class StreamDef extends SourceDef {
181
+ schema;
182
+ key;
183
+ reference;
184
+ constructor(name, schema, key, reference, loc) {
185
+ super("ingress", name, loc);
186
+ this.schema = schema;
187
+ this.key = key;
188
+ this.reference = reference;
189
+ }
190
+ }
191
+ /**
192
+ * `reference`: static records the project ships with the stream (a solution's tenant
193
+ * configuration, say). The build validates them against `schema` and compiles them into the
194
+ * version; every rollout of the version loads them into the environment through Ingress, so a
195
+ * redeploy updates them (a record replaces the earlier one of its key; a record dropped from the
196
+ * list is not deleted).
197
+ */
198
+ export function stream(name, options) {
199
+ return new StreamDef(name, options.schema, options.key, options.reference ?? [], callSite());
200
+ }
201
+ export function sqlFile(path) {
202
+ return { kind: "sqlFile", path, loc: callSite() };
203
+ }
204
+ export const tests = {
205
+ unique: (column) => ({ kind: "unique", column }),
206
+ notNull: (column) => ({ kind: "not_null", column }),
207
+ acceptedValues: (column, values) => ({ kind: "accepted_values", column, values }),
208
+ relationships: (column, to, field) => ({ kind: "relationships", column, to, field }),
209
+ };
210
+ export class ModelDef {
211
+ spec;
212
+ loc;
213
+ kind = "model";
214
+ id;
215
+ /** Set by the transactional view a cell model belongs to (one view only: a second is a build error). */
216
+ cell = null;
217
+ constructor(spec, loc) {
218
+ this.spec = spec;
219
+ this.loc = loc;
220
+ this.id = `model:${spec.name}`;
221
+ }
222
+ }
223
+ export function model(spec) {
224
+ return new ModelDef(spec, callSite());
225
+ }
226
+ /**
227
+ * ducktail's `cdc_current`, verbatim from its README ("Current state from CDC"): the latest
228
+ * row per `_key` of a CDC stream (`_key, _pos, _seq, _source_ts, payload, _deleted`), applying
229
+ * deletes, honouring truncates and snapshot restarts (`t` rows: an incremental pre-hook clears
230
+ * the target) and carrying unchanged TOAST columns forward. Spread it into a model:
231
+ * `model({ name: "app_users", schema: "current", ...cdcCurrent(source("app", "users")) })`.
232
+ */
233
+ export function cdcCurrent(of) {
234
+ const body = (changes, base) => sql `WITH __changes AS (
235
+ SELECT _key, _op, _pos, _seq, _source_ts, _headers, payload
236
+ FROM ${changes} __c
237
+ WHERE _change_type = 'insert'
238
+ ),
239
+ __cutoff AS (
240
+ SELECT _pos, _seq FROM __changes WHERE _op = 't' ORDER BY _pos DESC, _seq DESC LIMIT 1
241
+ ),
242
+ __versions AS (
243
+ SELECT _key,
244
+ list({'p': payload,
245
+ 'o': coalesce((_headers -> 'unchanged_toast')::VARCHAR[], []::VARCHAR[]),
246
+ 'op': _op, 'pos': _pos, 'seq': _seq, 'ts': _source_ts}
247
+ ORDER BY _pos, _seq) AS v
248
+ FROM __changes c
249
+ WHERE _op <> 't' AND _key IS NOT NULL
250
+ AND NOT EXISTS (SELECT 1 FROM __cutoff t WHERE (c._pos, c._seq) < (t._pos, t._seq))
251
+ GROUP BY _key
252
+ )
253
+ SELECT __versions._key,
254
+ v[-1].pos AS _pos,
255
+ v[-1].seq AS _seq,
256
+ v[-1].ts AS _source_ts,
257
+ CASE WHEN v[-1].op = 'd' THEN NULL ELSE
258
+ list_reduce(
259
+ list_transform(v, lambda x: {'p': x.p, 'o': x.o}),
260
+ lambda acc, x: CASE WHEN len(x.o) = 0 THEN x ELSE
261
+ {'p': json_merge_patch(x.p, to_json(map_from_entries(list_transform(x.o, lambda k: {'k': k, 'v': acc.p -> k})))),
262
+ 'o': []::VARCHAR[]} END,
263
+ {'p': coalesce(${base}, '{}')::JSON, 'o': []::VARCHAR[]}
264
+ ).p
265
+ END AS payload,
266
+ v[-1].op = 'd' AS _deleted
267
+ FROM __versions`;
268
+ // Postgres: the same result without lists and lambdas. The latest version per key wins; a
269
+ // column it lists as unchanged TOAST comes from the latest earlier version of the window
270
+ // that carried it, else from the stored row. (A fold in DuckDB; here a lookup per column,
271
+ // which differs only if a delete inside the window precedes an update that omits a column.)
272
+ const pgBody = (changes, base, current) => sql `WITH __changes AS (
273
+ SELECT _key, _op, _pos, _seq, _source_ts, _headers, payload
274
+ FROM ${changes} AS __c
275
+ WHERE _change_type = 'insert'
276
+ ),
277
+ __cutoff AS (
278
+ SELECT _pos, _seq FROM __changes WHERE _op = 't' ORDER BY _pos DESC, _seq DESC LIMIT 1
279
+ ),
280
+ __versions AS (
281
+ SELECT c._key, c._op, c._pos, c._seq, c._source_ts, c.payload,
282
+ coalesce(c._headers -> 'unchanged_toast', '[]'::jsonb) AS _toast,
283
+ row_number() OVER (PARTITION BY c._key ORDER BY c._pos DESC, c._seq DESC) AS _n
284
+ FROM __changes AS c
285
+ WHERE c._op <> 't' AND c._key IS NOT NULL
286
+ AND NOT EXISTS (SELECT 1 FROM __cutoff AS t WHERE (c._pos, c._seq) < (t._pos, t._seq))
287
+ )
288
+ SELECT v._key,
289
+ v._pos,
290
+ v._seq,
291
+ v._source_ts,
292
+ CASE WHEN v._op = 'd' THEN NULL
293
+ WHEN jsonb_array_length(v._toast) = 0 THEN v.payload
294
+ ELSE v.payload || coalesce((
295
+ SELECT jsonb_object_agg(k.col, x.val)
296
+ FROM jsonb_array_elements_text(v._toast) AS k(col)
297
+ CROSS JOIN LATERAL (
298
+ SELECT coalesce(
299
+ (SELECT p.payload -> k.col FROM __versions AS p
300
+ WHERE p._key = v._key AND p._n > 1 AND NOT p._toast ? k.col
301
+ ORDER BY p._n LIMIT 1),
302
+ ${base} -> k.col) AS val
303
+ ) AS x
304
+ WHERE x.val IS NOT NULL), '{}'::jsonb)
305
+ END AS payload,
306
+ v._op = 'd' AS _deleted
307
+ FROM __versions AS v${current}
308
+ WHERE v._n = 1`;
309
+ return {
310
+ materialized: "incremental",
311
+ uniqueKey: "_key",
312
+ incrementalStrategy: "delete+insert",
313
+ sql: ({ changes, isIncremental, self, dialect }) => {
314
+ if (dialect === "postgres") {
315
+ return isIncremental
316
+ ? pgBody(changes(of), sql `__current.payload`, sql `\nLEFT JOIN ${self} AS __current ON __current._key = v._key`)
317
+ : pgBody(changes(of), sql `NULL::jsonb`, sql ``);
318
+ }
319
+ return isIncremental
320
+ ? sql `${body(changes(of), sql `__current.payload`)}
321
+ LEFT JOIN ${self} __current ON __current._key = __versions._key`
322
+ : body(changes(of), sql `NULL`);
323
+ },
324
+ preHooks: {
325
+ incremental: [
326
+ ({ changes, self }) => sql `DELETE FROM ${self} WHERE EXISTS (SELECT 1 FROM ${changes(of)} c WHERE c._op = 't' AND c._change_type = 'insert')`,
327
+ ],
328
+ },
329
+ };
330
+ }
331
+ /**
332
+ * An object type. Objects without a `source` are owned by the ontology (created by actions).
333
+ * `history: true` keeps every change of its properties in `lake.ontology.<id>__changes` from
334
+ * then on (read it with `history(Object)`); `historyAt` names a source-owned timestamp
335
+ * property that dates source-side changes (else the time the lake saw them).
336
+ *
337
+ * With Postgres storage, an object whose `source` materializes to a ClickHouse destination is
338
+ * read there (`ctx.lake.destination(<name>).query`): read-only (no owned properties, no
339
+ * history), its mappings ClickHouse SQL. `replicas: ["events"]` keeps a copy of a storage
340
+ * object's table in that destination, so SQL there can join it.
341
+ */
342
+ export function object(name, spec) {
343
+ const def = { $kind: "object", $name: name, $spec: spec, $loc: callSite() };
344
+ for (const [property, prop] of Object.entries(spec.properties))
345
+ def[property] = { kind: "prop", object: name, property, prop };
346
+ return def;
347
+ }
348
+ export function history(object) {
349
+ return { kind: "history", object: object.$name, model: `${object.$spec.id}__changes` };
350
+ }
351
+ /** A link type: 1:1 / 1:N via a ref property on `to`, or N:M with its own model. */
352
+ export function link(name, spec) {
353
+ const ir = { name, id: spec.id, from: spec.from.$name, to: spec.to.$name, cardinality: spec.cardinality, loc: callSite() };
354
+ if ("via" in spec) {
355
+ ir.via = `${spec.to.$name}.${spec.via}`;
356
+ return { kind: "link", name, ir, source: null };
357
+ }
358
+ Object.assign(ir, { source: spec.source.id, map: { from: spec.map.from.sql, to: spec.map.to.sql } });
359
+ return { kind: "link", name, ir, source: spec.source };
360
+ }
361
+ /** One member type of an entity resolution: feature name -> SQL over its properties. */
362
+ export function member(object, features) {
363
+ return { object: object.$name, features: Object.fromEntries(Object.entries(features).map(([k, v]) => [k, v.sql])) };
364
+ }
365
+ /** Entity resolution across object types (deterministic rules, fuzzy candidates). */
366
+ export function resolution(name, spec) {
367
+ return { name, ...spec, fuzzy: spec.fuzzy ?? null, loc: callSite() };
368
+ }
369
+ // ---------------------------------------------------------------------------- transactional views
370
+ /**
371
+ * A transactional view: a portion of the ontology graph materialised per key in one celld
372
+ * SQLite cell (`<view id>:<key>`) for hot transactional work. Its `tables` are ducktail cell
373
+ * models, each partitioned by the `key` column; the root table is the one keyed by `key`.
374
+ * `dependsOn` lists the objects and links the view serves; the build warns where it disagrees
375
+ * with what the models' lineage shows. For ontology-owned objects (no source) it is what makes
376
+ * them members: an ontology-owned object belongs to the view that lists it.
377
+ */
378
+ export class ViewDef {
379
+ name;
380
+ spec;
381
+ loc;
382
+ kind = "view";
383
+ id;
384
+ constructor(name, spec, loc) {
385
+ this.name = name;
386
+ this.spec = spec;
387
+ this.loc = loc;
388
+ this.id = name.replace(/[A-Z]/g, (c, i) => (i ? "_" : "") + c.toLowerCase());
389
+ for (const m of Object.values(spec.tables))
390
+ m.cell = { view: this.id, partitionBy: spec.key };
391
+ }
392
+ }
393
+ export function transactionalView(name, spec) {
394
+ return new ViewDef(name, spec, callSite());
395
+ }
396
+ export const secret = () => ({ kind: "secret", default: null });
397
+ export const setting = (defaultValue) => ({ kind: "setting", default: defaultValue ?? null });
398
+ /** A connection slot; `provider` defaults to the slot's name. */
399
+ export function connection(name, options = {}) {
400
+ return { kind: "connection", name, provider: options.provider ?? name, type: options.type ?? null, loc: callSite() };
401
+ }
402
+ /** A connection slot of a Tilde connection provider (and optionally one of its types), named by
403
+ * its key in `defineSlots`. */
404
+ export function slot(provider, options = {}) {
405
+ return { kind: "slot", provider, type: options.type ?? null, loc: callSite() };
406
+ }
407
+ /**
408
+ * The connection slots the ontology needs, by name: `defineSlots({ linear: slot("linear"),
409
+ * github: slot("github") })`. Pipelines and requests name them as `slots.linear` (a pipeline
410
+ * helper takes only a slot of its provider), each environment binds them to its organization's
411
+ * connections, and `ontology({ slots })` declares them.
412
+ */
413
+ export function defineSlots(slots) {
414
+ return Object.fromEntries(Object.entries(slots).map(([name, s]) => [name, { kind: "connection", name, provider: s.provider, type: s.type, loc: s.loc }]));
415
+ }
416
+ /**
417
+ * The raw secrets the ontology's pipelines need, by name: `defineSecrets({ PG_PASSWORD:
418
+ * secret() })`, used as `postgres.cdc({ password: secrets.PG_PASSWORD, ... })` and declared with
419
+ * `ontology({ secrets })`. Each environment supplies them (bound to its team's Tilde secrets, or
420
+ * set on the environment); their values never enter the version. Handlers do not see them (that
421
+ * is `env`).
422
+ */
423
+ export function defineSecrets(secrets) {
424
+ const loc = callSite();
425
+ return Object.fromEntries(Object.entries(secrets).map(([name, e]) => {
426
+ if (e.kind !== "secret")
427
+ throw new Error(`${loc ?? ""} defineSecrets: \`${name}\` is a setting, not a secret()`);
428
+ return [name, { kind: "secretRef", name, loc }];
429
+ }));
430
+ }
431
+ /**
432
+ * What feeds a source's raw streams (`lake.raw.<source>__<stream>`): one ducktail pipeline of
433
+ * `type`, optionally through a connection slot, with its streams and ducktail's own config keys
434
+ * (`options`, snake_case as ducktail's README writes them). Made by the helpers below; the build
435
+ * compiles it into the version and the environment's rollout gives it to ducktail.
436
+ */
437
+ export class Pipeline {
438
+ type;
439
+ slot;
440
+ streams;
441
+ options;
442
+ loc;
443
+ name;
444
+ kind = "pipeline";
445
+ constructor(type, slot, streams, options, loc,
446
+ /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
447
+ name = null) {
448
+ this.type = type;
449
+ this.slot = slot;
450
+ this.streams = streams;
451
+ this.options = options;
452
+ this.loc = loc;
453
+ this.name = name;
454
+ }
455
+ /** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
456
+ untypedStreams(...names) {
457
+ return new Pipeline(this.type, this.slot, [...this.streams, ...names], this.options, this.loc, this.name);
458
+ }
459
+ }
460
+ /** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
461
+ export class WebhookPipeline extends Pipeline {
462
+ /** More routes, for event names this SDK's catalog does not know. */
463
+ untypedEvents(routes) {
464
+ const route = this.options.route;
465
+ const options = { ...this.options, route: { ...route, streams: { ...route.streams, ...routes } } };
466
+ return new WebhookPipeline(this.type, this.slot, this.streams, options, this.loc, this.name);
467
+ }
468
+ }
469
+ /** A declared source: a pipeline under its name, whose streams are sources. */
470
+ export class PipelineSource {
471
+ name;
472
+ pipeline;
473
+ loc;
474
+ kind = "pipelineSource";
475
+ constructor(name, pipeline, loc) {
476
+ this.name = name;
477
+ this.pipeline = pipeline;
478
+ this.loc = loc;
479
+ }
480
+ /** One of the pipeline's streams: `lake.raw.<name>__<stream>`. */
481
+ stream(stream) {
482
+ return new SourceDef(this.name, stream, callSite());
483
+ }
484
+ }
485
+ const poll = (kind, slot, o, extra) => new Pipeline(kind, slot, o.streams ?? [], {
486
+ interval: o.interval,
487
+ backfill: o.backfill,
488
+ request_timeout: o.requestTimeout,
489
+ ...extra,
490
+ }, callSite());
491
+ function providerWebhook(provider, o, extra = {}) {
492
+ const headers = webhookHeaders[provider];
493
+ const routes = Object.fromEntries(Object.entries(o.route).filter(([, v]) => v !== undefined));
494
+ return new WebhookPipeline("webhook", o.slot, o.streams, {
495
+ key_header: headers.key,
496
+ route: { header: headers.event, streams: routes, fallback: o.fallback },
497
+ ...extra,
498
+ }, callSite());
499
+ }
500
+ /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
501
+ export const linear = {
502
+ poll: (o) => poll("linear", o.slot, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
503
+ webhook: (o) => providerWebhook("linear", o),
504
+ };
505
+ /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
506
+ export const sentry = {
507
+ poll: (o) => poll("sentry", o.slot, o, {
508
+ organization: o.organization,
509
+ projects: o.projects,
510
+ base_url: o.baseUrl,
511
+ query: o.query,
512
+ full_sweep_interval: o.fullSweepInterval,
513
+ }),
514
+ webhook: (o) => providerWebhook("sentry", o),
515
+ };
516
+ /** GitHub: the connection's webhooks (a GitHub App's), with an optional backfill of history. */
517
+ export const github = {
518
+ webhook: (o) => providerWebhook("github", o, {
519
+ backfill: o.backfill && {
520
+ provider: "github",
521
+ repositories: o.backfill.repositories,
522
+ start: o.backfill.start,
523
+ base_url: o.backfill.baseUrl,
524
+ page_size: o.backfill.pageSize,
525
+ },
526
+ }),
527
+ };
528
+ /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
529
+ export const cloudwatch = {
530
+ poll: (o) => poll("cloudwatch", o.slot, o, {
531
+ region: o.region,
532
+ discovery_interval: o.discoveryInterval,
533
+ period: o.period,
534
+ delay: o.delay,
535
+ clusters: o.clusters,
536
+ accounts: o.accounts,
537
+ discover_metrics: o.discoverMetrics,
538
+ metrics: o.metrics,
539
+ endpoint: o.endpoint,
540
+ }),
541
+ };
542
+ /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
543
+ * `options` are ducktail's keys for it (README, "Polled sources"). */
544
+ export function polled(kind, o) {
545
+ return poll(kind, o.slot, o, o.options ?? {});
546
+ }
547
+ /** ducktail's raw stream of a Postgres table or a Kafka topic. */
548
+ const streamName = (name) => name.replace(/[^A-Za-z0-9]/g, "_").toLowerCase();
549
+ /** A libpq value, quoted where it must be. */
550
+ const libpq = (v) => (/^[^\s'\\]+$/.test(v) ? v : `'${v.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`);
551
+ /** Postgres logical replication of tables (streams `<schema>_<table>`). */
552
+ export const postgres = {
553
+ cdc: (o) => {
554
+ const port = o.port ? ` port=${o.port}` : "";
555
+ const sslmode = o.sslmode ? ` sslmode=${o.sslmode}` : "";
556
+ const connection = {
557
+ kind: "secretText",
558
+ parts: [`host=${libpq(o.host)}${port} user=${libpq(o.user)} password=`, o.password, ` dbname=${libpq(o.database)}${sslmode}`],
559
+ };
560
+ return new Pipeline("postgres", null, o.tables.map(streamName), {
561
+ connection,
562
+ tables: o.tables,
563
+ slot: o.replicationSlot,
564
+ publication: o.publication,
565
+ snapshot_workers: o.snapshotWorkers,
566
+ }, callSite());
567
+ },
568
+ };
569
+ /** Kafka topics (streams: the topic names, lower-cased, other characters `_`). */
570
+ export const kafka = {
571
+ consume: (o) => new Pipeline("kafka", null, o.topics.map(streamName), {
572
+ brokers: o.brokers,
573
+ topics: o.topics,
574
+ start: o.start,
575
+ format: o.format,
576
+ tls: o.tls && { ca_file: o.tls.caFile, verify: o.tls.verify },
577
+ sasl: o.sasl,
578
+ }, callSite()),
579
+ };
580
+ /**
581
+ * A webhook pipeline of the solution's own, which Tilde delivers to (records written through
582
+ * Ingress, a system posting at Tilde): `POST /webhooks/<source>/<stream>`, or one URL routed by
583
+ * a header.
584
+ */
585
+ export function webhook(o) {
586
+ return new Pipeline("webhook", null, o.streams, { key_header: o.keyHeader, route: o.route }, callSite());
587
+ }
588
+ /** Tilde itself. */
589
+ export const tilde = {
590
+ /**
591
+ * The organization's registry events (threads, runs, tasks, invocations, inference usage,
592
+ * messages...), pushed by Tilde to environments that turn them on: only the streams listed
593
+ * are delivered. The source must be named `tilde`.
594
+ */
595
+ events: (o) => new Pipeline("webhook", null, o.streams, { key_header: "x-tilde-key" }, callSite(), "tilde"),
596
+ };
597
+ export function auth(name, resolve) {
598
+ return { kind: "auth", name, resolve, loc: callSite() };
599
+ }
600
+ /** The input a continuation (`DeferredOptions.then`) receives: extend it to type `body`. */
601
+ export const deferredResponse = z.object({
602
+ /** The delivered request's HTTP status (2xx). */
603
+ status: z.number().int(),
604
+ /** The response body: parsed JSON, else the text; null when the body was over 1 MB or not
605
+ * UTF-8 text (a warning says which). */
606
+ body: z.unknown(),
607
+ /** The outbox request's id (the continuation's idempotency key). */
608
+ callId: z.string(),
609
+ /** The invocation that made the request. */
610
+ invocationId: z.string(),
611
+ });
612
+ // ---------------------------------------------------------------------------- reads and verbs
613
+ /** Thrown by `ctx.fail` / `ctx.require`: a business failure (nothing is written). */
614
+ export class ActionError extends Error {
615
+ constructor(message) {
616
+ super(message);
617
+ this.name = "ActionError";
618
+ }
619
+ }
620
+ /** Tag an output field with the ontology property it carries (field masking). The field is
621
+ * nullable: a caller who may not `readField` the property gets null there (and the lake
622
+ * already reads it as NULL), so the output schema and client types say so. */
623
+ export function prop(ref) {
624
+ const schema = zodOf(ref.prop).nullable().meta({ ontologyProperty: `${ref.object}.${ref.property}` });
625
+ propSchemas.set(schema, `${ref.object}.${ref.property}`);
626
+ return schema;
627
+ }
628
+ /** Every `prop()` schema, to find tags the output's JSON Schema loses (transforms, ...). */
629
+ const propSchemas = new WeakMap();
630
+ function refIr(r) {
631
+ if ("kind" in r && r.kind === "prop")
632
+ return { object: r.object, property: r.property };
633
+ if ("kind" in r && r.kind === "model")
634
+ return { model: r.id };
635
+ if ("kind" in r && r.kind === "history")
636
+ return { history: r.object };
637
+ return { object: r.$name, property: null };
638
+ }
639
+ /** Output fields tagged with `prop(...)`: JSON pointer-ish path -> `Object.property`. */
640
+ function taggedFields(schema) {
641
+ const out = [];
642
+ // Paths: property names, `*` for every array item, `{}` for every value of a record, an
643
+ // index for a tuple position; unions and intersections keep the path.
644
+ const walk = (node, path) => {
645
+ if (typeof node !== "object" || node === null)
646
+ return;
647
+ if (typeof node.ontologyProperty === "string")
648
+ out.push({ path, property: node.ontologyProperty });
649
+ for (const [k, v] of Object.entries((node.properties ?? {})))
650
+ walk(v, [...path, k]);
651
+ if (node.items && !Array.isArray(node.items))
652
+ walk(node.items, [...path, "*"]);
653
+ for (const [i, v] of (node.prefixItems ?? []).entries())
654
+ walk(v, [...path, String(i)]);
655
+ if (node.additionalProperties && typeof node.additionalProperties === "object") {
656
+ walk(node.additionalProperties, [...path, "{}"]);
657
+ }
658
+ for (const key of ["anyOf", "oneOf", "allOf"])
659
+ for (const alt of (node[key] ?? []))
660
+ walk(alt, path);
661
+ };
662
+ walk(z.toJSONSchema(schema, { unrepresentable: "any" }), []);
663
+ return out;
664
+ }
665
+ /** `prop()` tags in the zod schema that its JSON Schema does not carry (so they could not be
666
+ * masked: inside a transform, a pipe, a recursive schema, ...); the build refuses them.
667
+ * Occurrences are counted per path on both sides, so a property tagged once where it can be
668
+ * masked and again where it cannot is still caught. */
669
+ function unmaskableTags(schema, masked) {
670
+ const found = new Map();
671
+ // A stack, not a seen-set: a schema shared by two paths counts on both; a cycle stops.
672
+ const stack = new Set();
673
+ const visit = (v) => {
674
+ if (typeof v !== "object" || v === null || stack.has(v))
675
+ return;
676
+ stack.add(v);
677
+ const tag = propSchemas.get(v);
678
+ if (tag)
679
+ found.set(tag, (found.get(tag) ?? 0) + 1);
680
+ const def = v._zod?.def;
681
+ const children = new Set();
682
+ if (def) {
683
+ for (const key of Object.keys(def))
684
+ children.add(def[key]);
685
+ if ("shape" in def)
686
+ children.add(def.shape);
687
+ }
688
+ else if (Array.isArray(v))
689
+ v.forEach((c) => children.add(c));
690
+ else if (Object.getPrototypeOf(v) === Object.prototype)
691
+ Object.values(v).forEach((c) => children.add(c));
692
+ for (const c of children)
693
+ visit(c);
694
+ stack.delete(v);
695
+ };
696
+ visit(schema);
697
+ const counts = new Map();
698
+ for (const m of masked)
699
+ counts.set(m.property, (counts.get(m.property) ?? 0) + 1);
700
+ return [...found].filter(([t, n]) => n > (counts.get(t) ?? 0)).map(([t]) => t);
701
+ }
702
+ function handlerIr(name, kind, view, spec) {
703
+ const masked = taggedFields(spec.output);
704
+ return {
705
+ name,
706
+ kind,
707
+ view: view?.name ?? null,
708
+ description: spec.description ?? null,
709
+ input: z.toJSONSchema(spec.input, { unrepresentable: "any", io: "input" }),
710
+ output: z.toJSONSchema(spec.output, { unrepresentable: "any" }),
711
+ reads: spec.reads.map(refIr),
712
+ edits: (spec.edits ?? []).map(refIr),
713
+ masked,
714
+ unmaskable: unmaskableTags(spec.output, masked),
715
+ idempotent: !!spec.idempotency,
716
+ continuations: (spec.continuations ?? []).map((h) => h.name),
717
+ pending: (spec.pending ?? []).map(refIr),
718
+ ...(spec.watch ? { watch: spec.watch.map(refIr) } : {}),
719
+ loc: callSite(),
720
+ };
721
+ }
722
+ /** A transactional write in one view instance. `edits` and `reads` are hard limits. */
723
+ export function action(name, spec) {
724
+ return { kind: "action", name, ir: handlerIr(name, "txWrite", spec.view, spec), input: spec.input, output: spec.output, idempotency: spec.idempotency, handler: spec.handler };
725
+ }
726
+ export function read(name,
727
+ // deno-lint-ignore no-explicit-any
728
+ spec) {
729
+ return { kind: "read", name, ir: handlerIr(name, spec.kind, spec.view ?? null, spec), input: spec.input, output: spec.output, handler: spec.handler };
730
+ }
731
+ export function realtime(name,
732
+ // deno-lint-ignore no-explicit-any
733
+ spec) {
734
+ const ir = handlerIr(name, spec.view ? "txRead" : "read", spec.view ?? null, { ...spec, watch: spec.watch ?? [] });
735
+ return { kind: "realtime", name, ir, input: spec.input, output: spec.output, handler: spec.handler };
736
+ }
737
+ /** The Cedar action of a handler: `followUpInvoice` -> `FollowUpInvoice`. */
738
+ export const cedarActionId = (name) => name.charAt(0).toUpperCase() + name.slice(1);
739
+ /**
740
+ * Cedar with typed interpolation: a handler becomes its action (`Action::"FollowUpInvoice"`),
741
+ * a transactional view its entity type (`Customer`, for `resource is ${CustomerView}`), an
742
+ * object type `ObjectType::"Customer"`, a property `Property::"Customer.email"`, a history
743
+ * `Model::"customer__changes"`, a string a Cedar string literal, a number or boolean itself.
744
+ */
745
+ export function cedar(strings, ...parts) {
746
+ const render = (p) => {
747
+ if (typeof p === "string")
748
+ return JSON.stringify(p);
749
+ if (typeof p === "number") {
750
+ if (!Number.isInteger(p))
751
+ throw new Error(`cedar: ${p} is not an integer (Cedar has no floats)`);
752
+ return String(p);
753
+ }
754
+ if (typeof p === "boolean")
755
+ return String(p);
756
+ if (p instanceof ViewDef)
757
+ return p.name;
758
+ if ("$kind" in p && p.$kind === "object")
759
+ return `ObjectType::${JSON.stringify(p.$name)}`;
760
+ p = p;
761
+ if (p.kind === "cedar")
762
+ return p.text;
763
+ if (p.kind === "prop")
764
+ return `Property::${JSON.stringify(`${p.object}.${p.property}`)}`;
765
+ if (p.kind === "history")
766
+ return `Model::${JSON.stringify(p.model)}`;
767
+ if (p.kind === "action" || p.kind === "read" || p.kind === "realtime")
768
+ return `Action::${JSON.stringify(cedarActionId(p.name))}`;
769
+ throw new Error("cedar: cannot interpolate this value");
770
+ };
771
+ return { kind: "cedar", text: strings.reduce((out, str, i) => out + str + (i < parts.length ? render(parts[i]) : ""), "") };
772
+ }
773
+ /** The runtime's own Cedar actions and the lake resource. */
774
+ export const readField = { kind: "cedar", text: 'Action::"readField"' };
775
+ export const query = { kind: "cedar", text: 'Action::"query"' };
776
+ /** Every approve action (`action in ${approve}`): approving any parked invocation. */
777
+ export const approve = { kind: "cedar", text: 'Action::"approve"' };
778
+ /** Approving a parked invocation of one action, with `context.input` typed like the action's
779
+ * (`action == ${approveOf(followUpInvoice)}`). */
780
+ export function approveOf(action) {
781
+ if (action.kind !== "action")
782
+ throw new Error(`approveOf: \`${action.name}\` is a read; only actions are approved`);
783
+ return { kind: "cedar", text: `Action::${JSON.stringify(`Approve${cedarActionId(action.name)}`)}` };
784
+ }
785
+ export const lake = { kind: "cedar", text: 'Lake::"lake"' };
786
+ /** Who may open a space: `permit(principal in ${group("sales")}, action == ${openSpace}, resource == ${space("pipeline")});`. */
787
+ export const openSpace = { kind: "cedar", text: 'Action::"OpenSpace"' };
788
+ /** A space of the project (`spaces/<id>/`), a Cedar resource. */
789
+ export function space(id) {
790
+ return { kind: "cedar", text: `Space::${JSON.stringify(id)}` };
791
+ }
792
+ /** A group: the token's subject is in each group its `groups` attribute lists (comma-separated). */
793
+ export function group(name) {
794
+ return { kind: "cedar", text: `Group::${JSON.stringify(name)}` };
795
+ }
796
+ /** One Cedar policy (exactly one `permit` or `forbid`), validated against the generated schema at build time. */
797
+ export function policy(id, text) {
798
+ return { kind: "policy", id, text: text.text, loc: callSite() };
799
+ }
800
+ /** The default export of `<root>/ontology.ts`. */
801
+ export function ontology(spec) {
802
+ return {
803
+ kind: "ontology",
804
+ models: [],
805
+ objects: [],
806
+ links: [],
807
+ resolutions: [],
808
+ views: [],
809
+ actions: [],
810
+ reads: [],
811
+ realtime: [],
812
+ env: {},
813
+ policies: [],
814
+ auths: [],
815
+ connections: [],
816
+ streams: [],
817
+ slots: {},
818
+ secrets: {},
819
+ pipelines: [],
820
+ storage: "cell",
821
+ destinations: {},
822
+ ...spec,
823
+ };
824
+ }
825
+ /** Render a `sqlFile` template for one run (see `SqlFile`). */
826
+ function renderSqlFile(text, ctx, byName, src) {
827
+ let out = text;
828
+ const block = /\{%-?\s*if\s+is_incremental\(\)\s*-?%\}([\s\S]*?)(?:\{%-?\s*else\s*-?%\}([\s\S]*?))?\{%-?\s*endif\s*-?%\}/g;
829
+ out = out.replace(block, (_m, a, b) => (ctx.isIncremental ? a : b ?? ""));
830
+ const arg = (s) => s.trim().replace(/^['"]|['"]$/g, "");
831
+ const relation = (expr) => {
832
+ const r = expr.match(/^ref\(\s*(['"][^'"]+['"])\s*\)$/);
833
+ if (r)
834
+ return byName(arg(r[1]));
835
+ const s = expr.match(/^src\(\s*(['"][^'"]+['"])\s*,\s*(['"][^'"]+['"])\s*\)$/);
836
+ if (s)
837
+ return src(arg(s[1]), arg(s[2]));
838
+ throw new Error(`sqlFile: unknown relation \`${expr}\` (ref('model') or src('pipeline', 'stream'))`);
839
+ };
840
+ return out.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_m, expr) => {
841
+ if (expr === "this")
842
+ return ctx.self.sql;
843
+ const c = expr.match(/^changes\(\s*([\s\S]+)\s*\)$/);
844
+ if (c)
845
+ return ctx.changes(relation(c[1].trim())).sql;
846
+ const rel = relation(expr);
847
+ return rel.kind === "model" ? ctx.ref(rel).sql : ctx.src(rel).sql;
848
+ });
849
+ }
850
+ /** A source's raw table: `lake.raw.<pipeline>__<stream>` in the lake, `raw_<pipeline>__<stream>`
851
+ * in a Postgres environment schema (ducktail's naming). */
852
+ function sourceTable(s, dialect) {
853
+ return dialect === "duckdb" ? s.table : `raw_${s.pipeline}__${s.stream}`;
854
+ }
855
+ /** A relation name as Postgres SQL takes any id, reserved words included (`"check"`, `"order"`). */
856
+ const pgIdent = (name) => `"${name.replaceAll('"', '""')}"`;
857
+ function evaluateModel(m, incremental, dialect, readFile, byName, sources) {
858
+ const deps = new Set();
859
+ const found = [];
860
+ const note = (r) => {
861
+ if (!deps.has(r.id))
862
+ found.push(r);
863
+ deps.add(r.id);
864
+ };
865
+ // An object type's generated table: a dependency by id, nothing to evaluate.
866
+ const objectTable = (o) => {
867
+ if (o.$kind !== "object")
868
+ return null;
869
+ const spec = o.$spec;
870
+ return { id: `model:${spec.id}`, table: dialect === "duckdb" ? `lake.ontology.${spec.id}` : pgIdent(spec.id) };
871
+ };
872
+ const ctx = {
873
+ ref: (r) => {
874
+ const o = objectTable(r);
875
+ if (o) {
876
+ deps.add(o.id);
877
+ return { sql: o.table };
878
+ }
879
+ r = r;
880
+ note(r);
881
+ // Postgres (and a ClickHouse destination): one schema (database) per environment, so
882
+ // relations are named unqualified; ClickHouse takes double-quoted identifiers too.
883
+ return { sql: dialect === "duckdb" ? `lake.${r.spec.schema ?? "main"}.${r.spec.name}` : pgIdent(r.spec.name) };
884
+ },
885
+ src: (s) => {
886
+ note(s);
887
+ return { sql: dialect === "duckdb" ? sourceTable(s, dialect) : pgIdent(sourceTable(s, dialect)) };
888
+ },
889
+ changes: (r) => {
890
+ const o = objectTable(r);
891
+ if (o) {
892
+ deps.add(o.id);
893
+ return { sql: `{{changes:${o.id}}}` };
894
+ }
895
+ r = r;
896
+ note(r);
897
+ return { sql: `{{changes:${r.id}}}` };
898
+ },
899
+ isIncremental: incremental,
900
+ dialect,
901
+ // Rendered in both runs (helpers destructure it); the build rejects it in full SQL.
902
+ self: { sql: "{{this}}" },
903
+ batchStart: { sql: "{{batch_start}}" },
904
+ batchEnd: { sql: "{{batch_end}}" },
905
+ };
906
+ const body = "kind" in m.spec.sql && m.spec.sql.kind === "sqlFile"
907
+ ? renderSqlFile(readFile(m.spec.sql.path), ctx, byName, (p, s) => sources.get(`src:${p}.${s}`) ?? new SourceDef(p, s, null))
908
+ : m.spec.sql(ctx).sql;
909
+ const hooks = (h) => ((incremental ? h?.incremental : h?.full) ?? []).map((f) => f(ctx).sql);
910
+ return { sql: body, pre: hooks(m.spec.preHooks), post: hooks(m.spec.postHooks), deps: [...deps], found };
911
+ }
912
+ /** A declared pipeline in the IR: ducktail's keys for it, secrets as `${NAME}` (listed). */
913
+ function pipelineIR(p) {
914
+ const secrets = new Set();
915
+ const ref = (s) => {
916
+ secrets.add(s.name);
917
+ return `\${${s.name}}`;
918
+ };
919
+ const value = (v) => {
920
+ if (Array.isArray(v))
921
+ return v.map(value);
922
+ if (typeof v !== "object" || v === null)
923
+ return v;
924
+ const tagged = v;
925
+ if (tagged.kind === "secretRef" && typeof tagged.name === "string")
926
+ return ref(tagged);
927
+ if (tagged.kind === "secretText" && Array.isArray(tagged.parts)) {
928
+ return tagged.parts.map((x) => (typeof x === "string" ? x : ref(x))).join("");
929
+ }
930
+ return table(v);
931
+ };
932
+ const table = (o) => Object.fromEntries(Object.entries(o).filter(([, x]) => x !== undefined).map(([k, x]) => [k, value(x)]));
933
+ const options = table(p.pipeline.options);
934
+ return {
935
+ name: p.name,
936
+ kind: p.pipeline.type,
937
+ slot: p.pipeline.slot?.name ?? null,
938
+ streams: [...p.pipeline.streams],
939
+ secrets: [...secrets].sort(),
940
+ options,
941
+ loc: p.loc,
942
+ };
943
+ }
944
+ /** The JSON IR consumed by the Rust core. Locations are made relative to `root`. */
945
+ export function toIR(o, root, readFile) {
946
+ const rel = (loc) => (loc ? loc.replace(`file://${root.replace(/\/$/, "")}/`, "") : null);
947
+ const relDeep = (v) => Array.isArray(v)
948
+ ? v.map(relDeep)
949
+ : v && typeof v === "object"
950
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, k === "loc" ? rel(x) : relDeep(x)]))
951
+ : v;
952
+ const dialect = o.storage === "postgres" ? "postgres" : "duckdb";
953
+ // Every model and source reachable from the definitions (and from model SQL).
954
+ const models = new Map();
955
+ const sources = new Map();
956
+ const queue = [
957
+ ...o.models,
958
+ ...o.objects.flatMap((x) => (x.$spec.source ? [x.$spec.source] : [])),
959
+ ...o.links.flatMap((l) => (l.source ? [l.source] : [])),
960
+ ...o.views.flatMap((v) => Object.values(v.spec.tables)),
961
+ ];
962
+ const byName = (name) => {
963
+ const m = [...models.values(), ...queue].find((x) => x.spec.name === name);
964
+ if (!m)
965
+ throw new Error(`sqlFile: ref('${name}') names no model of this project`);
966
+ return m;
967
+ };
968
+ const evaluated = new Map();
969
+ while (queue.length) {
970
+ const m = queue.shift();
971
+ if (models.has(m.id))
972
+ continue;
973
+ models.set(m.id, m);
974
+ const isIncremental = m.spec.materialized === "incremental" || m.spec.materialized === "cell";
975
+ const own = m.spec.destination ? "clickhouse" : dialect;
976
+ const full = evaluateModel(m, false, own, readFile, byName, sources);
977
+ const incremental = isIncremental ? evaluateModel(m, true, own, readFile, byName, sources) : null;
978
+ evaluated.set(m.id, { full, incremental });
979
+ for (const r of [...full.found, ...(incremental?.found ?? [])]) {
980
+ if (r.kind === "model")
981
+ queue.push(r);
982
+ else
983
+ sources.set(r.id, r);
984
+ }
985
+ }
986
+ return relDeep({
987
+ storage: o.storage,
988
+ ...(Object.keys(o.destinations ?? {}).length ? { destinations: o.destinations } : {}),
989
+ sources: [...sources.values()].map((s) => ({ id: s.id, pipeline: s.pipeline, stream: s.stream, table: sourceTable(s, dialect) })),
990
+ models: [...models.values()].map((m) => {
991
+ const e = evaluated.get(m.id);
992
+ const s = m.spec;
993
+ return {
994
+ id: m.id,
995
+ name: s.name,
996
+ schema: s.schema ?? "main",
997
+ description: s.description ?? null,
998
+ materialized: s.materialized,
999
+ unique_key: s.uniqueKey === undefined ? [] : Array.isArray(s.uniqueKey) ? s.uniqueKey : [s.uniqueKey],
1000
+ incremental_strategy: s.incrementalStrategy ?? null,
1001
+ cluster_by: s.clusterBy ?? null,
1002
+ full_refresh: s.fullRefresh ?? false,
1003
+ cell: m.cell?.view ?? null,
1004
+ partition_by: m.cell?.partitionBy ?? null,
1005
+ ...(s.microbatch
1006
+ ? { microbatch: { event_time: s.microbatch.eventTime, begin: s.microbatch.begin ?? null, batch_size: s.microbatch.batchSize, lookback: s.microbatch.lookback ?? null } }
1007
+ : {}),
1008
+ columns: Object.entries(s.columns ?? {}).map(([name, p]) => ({ name, type: p.spec.optional ? `${p.type}?` : p.type })),
1009
+ depends_on: [...new Set([...e.full.deps, ...(e.incremental?.deps ?? [])])].sort(),
1010
+ sql: { full: e.full.sql, incremental: e.incremental?.sql ?? null },
1011
+ pre_hooks: { full: e.full.pre, incremental: e.incremental?.pre ?? [] },
1012
+ post_hooks: { full: e.full.post, incremental: e.incremental?.post ?? [] },
1013
+ ...(s.indexes?.length ? { indexes: s.indexes.map((i) => ({ columns: i.columns, unique: i.unique ?? false, method: i.method ?? "btree" })) } : {}),
1014
+ ...(s.destination ? { destination: s.destination } : {}),
1015
+ tests: (s.tests ?? []).map((x) => ({
1016
+ kind: x.kind,
1017
+ column: x.column,
1018
+ values: x.kind === "accepted_values" ? x.values : null,
1019
+ to: x.kind === "relationships" ? x.to.id : null,
1020
+ field: x.kind === "relationships" ? x.field : null,
1021
+ })),
1022
+ loc: m.loc,
1023
+ };
1024
+ }),
1025
+ objects: o.objects.map((obj) => ({
1026
+ name: obj.$name,
1027
+ id: obj.$spec.id,
1028
+ description: obj.$spec.description ?? null,
1029
+ key: obj.$spec.key,
1030
+ source: obj.$spec.source?.id ?? null,
1031
+ history: !!obj.$spec.history,
1032
+ history_at: obj.$spec.historyAt ?? null,
1033
+ ...(obj.$spec.replicas?.length ? { replicas: obj.$spec.replicas } : {}),
1034
+ properties: Object.entries(obj.$spec.properties).map(([name, p]) => ({
1035
+ name,
1036
+ id: p.spec.id ?? null,
1037
+ type: p.type,
1038
+ optional: !!p.spec.optional,
1039
+ owned: !!p.spec.owned,
1040
+ map: p.spec.map ?? null,
1041
+ default: p.spec.default ?? null,
1042
+ description: p.spec.description ?? null,
1043
+ loc: p.spec.loc ?? null,
1044
+ })),
1045
+ loc: obj.$loc,
1046
+ })),
1047
+ links: o.links.map((l) => l.ir),
1048
+ resolutions: o.resolutions,
1049
+ views: o.views.map((v) => ({
1050
+ name: v.name,
1051
+ id: v.id,
1052
+ key: v.spec.key,
1053
+ tables: Object.fromEntries(Object.entries(v.spec.tables).map(([k, m]) => [k, m.id])),
1054
+ depends_on: {
1055
+ objects: (v.spec.dependsOn?.objects ?? []).map((x) => x.$name),
1056
+ links: (v.spec.dependsOn?.links ?? []).map((x) => x.name),
1057
+ },
1058
+ loc: v.loc,
1059
+ })),
1060
+ actions: o.actions.map((a) => a.ir),
1061
+ reads: o.reads.map((r) => r.ir),
1062
+ realtime: o.realtime.map((r) => r.ir),
1063
+ env: Object.entries(o.env).map(([name, e]) => ({ name, kind: e.kind, default: e.default })),
1064
+ policies: o.policies.map((p) => ({ id: p.id, text: p.text, loc: p.loc })),
1065
+ auths: o.auths.map((a) => ({ name: a.name, loc: a.loc })),
1066
+ connections: [...o.connections, ...Object.values(o.slots)].map((c) => ({ name: c.name, provider: c.provider, type: c.type, loc: c.loc })),
1067
+ // Only when declared, so the IR of a project without them is unchanged.
1068
+ ...(Object.keys(o.secrets).length ? { secrets: Object.values(o.secrets).map((x) => ({ name: x.name, loc: x.loc })) } : {}),
1069
+ ...(o.pipelines.length ? { pipelines: o.pipelines.map(pipelineIR) } : {}),
1070
+ streams: o.streams.map((st) => ({
1071
+ name: st.stream,
1072
+ key: st.key,
1073
+ schema: z.toJSONSchema(st.schema, { unrepresentable: "any", io: "input" }),
1074
+ reference: st.reference.map((record, i) => {
1075
+ const parsed = st.schema.safeParse(record);
1076
+ if (!parsed.success)
1077
+ throw new Error(`${st.loc ?? ""} stream \`${st.stream}\`: reference record ${i} does not match its schema: ${parsed.error.message}`);
1078
+ return parsed.data;
1079
+ }),
1080
+ loc: st.loc,
1081
+ })),
1082
+ });
1083
+ }