@hockeymask/core 0.1.0 → 0.1.1
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/index.d.mts +12 -11
- package/dist/index.mjs +24 -24
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["pad","SAMPLES","params","params","params","params","scalar","params","params","params","index","params","params","params","params","params","SCALAR","params","params","params","params","truncate","params","all","truncate","params","params","params","params"],"sources":["../src/connector.ts","../src/mapping/context.ts","../src/mapping/result.ts","../src/mapping/time.ts","../src/mapping/types.ts","../src/mapping/values.ts","../src/mapping/predicate.ts","../src/mapping/expect.ts","../src/mapping/nodes/def.ts","../src/mapping/nodes/aggregate.ts","../src/mapping/ops/def.ts","../src/mapping/document.ts","../src/mapping/nodes/assert.ts","../src/mapping/nodes/distinct.ts","../src/mapping/jsonschema.ts","../src/mapping/nodes/source.ts","../src/mapping/nodes/filter.ts","../src/mapping/nodes/join.ts","../src/mapping/ops/access.ts","../src/mapping/ops/convert.ts","../src/mapping/ops/date.ts","../src/mapping/ops/fn.ts","../src/mapping/ops/list.ts","../src/mapping/ops/lookup.ts","../src/mapping/ops/nulls.ts","../src/mapping/units.ts","../src/mapping/ops/numeric.ts","../src/mapping/ops/string.ts","../src/mapping/ops/when.ts","../src/mapping/ops/index.ts","../src/mapping/sugar.ts","../src/mapping/pipeline.ts","../src/mapping/nodes/map.ts","../src/mapping/nodes/metrics.ts","../src/mapping/nodes/sink.ts","../src/mapping/nodes/transform.ts","../src/mapping/nodes/union.ts","../src/mapping/nodes/index.ts","../src/mapping/graph.ts","../src/mapping/compile.ts","../src/mapping/execute.ts","../src/mapping/examples.ts","../src/mapping/check.ts","../src/mapping/edit.ts","../src/schema.ts"],"sourcesContent":["/**\n * The contract every source connector fulfils: the brief's \"list tables, read column names\n * and types, sample rows\", plus a full `read` and a native `query`. Concrete connectors live\n * with the host that reaches its systems (the demo's NetSuite and Snowflake clients are in\n * apps/spherecast-api); the mapping engine only ever sees rows.\n *\n * Connectors decode the wire format (numbers sent as strings, dates as epoch days or in the\n * account's date format) but never interpret values: a NetSuite checkbox still arrives as\n * 'T' / 'F', a sentinel date still arrives as '9999-01-01'. Interpretation is the mapping's job.\n */\n\nimport type { Row, RowSet, Table, TableRef } from './schema'\n\nexport interface Connector {\n /** Name of the source system, e.g. \"NetSuite\"; becomes `source_system` on imported rows. */\n readonly system: string\n /** Language `query` accepts, e.g. \"suiteql\" or \"snowflake\". */\n readonly dialect: string\n listTables(): Promise<TableRef[]>\n describe(table: string): Promise<Table>\n sample(table: string, limit?: number): Promise<RowSet>\n read(table: string, options?: { batchSize?: number }): AsyncIterable<Row[]>\n query(sql: string, options?: { limit?: number }): Promise<RowSet>\n}\n\n/** The source rejected a request; the message is safe to show to the user. */\nexport class ConnectorError extends Error {\n override name = 'ConnectorError'\n}\n\n/** The source could not be reached at all (network, DNS, timeout). */\nexport class SourceUnavailable extends ConnectorError {\n override name = 'SourceUnavailable'\n}\n","/**\n * Contexts: the only channel through which a node or step learns anything not in its input\n * (arch.md, \"Contexts\"). They hold frozen data, never clocks, clients or handles.\n *\n * `RunContext` / `RecordContext` exist at sync time. `GraphEnv` (from the host) and\n * `RecordEnv` (built by the compiler) exist at compile time.\n */\n\nimport type { TargetSchema } from '../schema'\nimport type { Result, StepError } from './result'\nimport type { Instant } from './time'\nimport type { MType, RecordType } from './types'\nimport type { Json, Rec, Relation, Val } from './values'\n\nexport interface RunContext {\n /** Clock frozen at the start of the run. The only source of \"now\". */\n readonly now: Instant\n readonly tz: string\n readonly locale: string\n /** Every source, read once at run start and frozen, keyed by `source` node id. */\n readonly snapshot: Readonly<Record<string, Relation>>\n /** Named constants of the version. */\n readonly params: Readonly<Record<string, Json>>\n /** Static lookup tables of the version, for the `lookup` op. */\n readonly tables: Readonly<Record<string, Readonly<Record<string, Json>>>>\n readonly run: { readonly syncRunId: string; readonly mappingVersionId: string }\n}\n\nexport interface RecordContext extends RunContext {\n /** The record under mapping inside a `map` node. */\n readonly record: Rec\n}\n\n/** A reviewed, version-pinned record function for the `fn` op (escape hatch). */\nexport interface FnDef {\n /** Accepted input type; omitted means any. */\n readonly input?: MType\n readonly output: MType\n /** Whether it can return an error. Defaults to true. */\n readonly fallible?: boolean\n readonly run: (value: Val, ctx: RecordContext) => Result<Val, StepError>\n}\n\n/** A reviewed, version-pinned collection function for the `transform` node (escape hatch). */\nexport interface TransformDef {\n readonly run: (inputs: readonly Relation[], ctx: RunContext) => Result<Relation, string>\n}\n\n/** What the host supplies to compile a version. */\nexport interface GraphEnv {\n /** The internal model sinks write to; also the schema of `system: \"internal\"` sources. */\n readonly targets: TargetSchema\n readonly functions?: Readonly<Record<string, FnDef>>\n readonly transforms?: Readonly<Record<string, TransformDef>>\n}\n\n/** Compile-time view of a record scope: field pipelines, predicates. */\nexport interface RecordEnv {\n /** Type of the current record, against which `extract` and `path` are checked. */\n readonly record: RecordType\n readonly params: Readonly<Record<string, Json>>\n readonly tables: Readonly<Record<string, Readonly<Record<string, Json>>>>\n readonly functions: Readonly<Record<string, FnDef>>\n /** `each` nesting depth; capped at 1. */\n readonly depth: number\n /** Set when anything resolves against the run clock (`today`, `now`). */\n readonly clock: { used: boolean }\n}\n\n/** Type of a record field, or an error naming the missing field. */\nexport function fieldType(record: RecordType, path: string): Result<MType, string> {\n const type = Object.hasOwn(record.fields, path) ? record.fields[path] : undefined\n return type\n ? { ok: true, value: type }\n : {\n ok: false,\n error: `unknown field '${path}' (record has ${Object.keys(record.fields).join(', ') || 'no fields'})`,\n }\n}\n\nexport function recordEnv(\n record: RecordType,\n from: Partial<Omit<RecordEnv, 'record'>> = {},\n): RecordEnv {\n return {\n record,\n params: from.params ?? {},\n tables: from.tables ?? {},\n functions: from.functions ?? {},\n depth: from.depth ?? 0,\n clock: from.clock ?? { used: false },\n }\n}\n","/**\n * Failure as a value. Steps, nodes and the compiler return `Result` instead of throwing, so\n * the executor can apply each node's failure policy (arch.md, \"Step signature\").\n */\n\nexport type Result<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E }\n\nexport function ok<T>(value: T): { readonly ok: true; readonly value: T } {\n return { ok: true, value }\n}\n\n/** The value of a result the caller has already checked, e.g. by `signature` before `run`. */\nexport function expectOk<T>(result: Result<T, unknown>): T {\n if (!result.ok) throw new Error(`unexpected failure: ${JSON.stringify(result.error)}`)\n return result.value\n}\n\nexport function err<E>(error: E): { readonly ok: false; readonly error: E } {\n return { ok: false, error }\n}\n\n/** What a failing record op reports. The pipeline adds the op and step, the map the node. */\nexport type ErrorCode =\n | 'type_mismatch'\n | 'parse_failed'\n | 'unknown_unit'\n | 'lookup_miss'\n | 'required_null'\n | 'domain_error'\n | 'fn_failed'\n\nexport interface StepError {\n readonly code: ErrorCode\n readonly detail: string\n}\n\n/** A runtime failure located in the graph (arch.md `MappingError`). */\nexport interface MappingError extends StepError {\n readonly node: string\n readonly op: string\n readonly step?: number\n readonly key?: string\n}\n\nexport function stepError(code: ErrorCode, detail: string): { ok: false; error: StepError } {\n return err({ code, detail })\n}\n\n/** A problem found while checking a version, located as precisely as possible. */\nexport interface CompileIssue {\n readonly code: CompileCode\n readonly message: string\n readonly node?: string\n /** The `map` field key, aggregate field name, or expectation clause. */\n readonly field?: string\n /** Index of the step inside the field pipeline. */\n readonly step?: number\n}\n\nexport type CompileCode =\n | 'invalid_params'\n | 'unknown_op'\n | 'type_error'\n | 'duplicate_id'\n | 'dangling_ref'\n | 'missing_input'\n | 'cycle'\n | 'dead_node'\n | 'missing_schema'\n | 'duplicate_sink'\n | 'skip_tolerance'\n | 'missing_expectation'\n | 'invalid_expectation'\n | 'unknown_reference'\n | 'example_failed'\n","/**\n * Dates without a wall clock.\n *\n * The runtime value of the `date` type is an `Instant`: a frozen point in time in epoch\n * milliseconds. Calendar math (\"+10y\", \"start of day\") happens in an IANA time zone, using\n * `Intl.DateTimeFormat` to move between instants and wall-clock time. \"now\" only ever comes\n * from the run context (arch.md limitation #10), never from `Date.now()`.\n */\n\nimport { err, ok, type Result } from './result'\n\nexport class Instant {\n private constructor(readonly epochMs: number) {\n Object.freeze(this)\n }\n\n static ofEpochMs(epochMs: number): Instant {\n if (!Number.isFinite(epochMs)) throw new RangeError(`invalid epoch milliseconds ${epochMs}`)\n return new Instant(epochMs)\n }\n\n /** Strict ISO 8601 with an offset or `Z`, e.g. `2026-10-04T12:00:00Z`. */\n static parse(iso: string): Instant | undefined {\n if (!ISO_INSTANT.test(iso)) return undefined\n const ms = Date.parse(iso)\n return Number.isNaN(ms) ? undefined : new Instant(ms)\n }\n\n toISOString(): string {\n return new Date(this.epochMs).toISOString()\n }\n\n toJSON(): string {\n return this.toISOString()\n }\n\n toString(): string {\n return this.toISOString()\n }\n}\n\nconst ISO_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,3})?)?(Z|[+-]\\d{2}:\\d{2})$/\n\n// --- time zones ---------------------------------------------------------------------------\n\n/** Wall-clock fields in some time zone. Months are 1-12. */\nexport interface WallClock {\n readonly year: number\n readonly month: number\n readonly day: number\n readonly hour: number\n readonly minute: number\n readonly second: number\n readonly ms: number\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>()\n\nfunction formatter(tz: string): Intl.DateTimeFormat {\n let f = formatters.get(tz)\n if (!f) {\n f = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n })\n formatters.set(tz, f)\n }\n return f\n}\n\nexport function isTimeZone(tz: string): boolean {\n try {\n formatter(tz)\n return true\n } catch {\n return false\n }\n}\n\n/** The wall clock in `tz` at `instant`. */\nexport function toWallClock(instant: Instant, tz: string): WallClock {\n const parts: Record<string, number> = {}\n for (const p of formatter(tz).formatToParts(new Date(instant.epochMs))) {\n if (p.type !== 'literal') parts[p.type] = Number(p.value)\n }\n return {\n year: parts.year as number,\n month: parts.month as number,\n day: parts.day as number,\n hour: parts.hour as number,\n minute: parts.minute as number,\n second: parts.second as number,\n ms: ((instant.epochMs % 1000) + 1000) % 1000,\n }\n}\n\nfunction wallAsUtc(w: WallClock): number {\n // Date.UTC maps years 0-99 to 1900-1999; setUTCFullYear does not.\n const d = new Date(Date.UTC(2000, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms))\n d.setUTCFullYear(w.year)\n return d.getTime()\n}\n\n/** Offset of `tz` from UTC at `epochMs`, in milliseconds. */\nfunction offsetAt(epochMs: number, tz: string): number {\n return wallAsUtc(toWallClock(Instant.ofEpochMs(epochMs), tz)) - epochMs\n}\n\n/**\n * The instant at which the wall clock in `tz` shows `w`. A wall time skipped by a DST\n * transition resolves after the gap; an ambiguous one resolves to the earlier instant.\n */\nexport function fromWallClock(w: WallClock, tz: string): Instant {\n const local = wallAsUtc(w)\n // The offsets in force a day before and a day after cover both sides of any transition.\n const before = offsetAt(local - 86_400_000, tz)\n const after = offsetAt(local + 86_400_000, tz)\n const shows = (c: number) => wallAsUtc(toWallClock(Instant.ofEpochMs(c), tz)) === local\n const candidates = [local - before, local - after].filter(shows)\n // Inside a gap neither matches: keep the earlier offset, which lands after the gap.\n return Instant.ofEpochMs(candidates.length > 0 ? Math.min(...candidates) : local - before)\n}\n\nexport function daysInMonth(year: number, month: number): number {\n if (month === 2) return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28\n return [4, 6, 9, 11].includes(month) ? 30 : 31\n}\n\n// --- calendar math --------------------------------------------------------------------------\n\nexport type DurationUnit = 'y' | 'mo' | 'w' | 'd' | 'h'\n\nexport interface Duration {\n readonly amount: number\n readonly unit: DurationUnit\n}\n\nconst DURATION_PART = /([+-])(\\d+)(y|mo|w|d|h)/gy\n\n/** `+10y`, `-30d`, `+1y-2mo`: one or more signed amounts. */\nexport function parseDuration(text: string): Result<readonly Duration[], string> {\n const parts: Duration[] = []\n DURATION_PART.lastIndex = 0\n let at = 0\n while (at < text.length) {\n DURATION_PART.lastIndex = at\n const m = DURATION_PART.exec(text)\n if (!m) return err(`invalid duration '${text}', expected e.g. '+10y' or '-30d'`)\n const [, sign, digits, unit] = m\n parts.push({ amount: Number(digits) * (sign === '-' ? -1 : 1), unit: unit as DurationUnit })\n at = DURATION_PART.lastIndex\n }\n if (parts.length === 0) return err(`invalid duration '${text}', expected e.g. '+10y' or '-30d'`)\n return ok(parts)\n}\n\n/** A duration already validated by `parseDuration` (e.g. by a params schema). */\nexport function duration(text: string): readonly Duration[] {\n const parsed = parseDuration(text)\n if (!parsed.ok) throw new Error(parsed.error)\n return parsed.value\n}\n\n/** Shift by calendar units in `tz`. Month ends clamp: Feb 29 + 1y is Feb 28. */\nexport function shift(instant: Instant, by: readonly Duration[], tz: string): Instant {\n let current = instant\n for (const { amount, unit } of by) {\n if (unit === 'h') {\n current = Instant.ofEpochMs(current.epochMs + amount * 3_600_000)\n continue\n }\n const w = toWallClock(current, tz)\n if (unit === 'y' || unit === 'mo') {\n const months = w.year * 12 + (w.month - 1) + (unit === 'y' ? amount * 12 : amount)\n const year = Math.floor(months / 12)\n const month = (months % 12) + 1\n current = fromWallClock(\n { ...w, year, month, day: Math.min(w.day, daysInMonth(year, month)) },\n tz,\n )\n } else {\n const days = unit === 'w' ? amount * 7 : amount\n const d = new Date(wallAsUtc({ ...w, hour: 0, minute: 0, second: 0, ms: 0 }))\n d.setUTCDate(d.getUTCDate() + days)\n current = fromWallClock(\n { ...w, year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() },\n tz,\n )\n }\n }\n return current\n}\n\nexport type TruncateUnit = 'day' | 'month' | 'year'\n\n/** Start of the day, month or year containing `instant`, in `tz`. */\nexport function truncate(instant: Instant, unit: TruncateUnit, tz: string): Instant {\n const w = toWallClock(instant, tz)\n return fromWallClock(\n {\n year: w.year,\n month: unit === 'year' ? 1 : w.month,\n day: unit === 'day' ? w.day : 1,\n hour: 0,\n minute: 0,\n second: 0,\n ms: 0,\n },\n tz,\n )\n}\n\n// --- date expressions -------------------------------------------------------------------------\n\n/**\n * A comparison date in a predicate: `today` or `now` plus durations (resolved against the\n * run's frozen clock), or a literal ISO date or instant.\n */\nexport type DateExpr =\n | {\n readonly kind: 'relative'\n readonly anchor: 'today' | 'now'\n readonly by: readonly Duration[]\n }\n | { readonly kind: 'date'; readonly wall: WallClock }\n | { readonly kind: 'instant'; readonly instant: Instant }\n\nconst RELATIVE = /^(today|now)(.*)$/\n\nexport function parseDateExpr(text: string): Result<DateExpr, string> {\n const rel = RELATIVE.exec(text)\n if (rel) {\n const anchor = rel[1] as 'today' | 'now'\n if (rel[2] === '') return ok({ kind: 'relative', anchor, by: [] })\n const by = parseDuration(rel[2] as string)\n return by.ok ? ok({ kind: 'relative', anchor, by: by.value }) : by\n }\n const wall = parseWithFormat(text, DATE_ONLY)\n if (wall) return ok({ kind: 'date', wall })\n const instant = Instant.parse(text)\n if (instant) return ok({ kind: 'instant', instant })\n return err(\n `invalid date '${text}', expected 'today+10y', 'now-1d', 'YYYY-MM-DD' or an ISO instant`,\n )\n}\n\n/** Whether the expression reads the run clock (fixtures must then pin `now`). */\nexport function usesClock(expr: DateExpr): boolean {\n return expr.kind === 'relative'\n}\n\nexport function resolveDateExpr(expr: DateExpr, clock: { now: Instant; tz: string }): Instant {\n switch (expr.kind) {\n case 'instant':\n return expr.instant\n case 'date':\n return fromWallClock(expr.wall, clock.tz)\n case 'relative': {\n const anchor = expr.anchor === 'today' ? truncate(clock.now, 'day', clock.tz) : clock.now\n return shift(anchor, expr.by, clock.tz)\n }\n }\n}\n\n// --- formats ------------------------------------------------------------------------------------\n\n/**\n * A date format: `iso`, `epoch_ms`, `epoch_s`, or a pattern of the tokens `YYYY MM DD HH mm ss`\n * with any other characters taken literally.\n */\nexport type DateFormat =\n | { readonly kind: 'iso' }\n | { readonly kind: 'epoch'; readonly unit: 'ms' | 's' }\n | { readonly kind: 'pattern'; readonly tokens: readonly string[]; readonly regex: RegExp }\n\nconst TOKENS = ['YYYY', 'MM', 'DD', 'HH', 'mm', 'ss'] as const\nconst TOKEN_SPLIT = /(YYYY|MM|DD|HH|mm|ss)/\n\nexport function parseDateFormat(text: string): Result<DateFormat, string> {\n if (text === 'iso') return ok({ kind: 'iso' })\n if (text === 'epoch_ms') return ok({ kind: 'epoch', unit: 'ms' })\n if (text === 'epoch_s') return ok({ kind: 'epoch', unit: 's' })\n const tokens = text.split(TOKEN_SPLIT).filter((p) => p !== '')\n const used = tokens.filter((p) => (TOKENS as readonly string[]).includes(p))\n if (used.length === 0) return err(`date format '${text}' has none of ${TOKENS.join(' ')}`)\n if (new Set(used).size !== used.length) return err(`date format '${text}' repeats a token`)\n const source = tokens\n .map((p) => {\n if (p === 'YYYY') return '(\\\\d{4})'\n if ((TOKENS as readonly string[]).includes(p)) return '(\\\\d{2})'\n return p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n })\n .join('')\n return ok({ kind: 'pattern', tokens, regex: new RegExp(`^${source}$`) })\n}\n\n/** A format already validated by `parseDateFormat` (e.g. by a params schema). */\nexport function dateFormat(text: string): DateFormat {\n const format = parseDateFormat(text)\n if (!format.ok) throw new Error(format.error)\n return format.value\n}\n\nconst DATE_ONLY = parseDateFormat('YYYY-MM-DD')\nconst DATE_TIME = parseDateFormat('YYYY-MM-DDTHH:mm:ss')\n\n/** Whether a pattern format names a full calendar date (needed to parse, not to format). */\nexport function hasFullDate(format: DateFormat): boolean {\n return format.kind !== 'pattern' || ['YYYY', 'MM', 'DD'].every((x) => format.tokens.includes(x))\n}\n\nfunction parseWithFormat(text: string, format: Result<DateFormat, string>): WallClock | undefined {\n if (!format.ok || format.value.kind !== 'pattern') return undefined\n const m = format.value.regex.exec(text)\n if (!m) return undefined\n const fields: Record<string, number> = { YYYY: 1970, MM: 1, DD: 1, HH: 0, mm: 0, ss: 0 }\n let group = 1\n for (const token of format.value.tokens) {\n if ((TOKENS as readonly string[]).includes(token)) fields[token] = Number(m[group++])\n }\n const w: WallClock = {\n year: fields.YYYY as number,\n month: fields.MM as number,\n day: fields.DD as number,\n hour: fields.HH as number,\n minute: fields.mm as number,\n second: fields.ss as number,\n ms: 0,\n }\n const valid =\n w.month >= 1 &&\n w.month <= 12 &&\n w.day >= 1 &&\n w.day <= daysInMonth(w.year, w.month) &&\n w.hour <= 23 &&\n w.minute <= 59 &&\n w.second <= 59\n return valid ? w : undefined\n}\n\n/**\n * Parse a source value. Pattern and ISO strings without an offset are wall-clock times in\n * `tz`; epoch formats take a number or a numeric string. Undefined when it does not parse.\n */\nexport function parseDateValue(\n input: string | number,\n format: DateFormat,\n tz: string,\n): Instant | undefined {\n if (format.kind === 'epoch') {\n const n = typeof input === 'number' ? input : /^-?\\d+$/.test(input) ? Number(input) : Number.NaN\n return Number.isFinite(n) ? Instant.ofEpochMs(format.unit === 's' ? n * 1000 : n) : undefined\n }\n if (typeof input !== 'string') return undefined\n if (format.kind === 'pattern') {\n const w = parseWithFormat(input, ok(format))\n return w && fromWallClock(w, tz)\n }\n const wall = parseWithFormat(input, DATE_ONLY) ?? parseWithFormat(input, DATE_TIME)\n return wall ? fromWallClock(wall, tz) : Instant.parse(input)\n}\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, '0')\n\n/** Format an instant. `iso` is UTC (`...Z`); patterns and epoch formats as named. */\nexport function formatDate(instant: Instant, format: DateFormat, tz: string): string {\n if (format.kind === 'iso') return instant.toISOString()\n if (format.kind === 'epoch') {\n return String(format.unit === 's' ? Math.floor(instant.epochMs / 1000) : instant.epochMs)\n }\n const w = toWallClock(instant, tz)\n const values: Record<string, string> = {\n YYYY: pad(w.year, 4),\n MM: pad(w.month),\n DD: pad(w.day),\n HH: pad(w.hour),\n mm: pad(w.minute),\n ss: pad(w.second),\n }\n return format.tokens.map((p) => values[p] ?? p).join('')\n}\n\n/** `YYYY-MM-DD` of the instant in `tz`, how `date` target fields are written. */\nexport function toDateString(instant: Instant, tz: string): string {\n const w = toWallClock(instant, tz)\n return `${pad(w.year, 4)}-${pad(w.month)}-${pad(w.day)}`\n}\n","/**\n * The mapping language's type algebra (arch.md, \"Type algebra\").\n *\n * Nullability is part of the type, so the pipeline compiler (not each op) implements null\n * short-circuiting. `Rel` (a collection) is deliberately not an `MType`: a record field can be\n * a list, never a collection.\n *\n * Three kinds exist only for the checker: `unit` is the input of a pipeline's first step,\n * `unknown` is a value nothing is known about (top), and `never` is the bottom type, used for\n * the element of `[]` and, as `t.null = nullable(never)`, for a literal `null`.\n */\n\nimport type { LogicalType } from '../schema'\nimport { err, ok, type Result } from './result'\n\nexport type NonNull =\n | { readonly kind: 'string' }\n | { readonly kind: 'number' }\n | { readonly kind: 'boolean' }\n | { readonly kind: 'date' }\n | { readonly kind: 'list'; readonly of: MType }\n | { readonly kind: 'tuple'; readonly of: readonly MType[] }\n | { readonly kind: 'record'; readonly fields: Readonly<Record<string, MType>> }\n | { readonly kind: 'unit' }\n | { readonly kind: 'unknown' }\n | { readonly kind: 'never' }\n\nexport type NullableType = { readonly kind: 'nullable'; readonly of: NonNull }\n\nexport type MType = NonNull | NullableType\n\nexport type RecordType = Extract<NonNull, { kind: 'record' }>\nexport type ListType = Extract<NonNull, { kind: 'list' }>\nexport type TupleType = Extract<NonNull, { kind: 'tuple' }>\n\n/** Type constructors. `t.nullable` flattens, so `nullable(nullable(x))` is `nullable(x)`. */\nexport const t = {\n string: { kind: 'string' },\n number: { kind: 'number' },\n boolean: { kind: 'boolean' },\n date: { kind: 'date' },\n unit: { kind: 'unit' },\n unknown: { kind: 'unknown' },\n never: { kind: 'never' },\n null: { kind: 'nullable', of: { kind: 'never' } },\n list: (of: MType): MType => ({ kind: 'list', of }),\n tuple: (of: readonly MType[]): MType => ({ kind: 'tuple', of }),\n record: (fields: Readonly<Record<string, MType>>): RecordType => ({ kind: 'record', fields }),\n nullable: (of: MType): MType => (of.kind === 'nullable' ? of : { kind: 'nullable', of }),\n} as const satisfies Record<string, MType | ((...args: never[]) => MType)>\n\nexport function isNullable(type: MType): type is NullableType {\n return type.kind === 'nullable'\n}\n\n/** The type without its null. */\nexport function stripNull(type: MType): NonNull {\n return type.kind === 'nullable' ? type.of : type\n}\n\n/** Whether a value of this type can be null at runtime (`unknown` can be anything). */\nexport function mayBeNull(type: MType): boolean {\n return type.kind === 'nullable' || type.kind === 'unknown'\n}\n\n/** `nullable(x)` when `when` is true, else `x`. */\nexport function nullableIf(type: MType, when: boolean): MType {\n return when ? t.nullable(type) : type\n}\n\n/** Human-readable form used in every type error: `number?`, `list<string>`, `(number, string)`. */\nexport function show(type: MType): string {\n switch (type.kind) {\n case 'nullable':\n return type.of.kind === 'never' ? 'null' : `${show(type.of)}?`\n case 'list':\n return `list<${show(type.of)}>`\n case 'tuple':\n return `(${type.of.map(show).join(', ')})`\n case 'record':\n return `{ ${Object.entries(type.fields)\n .map(([k, v]) => `${k}: ${show(v)}`)\n .join(', ')} }`\n case 'unit':\n return '()'\n default:\n return type.kind\n }\n}\n\nexport function equalTypes(a: MType, b: MType): boolean {\n return show(a) === show(b)\n}\n\n/** Can a value of type `from` be used where `to` is expected? */\nexport function assignable(from: MType, to: MType): boolean {\n if (to.kind === 'unknown') return true\n if (from.kind === 'never') return true\n if (from.kind === 'nullable') {\n return to.kind === 'nullable' && assignable(from.of, to.of)\n }\n if (to.kind === 'nullable') return assignable(from, to.of)\n switch (from.kind) {\n case 'list':\n return to.kind === 'list' && assignable(from.of, to.of)\n case 'tuple':\n return (\n to.kind === 'tuple' &&\n to.of.length === from.of.length &&\n from.of.every((f, i) => assignable(f, to.of[i] as MType))\n )\n case 'record':\n return (\n to.kind === 'record' &&\n Object.entries(to.fields).every(\n ([k, v]) => k in from.fields && assignable(from.fields[k] as MType, v),\n )\n )\n default:\n return from.kind === to.kind\n }\n}\n\nconst SCALAR_KINDS = new Set(['string', 'number', 'boolean', 'date'])\n\n/** Can values of these types be compared for equality (join keys, `eq`, `in`)? */\nexport function comparable(a: MType, b: MType): boolean {\n const x = stripNull(a)\n const y = stripNull(b)\n if (x.kind === 'unknown' || y.kind === 'unknown') return true\n if (x.kind === 'never' || y.kind === 'never') return true\n if (x.kind === 'list' && y.kind === 'list') return comparable(x.of, y.of)\n return SCALAR_KINDS.has(x.kind) && x.kind === y.kind\n}\n\n/** Can values of this type be ordered (`lt`, `min`, sorting)? */\nexport function orderable(type: MType): boolean {\n const kind = stripNull(type).kind\n return kind === 'number' || kind === 'date' || kind === 'string'\n}\n\n/**\n * The common type of two branches (`when` cases, `coalesce`, `union` inputs): equal modulo\n * nullability, nullable when either side is. `never` unifies with anything.\n */\nexport function unify(a: MType, b: MType): Result<MType, string> {\n const nullable = isNullable(a) || isNullable(b)\n const x = stripNull(a)\n const y = stripNull(b)\n const base = unifyNonNull(x, y)\n if (!base.ok) return base\n return ok(nullableIf(base.value, nullable))\n}\n\nfunction unifyNonNull(x: NonNull, y: NonNull): Result<MType, string> {\n const mismatch = () => err(`${show(x)} and ${show(y)} have no common type`)\n if (x.kind === 'never') return ok(y)\n if (y.kind === 'never') return ok(x)\n if (x.kind === 'unknown' || y.kind === 'unknown') return ok(t.unknown)\n if (x.kind === 'list' && y.kind === 'list') {\n const of = unify(x.of, y.of)\n return of.ok ? ok(t.list(of.value)) : mismatch()\n }\n if (x.kind === 'tuple' && y.kind === 'tuple') {\n if (x.of.length !== y.of.length) return mismatch()\n const of: MType[] = []\n for (const [i, a] of x.of.entries()) {\n const u = unify(a, y.of[i] as MType)\n if (!u.ok) return mismatch()\n of.push(u.value)\n }\n return ok(t.tuple(of))\n }\n if (x.kind === 'record' && y.kind === 'record') {\n const keys = Object.keys(x.fields)\n if (keys.length !== Object.keys(y.fields).length) return mismatch()\n const fields: Record<string, MType> = {}\n for (const k of keys) {\n const other = y.fields[k]\n if (!other) return mismatch()\n const u = unify(x.fields[k] as MType, other)\n if (!u.ok) return mismatch()\n fields[k] = u.value\n }\n return ok(t.record(fields))\n }\n return x.kind === y.kind ? ok(x) : mismatch()\n}\n\n/** Unify a non-empty list of types, left to right. */\nexport function unifyAll(types: readonly MType[]): Result<MType, string> {\n let acc: MType = t.never\n for (const type of types) {\n const u = unify(acc, type)\n if (!u.ok) return u\n acc = u.value\n }\n return ok(acc)\n}\n\n/** Static type of a JSON literal: `null` is `t.null`, `[]` is `list<never>`. */\nexport function typeOfJson(value: unknown): MType {\n if (value === null) return t.null\n switch (typeof value) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n }\n if (Array.isArray(value)) {\n const element = unifyAll(value.map(typeOfJson))\n return t.list(element.ok ? element.value : t.unknown)\n }\n if (typeof value === 'object') {\n return t.record(\n Object.fromEntries(Object.entries(value as object).map(([k, v]) => [k, typeOfJson(v)])),\n )\n }\n return t.unknown\n}\n\n/** A connector/target logical type as an `MType`. References are opaque ids. */\nexport function fromLogicalType(logical: LogicalType): NonNull {\n switch (logical) {\n case 'string':\n return t.string\n case 'integer':\n case 'decimal':\n return t.number\n case 'boolean':\n return t.boolean\n case 'date':\n case 'timestamp':\n return t.date\n default:\n return t.unknown\n }\n}\n\n/**\n * Parse a type name as written in `assert_type`: `string`, `number`, `boolean`, `date`,\n * `list<T>`, and a trailing `?` for nullable.\n */\nexport function parseTypeName(text: string): Result<MType, string> {\n const source = text.replace(/\\s+/g, '')\n const parse = (s: string): MType | undefined => {\n if (s.endsWith('?')) {\n const inner = parse(s.slice(0, -1))\n return inner && inner.kind !== 'nullable' ? t.nullable(inner) : undefined\n }\n if (s.startsWith('list<') && s.endsWith('>')) {\n const inner = parse(s.slice(5, -1))\n return inner && t.list(inner)\n }\n switch (s) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n case 'date':\n return t.date\n default:\n return undefined\n }\n }\n const type = parse(source)\n return type ? ok(type) : err(`unknown type '${text}'`)\n}\n\n/** A type name already validated by `parseTypeName` (e.g. by a params schema). */\nexport function typeName(text: string): MType {\n const type = parseTypeName(text)\n if (!type.ok) throw new Error(type.error)\n return type.value\n}\n","/**\n * Runtime values and the relations that carry them.\n *\n * A record is a plain frozen-by-convention object; an absent key reads as null (that is how\n * `omit_if_null` and `skip_field` leave a field out of a write). Nothing here depends on\n * insertion order: hashing and sorting go through `canonicalKey` and `compareVals`, so two\n * runs over the same snapshot produce identical output (arch.md limitation #17).\n */\n\nimport { Instant } from './time'\n\nexport type Val =\n | null\n | string\n | number\n | boolean\n | Instant\n | readonly Val[]\n | { readonly [key: string]: Val }\n\nexport type Rec = Readonly<Record<string, Val>>\n\n/** A collection: records of one record type, in no meaningful order. */\nexport type Relation = readonly Rec[]\n\n/** JSON as stored in a version (params, tables, literals, fixtures). */\nexport type Json =\n | null\n | string\n | number\n | boolean\n | readonly Json[]\n | { readonly [key: string]: Json }\n\n/** Returned by a step to leave its field out of the record entirely (`omit_if_null`). */\nexport const OMIT: unique symbol = Symbol('omit')\nexport type Omitted = typeof OMIT\n\nexport function isRecordVal(v: Val): v is { readonly [key: string]: Val } {\n return typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Instant)\n}\n\n/** A string that is equal for equal values, used for hashing (joins, distinct, union, groups). */\nexport function canonicalKey(v: Val): string {\n if (v === null) return 'n'\n switch (typeof v) {\n case 'string':\n return `s${JSON.stringify(v)}`\n case 'number':\n return `d${Object.is(v, -0) ? 0 : v}`\n case 'boolean':\n return v ? 't' : 'f'\n }\n if (v instanceof Instant) return `i${v.epochMs}`\n if (Array.isArray(v)) return `[${(v as readonly Val[]).map(canonicalKey).join(',')}]`\n const rec = v as { readonly [key: string]: Val }\n return `{${Object.keys(rec)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonicalKey(rec[k] as Val)}`)\n .join(',')}}`\n}\n\n/** Canonical key of a tuple of fields of a record; absent fields count as null. */\nexport function keyOf(rec: Rec, fields: readonly string[]): string {\n return canonicalKey(fields.map((f) => rec[f] ?? null))\n}\n\nconst rank = (v: Val): number => {\n if (v === null) return 0\n switch (typeof v) {\n case 'boolean':\n return 1\n case 'number':\n return 2\n case 'string':\n return 3\n }\n if (v instanceof Instant) return 4\n return Array.isArray(v) ? 5 : 6\n}\n\n/**\n * A total order over values: null first, then booleans, numbers, strings (by UTF-16 code\n * unit, never locale), dates, lists (lexicographic), records (by canonical key).\n */\nexport function compareVals(a: Val, b: Val): number {\n const ra = rank(a)\n const rb = rank(b)\n if (ra !== rb) return ra - rb\n switch (ra) {\n case 0:\n return 0\n case 1:\n case 2:\n return Number(a) - Number(b)\n case 3:\n return a === b ? 0 : (a as string) < (b as string) ? -1 : 1\n case 4:\n return (a as Instant).epochMs - (b as Instant).epochMs\n case 5: {\n const x = a as readonly Val[]\n const y = b as readonly Val[]\n for (let i = 0; i < Math.min(x.length, y.length); i++) {\n const c = compareVals(x[i] as Val, y[i] as Val)\n if (c !== 0) return c\n }\n return x.length - y.length\n }\n default: {\n const x = canonicalKey(a)\n const y = canonicalKey(b)\n return x === y ? 0 : x < y ? -1 : 1\n }\n }\n}\n\nexport function valEquals(a: Val, b: Val): boolean {\n return compareVals(a, b) === 0\n}\n\n/** Values as JSON: dates become ISO strings. For fixtures, metrics and diagnostics. */\nexport function toJson(v: Val): Json {\n if (v instanceof Instant) return v.toISOString()\n if (Array.isArray(v)) return (v as readonly Val[]).map(toJson)\n if (isRecordVal(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toJson(x)]))\n return v as Json\n}\n\n/** Sort records by the values of `fields`, ties by whole-record canonical key. */\nexport function sortRecords(rows: readonly Rec[], fields: readonly string[]): Rec[] {\n return [...rows].sort((a, b) => {\n for (const f of fields) {\n const c = compareVals(a[f] ?? null, b[f] ?? null)\n if (c !== 0) return c\n }\n const x = canonicalKey(a)\n const y = canonicalKey(b)\n return x === y ? 0 : x < y ? -1 : 1\n })\n}\n","/**\n * The one predicate vocabulary (arch.md, \"Conditional\"), shared by `when`, `filter_list`,\n * the `filter` node, join `where`, aggregate `where`, and `rows` expectations.\n *\n * Shape: `{ path?, <predicate>: operand }` with exactly one predicate key, or a composition\n * `{ all: { of: [...] } }`, `{ any: { of: [...] } }`, `{ not: cond }`. Without `path` the\n * predicate tests the piped value. An operand is a literal, `{ ref: field }` or\n * `{ param: name }`.\n *\n * Null never compares: ordering and equality with a null side are false, `neq` and `not_in`\n * are their negations and so hold for null (arch.md L366).\n */\n\nimport { fieldType, type RecordEnv, type RunContext } from './context'\nimport { err, ok, type Result } from './result'\nimport { type DateExpr, Instant, parseDateExpr, resolveDateExpr, usesClock } from './time'\nimport { comparable, type MType, orderable, show, stripNull, t, typeOfJson } from './types'\nimport { compareVals, type Json, type Rec, type Val } from './values'\n\nexport type Test = (piped: Val, record: Rec, ctx: RunContext) => boolean\n\nconst COMPARISONS = ['eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'before', 'after'] as const\nconst MEMBERSHIP = ['in', 'not_in'] as const\nconst PRESENCE = ['is_null', 'is_blank'] as const\nconst COMPOSITION = ['all', 'any', 'not'] as const\n\n/** Every predicate name; the `if_<name>` sugar is derived from the non-composite ones. */\nexport const PREDICATES = [\n ...COMPARISONS,\n ...MEMBERSHIP,\n 'matches',\n ...PRESENCE,\n ...COMPOSITION,\n] as const\nexport type PredicateName = (typeof PREDICATES)[number]\n\n/** Predicate JSON, loosely typed: validated by `compilePredicate`. */\nexport type Predicate = { readonly [key: string]: unknown }\n\nexport type Getter = (piped: Val, record: Rec, ctx: RunContext) => Val\n\nexport interface Operand {\n readonly type: MType\n readonly get: Getter\n}\n\n/**\n * Compile a predicate. `piped` is the type of the piped value, or undefined where there is\n * none (`filter`, join `where`, aggregate `where`), in which case `path` is required.\n */\nexport function compilePredicate(\n raw: unknown,\n env: RecordEnv,\n piped?: MType,\n): Result<Test, string> {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return err('a condition must be an object such as { \"eq\": 1 }')\n }\n const cond = raw as Predicate\n const keys = Object.keys(cond).filter((k) => k !== 'path')\n if (keys.length !== 1) {\n return err(\n `a condition needs exactly one predicate, got ${keys.length ? keys.join(', ') : 'none'}`,\n )\n }\n const name = keys[0] as string\n if (!(PREDICATES as readonly string[]).includes(name)) return err(`unknown predicate '${name}'`)\n const value = cond[name]\n\n if ((COMPOSITION as readonly string[]).includes(name)) {\n if ('path' in cond) return err(`'${name}' does not take a path; put paths on its conditions`)\n return compileComposition(name as (typeof COMPOSITION)[number], value, env, piped)\n }\n\n const subject = compileSubject(cond.path, env, piped)\n if (!subject.ok) return subject\n const { type, get } = subject.value\n const base = stripNull(type)\n\n switch (name) {\n case 'is_null':\n case 'is_blank': {\n if (typeof value !== 'boolean') return err(`'${name}' takes true or false`)\n if (name === 'is_blank' && base.kind !== 'string' && base.kind !== 'unknown') {\n return err(`is_blank applies to strings, not ${show(type)}`)\n }\n const blank =\n name === 'is_null'\n ? (v: Val) => v === null\n : (v: Val) => v === null || (typeof v === 'string' && v.trim() === '')\n return ok((p, r, c) => blank(get(p, r, c)) === value)\n }\n case 'matches': {\n if (typeof value !== 'string') return err('matches takes a regular expression string')\n if (base.kind !== 'string' && base.kind !== 'unknown') {\n return err(`matches applies to strings, not ${show(type)}`)\n }\n const regex = compileRegex(value)\n if (!regex.ok) return regex\n const re = regex.value\n return ok((p, r, c) => {\n const v = get(p, r, c)\n return typeof v === 'string' && re.test(v)\n })\n }\n case 'in':\n case 'not_in': {\n const operand = compileOperand(value, env, base.kind === 'date')\n if (!operand.ok) return operand\n const listType = stripNull(operand.value.type)\n if (listType.kind !== 'list')\n return err(`'${name}' takes a list, got ${show(operand.value.type)}`)\n if (!comparable(type, listType.of)) {\n return err(`cannot test ${show(type)} for membership in ${show(listType)}`)\n }\n const list = operand.value.get\n const member: Test = (p, r, c) => {\n const v = get(p, r, c)\n const values = list(p, r, c)\n if (v === null || !Array.isArray(values)) return false\n return (values as readonly Val[]).some((x) => x !== null && compareVals(v, x) === 0)\n }\n return ok(name === 'in' ? member : (p, r, c) => !member(p, r, c))\n }\n }\n\n // Comparisons.\n const isDate = name === 'before' || name === 'after'\n if (isDate && base.kind !== 'date' && base.kind !== 'unknown') {\n return err(`'${name}' applies to dates, not ${show(type)}`)\n }\n if (!isDate && name !== 'eq' && name !== 'neq' && !orderable(base) && base.kind !== 'unknown') {\n return err(`'${name}' applies to numbers, strings and dates, not ${show(type)}`)\n }\n if (value === null) return err(`'${name}' cannot compare with null; use is_null`)\n const operand = compileOperand(value, env, base.kind === 'date' || isDate)\n if (!operand.ok) return operand\n if (!comparable(type, operand.value.type)) {\n return err(`cannot compare ${show(type)} with ${show(operand.value.type)}`)\n }\n const other = operand.value.get\n const test = COMPARE[name as (typeof COMPARISONS)[number]]\n return ok((p, r, c) => {\n const a = get(p, r, c)\n const b = other(p, r, c)\n const holds = a !== null && b !== null && test(compareVals(a, b))\n return name === 'neq' ? !holds : holds\n })\n}\n\nconst COMPARE: Record<(typeof COMPARISONS)[number], (c: number) => boolean> = {\n eq: (c) => c === 0,\n neq: (c) => c === 0, // negated by the caller, so null sides make `neq` true\n lt: (c) => c < 0,\n lte: (c) => c <= 0,\n gt: (c) => c > 0,\n gte: (c) => c >= 0,\n before: (c) => c < 0,\n after: (c) => c > 0,\n}\n\nfunction compileComposition(\n name: (typeof COMPOSITION)[number],\n value: unknown,\n env: RecordEnv,\n piped: MType | undefined,\n): Result<Test, string> {\n if (name === 'not') {\n const inner = compilePredicate(value, env, piped)\n if (!inner.ok) return inner\n const test = inner.value\n return ok((p, r, c) => !test(p, r, c))\n }\n const of = (value as { of?: unknown } | null)?.of\n if (\n typeof value !== 'object' ||\n value === null ||\n Object.keys(value).length !== 1 ||\n !Array.isArray(of)\n ) {\n return err(`'${name}' takes { \"of\": [conditions] }`)\n }\n const tests: Test[] = []\n for (const [i, c] of of.entries()) {\n const compiled = compilePredicate(c, env, piped)\n if (!compiled.ok) return err(`${name}.of[${i}]: ${compiled.error}`)\n tests.push(compiled.value)\n }\n return ok(\n name === 'all'\n ? (p, r, c) => tests.every((x) => x(p, r, c))\n : (p, r, c) => tests.some((x) => x(p, r, c)),\n )\n}\n\nfunction compileSubject(\n path: unknown,\n env: RecordEnv,\n piped: MType | undefined,\n): Result<{ type: MType; get: Getter }, string> {\n if (path !== undefined) {\n if (typeof path !== 'string') return err('path must be a field name')\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n return ok({ type: type.value, get: (_p, r) => r[path] ?? null })\n }\n if (!piped || piped.kind === 'unit') {\n return err('this condition has no piped value to test; give it a \"path\"')\n }\n return ok({ type: piped, get: (p) => p })\n}\n\n/** Literal, `{ ref }` or `{ param }`. Strings compared with a date are date expressions. */\nexport function compileOperand(\n value: unknown,\n env: RecordEnv,\n asDate: boolean,\n): Result<Operand, string> {\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const keys = Object.keys(value)\n const o = value as { ref?: unknown; param?: unknown }\n if (keys.length === 1 && typeof o.ref === 'string') {\n const ref = o.ref\n const type = fieldType(env.record, ref)\n if (!type.ok) return type\n return ok({ type: type.value, get: (_p, r) => r[ref] ?? null })\n }\n if (keys.length === 1 && typeof o.param === 'string') {\n const name = o.param\n if (!Object.hasOwn(env.params, name)) return err(`unknown param '${name}'`)\n return literal(env.params[name] as Json, env, asDate)\n }\n return err('a comparison value is a literal, { \"ref\": field } or { \"param\": name }')\n }\n return literal(value as Json, env, asDate)\n}\n\nfunction literal(value: Json, env: RecordEnv, asDate: boolean): Result<Operand, string> {\n if (asDate && typeof value === 'string') {\n const expr = parseDateExpr(value)\n if (!expr.ok) return expr\n if (usesClock(expr.value)) env.clock.used = true\n return ok({ type: t.date, get: dateGetter(expr.value) })\n }\n if (asDate && Array.isArray(value) && value.every((v) => typeof v === 'string')) {\n const exprs: DateExpr[] = []\n for (const v of value as string[]) {\n const expr = parseDateExpr(v)\n if (!expr.ok) return expr\n if (usesClock(expr.value)) env.clock.used = true\n exprs.push(expr.value)\n }\n const getters = exprs.map(dateGetter)\n return ok({ type: t.list(t.date), get: (p, r, c) => getters.map((g) => g(p, r, c)) })\n }\n const constant = value as Val\n return ok({ type: typeOfJson(value), get: () => constant })\n}\n\n/** Resolve a date expression against the run clock, once per distinct clock. */\nfunction dateGetter(expr: DateExpr): Getter {\n let key = ''\n let cached: Instant = Instant.ofEpochMs(0)\n return (_p, _r, ctx) => {\n const k = `${ctx.now.epochMs}|${ctx.tz}`\n if (k !== key) {\n cached = resolveDateExpr(expr, ctx)\n key = k\n }\n return cached\n }\n}\n\nexport function compileRegex(pattern: string): Result<RegExp, string> {\n try {\n return ok(new RegExp(pattern, 'u'))\n } catch (e) {\n return err(`invalid regular expression: ${(e as Error).message}`)\n }\n}\n\n/**\n * Fields a passing record is known to have non-null: `{ path, is_null: false }` at the top\n * level or inside `all`. The `filter` node narrows its output type with these.\n */\nexport function nonNullPaths(raw: unknown): string[] {\n if (typeof raw !== 'object' || raw === null) return []\n const cond = raw as Predicate\n if (typeof cond.path === 'string' && cond.is_null === false) return [cond.path]\n const of = (cond.all as { of?: unknown } | undefined)?.of\n return Array.isArray(of) ? of.flatMap(nonNullPaths) : []\n}\n","/**\n * Node expectations and the action building blocks (arch.md, \"Actions for expect and\n * assert\"), shared by the version's `expect` block and `assert` nodes.\n *\n * Every clause is detected on the node's raw output first; then `drop_rows` removes the\n * rows it names, then `set_null` / `set_default` repair the remaining violating rows. So\n * the order clauses are written in never matters. Every breach is reported as an issue,\n * whatever its action.\n */\n\nimport type { RecordEnv, RunContext } from './context'\nimport type { Action, ActionSpec, Bound, Clause, NodeExpectation } from './document'\nimport type { NodeIssue, NodeOutput, RunIssue } from './nodes/def'\nimport { compilePredicate, type Test } from './predicate'\nimport { err, ok, type Result } from './result'\nimport {\n assignable,\n comparable,\n type MType,\n type RecordType,\n show,\n stripNull,\n t,\n typeOfJson,\n} from './types'\nimport { type Json, keyOf, type Rec, type Relation, toJson, type Val } from './values'\n\ntype ActionName = 'alert' | 'drop_rows' | 'set_null' | 'set_default' | 'skip_downstream' | 'stop'\n\nconst VALID: Readonly<Record<Clause | 'acyclic', readonly ActionName[]>> = {\n count: ['alert', 'skip_downstream', 'stop'],\n unique: ['alert', 'drop_rows', 'skip_downstream', 'stop'],\n keyed: ['alert', 'skip_downstream', 'stop'],\n rows: ['alert', 'drop_rows', 'set_null', 'set_default', 'skip_downstream', 'stop'],\n acyclic: ['alert', 'skip_downstream', 'stop'],\n}\n\nexport function actionName(action: Action): ActionName {\n if (typeof action === 'string') return action\n return 'set_null' in action ? 'set_null' : 'set_default'\n}\n\n/** Precedence: a bound's own action, then the clause's, then `default`, then the plain spec. */\nexport function resolveAction(spec: ActionSpec | undefined, clause: Clause, own?: Action): Action {\n if (own !== undefined) return own\n if (spec === undefined) return 'alert'\n if (typeof spec === 'string' || 'set_null' in spec || 'set_default' in spec) return spec as Action\n const keyed = spec as Partial<Record<Clause | 'default', Action>>\n return keyed[clause] ?? keyed.default ?? 'alert'\n}\n\n/** Check an action fits its check and the output type; returns the repaired output type. */\nexport function checkAction(\n action: Action,\n check: Clause | 'acyclic',\n output: NodeOutput,\n): Result<NodeOutput, string> {\n const name = actionName(action)\n if (!VALID[check].includes(name)) return err(`action ${name} does not apply to ${check}`)\n if (typeof action === 'string') return ok(output)\n const fields = 'set_null' in action ? action.set_null : Object.keys(action.set_default)\n const unknown = fields.filter((f) => !Object.hasOwn(output.type.fields, f))\n if (unknown.length) return err(`${name} names unknown fields: ${unknown.join(', ')}`)\n if ('set_default' in action) {\n for (const [f, v] of Object.entries(action.set_default)) {\n const type = output.type.fields[f] as MType\n if (v === null || !assignable(typeOfJson(v), stripNull(type))) {\n return err(`set_default ${f}: ${JSON.stringify(v)} is not a ${show(stripNull(type))}`)\n }\n }\n return ok(output)\n }\n // set_null widens the repaired fields, so every consumer is checked against nulls there.\n const widened = { ...output.type.fields }\n for (const f of action.set_null) widened[f] = t.nullable(widened[f] as MType)\n return ok({ ...output, type: t.record(widened) })\n}\n\nexport interface Violation {\n readonly clause: string\n readonly action: Action\n readonly message: string\n readonly count: number\n readonly samples: readonly Json[]\n /** Positions of the violating rows, for row actions. */\n readonly rows?: readonly number[]\n}\n\nexport interface Outcome {\n readonly rows: Relation\n readonly changed: number\n readonly issues: readonly RunIssue[]\n readonly stop: boolean\n readonly skipDownstream: boolean\n}\n\n/** Apply the actions of the detected violations to `rows`, reporting each as an issue. */\nexport function applyViolations(\n node: string,\n code: string,\n rows: Relation,\n violations: readonly Violation[],\n): Outcome {\n const dropped = new Set<number>()\n for (const v of violations) {\n if (actionName(v.action) === 'drop_rows') for (const i of v.rows ?? []) dropped.add(i)\n }\n const patches = new Map<number, Record<string, Val>>()\n for (const v of violations) {\n if (typeof v.action === 'string') continue\n const patch: Record<string, Val> =\n 'set_null' in v.action\n ? Object.fromEntries(v.action.set_null.map((f) => [f, null]))\n : (v.action.set_default as Record<string, Val>)\n for (const i of v.rows ?? []) {\n if (!dropped.has(i)) patches.set(i, { ...patches.get(i), ...patch })\n }\n }\n const out: Rec[] = []\n for (const [i, row] of rows.entries()) {\n if (dropped.has(i)) continue\n const patch = patches.get(i)\n out.push(patch ? { ...row, ...patch } : row)\n }\n const affected = (v: Violation) =>\n actionName(v.action) === 'drop_rows'\n ? (v.rows ?? []).length\n : typeof v.action === 'string'\n ? undefined\n : (v.rows ?? []).filter((i) => !dropped.has(i)).length\n return {\n rows: out,\n changed: dropped.size + patches.size,\n stop: violations.some((v) => v.action === 'stop'),\n skipDownstream: violations.some((v) => v.action === 'skip_downstream'),\n issues: violations.map((v) => ({\n node,\n code,\n clause: v.clause,\n action: v.action,\n message: v.message,\n count: v.count,\n samples: v.samples,\n ...(affected(v) === undefined ? {} : { rowsAffected: affected(v) }),\n })),\n }\n}\n\nconst SAMPLES = 5\n\nexport function countViolation(\n count: number,\n bound: Bound & { readonly shiftRatio?: Bound },\n action: Action,\n baseline: number | undefined,\n): Violation | undefined {\n const problems: string[] = []\n if (bound.min !== undefined && count < bound.min)\n problems.push(`count ${count} below ${bound.min}`)\n if (bound.max !== undefined && count > bound.max)\n problems.push(`count ${count} above ${bound.max}`)\n const shift = bound.shiftRatio\n if (shift && baseline !== undefined && baseline > 0) {\n const ratio = count / baseline\n if (\n (shift.min !== undefined && ratio < shift.min) ||\n (shift.max !== undefined && ratio > shift.max)\n ) {\n problems.push(`count ${count} is ${ratio.toFixed(2)}x the baseline ${baseline}`)\n }\n }\n return problems.length\n ? { clause: 'count', action, message: problems.join('; '), count: 1, samples: [count] }\n : undefined\n}\n\nexport function uniqueViolation(\n rows: Relation,\n keys: readonly string[],\n action: Action,\n): Violation | undefined {\n const groups = new Map<string, number[]>()\n for (const [i, row] of rows.entries()) {\n const k = keyOf(row, keys)\n const g = groups.get(k)\n if (g) g.push(i)\n else groups.set(k, [i])\n }\n const duplicates = [...groups.values()].filter((g) => g.length > 1)\n if (duplicates.length === 0) return undefined\n return {\n clause: 'unique',\n action,\n message: `${keys.join(', ')} not unique: ${duplicates.length} duplicated keys`,\n count: duplicates.length,\n samples: duplicates\n .slice(0, SAMPLES)\n .map((g) => keys.map((k) => toJson((rows[g[0] as number] as Rec)[k] ?? null))),\n rows: duplicates.flat(),\n }\n}\n\nexport function rowsViolation(\n rows: Relation,\n test: Test,\n ctx: RunContext,\n action: Action,\n): Violation | undefined {\n const bad: number[] = []\n for (const [i, row] of rows.entries()) if (!test(null, row, ctx)) bad.push(i)\n if (bad.length === 0) return undefined\n return {\n clause: 'rows',\n action,\n message: `${bad.length} rows fail the row condition`,\n count: bad.length,\n samples: bad.slice(0, SAMPLES).map((i) => toJson(rows[i] as Rec)),\n rows: bad,\n }\n}\n\ntype Keyed = NonNullable<NodeExpectation['keyed']>\n\n/** A key with no row counts as 0, so it fails a positive `min` and passes any `max`. */\nexport function keyedViolations(\n rows: Relation,\n keyed: Keyed,\n spec: ActionSpec | undefined,\n): Violation[] {\n const values = new Map<string, Val>()\n for (const row of rows) {\n const by = row[keyed.by] ?? null\n const k = typeof by === 'string' ? by : JSON.stringify(toJson(by))\n if (!values.has(k)) values.set(k, row[keyed.value] ?? null)\n }\n const out: Violation[] = []\n for (const [key, bound] of Object.entries(keyed.bounds)) {\n const raw = values.get(key)\n const value = typeof raw === 'number' ? raw : 0\n const low = bound.min !== undefined && value < bound.min\n const high = bound.max !== undefined && value > bound.max\n if (low || high) {\n out.push({\n clause: 'keyed',\n action: resolveAction(spec, 'keyed', bound.onFail),\n message: `${keyed.by} ${key}: ${keyed.value} ${value} ${low ? `below ${bound.min}` : `above ${bound.max}`}`,\n count: 1,\n samples: [key],\n })\n }\n }\n return out\n}\n\nexport interface CheckOptions {\n /** Previous count of this node, for `count.shiftRatio`. */\n readonly baseline?: number\n /** Fixtures run at sample scale, so production `count` envelopes are skipped. */\n readonly skipCount?: boolean\n}\n\nexport type Checker = (rows: Relation, ctx: RunContext, options: CheckOptions) => Outcome\n\n/** Compile a node's `expect` entry against its output; returns the repaired output type. */\nexport function compileExpectation(\n node: string,\n exp: NodeExpectation,\n output: NodeOutput,\n renv: (record: RecordType) => RecordEnv,\n): Result<{ output: NodeOutput; check: Checker }, readonly NodeIssue[]> {\n const issues: NodeIssue[] = []\n const issue = (field: Clause, message: string) =>\n issues.push({ message, field, code: 'invalid_expectation' })\n let repaired = output\n const fields = output.type.fields\n const missing = (names: readonly string[]) => names.filter((f) => !Object.hasOwn(fields, f))\n\n for (const clause of ['count', 'unique', 'keyed', 'rows'] as const) {\n if (exp[clause] === undefined) continue\n const action = resolveAction(exp.onFail, clause)\n const checked = checkAction(action, clause, repaired)\n if (checked.ok) repaired = checked.value\n else issue(clause, checked.error)\n }\n if (exp.unique && missing(exp.unique).length) {\n issue('unique', `unknown fields: ${missing(exp.unique).join(', ')}`)\n }\n if (exp.keyed) {\n const keyed = exp.keyed\n if (missing([keyed.by, keyed.value]).length) {\n issue('keyed', `unknown fields: ${missing([keyed.by, keyed.value]).join(', ')}`)\n } else if (!comparable(fields[keyed.value] as MType, t.number)) {\n issue('keyed', `${keyed.value} must be a number`)\n }\n for (const bound of Object.values(keyed.bounds)) {\n if (bound.onFail === undefined) continue\n const checked = checkAction(bound.onFail, 'keyed', repaired)\n if (!checked.ok) issue('keyed', checked.error)\n }\n }\n let test: Test | undefined\n if (exp.rows) {\n const compiled = compilePredicate(exp.rows.cond, renv(output.type))\n if (compiled.ok) test = compiled.value\n else issue('rows', compiled.error)\n }\n if (issues.length) return { ok: false, error: issues }\n\n const check: Checker = (rows, ctx, options) => {\n const violations: Violation[] = []\n const push = (v: Violation | undefined) => v && violations.push(v)\n if (exp.count && !options.skipCount) {\n push(\n countViolation(\n rows.length,\n exp.count,\n resolveAction(exp.onFail, 'count'),\n options.baseline,\n ),\n )\n }\n if (exp.unique) push(uniqueViolation(rows, exp.unique, resolveAction(exp.onFail, 'unique')))\n if (exp.keyed) violations.push(...keyedViolations(rows, exp.keyed, exp.onFail))\n if (test) push(rowsViolation(rows, test, ctx, resolveAction(exp.onFail, 'rows')))\n return applyViolations(node, 'expectation', rows, violations)\n }\n return ok({ output: repaired, check })\n}\n","/**\n * Collection node definitions (arch.md, \"Node definition, collection scope\").\n *\n * A node definition compiles itself: from its params and the types of its inputs it returns\n * its output type and a closure, in one step, so type checking and compilation stay the same\n * pass. Nodes reference their inputs by id; `slots` say which params hold those ids, which is\n * all the graph utilities and the editor need to know about edges.\n */\n\nimport { z } from 'zod'\nimport type { GraphEnv, RecordEnv, RunContext } from '../context'\nimport type { Action, JsonSchema, MappingVersion, NodeExpectation } from '../document'\nimport type { CompileCode, Result } from '../result'\nimport type { MType, RecordType } from '../types'\nimport type { Json, Relation } from '../values'\n\n/** Where a field's value was produced, so a sink can blame the right `map` field. */\nexport interface Origin {\n readonly node: string\n readonly field: string\n /** The field may be absent from a record (`omit_if_null`, `on_error: skip_field`). */\n readonly omittable: boolean\n /** Type of the value when present; set exactly for omittable fields. */\n readonly present?: MType\n}\n\n/**\n * Compile-time output of a node: its record type plus per-field provenance. Invariants: every\n * field has an origin, and an omittable field is typed nullable (an absent field reads null).\n */\nexport interface NodeOutput {\n readonly type: RecordType\n readonly origins: Readonly<Record<string, Origin>>\n /** Can drop records on a failed field (limitation #20). */\n readonly canSkip?: boolean\n}\n\n/** An input slot: the param path that holds an upstream node id. */\nexport interface Slot {\n readonly id: string\n readonly label: string\n readonly path: readonly string[]\n /** Holds a list of ids (`union.inputs`). */\n readonly multiple?: boolean\n readonly optional?: boolean\n}\n\nexport type NodeCategory = 'source' | 'transform' | 'target' | 'check'\n\n/** What a node definition sees while compiling. */\nexport interface NodeEnv {\n readonly id: string\n readonly graph: GraphEnv\n readonly version: Pick<\n MappingVersion,\n 'params' | 'tables' | 'expectedSchema' | 'onError' | 'expect'\n >\n /** This node's entry in the version's `expect` block. */\n readonly expect?: NodeExpectation\n readonly clock: { used: boolean }\n /** Output of an upstream node; the compiler only calls `compile` once all inputs exist. */\n input(id: string): NodeOutput\n recordEnv(record: RecordType): RecordEnv\n}\n\nexport interface NodeIssue {\n readonly message: string\n readonly code?: CompileCode\n /** Blame another node, e.g. the `map` that produced a field a sink rejects. */\n readonly node?: string\n readonly field?: string\n readonly step?: number\n}\n\n/** A problem found while running, reported on the run rather than failing it. */\nexport interface RunIssue {\n readonly node: string\n readonly code: string\n readonly message: string\n readonly field?: string\n readonly clause?: string\n readonly action?: Action\n readonly count?: number\n readonly rowsAffected?: number\n readonly samples?: readonly Json[]\n}\n\nexport interface SinkWrite {\n readonly sink: string\n readonly target: string\n /** Target paths of the upsert key. */\n readonly key: readonly string[]\n /** Rows by target path, sorted by key. Dates are `YYYY-MM-DD`, timestamps ISO. */\n readonly rows: readonly Readonly<Record<string, Json>>[]\n readonly write?: Readonly<Record<string, WritePolicy>>\n /**\n * Reference fields written as natural keys, by target path. The host resolves each value\n * (one field of `by`, or a list in `by` order) to the id of the `entity` row it names.\n */\n readonly refs?: Readonly<Record<string, SinkRef>>\n /**\n * The rows are the complete set of the target for the company (and source system, where\n * the identity has one): the host calls `synchronize_all(rows, scope)`, deleting rows not\n * written. Writes of one run go in one transaction, inserts parent-first and deletes\n * child-first (exclusions before the lanes they reference). A sink that does not write\n * (held, stopped, failed) deletes nothing.\n */\n readonly mode?: 'replace'\n}\n\nexport type WritePolicy = 'overwrite' | 'fill_if_null' | 'never'\n\nexport interface SinkRef {\n readonly entity: string\n readonly by: readonly string[]\n}\n\nexport interface Metric {\n readonly node: string\n readonly name: string\n readonly rows: readonly Readonly<Record<string, Json>>[]\n}\n\nexport interface NodeRun {\n readonly rows: Relation\n /** Records a `map` dropped under `skip_record`. */\n readonly skipped?: number\n /** Rows dropped or repaired by an action. */\n readonly changed?: number\n readonly issues?: readonly RunIssue[]\n readonly stop?: boolean\n readonly skipDownstream?: boolean\n readonly write?: SinkWrite\n readonly metric?: Metric\n}\n\nexport interface NodeFailure {\n readonly code: string\n readonly message: string\n /** Halts the run (`on_error: fail_sync`). */\n readonly stop?: boolean\n readonly issues?: readonly RunIssue[]\n readonly samples?: readonly Json[]\n}\n\nexport type Inputs = (id: string) => Relation\n\nexport interface RunOptions {\n /** Previous output count of this node, for `count.shiftRatio`. */\n readonly baseline?: number\n /** Fixture runs are sample-sized, so production `count` envelopes are skipped. */\n readonly skipCount?: boolean\n}\n\nexport interface CompiledNode {\n /** Null for a node without an output relation (`sink`); `metrics` types what it reports. */\n readonly output: NodeOutput | null\n /** Target entities a sink writes (one sink per entity, structural rule 3). */\n readonly writes?: readonly string[]\n readonly run: (\n inputs: Inputs,\n ctx: RunContext,\n options?: RunOptions,\n ) => Result<NodeRun, NodeFailure>\n}\n\nexport interface NodeDef<P = unknown> {\n readonly op: string\n readonly label: string\n readonly category: NodeCategory\n readonly description: string\n readonly slots: readonly Slot[]\n /** Has an output edge. */\n readonly output: boolean\n /** Has an effect: a write, a metric, or a check. Every node must reach one. */\n readonly effect?: 'sink' | 'metrics' | 'check'\n /** Params a new node starts with in the editor. */\n readonly defaults: () => Record<string, unknown>\n /** Parses the node object without `id`, `op` and `label`. */\n readonly params: z.ZodType<P>\n /** Accepts `tolerate_skips` (limitation #20). */\n readonly toleratesSkips?: (params: P) => boolean\n readonly compile: (params: P, env: NodeEnv) => Result<CompiledNode, readonly NodeIssue[]>\n}\n\nexport function defineNode<P>(def: NodeDef<P>): NodeDef<P> {\n return def\n}\n\nexport const nodeId = z.string().min(1)\n\n/** Origins for fields a node produces itself. */\nexport function ownOrigins(node: string, type: RecordType): Record<string, Origin> {\n return Object.fromEntries(\n Object.keys(type.fields).map((field) => [field, { node, field, omittable: false }]),\n )\n}\n\n/** Shorthand for a single issue result. */\nexport function fail(message: string, extra: Omit<NodeIssue, 'message'> = {}) {\n return { ok: false as const, error: [{ message, ...extra }] as readonly NodeIssue[] }\n}\n\nexport type { JsonSchema }\n","/**\n * `aggregate`: one record per group of `group_by` (one record overall for `group_by: []`,\n * even on empty input). Every aggregation takes an optional `where`, making it a filtered\n * aggregate. Results never depend on input order: `sum` adds in sorted order, `collect_set`\n * is sorted, and `collect_list`, `first`, `last` require `order_by` (limitation #17).\n */\n\nimport { z } from 'zod'\nimport type { RunContext } from '../context'\nimport { compilePredicate, type Test } from '../predicate'\nimport { ok } from '../result'\nimport { type MType, orderable, type RecordType, show, stripNull, t } from '../types'\nimport {\n canonicalKey,\n compareVals,\n keyOf,\n type Rec,\n type Relation,\n sortRecords,\n type Val,\n} from '../values'\nimport { defineNode, type NodeEnv, nodeId, type NodeIssue, type Origin, ownOrigins } from './def'\n\nconst orderBy = z\n .array(\n z.union([\n z.string().min(1),\n z.strictObject({ path: z.string().min(1), desc: z.boolean().optional() }),\n ]),\n )\n .min(1)\n\nconst agg = z.strictObject({\n agg: z.enum([\n 'count',\n 'count_distinct',\n 'sum',\n 'min',\n 'max',\n 'collect_set',\n 'collect_list',\n 'first',\n 'last',\n 'any',\n 'all',\n ]),\n path: z.string().min(1).optional(),\n where: z.unknown().optional(),\n order_by: orderBy.optional(),\n cond: z.unknown().optional(),\n})\ntype Agg = z.infer<typeof agg>\n\nconst params = z.strictObject({\n in: nodeId,\n group_by: z.array(z.string().min(1)),\n fields: z\n .record(z.string().min(1), agg)\n .refine((f) => Object.keys(f).length > 0, 'needs at least one field'),\n tolerate_skips: z.boolean().optional(),\n})\n\nconst NEEDS_PATH = new Set([\n 'count_distinct',\n 'sum',\n 'min',\n 'max',\n 'collect_set',\n 'collect_list',\n 'first',\n 'last',\n])\nconst NEEDS_ORDER = new Set(['collect_list', 'first', 'last'])\nconst NEEDS_COND = new Set(['any', 'all'])\n\ntype Compute = (rows: Relation, ctx: RunContext) => Val\n\nfunction compileAgg(\n name: string,\n spec: Agg,\n input: RecordType,\n env: NodeEnv,\n): { type: MType; compute: Compute } | NodeIssue {\n const issue = (message: string): NodeIssue => ({ message, field: name })\n const renv = env.recordEnv(input)\n if (NEEDS_PATH.has(spec.agg) !== (spec.path !== undefined)) {\n return issue(\n NEEDS_PATH.has(spec.agg) ? `${spec.agg} needs a path` : `${spec.agg} takes no path`,\n )\n }\n if (NEEDS_ORDER.has(spec.agg) !== (spec.order_by !== undefined)) {\n return issue(\n NEEDS_ORDER.has(spec.agg) ? `${spec.agg} needs order_by` : `${spec.agg} takes no order_by`,\n )\n }\n if (NEEDS_COND.has(spec.agg) !== (spec.cond !== undefined)) {\n return issue(\n NEEDS_COND.has(spec.agg) ? `${spec.agg} needs a cond` : `${spec.agg} takes no cond`,\n )\n }\n const path = spec.path\n const fieldType = path === undefined ? undefined : input.fields[path]\n if (path !== undefined && !fieldType) return issue(`unknown field '${path}'`)\n const order = (spec.order_by ?? []).map((o) =>\n typeof o === 'string' ? { path: o, desc: false } : { desc: false, ...o },\n )\n const unknownOrder = order.filter((o) => !Object.hasOwn(input.fields, o.path))\n if (unknownOrder.length)\n return issue(`order_by: unknown field '${(unknownOrder[0] as { path: string }).path}'`)\n\n let where: Test | undefined\n if (spec.where !== undefined) {\n const w = compilePredicate(spec.where, renv)\n if (!w.ok) return issue(`where: ${w.error}`)\n where = w.value\n }\n let cond: Test | undefined\n if (spec.cond !== undefined) {\n const c = compilePredicate(spec.cond, renv)\n if (!c.ok) return issue(`cond: ${c.error}`)\n cond = c.value\n }\n\n const values = (rows: Relation) => rows.map((r) => r[path as string] ?? null)\n const nonNull = (rows: Relation) => values(rows).filter((v) => v !== null)\n const sorted = (rows: Relation) =>\n [...rows].sort((a, b) => {\n for (const o of order) {\n const c = compareVals(a[o.path] ?? null, b[o.path] ?? null)\n if (c !== 0) return o.desc ? -c : c\n }\n return compareVals(canonicalKey(a), canonicalKey(b))\n })\n const base = fieldType ? stripNull(fieldType) : t.unknown\n\n let type: MType\n let compute: Compute\n switch (spec.agg) {\n case 'count':\n type = t.number\n compute = (rows) => rows.length\n break\n case 'count_distinct':\n type = t.number\n compute = (rows) => new Set(nonNull(rows).map(canonicalKey)).size\n break\n case 'sum':\n if (base.kind !== 'number')\n return issue(`sum needs a number field, ${path} is ${show(fieldType as MType)}`)\n type = t.nullable(t.number)\n compute = (rows) => {\n const xs = (nonNull(rows) as number[]).sort((a, b) => a - b)\n return xs.length === 0 ? null : xs.reduce((a, b) => a + b, 0)\n }\n break\n case 'min':\n case 'max': {\n if (!orderable(base))\n return issue(\n `${spec.agg} needs a number, string or date field, ${path} is ${show(fieldType as MType)}`,\n )\n type = t.nullable(base)\n const sign = spec.agg === 'min' ? 1 : -1\n compute = (rows) => nonNull(rows).sort((a, b) => sign * compareVals(a, b))[0] ?? null\n break\n }\n case 'collect_set':\n type = t.list(base)\n compute = (rows) => {\n const seen = new Map<string, Val>()\n for (const v of nonNull(rows)) seen.set(canonicalKey(v), v)\n return [...seen.values()].sort(compareVals)\n }\n break\n case 'collect_list':\n type = t.list(fieldType as MType)\n compute = (rows) => sorted(rows).map((r) => r[path as string] ?? null)\n break\n case 'first':\n case 'last': {\n type = t.nullable(fieldType as MType)\n const pick = spec.agg === 'first' ? 0 : -1\n compute = (rows) => sorted(rows).at(pick)?.[path as string] ?? null\n break\n }\n default: {\n type = t.boolean\n const test = cond as Test\n compute =\n spec.agg === 'any'\n ? (rows, ctx) => rows.some((r) => test(null, r, ctx))\n : (rows, ctx) => rows.every((r) => test(null, r, ctx))\n }\n }\n if (where) {\n const w = where\n const inner = compute\n compute = (rows, ctx) =>\n inner(\n rows.filter((r) => w(null, r, ctx)),\n ctx,\n )\n }\n return { type, compute }\n}\n\nexport const aggregateNode = defineNode({\n op: 'aggregate',\n label: 'Aggregate',\n category: 'transform',\n description: 'One record per group, with counts, sums, sets and other aggregates.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', group_by: [], fields: {} }),\n params,\n toleratesSkips: (p) => p.tolerate_skips === true,\n compile: (p, env) => {\n const input = env.input(p.in)\n const issues: NodeIssue[] = []\n const fields: Record<string, MType> = {}\n for (const g of p.group_by) {\n const type = input.type.fields[g]\n if (type) fields[g] = type\n else issues.push({ message: `group_by: unknown field '${g}'` })\n }\n const aggs: { name: string; compute: Compute }[] = []\n for (const [name, spec] of Object.entries(p.fields)) {\n if (p.group_by.includes(name)) {\n issues.push({ message: `'${name}' is both a group key and an aggregate`, field: name })\n continue\n }\n const compiled = compileAgg(name, spec, input.type, env)\n if ('message' in compiled) issues.push(compiled)\n else {\n fields[name] = compiled.type\n aggs.push({ name, compute: compiled.compute })\n }\n }\n if (issues.length) return { ok: false, error: issues }\n\n const type = t.record(fields)\n return ok({\n output: {\n type,\n origins: {\n ...ownOrigins(env.id, type),\n ...Object.fromEntries(p.group_by.map((g) => [g, input.origins[g] as Origin])),\n },\n },\n run: (inputs, ctx) => {\n const groups = new Map<string, Rec[]>()\n // `group_by: []` yields one record even for empty input.\n if (p.group_by.length === 0) groups.set(keyOf({}, []), [])\n for (const row of inputs(p.in)) {\n const k = keyOf(row, p.group_by)\n const g = groups.get(k)\n if (g) g.push(row)\n else groups.set(k, [row])\n }\n const rows: Rec[] = []\n for (const members of groups.values()) {\n const out: Record<string, Val> = {}\n const sample = members[0]\n for (const g of p.group_by) out[g] = (sample as Rec)[g] ?? null\n for (const a of aggs) out[a.name] = a.compute(members, ctx)\n rows.push(out)\n }\n return ok({ rows: sortRecords(rows, p.group_by) })\n },\n })\n },\n})\n","/**\n * Record op definitions (arch.md, \"Op definition, record scope\").\n *\n * An op is a params schema, a type function and a curried implementation. `signature` is\n * the validator's half; `run` binds params once per compiled version and returns the\n * per-record step. With `nulls: 'propagate'` the pipeline compiler handles a null input, so\n * `run` never sees null and `signature` never sees a nullable type.\n */\n\nimport { z } from 'zod'\nimport type { RecordContext, RecordEnv } from '../context'\nimport { err, ok, type Result, type StepError } from '../result'\nimport type { MType } from '../types'\nimport type { Omitted, Val } from '../values'\n\nexport type StepResult = Result<Val | Omitted, StepError>\n\nexport type Step = (input: Val, ctx: RecordContext) => StepResult\n\nexport interface OpDef<P = unknown> {\n readonly name: string\n /** Parses the step object without its `op` key. Unknown keys are rejected. */\n readonly params: z.ZodType<P>\n /** Who handles a null input: the compiler ('propagate') or this op ('consume'). */\n readonly nulls: 'propagate' | 'consume'\n /**\n * What the op reads: 'value' (default) needs a piped value; 'none' starts a pipeline and\n * takes no piped input (`()` in arch.md signatures); 'any' accepts either (`when`).\n */\n readonly input?: 'value' | 'none' | 'any'\n /** Must be the last step (`omit_if_null`). */\n readonly terminal?: boolean\n /** Whether this op can return an error at runtime, given its params (limitation #20). */\n readonly fallible: (params: P, env: RecordEnv, input: MType) => boolean\n /** Output type for an input type; an error message when the input is not accepted. */\n readonly signature: (input: MType, params: P, env: RecordEnv) => Result<MType, string>\n /** Bind params once; `input` is the (null-stripped) input type `signature` accepted. */\n readonly run: (params: P, env: RecordEnv, input: MType) => Step\n}\n\n/** Identity function that keeps `P` inferred from the params schema. */\nexport function defineOp<P>(def: OpDef<P>): OpDef<P> {\n return def\n}\n\nexport const never = () => false\nexport const always = () => true\n\n/** Expect an exact non-null kind. */\nexport function expectKind(\n input: MType,\n kinds: readonly MType['kind'][],\n op: string,\n): Result<MType, string> {\n return kinds.includes(input.kind)\n ? ok(input)\n : err(`${op} expects ${kinds.join(' or ')}, got ${showKind(input)}`)\n}\n\nfunction showKind(input: MType): string {\n return input.kind === 'nullable'\n ? `${input.of.kind}?`\n : input.kind === 'unit'\n ? 'no input'\n : input.kind\n}\n\n/** JSON literal accepted in params. */\nexport const json: z.ZodType<import('../values').Json> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(json),\n z.record(z.string(), json),\n ]),\n)\n\n/** Strict object schema, so a typo'd param is an error rather than ignored. */\nexport const params = <S extends z.ZodRawShape>(shape: S) => z.strictObject(shape)\n","/**\n * The mapping document (arch.md, \"The mapping document\"): one version of a mapping, stored as\n * JSON. It carries the graph (`nodes`), the assumptions about each source (`expectedSchema`,\n * which is also the type environment), expectations about what nodes produce (`expect`),\n * named constants (`params`), lookup tables (`tables`) and fixtures (`examples`).\n *\n * Nodes are flat objects, `{ id, op, ...params }`, and reference their inputs by id; there is\n * no edge list. Node params are validated by the node's definition when the version compiles,\n * so a draft with a half-edited node still parses. `layout` is editor state only.\n */\n\nimport { z } from 'zod'\nimport { json } from './ops/def'\n\nexport const OnError = z.enum(['null', 'skip_field', 'skip_record', 'fail_sync'])\nexport type OnError = z.infer<typeof OnError>\n\nexport const Action = z.union([\n z.enum(['alert', 'drop_rows', 'skip_downstream', 'stop']),\n z.strictObject({ set_null: z.array(z.string().min(1)).min(1) }),\n z.strictObject({ set_default: z.record(z.string(), json) }),\n])\nexport type Action = z.infer<typeof Action>\n\nexport const CLAUSES = ['count', 'unique', 'keyed', 'rows'] as const\nexport type Clause = (typeof CLAUSES)[number]\n\n/** One action for every clause, or one per clause with a fallback. */\nexport const ActionSpec = z.union([\n Action,\n z.strictObject({\n default: Action.optional(),\n count: Action.optional(),\n unique: Action.optional(),\n keyed: Action.optional(),\n rows: Action.optional(),\n }),\n])\nexport type ActionSpec = z.infer<typeof ActionSpec>\n\nexport const Bound = z.strictObject({ min: z.number().optional(), max: z.number().optional() })\nexport type Bound = z.infer<typeof Bound>\n\nexport const NodeExpectation = z.strictObject({\n /** Absolute bounds, and drift relative to a baseline the host passes per run. */\n count: Bound.extend({ shiftRatio: Bound.optional() }).optional(),\n /** Fields whose combination must be unique in the node's output. */\n unique: z.array(z.string().min(1)).min(1).optional(),\n /** Bounds on individual rows of a small keyed relation, typically counters. */\n keyed: z\n .strictObject({\n by: z.string().min(1),\n value: z.string().min(1),\n bounds: z.record(z.string(), Bound.extend({ onFail: Action.optional() })),\n })\n .optional(),\n /** A predicate every row must satisfy. */\n rows: z.strictObject({ cond: z.unknown() }).optional(),\n onFail: ActionSpec.optional(),\n note: z.string().optional(),\n})\nexport type NodeExpectation = z.infer<typeof NodeExpectation>\n\nconst Rows = z.array(z.record(z.string(), json))\n\n/** A fixture: relations in, keyed by source node id; relations out, keyed by any node id. */\nexport const Example = z.strictObject({\n name: z.string().optional(),\n sources: z.record(z.string(), Rows).default({}),\n expect: z.record(z.string(), Rows).default({}),\n /** Frozen clock for the fixture run (ISO instant); required if the graph reads the clock. */\n now: z.string().optional(),\n tz: z.string().optional(),\n})\nexport type Example = z.infer<typeof Example>\n\nexport const NodeJson = z.looseObject({\n id: z.string().min(1),\n op: z.string().min(1),\n label: z.string().optional(),\n})\nexport type NodeJson = z.infer<typeof NodeJson>\n\nexport const Position = z.object({ x: z.number(), y: z.number() })\nexport type Position = z.infer<typeof Position>\n\n/** One JSON Schema document per source node, describing one record of that source. */\nexport const JsonSchema = z.record(z.string(), z.unknown())\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\nexport const MappingVersion = z.object({\n id: z.string().min(1),\n name: z.string().optional(),\n version: z.number().int().min(1).default(1),\n status: z.enum(['draft', 'published']).default('draft'),\n /** Default `on_error` of `map` nodes; a node's own `on_error` overrides it. */\n onError: OnError.optional(),\n unknownFields: z.enum(['ignore', 'notify']).optional(),\n params: z.record(z.string(), json).default({}),\n tables: z.record(z.string(), z.record(z.string(), json)).default({}),\n expectedSchema: z.record(z.string(), JsonSchema).default({}),\n nodes: z.array(NodeJson).default([]),\n expect: z.record(z.string(), NodeExpectation).default({}),\n examples: z.array(Example).default([]),\n layout: z.record(z.string(), Position).optional(),\n})\nexport type MappingVersion = z.infer<typeof MappingVersion>\n/** A version as authored, before defaults are filled in. */\nexport type MappingVersionInput = z.input<typeof MappingVersion>\n\n/** Parse untrusted JSON into a version; throws a zod error with paths on failure. */\nexport function parseVersion(input: unknown): MappingVersion {\n return MappingVersion.parse(input)\n}\n\nexport function emptyVersion(id: string, name?: string): MappingVersion {\n return parseVersion(name === undefined ? { id } : { id, name })\n}\n\n/** JSON Schema of the mapping document, for tools and models that produce mappings. */\nexport function versionJsonSchema(): Record<string, unknown> {\n return z.toJSONSchema(MappingVersion, { io: 'input' }) as Record<string, unknown>\n}\n","/**\n * `assert`: a named built-in check on its `in` relation, which it passes through (repaired, if\n * the chosen action repairs rows), so it can guard a flow or end a branch. `on_fail` is one\n * of the expectation actions, `alert` by default.\n *\n * - `count`: `min` / `max` rows.\n * - `unique`: `keys` unique.\n * - `rows`: every row satisfies `cond`.\n * - `acyclic`: the edges `edge.from -> edge.to` of `in` contain no cycle. With `edge.key` the\n * edges belong to groups (an article's own routing graph) and each group is checked on its\n * own; with `per`, every distinct `per.key` of `per.in` is checked against all edges. Either\n * way a group's rows of `remove.in` are taken out first. Cycle detection is iterative, so\n * it is engine code rather than a composition of DAG nodes.\n */\n\nimport { z } from 'zod'\nimport type { RunContext } from '../context'\nimport { Action } from '../document'\nimport {\n applyViolations,\n checkAction,\n countViolation,\n rowsViolation,\n uniqueViolation,\n type Violation,\n} from '../expect'\nimport { compilePredicate, type Test } from '../predicate'\nimport { ok } from '../result'\nimport { comparable, type MType, show } from '../types'\nimport { canonicalKey, compareVals, type Json, type Relation, toJson, type Val } from '../values'\nimport { defineNode, type NodeEnv, nodeId, type NodeIssue, type NodeOutput } from './def'\n\nconst common = { in: nodeId, on_fail: Action.optional() }\n\nconst params = z.discriminatedUnion('check', [\n z.strictObject({\n ...common,\n check: z.literal('count'),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n z.strictObject({\n ...common,\n check: z.literal('unique'),\n keys: z.array(z.string().min(1)).min(1),\n }),\n z.strictObject({ ...common, check: z.literal('rows'), cond: z.unknown() }),\n z.strictObject({\n ...common,\n check: z.literal('acyclic'),\n edge: z.strictObject({\n from: z.string().min(1),\n to: z.string().min(1),\n key: z.string().min(1).optional(),\n }),\n per: z.strictObject({ in: nodeId, key: z.string().min(1) }).optional(),\n remove: z\n .strictObject({\n in: nodeId,\n key: z.string().min(1),\n from: z.string().min(1),\n to: z.string().min(1),\n where: z.unknown().optional(),\n })\n .optional(),\n }),\n])\ntype Params = z.infer<typeof params>\ntype Acyclic = Extract<Params, { check: 'acyclic' }>\n\n/** One cycle as a path (first node repeated at the end), or undefined. */\nexport function findCycle(edges: readonly (readonly [string, string])[]): string[] | undefined {\n const next = new Map<string, string[]>()\n for (const [from, to] of edges) next.set(from, [...(next.get(from) ?? []), to])\n const state = new Map<string, 'open' | 'done'>()\n const path: string[] = []\n const visit = (node: string): string[] | undefined => {\n state.set(node, 'open')\n path.push(node)\n for (const to of next.get(node) ?? []) {\n if (state.get(to) === 'open') return [...path.slice(path.indexOf(to)), to]\n if (!state.has(to)) {\n const cycle = visit(to)\n if (cycle) return cycle\n }\n }\n path.pop()\n state.set(node, 'done')\n return undefined\n }\n for (const node of [...next.keys()].sort()) {\n if (state.has(node)) continue\n const cycle = visit(node)\n if (cycle) return cycle\n }\n return undefined\n}\n\nfunction fieldIssues(output: NodeOutput, fields: readonly string[], where: string): NodeIssue[] {\n return fields\n .filter((f) => !Object.hasOwn(output.type.fields, f))\n .map((f) => ({ message: `${where}: unknown field '${f}'` }))\n}\n\nfunction compileAcyclic(p: Acyclic, input: NodeOutput, env: NodeEnv) {\n const issues = fieldIssues(\n input,\n [p.edge.from, p.edge.to, ...(p.edge.key ? [p.edge.key] : [])],\n 'edge',\n )\n const edgeType = input.type.fields[p.edge.from]\n let removeWhere: Test | undefined\n if (p.per) issues.push(...fieldIssues(env.input(p.per.in), [p.per.key], 'per'))\n // A group without edges cannot have a cycle, so per adds nothing to grouped edges.\n if (p.edge.key && p.per) issues.push({ message: 'edge.key groups the edges itself; drop per' })\n const groupType = p.edge.key\n ? input.type.fields[p.edge.key]\n : p.per && env.input(p.per.in).type.fields[p.per.key]\n if (p.remove) {\n if (!p.per && !p.edge.key) issues.push({ message: 'remove needs per or edge.key' })\n const removal = env.input(p.remove.in)\n issues.push(...fieldIssues(removal, [p.remove.key, p.remove.from, p.remove.to], 'remove'))\n const checks: [string, MType | undefined, MType | undefined][] = [\n [`remove.from`, removal.type.fields[p.remove.from], edgeType],\n [`remove.to`, removal.type.fields[p.remove.to], edgeType],\n [`remove.key`, removal.type.fields[p.remove.key], groupType],\n ]\n for (const [name, a, b] of checks) {\n if (a && b && !comparable(a, b)) issues.push({ message: `${name}: ${show(a)} vs ${show(b)}` })\n }\n if (p.remove.where !== undefined) {\n const w = compilePredicate(p.remove.where, env.recordEnv(removal.type))\n if (w.ok) removeWhere = w.value\n else issues.push({ message: `remove.where: ${w.error}` })\n }\n }\n const toType = input.type.fields[p.edge.to]\n if (edgeType && toType && !comparable(edgeType, toType)) {\n issues.push({ message: `edge: ${show(edgeType)} vs ${show(toType)}` })\n }\n return { issues, removeWhere }\n}\n\nconst str = (v: Val) => (typeof v === 'string' ? v : canonicalKey(v))\n\ntype Edge = readonly [string, string]\n\nfunction acyclicViolation(\n p: Acyclic,\n inputs: (id: string) => Relation,\n ctx: RunContext,\n removeWhere: Test | undefined,\n action: Action,\n): Violation | undefined {\n const keyed = p.edge.key\n const grouped = keyed !== undefined || p.per !== undefined\n // Edges by canonical group key: by `edge.key`, or one set every group shares under null.\n const edgesOf = new Map<string, Map<string, Edge>>()\n const keys = new Map<string, Val>()\n for (const row of inputs(p.in)) {\n const from = row[p.edge.from] ?? null\n const to = row[p.edge.to] ?? null\n const k = keyed ? (row[keyed] ?? null) : null\n if (from === null || to === null || (keyed && k === null)) continue\n const g = canonicalKey(k)\n keys.set(g, k)\n const edges = edgesOf.get(g) ?? new Map<string, Edge>()\n edges.set(canonicalKey([from, to]), [str(from), str(to)])\n edgesOf.set(g, edges)\n }\n let groups: Val[] = [null]\n if (keyed) groups = [...keys.values()].sort(compareVals)\n else if (p.per) {\n const seen = new Map<string, Val>()\n for (const row of inputs(p.per.in)) {\n const k = row[p.per.key] ?? null\n if (k !== null) seen.set(canonicalKey(k), k)\n }\n groups = [...seen.values()].sort(compareVals)\n }\n const removals = new Map<string, Set<string>>()\n if (p.remove) {\n for (const row of inputs(p.remove.in)) {\n if (removeWhere && !removeWhere(null, row, ctx)) continue\n const g = canonicalKey(row[p.remove.key] ?? null)\n const set = removals.get(g) ?? new Set<string>()\n set.add(canonicalKey([row[p.remove.from] ?? null, row[p.remove.to] ?? null]))\n removals.set(g, set)\n }\n }\n // With shared edges most groups remove the same ones (often none), so cycles are cached\n // by removal set; a group with edges of its own is small and checked directly.\n const cache = new Map<string, string[] | undefined>()\n const failing: Json[] = []\n let count = 0\n for (const g of groups) {\n const removed = removals.get(canonicalKey(g)) ?? new Set<string>()\n const edges = edgesOf.get(canonicalKey(keyed ? g : null)) ?? new Map<string, Edge>()\n const kept = () => [...edges].filter(([k]) => !removed.has(k)).map(([, e]) => e)\n let cycle: string[] | undefined\n if (keyed) cycle = findCycle(kept())\n else {\n const signature = [...removed].sort().join('|')\n if (!cache.has(signature)) cache.set(signature, findCycle(kept()))\n cycle = cache.get(signature)\n }\n if (cycle) {\n count += 1\n if (failing.length < 5) failing.push({ group: toJson(g), cycle })\n }\n }\n if (count === 0) return undefined\n const first = failing[0] as { group: Json; cycle: string[] }\n return {\n clause: 'acyclic',\n action,\n message: `${count} ${grouped ? 'groups have' : 'graph has'} a cycle, e.g. ${grouped ? `${typeof first.group === 'string' ? first.group : JSON.stringify(first.group)}: ` : ''}${first.cycle.join(' -> ')}`,\n count,\n samples: failing,\n }\n}\n\nexport const assertNode = defineNode({\n op: 'assert',\n label: 'Assert',\n category: 'check',\n description: 'A built-in check (count, unique, rows, acyclic) that passes its input through.',\n slots: [\n { id: 'in', label: 'In', path: ['in'] },\n { id: 'per', label: 'Per', path: ['per', 'in'], optional: true },\n { id: 'remove', label: 'Remove', path: ['remove', 'in'], optional: true },\n ],\n output: true,\n effect: 'check',\n defaults: () => ({ in: '', check: 'count' }),\n params,\n compile: (p: Params, env) => {\n const input = env.input(p.in)\n const action = p.on_fail ?? 'alert'\n const checked = checkAction(action, p.check, input)\n const issues: NodeIssue[] = checked.ok ? [] : [{ message: `on_fail: ${checked.error}` }]\n let test: Test | undefined\n let removeWhere: Test | undefined\n switch (p.check) {\n case 'unique':\n issues.push(...fieldIssues(input, p.keys, 'keys'))\n break\n case 'rows': {\n const compiled = compilePredicate(p.cond, env.recordEnv(input.type))\n if (compiled.ok) test = compiled.value\n else issues.push({ message: `cond: ${compiled.error}` })\n break\n }\n case 'acyclic': {\n const compiled = compileAcyclic(p, input, env)\n issues.push(...compiled.issues)\n removeWhere = compiled.removeWhere\n break\n }\n }\n if (!checked.ok || issues.length > 0) return { ok: false, error: issues }\n\n return ok({\n output: checked.value,\n run: (inputs, ctx, options = {}) => {\n const rows = inputs(p.in)\n let violation: Violation | undefined\n switch (p.check) {\n case 'count':\n violation = options.skipCount\n ? undefined\n : countViolation(rows.length, p, action, undefined)\n break\n case 'unique':\n violation = uniqueViolation(rows, p.keys, action)\n break\n case 'rows':\n violation = rowsViolation(rows, test as Test, ctx, action)\n break\n default:\n violation = acyclicViolation(p, inputs, ctx, removeWhere, action)\n }\n return ok(applyViolations(env.id, 'assert', rows, violation ? [violation] : []))\n },\n })\n },\n})\n","/** `distinct`: deduplicates on `keys` and projects to them. */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport { type MType, t } from '../types'\nimport { keyOf, type Rec, type Val } from '../values'\nimport { defineNode, fail, nodeId, type Origin } from './def'\n\nconst params = z.strictObject({ in: nodeId, keys: z.array(z.string().min(1)).min(1) })\n\nexport const distinctNode = defineNode({\n op: 'distinct',\n label: 'Distinct',\n category: 'transform',\n description: 'One record per distinct combination of the key fields.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', keys: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const unknown = p.keys.filter((k) => !Object.hasOwn(input.type.fields, k))\n if (unknown.length) return fail(`unknown keys: ${unknown.join(', ')}`)\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const k of p.keys) {\n fields[k] = input.type.fields[k] as MType\n origins[k] = input.origins[k] as Origin\n }\n return ok({\n output: { type: t.record(fields), origins },\n run: (inputs) => {\n const seen = new Set<string>()\n const rows: Rec[] = []\n for (const row of inputs(p.in)) {\n const k = keyOf(row, p.keys)\n if (seen.has(k)) continue\n seen.add(k)\n rows.push(Object.fromEntries(p.keys.map((f) => [f, (row[f] ?? null) as Val])))\n }\n return ok({ rows })\n },\n })\n },\n})\n","/**\n * `expectedSchema` as JSON Schema (arch.md, \"expectedSchema as JSON Schema\").\n *\n * The stored schema of a source is its type environment: `sourceRecordType` derives the\n * record type a `source` node emits. `format` stays a validation constraint, never a type: a\n * `{ \"type\": \"string\", \"format\": \"date\" }` field is a `string`, and `to_date` makes a date.\n *\n * Until per-record contract validation (Ajv) exists, `conformRows` is the runtime guard: it\n * projects rows onto the declared fields and checks every value against its declared type.\n */\n\nimport type { Column, LogicalType, Table, TargetEntity } from '../schema'\nimport type { JsonSchema } from './document'\nimport { err, ok, type Result } from './result'\nimport { Instant } from './time'\nimport { type MType, type NonNull, type RecordType, show, t } from './types'\nimport { isRecordVal, type Json, type Rec, type Val } from './values'\n\ntype Node = Readonly<Record<string, unknown>>\n\nconst DIALECT = 'https://json-schema.org/draft/2020-12/schema'\n\n/** The record type of a source's schema. Optional fields read as null, so are nullable. */\nexport function sourceRecordType(schema: JsonSchema): Result<RecordType, string> {\n const properties = schema.properties as Readonly<Record<string, Node>> | undefined\n if (schema.type !== 'object' || typeof properties !== 'object' || properties === null) {\n return err(\n 'a source schema must describe one object record (\"type\": \"object\" with \"properties\")',\n )\n }\n const required = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : [])\n const fields: Record<string, MType> = {}\n for (const [name, node] of Object.entries(properties)) {\n const type = toMType(node)\n fields[name] = required.has(name) ? type : t.nullable(type)\n }\n return ok(t.record(fields))\n}\n\nfunction toMType(node: Node): MType {\n const union = (node.anyOf ?? node.oneOf) as readonly Node[] | undefined\n if (Array.isArray(union)) {\n const nonNull = union.filter((m) => m.type !== 'null')\n const inner = nonNull.length === 1 ? toMType(nonNull[0] as Node) : t.unknown\n return union.length > nonNull.length ? t.nullable(inner) : inner\n }\n if (Array.isArray(node.type)) {\n const types = node.type as readonly string[]\n const nonNull = types.filter((x) => x !== 'null')\n const inner = nonNull.length === 1 ? toMType({ ...node, type: nonNull[0] }) : t.unknown\n return nonNull.length < types.length ? t.nullable(inner) : inner\n }\n if (Array.isArray(node.enum)) {\n const kinds = new Set(\n (node.enum as readonly unknown[]).map((v) => (v === null ? 'null' : typeof v)),\n )\n const hasNull = kinds.delete('null')\n const inner: MType = kinds.size === 1 ? scalar([...kinds][0] as string) : t.unknown\n return hasNull ? t.nullable(inner) : inner\n }\n switch (node.type) {\n case 'string':\n case 'number':\n case 'boolean':\n return scalar(node.type)\n case 'integer':\n return t.number\n case 'array':\n return t.list(\n typeof node.items === 'object' && node.items ? toMType(node.items as Node) : t.unknown,\n )\n case 'object': {\n const props = (node.properties ?? {}) as Readonly<Record<string, Node>>\n return t.record(Object.fromEntries(Object.entries(props).map(([k, v]) => [k, toMType(v)])))\n }\n default:\n return t.unknown\n }\n}\n\nfunction scalar(kind: string): NonNull {\n switch (kind) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n default:\n return t.unknown\n }\n}\n\nfunction logicalSchema(logical: LogicalType): Record<string, Json> {\n switch (logical) {\n case 'string':\n return { type: 'string' }\n case 'integer':\n return { type: 'integer' }\n case 'decimal':\n return { type: 'number' }\n case 'boolean':\n return { type: 'boolean' }\n case 'date':\n return { type: 'string', format: 'date' }\n case 'timestamp':\n return { type: 'string', format: 'date-time' }\n default:\n return {}\n }\n}\n\nfunction fieldSchema(logical: LogicalType, nullable: boolean, description?: string | null) {\n const base = logicalSchema(logical)\n const typed =\n nullable && typeof base.type === 'string' ? { ...base, type: [base.type, 'null'] } : base\n return description ? { ...typed, description } : typed\n}\n\nfunction objectSchema(\n id: string,\n fields: readonly {\n name: string\n logical: LogicalType\n nullable: boolean\n description?: string | null\n }[],\n): JsonSchema {\n return {\n $schema: DIALECT,\n $id: id,\n type: 'object',\n required: fields.filter((f) => !f.nullable).map((f) => f.name),\n properties: Object.fromEntries(\n fields.map((f) => [f.name, fieldSchema(f.logical, f.nullable, f.description)]),\n ),\n additionalProperties: true,\n }\n}\n\n/** A starting `expectedSchema` for a source table, from what its connector describes. */\nexport function tableJsonSchema(table: Table, system?: string): JsonSchema {\n return objectSchema(\n system ? `${system}.${table.name}` : table.name,\n table.columns.map((c: Column) => ({\n name: c.name,\n logical: c.logicalType,\n nullable: c.nullable,\n description: c.description,\n })),\n )\n}\n\n/** The pinned schema of an internal entity read as a source (structural rule 4). */\nexport function entityJsonSchema(entity: TargetEntity): JsonSchema {\n return objectSchema(\n `internal.${entity.name}`,\n entity.fields.map((f) => ({\n name: f.name,\n logical: f.logicalType,\n nullable: f.nullable,\n description: f.description,\n })),\n )\n}\n\n/** Does a runtime value inhabit this type? */\nexport function conforms(value: Val, type: MType): boolean {\n if (value === null) return type.kind === 'nullable' || type.kind === 'unknown'\n switch (type.kind) {\n case 'nullable':\n return conforms(value, type.of)\n case 'unknown':\n return true\n case 'string':\n return typeof value === 'string'\n case 'number':\n return typeof value === 'number' && Number.isFinite(value)\n case 'boolean':\n return typeof value === 'boolean'\n case 'date':\n return value instanceof Instant\n case 'list':\n return Array.isArray(value) && (value as readonly Val[]).every((v) => conforms(v, type.of))\n case 'tuple':\n return (\n Array.isArray(value) &&\n value.length === type.of.length &&\n type.of.every((x, i) => conforms((value as readonly Val[])[i] as Val, x))\n )\n case 'record':\n return (\n isRecordVal(value) &&\n Object.entries(type.fields).every(([k, v]) => conforms(value[k] ?? null, v))\n )\n default:\n return false\n }\n}\n\nexport interface FieldViolation {\n readonly field: string\n readonly expected: string\n readonly count: number\n /** Row positions of the first violations. */\n readonly samples: readonly number[]\n}\n\n/** Project rows onto the declared fields and check each value; one violation per field. */\nexport function conformRows(\n rows: readonly Readonly<Record<string, unknown>>[],\n type: RecordType,\n): { rows: Rec[]; violations: FieldViolation[] } {\n const fields = Object.entries(type.fields)\n const counts = new Map<string, { count: number; samples: number[] }>()\n const out: Rec[] = []\n for (const [i, row] of rows.entries()) {\n const rec: Record<string, Val> = {}\n for (const [name, fieldType] of fields) {\n const value = (row[name] ?? null) as Val\n if (!conforms(value, fieldType)) {\n const v = counts.get(name) ?? { count: 0, samples: [] }\n v.count += 1\n if (v.samples.length < 5) v.samples.push(i)\n counts.set(name, v)\n }\n rec[name] = value\n }\n out.push(rec)\n }\n return {\n rows: out,\n violations: [...counts].map(([field, v]) => ({\n field,\n expected: show(type.fields[field] as MType),\n ...v,\n })),\n }\n}\n","/**\n * `source`: one entity of an external or internal system, read once per run into the\n * snapshot. Its record type comes from the version's `expectedSchema` entry for this node.\n * Loading checks every value against that type; a violation fails the node, so nothing\n * downstream runs on data the version never claimed to handle.\n */\n\nimport { z } from 'zod'\nimport { conformRows, type FieldViolation, sourceRecordType } from '../jsonschema'\nimport { compilePredicate, nonNullPaths, type Test } from '../predicate'\nimport { err, ok, type Result } from '../result'\nimport { type MType, type RecordType, stripNull, t } from '../types'\nimport type { Rec, Relation } from '../values'\nimport {\n defineNode,\n fail,\n type NodeFailure,\n type NodeIssue,\n type NodeOutput,\n type Origin,\n ownOrigins,\n type RunIssue,\n} from './def'\n\nconst params = z.strictObject({\n system: z.string().min(1),\n entity: z.string().min(1),\n filter: z.unknown().optional(),\n})\n\n/**\n * Narrow the fields a passing filter guarantees are non-null (and so present). The condition\n * has compiled against `output`, so every path it names exists.\n */\nexport function narrow(output: NodeOutput, cond: unknown): NodeOutput {\n const fields = { ...output.type.fields }\n const origins = { ...output.origins }\n for (const path of nonNullPaths(cond)) {\n fields[path] = stripNull(fields[path] as MType)\n const origin = origins[path] as Origin\n origins[path] = { node: origin.node, field: origin.field, omittable: false }\n }\n return { ...output, type: t.record(fields), origins }\n}\n\n/** Shared by `source` and `transform`: conform rows, or fail with one issue per field. */\nexport function loadRows(\n node: string,\n rows: readonly Readonly<Record<string, unknown>>[],\n type: RecordType,\n): Result<Rec[], NodeFailure> {\n const loaded = conformRows(rows, type)\n if (loaded.violations.length === 0) return ok(loaded.rows)\n const issues: RunIssue[] = loaded.violations.map((v: FieldViolation) => ({\n node,\n code: 'schema_violation',\n field: v.field,\n message: `${v.field}: ${v.count} values are not ${v.expected}`,\n count: v.count,\n samples: v.samples,\n }))\n return err({\n code: 'schema_violation',\n message: `${loaded.violations.length} fields do not match the declared schema`,\n issues,\n })\n}\n\nexport const sourceNode = defineNode({\n op: 'source',\n label: 'Source',\n category: 'source',\n description: 'Reads one entity of a source system into the run snapshot.',\n slots: [],\n output: true,\n defaults: () => ({ system: '', entity: '' }),\n params,\n compile: (p, env) => {\n const schema = env.version.expectedSchema[env.id]\n if (!schema) {\n return fail(`no expectedSchema for source '${env.id}'`, { code: 'missing_schema' })\n }\n const declared = sourceRecordType(schema)\n if (!declared.ok) return fail(declared.error, { code: 'missing_schema' })\n const type = declared.value\n\n let test: Test | undefined\n if (p.filter !== undefined) {\n const compiled = compilePredicate(p.filter, env.recordEnv(type))\n if (!compiled.ok)\n return { ok: false, error: [{ message: `filter: ${compiled.error}` }] as NodeIssue[] }\n test = compiled.value\n }\n const declaredOutput: NodeOutput = { type, origins: ownOrigins(env.id, type) }\n const output = test ? narrow(declaredOutput, p.filter) : declaredOutput\n\n return ok({\n output,\n run: (_inputs, ctx) => {\n const loaded = loadRows(env.id, ctx.snapshot[env.id] ?? [], type)\n if (!loaded.ok) return loaded\n const rows: Relation = test\n ? loaded.value.filter((r) => (test as Test)(null, r, ctx))\n : loaded.value\n return ok({ rows })\n },\n })\n },\n})\n","/**\n * `filter`: keeps records where the predicate holds. A `{ path, is_null: false }` condition\n * (alone or inside `all`) narrows that field to non-null in the output type.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate } from '../predicate'\nimport { ok } from '../result'\nimport { defineNode, fail, nodeId } from './def'\nimport { narrow } from './source'\n\nconst params = z.strictObject({ in: nodeId, cond: z.unknown() })\n\nexport const filterNode = defineNode({\n op: 'filter',\n label: 'Filter',\n category: 'transform',\n description: 'Keeps the records where a condition holds.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', cond: {} }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const test = compilePredicate(p.cond, env.recordEnv(input.type))\n if (!test.ok) return fail(`cond: ${test.error}`)\n const cond = test.value\n return ok({\n output: narrow(input, p.cond),\n run: (inputs, ctx) => ok({ rows: inputs(p.in).filter((r) => cond(null, r, ctx)) }),\n })\n },\n})\n","/**\n * `join`: equi-join on key pairs plus an optional residual `where`, part of the match (as in\n * SQL `ON`). `left` makes every right field nullable; `semi` / `anti` keep left records with\n * at least one / no match and return the left schema.\n *\n * `select` picks and renames right fields; without it every right field is kept, a join key\n * with the same name on both sides merges, and any other collision is a save error. Null keys\n * never match.\n *\n * `cardinality` is declared and enforced while the hash table is built (limitation #16):\n * `n:1` right keys unique, `1:n` left keys unique, `1:1` both, `n:m` unrestricted but needs a\n * `count` expectation on this node.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate, type Test } from '../predicate'\nimport { err, ok } from '../result'\nimport { comparable, type MType, show, t } from '../types'\nimport { type Json, keyOf, type Rec, type Relation, toJson, type Val } from '../values'\nimport { defineNode, nodeId, type NodeIssue, type Origin } from './def'\n\nconst params = z.strictObject({\n left: nodeId,\n right: nodeId,\n on: z.array(z.tuple([z.string().min(1), z.string().min(1)])).min(1),\n type: z.enum(['inner', 'left', 'semi', 'anti']).optional(),\n cardinality: z.enum(['1:1', 'n:1', '1:n', 'n:m']),\n select: z.record(z.string().min(1), z.string().min(1)).optional(),\n where: z.unknown().optional(),\n tolerate_skips: z.boolean().optional(),\n})\n\n/** Index of rows by key, skipping null keys; reports the first duplicate when `unique`. */\nfunction index(rows: Relation, keys: readonly string[], unique: boolean) {\n const byKey = new Map<string, Rec[]>()\n for (const row of rows) {\n if (keys.some((k) => (row[k] ?? null) === null)) continue\n const k = keyOf(row, keys)\n const bucket = byKey.get(k)\n if (!bucket) byKey.set(k, [row])\n else if (unique) return { duplicate: keys.map((f) => toJson(row[f] as Val)) }\n else bucket.push(row)\n }\n return { byKey }\n}\n\nexport const joinNode = defineNode({\n op: 'join',\n label: 'Join',\n category: 'transform',\n description: 'Combines two inputs on matching keys, with a declared cardinality.',\n slots: [\n { id: 'left', label: 'Left', path: ['left'] },\n { id: 'right', label: 'Right', path: ['right'] },\n ],\n output: true,\n defaults: () => ({ left: '', right: '', on: [], type: 'inner', cardinality: 'n:1' }),\n params,\n toleratesSkips: (p) => p.tolerate_skips === true,\n compile: (p, env) => {\n const left = env.input(p.left)\n const right = env.input(p.right)\n const kind = p.type ?? 'inner'\n const issues: NodeIssue[] = []\n\n for (const [lk, rk] of p.on) {\n const lt = left.type.fields[lk]\n const rt = right.type.fields[rk]\n if (!lt) issues.push({ message: `left has no field '${lk}'` })\n if (!rt) issues.push({ message: `right has no field '${rk}'` })\n if (lt && rt && !comparable(lt, rt)) {\n issues.push({ message: `join key ${lk}: ${show(lt)} vs ${rk}: ${show(rt)}` })\n }\n }\n if (p.cardinality === 'n:m' && env.expect?.count === undefined) {\n issues.push({\n message: \"an n:m join needs a count expectation in the version's expect block\",\n code: 'missing_expectation',\n })\n }\n\n // Right fields carried into the output: `select`ed and renamed, or all but merged keys.\n const carried: [string, string][] = []\n if (p.select) {\n for (const [from, to] of Object.entries(p.select)) {\n if (Object.hasOwn(right.type.fields, from)) carried.push([from, to])\n else issues.push({ message: `select: right has no field '${from}'` })\n }\n } else {\n const merged = new Set(p.on.filter(([l, r]) => l === r).map(([l]) => l))\n for (const name of Object.keys(right.type.fields))\n if (!merged.has(name)) carried.push([name, name])\n }\n const needsMerge = kind === 'inner' || kind === 'left' || p.where !== undefined\n const fields: Record<string, MType> = { ...left.type.fields }\n const origins: Record<string, Origin> = { ...left.origins }\n if (needsMerge) {\n for (const [from, to] of carried) {\n if (Object.hasOwn(fields, to)) {\n issues.push({ message: `field '${to}' exists on both sides; rename it with select` })\n continue\n }\n const type = right.type.fields[from] as MType\n fields[to] = kind === 'left' ? t.nullable(type) : type\n origins[to] =\n kind === 'left'\n ? { node: env.id, field: to, omittable: false }\n : (right.origins[from] as Origin)\n }\n }\n let where: Test | undefined\n if (p.where !== undefined && issues.length === 0) {\n const compiled = compilePredicate(p.where, env.recordEnv(t.record(fields)))\n if (compiled.ok) where = compiled.value\n else issues.push({ message: `where: ${compiled.error}` })\n }\n if (issues.length) return { ok: false, error: issues }\n\n const leftKeys = p.on.map(([l]) => l)\n const rightKeys = p.on.map(([, r]) => r)\n const leftUnique = p.cardinality === '1:1' || p.cardinality === '1:n'\n const rightUnique = p.cardinality === '1:1' || p.cardinality === 'n:1'\n const nullRight = Object.fromEntries(carried.map(([, to]) => [to, null]))\n const project = (r: Rec): Rec => {\n const out: Record<string, Val> = {}\n for (const [from, to] of carried) out[to] = r[from] ?? null\n return out\n }\n const violated = (side: 'left' | 'right', key: readonly Json[]) =>\n err({\n code: 'cardinality_violated',\n message: `${p.cardinality} join: ${side} key ${JSON.stringify(key)} is not unique`,\n samples: [key],\n })\n\n return ok({\n output: kind === 'inner' || kind === 'left' ? { type: t.record(fields), origins } : left,\n run: (inputs, ctx) => {\n const lrows = inputs(p.left)\n const built = index(inputs(p.right), rightKeys, rightUnique)\n if (built.duplicate) return violated('right', built.duplicate)\n if (leftUnique) {\n const checked = index(lrows, leftKeys, true)\n if (checked.duplicate) return violated('left', checked.duplicate)\n }\n const byKey = built.byKey as Map<string, Rec[]>\n const rows: Rec[] = []\n for (const l of lrows) {\n const nullKey = leftKeys.some((k) => (l[k] ?? null) === null)\n const candidates = nullKey ? [] : (byKey.get(keyOf(l, leftKeys)) ?? [])\n const matches: Rec[] = []\n for (const r of candidates) {\n const merged = { ...l, ...project(r) }\n if (!where || where(null, merged, ctx)) matches.push(merged)\n }\n if (kind === 'semi') {\n if (matches.length > 0) rows.push(l)\n } else if (kind === 'anti') {\n if (matches.length === 0) rows.push(l)\n } else if (matches.length > 0) rows.push(...matches)\n else if (kind === 'left') rows.push({ ...l, ...nullRight })\n }\n return ok({ rows })\n },\n })\n },\n})\n","/** Access ops, the pipeline entry points: `extract`, `const`, `coalesce`. */\n\nimport { z } from 'zod'\nimport { fieldType } from '../context'\nimport { ok, type Result } from '../result'\nimport { isNullable, type MType, stripNull, t, typeOfJson, unifyAll } from '../types'\nimport type { Val } from '../values'\nimport { defineOp, json, never, params } from './def'\n\n/** Reads one field of the current record, or a tuple of fields. A missing field is null. */\nexport const extract = defineOp({\n name: 'extract',\n params: params({ path: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]) }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p, env): Result<MType, string> => {\n if (typeof p.path === 'string') return fieldType(env.record, p.path)\n const types: MType[] = []\n for (const path of p.path) {\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n types.push(type.value)\n }\n return ok(t.tuple(types))\n },\n run: (p) => {\n if (typeof p.path === 'string') {\n const path = p.path\n return (_input, ctx) => ok(ctx.record[path] ?? null)\n }\n const paths = p.path\n return (_input, ctx) => ok(paths.map((x) => ctx.record[x] ?? null))\n },\n})\n\n/** A literal value. */\nexport const constant = defineOp({\n name: 'const',\n params: params({ value: json }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p) => ok(typeOfJson(p.value)),\n run: (p) => {\n const value = p.value as Val\n return () => ok(value)\n },\n})\n\n/** The first non-null of several fields. Nullable only if every field is. */\nexport const coalesce = defineOp({\n name: 'coalesce',\n params: params({ paths: z.array(z.string().min(1)).min(2) }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p, env): Result<MType, string> => {\n const types: MType[] = []\n for (const path of p.paths) {\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n types.push(type.value)\n }\n const common = unifyAll(types)\n if (!common.ok) return common\n return ok(types.every(isNullable) ? common.value : stripNull(common.value))\n },\n run: (p) => {\n const paths = p.paths\n return (_input, ctx) => {\n for (const path of paths) {\n const v = ctx.record[path] ?? null\n if (v !== null) return ok(v)\n }\n return ok(null)\n }\n },\n})\n","/** Type conversion: `to_number`, `to_string`, `to_bool`, `to_date`, `assert_type`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport {\n dateFormat,\n formatDate,\n hasFullDate,\n type Instant,\n isTimeZone,\n parseDateValue,\n parseDateFormat,\n} from '../time'\nimport { assignable, parseTypeName, show, t, typeName } from '../types'\nimport { toJson, type Val } from '../values'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst NUMBER = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/\n\nconst dateFormatParam = z.string().superRefine((s, ctx) => {\n const f = parseDateFormat(s)\n if (!f.ok) ctx.addIssue({ code: 'custom', message: f.error })\n})\n\nconst timeZone = z.string().refine(isTimeZone, 'unknown time zone')\n\n/** Parses a number from a string (a boolean gives 1 or 0). Strict raises, else null. */\nexport const toNumber = defineOp({\n name: 'to_number',\n params: params({ strict: z.boolean().optional() }),\n nulls: 'propagate',\n fallible: (p) => p.strict === true,\n signature: (input, p) => {\n const s = expectKind(input, ['string', 'boolean'], 'to_number')\n if (!s.ok) return s\n return ok(input.kind === 'boolean' || p.strict ? t.number : t.nullable(t.number))\n },\n run: (p) => (input) => {\n if (typeof input === 'boolean') return ok(input ? 1 : 0)\n const text = (input as string).trim()\n if (NUMBER.test(text)) return ok(Number(text))\n return p.strict ? stepError('parse_failed', `'${input as string}' is not a number`) : ok(null)\n },\n})\n\n/** Canonical string form. `format` applies to dates, in the run time zone. */\nexport const toString = defineOp({\n name: 'to_string',\n params: params({ format: dateFormatParam.optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p) => {\n if (input.kind === 'unknown') return err('to_string needs a known input type')\n if (p.format !== undefined && input.kind !== 'date') {\n return err('to_string format applies to dates only')\n }\n return ok(t.string)\n },\n run: (p, _env, input) => {\n if (input.kind === 'date') {\n const format = dateFormat(p.format ?? 'iso')\n return (v, ctx) => ok(formatDate(v as Instant, format, ctx.tz))\n }\n return (v) => ok(stringify(v))\n },\n})\n\nfunction stringify(v: Val): string {\n if (typeof v === 'string') return v\n if (typeof v === 'number' || typeof v === 'boolean') return String(v)\n return JSON.stringify(toJson(v))\n}\n\nconst TRUE_VALUES = ['true', '1']\nconst FALSE_VALUES = ['false', '0']\n\n/** Explicit truthiness: only the listed values convert, anything else is an error. */\nexport const toBool = defineOp({\n name: 'to_bool',\n params: params({\n true_values: z.array(z.string()).min(1).optional(),\n false_values: z.array(z.string()).min(1).optional(),\n }).refine(\n (p) =>\n !(p.true_values ?? TRUE_VALUES).some((v) => (p.false_values ?? FALSE_VALUES).includes(v)),\n 'true_values and false_values overlap',\n ),\n nulls: 'propagate',\n fallible: () => true,\n signature: (input) => {\n const s = expectKind(input, ['string', 'number'], 'to_bool')\n return s.ok ? ok(t.boolean) : s\n },\n run: (p) => {\n const yes = new Set(p.true_values ?? TRUE_VALUES)\n const no = new Set(p.false_values ?? FALSE_VALUES)\n return (input) => {\n const text = typeof input === 'number' ? String(input) : (input as string).trim()\n if (yes.has(text)) return ok(true)\n if (no.has(text)) return ok(false)\n return stepError('parse_failed', `'${text}' is not a listed boolean value`)\n }\n },\n})\n\n/**\n * Parses to an instant: `iso`, `epoch_ms`, `epoch_s`, or a `YYYY MM DD HH mm ss` pattern.\n * Wall-clock values are read in `tz`, by default the run's frozen time zone.\n */\nexport const toDate = defineOp({\n name: 'to_date',\n params: params({ format: dateFormatParam, tz: timeZone.optional() }).refine((p) => {\n const format = parseDateFormat(p.format)\n return !format.ok || hasFullDate(format.value)\n }, 'to_date format needs YYYY, MM and DD'),\n nulls: 'propagate',\n fallible: () => true,\n signature: (input, p) => {\n const epoch = dateFormat(p.format).kind === 'epoch'\n const s = expectKind(input, epoch ? ['string', 'number'] : ['string'], 'to_date')\n return s.ok ? ok(t.date) : s\n },\n run: (p) => {\n const format = dateFormat(p.format)\n return (input, ctx) => {\n const instant = parseDateValue(input as string | number, format, p.tz ?? ctx.tz)\n return instant\n ? ok(instant)\n : stepError(\n 'parse_failed',\n `'${String(input as string | number)}' does not match date format ${p.format}`,\n )\n }\n },\n})\n\n/** A runtime no-op and a checkpoint for the validator: the input must have this type. */\nexport const assertType = defineOp({\n name: 'assert_type',\n params: params({\n type: z.string().superRefine((s, ctx) => {\n const parsed = parseTypeName(s)\n if (!parsed.ok) ctx.addIssue({ code: 'custom', message: parsed.error })\n }),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p) => {\n const declared = typeName(p.type)\n return assignable(input, declared)\n ? ok(declared)\n : err(`expected ${p.type}, got ${show(input)}`)\n },\n run: () => (input) => ok(input),\n})\n","/**\n * Date ops: `format_date`, `shift_date`, `truncate_date`, `to_utc`. Calendar math happens in\n * the run's frozen time zone unless a `tz` is given.\n */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport {\n dateFormat,\n duration,\n formatDate,\n type Instant,\n isTimeZone,\n parseDateFormat,\n parseDuration,\n shift,\n truncate,\n} from '../time'\nimport { type MType, t } from '../types'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst dateIn =\n (op: string, out: MType = t.date) =>\n (input: MType) => {\n const s = expectKind(input, ['date'], op)\n return s.ok ? ok(out) : s\n }\n\nexport const formatDateOp = defineOp({\n name: 'format_date',\n params: params({\n format: z.string().superRefine((s, ctx) => {\n const f = parseDateFormat(s)\n if (!f.ok) ctx.addIssue({ code: 'custom', message: f.error })\n }),\n tz: z.string().refine(isTimeZone, 'unknown time zone').optional(),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('format_date', t.string),\n run: (p) => {\n const format = dateFormat(p.format)\n return (input, ctx) => ok(formatDate(input as Instant, format, p.tz ?? ctx.tz))\n },\n})\n\n/** Shift by a duration such as `+10y` or `-30d`. */\nexport const shiftDate = defineOp({\n name: 'shift_date',\n params: params({\n by: z.string().superRefine((s, ctx) => {\n const d = parseDuration(s)\n if (!d.ok) ctx.addIssue({ code: 'custom', message: d.error })\n }),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('shift_date'),\n run: (p) => {\n const by = duration(p.by)\n return (input, ctx) => ok(shift(input as Instant, by, ctx.tz))\n },\n})\n\nexport const truncateDate = defineOp({\n name: 'truncate_date',\n params: params({ unit: z.enum(['day', 'month', 'year']) }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('truncate_date'),\n run: (p) => (input, ctx) => ok(truncate(input as Instant, p.unit, ctx.tz)),\n})\n\n/** Instants carry no zone, so this is the identity; kept as an explicit normalisation step. */\nexport const toUtc = defineOp({\n name: 'to_utc',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('to_utc'),\n run: () => (input) => ok(input),\n})\n","/**\n * `fn`: the record-scope escape hatch. Calls a named, reviewed, version-pinned function the\n * host registers in `GraphEnv.functions`, with a declared input and output type.\n */\n\nimport { z } from 'zod'\nimport type { FnDef } from '../context'\nimport { err, ok } from '../result'\nimport { assignable, show } from '../types'\nimport { defineOp, params } from './def'\n\nexport const fn = defineOp({\n name: 'fn',\n params: params({ ref: z.string().min(1) }),\n nulls: 'consume',\n fallible: (p, env) => env.functions[p.ref]?.fallible ?? true,\n signature: (input, p, env) => {\n const def = Object.hasOwn(env.functions, p.ref) ? env.functions[p.ref] : undefined\n if (!def) return err(`unknown function '${p.ref}'`)\n if (def.input && !assignable(input, def.input)) {\n return err(`function '${p.ref}' takes ${show(def.input)}, got ${show(input)}`)\n }\n return ok(def.output)\n },\n run: (p, env) => {\n const def = env.functions[p.ref] as FnDef\n return (input, ctx) => def.run(input, ctx)\n },\n})\n","/**\n * List ops for list-typed fields within one record: `each`, `filter_list`, `index`, `first`,\n * `last`, `len`, `unique`, `sum`, `min`, `max`, `contains`. Collection-wide work belongs to\n * collection nodes.\n */\n\nimport { z } from 'zod'\nimport { compileOperand, compilePredicate } from '../predicate'\nimport { compileSteps } from '../pipeline'\nimport { err, expectOk, ok, type Result } from '../result'\nimport { comparable, type ListType, type MType, orderable, show, stripNull, t } from '../types'\nimport { canonicalKey, compareVals, type Val } from '../values'\nimport { defineOp, never, params } from './def'\n\nconst listIn = (input: MType, op: string): Result<MType, string> =>\n input.kind === 'list' ? ok(input.of) : err(`${op} expects a list, got ${show(input)}`)\n\n/** Applies a nested pipeline to every element. Nesting depth is capped at 1. */\nexport const each = defineOp({\n name: 'each',\n params: params({ pipeline: z.array(z.unknown()).min(1) }),\n nulls: 'propagate',\n fallible: (p, env, input) =>\n expectOk(compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, (input as ListType).of))\n .fallible,\n signature: (input, p, env) => {\n if (env.depth >= 1) return err('each cannot be nested inside each')\n const element = listIn(input, 'each')\n if (!element.ok) return element\n const nested = compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, element.value)\n if (!nested.ok) return err(`each step ${nested.error.step}: ${nested.error.message}`)\n if (nested.value.omittable) return err('each cannot end in omit_if_null')\n return ok(t.list(nested.value.type))\n },\n run: (p, env, input) => {\n const { run } = expectOk(\n compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, (input as ListType).of),\n )\n return (list, ctx) => {\n const out: Val[] = []\n for (const [i, element] of (list as readonly Val[]).entries()) {\n const r = run(element, ctx)\n if (!r.ok)\n return err({\n code: r.error.code,\n detail: `element ${i}, ${r.error.op}: ${r.error.detail}`,\n })\n out.push(r.value as Val)\n }\n return ok(out)\n }\n },\n})\n\nexport const filterList = defineOp({\n name: 'filter_list',\n params: params({ cond: z.unknown() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p, env) => {\n const element = listIn(input, 'filter_list')\n if (!element.ok) return element\n const test = compilePredicate(p.cond, env, element.value)\n return test.ok ? ok(input) : test\n },\n run: (p, env, input) => {\n const test = expectOk(compilePredicate(p.cond, env, (input as ListType).of))\n return (list, ctx) => ok((list as readonly Val[]).filter((e) => test(e, ctx.record, ctx)))\n },\n})\n\nconst pick = (name: string, at: (length: number) => number) =>\n defineOp({\n name,\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, name)\n return element.ok ? ok(t.nullable(element.value)) : element\n },\n run: () => (list) => ok((list as readonly Val[])[at((list as readonly Val[]).length)] ?? null),\n })\n\nexport const first = pick('first', () => 0)\nexport const last = pick('last', (n) => n - 1)\n\n/** Element at `at`; a negative index counts from the end. Out of range gives null. */\nexport const index = defineOp({\n name: 'index',\n params: params({ at: z.number().int() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'index')\n return element.ok ? ok(t.nullable(element.value)) : element\n },\n run: (p) => (list) => ok((list as readonly Val[]).at(p.at) ?? null),\n})\n\n/** Length of a list, or of a string in code points. */\nexport const len = defineOp({\n name: 'len',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) =>\n input.kind === 'list' || input.kind === 'string'\n ? ok(t.number)\n : err(`len expects a list or string, got ${show(input)}`),\n run: () => (v) => ok(typeof v === 'string' ? Array.from(v).length : (v as readonly Val[]).length),\n})\n\n/** Drops repeated elements, keeping the first occurrence. */\nexport const unique = defineOp({\n name: 'unique',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'unique')\n return element.ok ? ok(input) : element\n },\n run: () => (list) => {\n const seen = new Set<string>()\n return ok(\n (list as readonly Val[]).filter((e) => {\n const k = canonicalKey(e)\n if (seen.has(k)) return false\n seen.add(k)\n return true\n }),\n )\n },\n})\n\n/** Null elements are skipped; an empty list gives null. */\nexport const sum = defineOp({\n name: 'sum',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'sum')\n if (!element.ok) return element\n return stripNull(element.value).kind === 'number'\n ? ok(t.nullable(t.number))\n : err(`sum expects list<number>, got ${show(input)}`)\n },\n // Sorted first, so floating-point results do not depend on element order.\n run: () => (list) => {\n const numbers = (list as readonly Val[])\n .filter((x): x is number => x !== null)\n .sort((a, b) => a - b)\n return ok(numbers.length === 0 ? null : numbers.reduce((a, b) => a + b, 0))\n },\n})\n\nconst extreme = (name: 'min' | 'max') =>\n defineOp({\n name,\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, name)\n if (!element.ok) return element\n return orderable(element.value)\n ? ok(t.nullable(stripNull(element.value)))\n : err(`${name} expects a list of numbers, strings or dates, got ${show(input)}`)\n },\n run: () => (list) => {\n let best: Val = null\n for (const x of list as readonly Val[]) {\n if (x === null) continue\n if (best === null || (name === 'min' ? compareVals(x, best) < 0 : compareVals(x, best) > 0))\n best = x\n }\n return ok(best)\n },\n })\n\nexport const min = extreme('min')\nexport const max = extreme('max')\n\n/** Membership of a literal, `{ ref }` or `{ param }` value. Null is never a member. */\nexport const contains = defineOp({\n name: 'contains',\n params: params({ value: z.unknown().refine((v) => v !== undefined, 'contains needs a value') }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p, env) => {\n const element = listIn(input, 'contains')\n if (!element.ok) return element\n const operand = compileOperand(p.value, env, stripNull(element.value).kind === 'date')\n if (!operand.ok) return operand\n return comparable(element.value, operand.value.type)\n ? ok(t.boolean)\n : err(`cannot look for ${show(operand.value.type)} in ${show(input)}`)\n },\n run: (p, env, input) => {\n const element = (input as ListType).of\n const { get } = expectOk(compileOperand(p.value, env, stripNull(element).kind === 'date'))\n return (list, ctx) => {\n const v = get(list, ctx.record, ctx)\n return ok(\n v !== null && (list as readonly Val[]).some((x) => x !== null && compareVals(x, v) === 0),\n )\n }\n },\n})\n","/** `lookup`: a static value map stored with the version, for enum and code translation. */\n\nimport { z } from 'zod'\nimport { err, expectOk, ok, stepError } from '../result'\nimport { comparable, show, t, typeOfJson, unify, unifyAll } from '../types'\nimport type { Json, Val } from '../values'\nimport { defineOp, params } from './def'\n\nconst SCALAR = new Set(['string', 'number', 'boolean'])\n\n/**\n * Translate a scalar through `tables[table]` (keys are the value's string form). `on_miss`:\n * `null` (default) yields null, `pass` forwards the input, `error` raises `lookup_miss`.\n */\nexport const lookup = defineOp({\n name: 'lookup',\n params: params({\n table: z.string().min(1),\n on_miss: z.enum(['null', 'pass', 'error']).optional(),\n }),\n nulls: 'propagate',\n fallible: (p) => p.on_miss === 'error',\n signature: (input, p, env) => {\n if (!SCALAR.has(input.kind))\n return err(`lookup expects a string, number or boolean, got ${show(input)}`)\n if (!Object.hasOwn(env.tables, p.table)) return err(`unknown lookup table '${p.table}'`)\n const values = Object.values(env.tables[p.table] as Record<string, Json>)\n const value = unifyAll(values.map(typeOfJson))\n if (!value.ok) return err(`lookup table '${p.table}' mixes value types: ${value.error}`)\n switch (p.on_miss ?? 'null') {\n case 'null':\n return ok(t.nullable(value.value))\n case 'error':\n return ok(value.value)\n default: {\n if (!comparable(input, value.value)) {\n return err(\n `on_miss \"pass\" forwards ${show(input)}, but the table yields ${show(value.value)}`,\n )\n }\n return ok(expectOk(unify(input, value.value)))\n }\n }\n },\n run: (p, env) => {\n const table = env.tables[p.table] as Readonly<Record<string, Json>>\n const miss = p.on_miss ?? 'null'\n return (input) => {\n const key = String(input as string | number | boolean)\n if (Object.hasOwn(table, key)) return ok(table[key] as Val)\n if (miss === 'error') return stepError('lookup_miss', `'${key}' is not in table '${p.table}'`)\n return ok(miss === 'pass' ? input : null)\n }\n },\n})\n","/** Null and blank handling: `blank_to_null`, `default`, `require`, `omit_if_null`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport { assignable, show, stripNull, t, typeOfJson } from '../types'\nimport { OMIT, type Val } from '../values'\nimport { always, defineOp, expectKind, json, never, params } from './def'\n\n/** An empty or whitespace-only string becomes null. */\nexport const blankToNull = defineOp({\n name: 'blank_to_null',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'blank_to_null')\n return s.ok ? ok(t.nullable(t.string)) : s\n },\n run: () => (input) => ok((input as string).trim() === '' ? null : input),\n})\n\n/** Replaces null with a literal of the input's type. */\nexport const defaultOp = defineOp({\n name: 'default',\n params: params({ value: json }),\n nulls: 'consume',\n fallible: never,\n signature: (input, p) => {\n if (p.value === null) return err('default needs a non-null value')\n const base = stripNull(input)\n const literal = typeOfJson(p.value)\n if (base.kind === 'unknown') return ok(literal)\n return assignable(literal, base)\n ? ok(base)\n : err(`default value is ${show(literal)}, input is ${show(input)}`)\n },\n run: (p) => {\n const value = p.value as Val\n return (input) => ok(input ?? value)\n },\n})\n\n/** Null triggers the node's `on_error` policy. */\nexport const requireOp = defineOp({\n name: 'require',\n params: params({ message: z.string().optional() }),\n nulls: 'consume',\n fallible: always,\n signature: (input) => ok(stripNull(input)),\n run: (p) => {\n const message = p.message ?? 'required value is null'\n return (input) => (input === null ? stepError('required_null', message) : ok(input))\n },\n})\n\n/**\n * Terminal. A null leaves the field out of the record (and so out of the write) instead of\n * setting it to null (limitation #8). Readers downstream see the field as nullable.\n */\nexport const omitIfNull = defineOp({\n name: 'omit_if_null',\n params: params({}),\n nulls: 'consume',\n terminal: true,\n fallible: never,\n signature: (input) => ok(t.nullable(stripNull(input))),\n run: () => (input) => ok(input === null ? OMIT : input),\n})\n","/**\n * The unit table behind `convert_unit`: mass, length and volume, each against one base unit.\n * Unit names are matched case-insensitively. Anything else, and any conversion across\n * dimensions, is unknown.\n */\n\ntype Dimension = 'mass' | 'length' | 'volume'\n\nconst UNITS: Readonly<Record<string, { readonly dimension: Dimension; readonly factor: number }>> =\n {\n // mass, in grams\n mg: { dimension: 'mass', factor: 0.001 },\n g: { dimension: 'mass', factor: 1 },\n kg: { dimension: 'mass', factor: 1000 },\n t: { dimension: 'mass', factor: 1_000_000 },\n oz: { dimension: 'mass', factor: 28.349523125 },\n lb: { dimension: 'mass', factor: 453.59237 },\n // length, in metres\n mm: { dimension: 'length', factor: 0.001 },\n cm: { dimension: 'length', factor: 0.01 },\n m: { dimension: 'length', factor: 1 },\n km: { dimension: 'length', factor: 1000 },\n in: { dimension: 'length', factor: 0.0254 },\n ft: { dimension: 'length', factor: 0.3048 },\n // volume, in litres\n ml: { dimension: 'volume', factor: 0.001 },\n l: { dimension: 'volume', factor: 1 },\n m3: { dimension: 'volume', factor: 1000 },\n }\n\nconst unit = (name: string) => UNITS[name.trim().toLowerCase()]\n\nexport function isUnit(name: string): boolean {\n return unit(name) !== undefined\n}\n\n/** Multiply by this to convert `from` into `to`; undefined if unknown or across dimensions. */\nexport function conversionFactor(from: string, to: string): number | undefined {\n const a = unit(from)\n const b = unit(to)\n if (!a || !b || a.dimension !== b.dimension) return undefined\n // Divide instead of multiplying by a reciprocal, so kg -> g is exactly 1000.\n return a.factor / b.factor\n}\n","/** Numeric ops: `add`, `subtract`, `multiply`, `divide`, `round`, `abs`, `clamp`, `convert_unit`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport { isNullable, type MType, nullableIf, show, stripNull, t } from '../types'\nimport { conversionFactor, isUnit } from '../units'\nimport { defineOp, expectKind, never, params } from './def'\n\n// Zod 4 numbers are finite: Infinity and NaN are rejected.\nconst finite = z.number()\n\nconst numberIn = (op: string) => (input: MType) => {\n const s = expectKind(input, ['number'], op)\n return s.ok ? ok(t.number) : s\n}\n\nconst arithmetic = <K extends string>(\n name: string,\n key: K,\n apply: (a: number, b: number) => number,\n) =>\n defineOp({\n name,\n params: params({ [key]: finite } as { [P in K]: typeof finite }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn(name),\n run: (p) => {\n const operand = (p as Record<K, number>)[key]\n return (input) => ok(apply(input as number, operand))\n },\n })\n\nexport const add = arithmetic('add', 'value', (a, b) => a + b)\nexport const subtract = arithmetic('subtract', 'value', (a, b) => a - b)\nexport const multiply = arithmetic('multiply', 'by', (a, b) => a * b)\n\n/** `by: 0` is rejected when the version is saved, never at runtime. */\nexport const divide = defineOp({\n name: 'divide',\n params: params({ by: finite.refine((n) => n !== 0, 'divide by zero') }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('divide'),\n run: (p) => (input) => ok((input as number) / p.by),\n})\n\n/** Shift the decimal point by `places` without floating-point drift (1.005 stays 1.005). */\nfunction shiftDecimal(n: number, places: number): number {\n const [mantissa, exponent = '0'] = String(n).split('e')\n return Number(`${mantissa}e${Number(exponent) + places}`)\n}\n\ntype RoundMode = 'half_up' | 'half_even' | 'floor' | 'ceil'\n\nfunction roundScaled(x: number, mode: RoundMode): number {\n switch (mode) {\n case 'floor':\n return Math.floor(x)\n case 'ceil':\n return Math.ceil(x)\n case 'half_up':\n return Math.sign(x) * Math.round(Math.abs(x))\n case 'half_even': {\n const a = Math.abs(x)\n const floor = Math.floor(a)\n const diff = a - floor\n const r = diff > 0.5 || (diff === 0.5 && floor % 2 === 1) ? floor + 1 : floor\n return Math.sign(x) * r\n }\n }\n}\n\n/** Round to `precision` decimals. `half_up` rounds halves away from zero. */\nexport const round = defineOp({\n name: 'round',\n params: params({\n precision: z.number().int().min(0).max(15).optional(),\n mode: z.enum(['half_up', 'half_even', 'floor', 'ceil']).optional(),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('round'),\n run: (p) => {\n const precision = p.precision ?? 0\n const mode = p.mode ?? 'half_up'\n // The final shift goes through String(), which also turns -0 into 0.\n return (input) =>\n ok(shiftDecimal(roundScaled(shiftDecimal(input as number, precision), mode), -precision))\n },\n})\n\nexport const abs = defineOp({\n name: 'abs',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('abs'),\n run: () => (input) => ok(Math.abs(input as number)),\n})\n\nexport const clamp = defineOp({\n name: 'clamp',\n params: params({ min: finite.optional(), max: finite.optional() })\n .refine((p) => p.min !== undefined || p.max !== undefined, 'clamp needs min or max')\n .refine(\n (p) => p.min === undefined || p.max === undefined || p.min <= p.max,\n 'min is above max',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('clamp'),\n run: (p) => {\n const min = p.min ?? -Infinity\n const max = p.max ?? Infinity\n return (input) => ok(Math.min(max, Math.max(min, input as number)))\n },\n})\n\nconst unitName = z.string().refine(isUnit, 'unknown unit')\n\n/**\n * Convert over the unit table. The source unit is `from`, or the second element of an\n * extracted `(value, unit)` tuple. With a static `from` the conversion is checked at save\n * and cannot fail; with a unit read from the record an unknown unit raises.\n */\nexport const convertUnit = defineOp({\n name: 'convert_unit',\n params: params({ to: unitName, from: unitName.optional() }).refine(\n (p) =>\n p.from === undefined ||\n !isUnit(p.from) ||\n !isUnit(p.to) ||\n conversionFactor(p.from, p.to) !== undefined,\n 'from and to measure different things',\n ),\n nulls: 'propagate',\n fallible: (p) => p.from === undefined,\n signature: (input, p) => {\n if (input.kind === 'tuple') {\n if (p.from !== undefined)\n return err('convert_unit takes a unit from the record or from \"from\", not both')\n const [value, unit] = input.of as readonly [MType, MType]\n const pair =\n input.of.length === 2 &&\n stripNull(value).kind === 'number' &&\n stripNull(unit).kind === 'string'\n if (!pair) return err(`convert_unit expects (number, string), got ${show(input)}`)\n return ok(nullableIf(t.number, isNullable(value)))\n }\n if (p.from === undefined) return err('convert_unit needs a unit input or a \"from\" param')\n return numberIn('convert_unit')(input)\n },\n run: (p, _env, input) => {\n const to = p.to\n if (input.kind !== 'tuple') {\n const factor = conversionFactor(p.from as string, to) as number\n return (v) => ok((v as number) * factor)\n }\n return (v) => {\n const [value, from] = v as readonly [number | null, string | null]\n if (value === null) return ok(null)\n if (from === null) return stepError('unknown_unit', `no unit given for ${value}`)\n const factor = conversionFactor(from, to)\n return factor === undefined\n ? stepError('unknown_unit', `cannot convert ${from} to ${to}`)\n : ok(value * factor)\n }\n },\n})\n","/**\n * String ops: `trim`, `lower`, `upper`, `truncate`, `pad`, `replace`, `regex_extract`,\n * `split`, `join`, `concat`, `slug`. Lengths count code points, not UTF-16 units.\n */\n\nimport { z } from 'zod'\nimport { compileRegex } from '../predicate'\nimport { err, ok } from '../result'\nimport { type MType, show, stripNull, t } from '../types'\nimport type { Val } from '../values'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst stringIn = (op: string) => (input: MType) => {\n const s = expectKind(input, ['string'], op)\n return s.ok ? ok(t.string) : s\n}\n\nconst regex = z.string().superRefine((s, ctx) => {\n const r = compileRegex(s)\n if (!r.ok) ctx.addIssue({ code: 'custom', message: r.error })\n})\n\nconst escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nexport const trim = defineOp({\n name: 'trim',\n params: params({ chars: z.string().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('trim'),\n run: (p) => {\n if (p.chars === undefined) return (input) => ok((input as string).trim())\n const set = `[${p.chars.replace(/[\\\\\\]^-]/g, '\\\\$&')}]+`\n const edges = new RegExp(`^${set}|${set}$`, 'gu')\n return (input) => ok((input as string).replace(edges, ''))\n },\n})\n\nexport const lower = defineOp({\n name: 'lower',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('lower'),\n run: () => (input) => ok((input as string).toLowerCase()),\n})\n\nexport const upper = defineOp({\n name: 'upper',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('upper'),\n run: () => (input) => ok((input as string).toUpperCase()),\n})\n\n/** Lossy, no inverse. With `ellipsis` the result, ellipsis included, fits `length`. */\nexport const truncate = defineOp({\n name: 'truncate',\n params: params({ length: z.number().int().min(0), ellipsis: z.boolean().optional() }).refine(\n (p) => !p.ellipsis || p.length >= 1,\n 'truncate with ellipsis needs length >= 1',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('truncate'),\n run: (p) => (input) => {\n const chars = Array.from(input as string)\n if (chars.length <= p.length) return ok(input)\n return ok(\n p.ellipsis ? `${chars.slice(0, p.length - 1).join('')}…` : chars.slice(0, p.length).join(''),\n )\n },\n})\n\n/** Fixed-width codes, zero-padded SKUs. Strings already as long are unchanged. */\nexport const pad = defineOp({\n name: 'pad',\n params: params({\n length: z.number().int().min(1),\n with: z.string().min(1),\n side: z.enum(['left', 'right']),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('pad'),\n run: (p) => (input) => {\n const s = input as string\n return ok(p.side === 'left' ? s.padStart(p.length, p.with) : s.padEnd(p.length, p.with))\n },\n})\n\n/** Replace every occurrence; `regex: true` treats `pattern` as a regular expression. */\nexport const replace = defineOp({\n name: 'replace',\n params: params({\n pattern: z.string().min(1),\n with: z.string(),\n regex: z.boolean().optional(),\n }).superRefine((p, ctx) => {\n if (!p.regex || typeof p.pattern !== 'string') return\n const r = compileRegex(p.pattern)\n if (!r.ok) ctx.addIssue({ code: 'custom', path: ['pattern'], message: r.error })\n }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('replace'),\n run: (p) => {\n const pattern = new RegExp(p.regex ? p.pattern : escapeRegex(p.pattern), 'gu')\n // Literal replacement: `$` in `with` has no special meaning.\n return (input) => ok((input as string).replace(pattern, () => p.with))\n },\n})\n\nfunction groupCount(pattern: string): number {\n return (new RegExp(`${pattern}|`, 'u').exec('') as RegExpExecArray).length - 1\n}\n\n/** The match (or capture `group`) of the first match; no match gives null. */\nexport const regexExtract = defineOp({\n name: 'regex_extract',\n params: params({ pattern: regex, group: z.number().int().min(0).optional() }).refine(\n (p) => !compileRegex(p.pattern).ok || (p.group ?? 0) <= groupCount(p.pattern),\n 'group is larger than the number of capture groups',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'regex_extract')\n return s.ok ? ok(t.nullable(t.string)) : s\n },\n run: (p) => {\n const re = new RegExp(p.pattern, 'u')\n const group = p.group ?? 0\n return (input) => ok(re.exec(input as string)?.[group] ?? null)\n },\n})\n\n/** Split on a separator. With `limit`, at most that many parts; the last keeps the rest. */\nexport const split = defineOp({\n name: 'split',\n params: params({ separator: z.string().min(1), limit: z.number().int().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'split')\n return s.ok ? ok(t.list(t.string)) : s\n },\n run: (p) => (input) => {\n const parts = (input as string).split(p.separator)\n if (p.limit === undefined || parts.length <= p.limit) return ok(parts)\n return ok([...parts.slice(0, p.limit - 1), parts.slice(p.limit - 1).join(p.separator)])\n },\n})\n\n/** String join of a list; null elements are skipped. Unrelated to the `join` node. */\nexport const join = defineOp({\n name: 'join',\n params: params({ separator: z.string() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n if (input.kind !== 'list' || stripNull(input.of).kind !== 'string') {\n return err(`join expects list<string>, got ${show(input)}`)\n }\n return ok(t.string)\n },\n run: (p) => (input) =>\n ok((input as readonly (string | null)[]).filter((x) => x !== null).join(p.separator)),\n})\n\nconst SCALAR = new Set(['string', 'number', 'boolean'])\n\n/** Join the parts of a multi-path `extract`; null parts are skipped. */\nexport const concat = defineOp({\n name: 'concat',\n params: params({ separator: z.string().optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n if (input.kind !== 'tuple' || !input.of.every((x) => SCALAR.has(stripNull(x).kind))) {\n return err(`concat expects a tuple of strings, numbers or booleans, got ${show(input)}`)\n }\n return ok(t.string)\n },\n run: (p) => (input) =>\n ok(\n (input as readonly Val[])\n .filter((x) => x !== null)\n .map((x) => String(x as string | number | boolean))\n .join(p.separator ?? ''),\n ),\n})\n\n/** URL-safe form: ASCII letters and digits, lowercase, runs of anything else to `separator`. */\nexport const slug = defineOp({\n name: 'slug',\n params: params({ separator: z.string().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('slug'),\n run: (p) => {\n const sep = p.separator ?? '-'\n return (input) =>\n ok(\n (input as string)\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((x) => x !== '')\n .join(sep),\n )\n },\n})\n","/**\n * `when`: the one general conditional (arch.md limitation #12). First matching case wins;\n * `then` and `else` are a literal, `null`, or `{ \"pass\": true }` to forward the input. `else`\n * defaults to pass-through. As a pipeline's first step there is no input: every case must\n * test a `path`, and `else` is required.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate } from '../predicate'\nimport { err, expectOk, ok, type Result } from '../result'\nimport { type MType, show, typeOfJson, unifyAll } from '../types'\nimport type { Json, Val } from '../values'\nimport { defineOp, json, never, params } from './def'\n\nconst pass = z.strictObject({ pass: z.literal(true) })\nconst scalar = z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(json)])\nconst branch = z.union([pass, scalar])\n\ntype Branch = z.infer<typeof branch>\n\nconst isPass = (b: Branch): b is { pass: true } =>\n typeof b === 'object' && b !== null && !Array.isArray(b)\n\nexport const when = defineOp({\n name: 'when',\n params: params({\n cases: z.array(z.strictObject({ cond: z.unknown(), then: branch })).min(1),\n else: branch.optional(),\n }),\n nulls: 'consume',\n input: 'any',\n fallible: never,\n signature: (input, p, env): Result<MType, string> => {\n const first = input.kind === 'unit'\n const branches = [...p.cases.map((c) => c.then), ...(p.else === undefined ? [] : [p.else])]\n if (first && p.else === undefined) return err('when as the first step needs an \"else\"')\n if (first && branches.some(isPass)) return err('when as the first step has no input to pass')\n for (const [i, c] of p.cases.entries()) {\n const test = compilePredicate(c.cond, env, input)\n if (!test.ok) return err(`case ${i}: ${test.error}`)\n }\n const types = branches.map((b) => (isPass(b) ? input : typeOfJson(b)))\n if (p.else === undefined) types.push(input)\n const out = unifyAll(types)\n return out.ok ? out : err(`when branches disagree: ${types.map(show).join(', ')}`)\n },\n run: (p, env, input) => {\n const cases = p.cases.map((c) => ({\n test: expectOk(compilePredicate(c.cond, env, input)),\n then: c.then,\n }))\n const otherwise = p.else ?? { pass: true as const }\n const resolve = (b: Branch, v: Val): Val => (isPass(b) ? v : (b as Json as Val))\n return (v, ctx) => {\n for (const c of cases) if (c.test(v, ctx.record, ctx)) return ok(resolve(c.then, v))\n return ok(resolve(otherwise, v))\n }\n },\n})\n","/** The record op registry: every op a `map` field pipeline may use, by name. */\n\nimport { coalesce, constant, extract } from './access'\nimport { assertType, toBool, toDate, toNumber, toString } from './convert'\nimport { formatDateOp, shiftDate, toUtc, truncateDate } from './date'\nimport type { OpDef } from './def'\nimport { fn } from './fn'\nimport { contains, each, filterList, first, index, last, len, max, min, sum, unique } from './list'\nimport { lookup } from './lookup'\nimport { blankToNull, defaultOp, omitIfNull, requireOp } from './nulls'\nimport { abs, add, clamp, convertUnit, divide, multiply, round, subtract } from './numeric'\nimport {\n concat,\n join,\n lower,\n pad,\n regexExtract,\n replace,\n slug,\n split,\n trim,\n truncate,\n upper,\n} from './string'\nimport { when } from './when'\n\nexport type { OpDef, Step, StepResult } from './def'\nexport { defineOp } from './def'\n\nconst all = [\n extract,\n constant,\n coalesce,\n blankToNull,\n defaultOp,\n requireOp,\n omitIfNull,\n toNumber,\n toString,\n toBool,\n toDate,\n assertType,\n add,\n subtract,\n multiply,\n divide,\n round,\n abs,\n clamp,\n convertUnit,\n trim,\n lower,\n upper,\n truncate,\n pad,\n replace,\n regexExtract,\n split,\n join,\n concat,\n slug,\n formatDateOp,\n shiftDate,\n truncateDate,\n toUtc,\n when,\n each,\n filterList,\n index,\n first,\n last,\n len,\n unique,\n sum,\n min,\n max,\n contains,\n lookup,\n fn,\n]\n\nexport const opRegistry: Readonly<Record<string, OpDef<unknown>>> = Object.fromEntries(\n all.map((op) => [op.name, op as unknown as OpDef<unknown>]),\n)\n","/**\n * Sugar, kept for readability and expanded on save (arch.md, \"Conditional\" and \"Lookup\").\n *\n * - `{ op: \"if_<predicate>\", <operand>, then, else? }` expands to a one-case `when`, e.g.\n * `{ op: \"if_lte\", value: 0, then: null }` to\n * `{ op: \"when\", cases: [{ cond: { lte: 0 }, then: null }] }`.\n * - `{ op: \"lookup_entity\", entity, by, field, on_miss? }` expands into a `source` for the\n * internal entity, an `n:1` left `join` on `by`, and an `extract` of `field` (see\n * `normalizeVersion`).\n */\n\nimport { z } from 'zod'\nimport type { GraphEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { entityJsonSchema } from './jsonschema'\nimport { PREDICATES } from './predicate'\nimport { type CompileIssue, err, ok, type Result } from './result'\n\nconst OPERAND_KEYS = ['value', 'values', 'date', 'pattern'] as const\nconst SUGAR_PREDICATES = new Set<string>(\n PREDICATES.filter((p) => !['all', 'any', 'not'].includes(p)),\n)\n\nexport type StepJson = { readonly op: string } & { readonly [key: string]: unknown }\n\n/** Expand one step if it is sugar; other steps pass through unchanged. */\nexport function expandStep(raw: StepJson): Result<StepJson, string> {\n const m = /^if_(.+)$/.exec(raw.op)\n if (!m) return ok(raw)\n const predicate = m[1] as string\n if (!SUGAR_PREDICATES.has(predicate)) return err(`unknown op '${raw.op}'`)\n const { op: _op, then, else: otherwise, path, ...rest } = raw\n if (!('then' in raw)) return err(`${raw.op} needs \"then\"`)\n\n const extra = Object.keys(rest).filter((k) => !(OPERAND_KEYS as readonly string[]).includes(k))\n if (extra.length) return err(`${raw.op} does not take ${extra.join(', ')}`)\n const given = OPERAND_KEYS.filter((k) => k in rest)\n const presence = predicate === 'is_null' || predicate === 'is_blank'\n if (presence ? given.length > 0 : given.length !== 1) {\n return err(\n presence\n ? `${raw.op} takes no comparison value`\n : `${raw.op} takes exactly one of ${OPERAND_KEYS.join(', ')}`,\n )\n }\n const operand = presence ? true : rest[given[0] as string]\n const cond = { ...(path === undefined ? {} : { path }), [predicate]: operand }\n return ok({\n op: 'when',\n cases: [{ cond, then }],\n ...(otherwise === undefined ? {} : { else: otherwise }),\n })\n}\n\nconst LookupEntity = z.strictObject({\n op: z.literal('lookup_entity'),\n entity: z.string().min(1),\n by: z.string().min(1),\n field: z.string().min(1).default('id'),\n on_miss: z.enum(['null', 'pass', 'error']).optional(),\n})\n\nconst isStep = (v: unknown): v is StepJson =>\n typeof v === 'object' && v !== null && typeof (v as StepJson).op === 'string'\n\n/** Expand `if_*` steps (also inside `each`); report `lookup_entity` where it cannot go. */\nfunction expandPipeline(\n steps: readonly unknown[],\n nested: boolean,\n issue: (message: string, step: number) => void,\n): unknown[] {\n return steps.map((step, i) => {\n if (!isStep(step)) return step\n if (nested && step.op === 'lookup_entity') {\n issue('lookup_entity cannot be used inside each', i)\n return step\n }\n if (step.op === 'each' && Array.isArray(step.pipeline)) {\n return {\n ...step,\n pipeline: expandPipeline(step.pipeline, true, (m) => issue(`each: ${m}`, i)),\n }\n }\n const expanded = expandStep(step)\n if (expanded.ok) return expanded.value\n issue(expanded.error, i)\n return step\n })\n}\n\ninterface Rewrite {\n readonly generated: NodeJson[]\n readonly node: NodeJson\n}\n\n/** Rewrite the `lookup_entity` steps of one map node into generated nodes. */\nfunction rewriteLookups(\n node: NodeJson,\n env: Pick<GraphEnv, 'targets'>,\n sources: Set<string>,\n issues: CompileIssue[],\n): Rewrite {\n const generated: NodeJson[] = []\n let input = node.in\n const drop = Array.isArray(node.drop) ? [...(node.drop as string[])] : []\n let n = 0\n const fields = (node.fields as unknown[]).map((raw) => {\n const f = raw as { key?: unknown; pipeline?: unknown }\n if (typeof f !== 'object' || f === null || !Array.isArray(f.pipeline)) return raw\n const key = String(f.key)\n const issue = (message: string, step: number) =>\n issues.push({ code: 'invalid_params', message, node: node.id, field: key, step })\n const pipeline = expandPipeline(f.pipeline, false, issue)\n const at = pipeline.findIndex((s) => isStep(s) && s.op === 'lookup_entity')\n if (at < 0) return { ...f, pipeline }\n if (pipeline.findLastIndex((s) => isStep(s) && s.op === 'lookup_entity') !== at) {\n issue('use one lookup_entity per field; resolve the others in an upstream map', at)\n return { ...f, pipeline }\n }\n const parsed = LookupEntity.safeParse(pipeline[at])\n if (!parsed.success) {\n issue(\n `lookup_entity: ${parsed.error.issues.map((x) => `${x.path.join('.')}: ${x.message}`).join('; ')}`,\n at,\n )\n return { ...f, pipeline }\n }\n if (at === 0) {\n issue('lookup_entity needs a key; extract it first', at)\n return { ...f, pipeline }\n }\n const { entity, by, field, on_miss: onMiss } = parsed.data\n if (!env.targets.entities.some((e) => e.name === entity)) {\n issue(`lookup_entity: unknown entity '${entity}'`, at)\n return { ...f, pipeline }\n }\n n += 1\n const prefix = pipeline.slice(0, at) as StepJson[]\n const only = prefix[0] as StepJson\n let keyField: string\n if (prefix.length === 1 && only.op === 'extract' && typeof only.path === 'string') {\n keyField = only.path\n } else {\n // A computed key is materialised as a field of a preceding map first.\n keyField = `__${key}__key`\n const helper: NodeJson = {\n id: `${node.id}__key${n}`,\n op: 'map',\n in: input,\n keep: 'all',\n fields: [{ key: keyField, pipeline: prefix }],\n ...(node.on_error === undefined ? {} : { on_error: node.on_error }),\n }\n generated.push(helper)\n input = helper.id\n drop.push(keyField)\n }\n const source = `__internal_${entity}`\n if (!sources.has(source)) {\n sources.add(source)\n generated.push({ id: source, op: 'source', system: 'internal', entity })\n }\n const valueField = `__${key}__lookup`\n const join: NodeJson = {\n id: `${node.id}__lookup${n}`,\n op: 'join',\n left: input,\n right: source,\n on: [[keyField, by]],\n type: 'left',\n cardinality: 'n:1',\n select: { [field]: valueField },\n tolerate_skips: true,\n }\n generated.push(join)\n input = join.id\n drop.push(valueField)\n const head: StepJson[] =\n onMiss === 'pass'\n ? [{ op: 'coalesce', paths: [valueField, keyField] }]\n : onMiss === 'error'\n ? [\n { op: 'extract', path: valueField },\n { op: 'require', message: `no ${entity} with ${by} equal to the key` },\n ]\n : [{ op: 'extract', path: valueField }]\n return { ...f, pipeline: [...head, ...pipeline.slice(at + 1)] }\n })\n if (n === 0) return { generated, node: { ...node, fields } }\n const keepAll = node.keep === 'all'\n return {\n generated,\n node: { ...node, in: input, fields, ...(keepAll ? { drop } : {}) },\n }\n}\n\n/**\n * The form a version is stored and compiled in: sugar expanded, `lookup_entity` rewritten\n * into graph nodes, and every internal source's schema pinned from the target model\n * (structural rule 4). Idempotent.\n */\nexport function normalizeVersion(\n version: MappingVersion,\n env: Pick<GraphEnv, 'targets'>,\n): { version: MappingVersion; issues: CompileIssue[] } {\n const issues: CompileIssue[] = []\n const sources = new Set(version.nodes.filter((n) => n.op === 'source').map((n) => n.id))\n const nodes: NodeJson[] = []\n for (const node of version.nodes) {\n if (node.op !== 'map' || !Array.isArray(node.fields)) {\n nodes.push(node)\n continue\n }\n const rewrite = rewriteLookups(node, env, sources, issues)\n nodes.push(...rewrite.generated, rewrite.node)\n }\n const expectedSchema = { ...version.expectedSchema }\n for (const node of nodes) {\n if (node.op !== 'source' || node.system !== 'internal' || expectedSchema[node.id]) continue\n const entity = env.targets.entities.find((e) => e.name === node.entity)\n if (entity) expectedSchema[node.id] = entityJsonSchema(entity)\n }\n return { version: { ...version, nodes, expectedSchema }, issues }\n}\n","/**\n * The step compiler (arch.md, \"The compiler\"): a fold over the steps of one field pipeline\n * that threads a value type and a closure. Nullability is lifted here, so an op marked\n * `nulls: 'propagate'` never sees null: a null input skips it and stays null.\n */\n\nimport type { RecordContext, RecordEnv } from './context'\nimport { opRegistry } from './ops'\nimport type { Step } from './ops/def'\nimport { err, ok, type Result, type StepError } from './result'\nimport { expandStep, type StepJson } from './sugar'\nimport { mayBeNull, type MType, stripNull, t } from './types'\nimport type { Omitted, Val } from './values'\n\nexport interface PipelineError extends StepError {\n readonly step: number\n readonly op: string\n}\n\nexport interface CompiledPipeline {\n readonly type: MType\n /** Can return an error at runtime. */\n readonly fallible: boolean\n /** Ends in `omit_if_null`: the field may be left out of the record. */\n readonly omittable: boolean\n readonly run: (input: Val, ctx: RecordContext) => Result<Val | Omitted, PipelineError>\n}\n\nexport interface StepIssue {\n readonly step: number\n readonly message: string\n}\n\nconst NULL_RESULT = ok(null)\n\n/** Compile a pipeline. Top-level pipelines start from `t.unit`; `each` passes the element type. */\nexport function compileSteps(\n raw: readonly unknown[],\n env: RecordEnv,\n input: MType = t.unit,\n): Result<CompiledPipeline, StepIssue> {\n if (raw.length === 0) return err({ step: 0, message: 'a pipeline needs at least one step' })\n\n let type = input\n let fallible = false\n let omittable = false\n const steps: Step[] = []\n const names: string[] = []\n\n for (const [i, value] of raw.entries()) {\n const issue = (message: string) => err({ step: i, message })\n if (typeof value !== 'object' || value === null || typeof (value as StepJson).op !== 'string') {\n return issue('a step is an object with an \"op\"')\n }\n const expanded = expandStep(value as StepJson)\n if (!expanded.ok) return issue(expanded.error)\n const { op, ...rest } = expanded.value\n const def = Object.hasOwn(opRegistry, op) ? opRegistry[op] : undefined\n if (!def) return issue(`unknown op '${op}'`)\n if (omittable) return issue(`${names.at(-1)} must be the last step`)\n\n const params = def.params.safeParse(rest)\n if (!params.success) {\n return issue(\n `${op}: ${params.error.issues.map((x) => `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`).join('; ')}`,\n )\n }\n\n const mode = def.input ?? 'value'\n if (mode === 'none' && type.kind !== 'unit') {\n return issue(`${op} starts a pipeline; it cannot follow another step`)\n }\n if (mode === 'value' && type.kind === 'unit') {\n return issue(`${op} needs an input; start the pipeline with extract, const, coalesce or when`)\n }\n\n // Nullability is lifted here, so the op only ever sees a non-null input.\n const propagate = def.nulls === 'propagate'\n const lifted = propagate && mayBeNull(type)\n const inner = propagate ? stripNull(type) : type\n if (inner.kind === 'never') return issue(`${op} receives only null; nothing to do`)\n\n const out = def.signature(inner, params.data, env)\n if (!out.ok) return issue(out.error)\n\n const bound = def.run(params.data, env, inner)\n steps.push(lifted ? (v, ctx) => (v === null ? NULL_RESULT : bound(v, ctx)) : bound)\n names.push(op)\n type = lifted ? t.nullable(out.value) : out.value\n fallible ||= def.fallible(params.data, env, inner)\n omittable = def.terminal === true\n }\n\n return ok({\n type,\n fallible,\n omittable,\n run: (input, ctx) => {\n let v: Val | Omitted = input\n for (let i = 0; i < steps.length; i++) {\n const r = (steps[i] as Step)(v as Val, ctx)\n if (!r.ok) return err({ ...r.error, step: i, op: names[i] as string })\n v = r.value\n }\n return ok(v)\n },\n })\n}\n","/**\n * `map`: where the scopes meet. Splits a collection into records, runs one field pipeline per\n * target field with the record as the `extract` scope, and collects the results.\n *\n * `keep: \"all\"` passes the input fields through alongside the new ones, except those listed in\n * `drop` (the `lookup_entity` rewrite drops its helper fields that way). A failing field\n * applies `on_error`:\n * `null` writes null, `skip_field` leaves the field out, `skip_record` (default) drops the\n * record, `fail_sync` fails the node and stops the run.\n */\n\nimport { z } from 'zod'\nimport { OnError } from '../document'\nimport { type CompiledPipeline, compileSteps } from '../pipeline'\nimport { err, ok } from '../result'\nimport { type MType, stripNull, t } from '../types'\nimport { OMIT, type Rec, type Val } from '../values'\nimport { defineNode, nodeId, type NodeIssue, type Origin, type RunIssue } from './def'\n\nconst field = z.strictObject({ key: z.string().min(1), pipeline: z.array(z.unknown()).min(1) })\n\nconst params = z.strictObject({\n in: nodeId,\n fields: z.array(field).min(1),\n keep: z.enum(['none', 'all']).optional(),\n drop: z.array(z.string().min(1)).optional(),\n on_error: OnError.optional(),\n})\n\nconst SAMPLES = 5\n\nexport const mapNode = defineNode({\n op: 'map',\n label: 'Map fields',\n category: 'transform',\n description: 'One output field per pipeline, computed from each input record.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', fields: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const renv = env.recordEnv(input.type)\n const policy = p.on_error ?? env.version.onError ?? 'skip_record'\n const issues: NodeIssue[] = []\n\n const drop = new Set(p.drop ?? [])\n if (drop.size > 0 && p.keep !== 'all')\n issues.push({ message: 'drop applies only with keep: \"all\"' })\n for (const name of drop) {\n if (!Object.hasOwn(input.type.fields, name))\n issues.push({ message: `drop: unknown field '${name}'` })\n }\n const keep = p.keep === 'all' ? Object.keys(input.type.fields).filter((f) => !drop.has(f)) : []\n\n const seen = new Set<string>()\n const compiled: { key: string; pipeline: CompiledPipeline }[] = []\n for (const f of p.fields) {\n if (seen.has(f.key))\n issues.push({ message: `field '${f.key}' is defined twice`, field: f.key })\n seen.add(f.key)\n const c = compileSteps(f.pipeline, renv)\n if (c.ok) compiled.push({ key: f.key, pipeline: c.value })\n else issues.push({ message: c.error.message, field: f.key, step: c.error.step })\n }\n if (issues.length) return { ok: false, error: issues }\n\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const name of keep) {\n fields[name] = input.type.fields[name] as MType\n origins[name] = input.origins[name] as Origin\n }\n for (const { key, pipeline } of compiled) {\n const soft = pipeline.fallible && (policy === 'null' || policy === 'skip_field')\n const omittable = pipeline.omittable || (pipeline.fallible && policy === 'skip_field')\n fields[key] = soft ? t.nullable(pipeline.type) : pipeline.type\n origins[key] = {\n node: env.id,\n field: key,\n omittable,\n ...(omittable\n ? { present: pipeline.omittable ? stripNull(pipeline.type) : pipeline.type }\n : {}),\n }\n }\n\n return ok({\n output: {\n type: t.record(fields),\n origins,\n canSkip: policy === 'skip_record' && compiled.some((c) => c.pipeline.fallible),\n },\n run: (inputs, ctx) => {\n const errors = new Map<\n string,\n { field: string; code: string; count: number; samples: string[] }\n >()\n const rows: Rec[] = []\n let skipped = 0\n for (const record of inputs(p.in)) {\n const rc = { ...ctx, record }\n const out: Record<string, Val> = {}\n for (const name of keep) if (Object.hasOwn(record, name)) out[name] = record[name] as Val\n let drop = false\n for (const { key, pipeline } of compiled) {\n const r = pipeline.run(null, rc)\n if (r.ok) {\n if (r.value === OMIT) delete out[key]\n else out[key] = r.value\n continue\n }\n const detail = `step ${r.error.step} ${r.error.op}: ${r.error.detail}`\n if (policy === 'fail_sync') {\n return err({ code: r.error.code, message: `${key} ${detail}`, stop: true })\n }\n const k = `${key}\\u0000${r.error.code}`\n const e = errors.get(k) ?? { field: key, code: r.error.code, count: 0, samples: [] }\n e.count += 1\n if (e.samples.length < SAMPLES) e.samples.push(detail)\n errors.set(k, e)\n if (policy === 'null') out[key] = null\n else if (policy === 'skip_field') delete out[key]\n else {\n drop = true\n break\n }\n }\n if (drop) skipped += 1\n else rows.push(out)\n }\n const issues: RunIssue[] = [...errors.values()].map((e) => ({\n node: env.id,\n code: e.code,\n field: e.field,\n message: `${e.field}: ${e.count} records failed (${policy})`,\n count: e.count,\n samples: e.samples,\n }))\n return ok({ rows, skipped, issues })\n },\n })\n },\n})\n","/**\n * `metrics`: writes a small relation, such as counters, onto the sync run rather than into the\n * domain. Never held back by any check: it describes the run, and matters most when a run\n * is stopped.\n *\n * `count_by` reports one row per distinct combination of those fields with its number of\n * `rows`, the usual counter, so it needs no `aggregate` in front. The reported relation is the\n * node's output for `expect` (a `keyed` bound alerts on one counter); nothing reads it.\n */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport { type MType, t } from '../types'\nimport { type Json, keyOf, type Rec, sortRecords, toJson } from '../values'\nimport { defineNode, fail, nodeId, type Origin, ownOrigins } from './def'\n\nconst params = z.strictObject({\n in: nodeId,\n name: z.string().min(1),\n count_by: z.array(z.string().min(1)).min(1).optional(),\n})\n\n/** The count field `count_by` adds next to the group fields. */\nconst COUNT = 'rows'\n\nexport const metricsNode = defineNode({\n op: 'metrics',\n label: 'Run metrics',\n category: 'target',\n description: 'Reports a small relation (counters) on the run instead of the domain.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: false,\n effect: 'metrics',\n defaults: () => ({ in: '', name: '' }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const by = p.count_by\n if (!by) {\n return ok({\n output: input,\n run: (inputs) => {\n const rows = sortRecords(inputs(p.in), [])\n return ok({ rows, metric: metric(env.id, p.name, rows) })\n },\n })\n }\n const unknown = by.filter((f) => !Object.hasOwn(input.type.fields, f))\n if (unknown.length) return fail(`count_by: unknown fields: ${unknown.join(', ')}`)\n if (by.includes(COUNT)) return fail(`count_by: '${COUNT}' is the count field; rename it first`)\n const fields: Record<string, MType> = Object.fromEntries(\n by.map((f) => [f, input.type.fields[f] as MType]),\n )\n const type = t.record({ ...fields, [COUNT]: t.number })\n return ok({\n output: {\n type,\n origins: {\n ...ownOrigins(env.id, type),\n ...Object.fromEntries(by.map((f) => [f, input.origins[f] as Origin])),\n },\n },\n run: (inputs) => {\n const groups = new Map<string, { first: Rec; n: number }>()\n for (const row of inputs(p.in)) {\n const k = keyOf(row, by)\n const group = groups.get(k)\n if (group) group.n += 1\n else groups.set(k, { first: row, n: 1 })\n }\n const counted = [...groups.values()].map(({ first, n }) => ({\n ...Object.fromEntries(by.map((f) => [f, first[f] ?? null])),\n [COUNT]: n,\n }))\n const rows = sortRecords(counted, by)\n return ok({ rows, metric: metric(env.id, p.name, rows) })\n },\n })\n },\n})\n\nfunction metric(node: string, name: string, rows: readonly Rec[]) {\n return { node, name, rows: rows.map((r) => toJson(r) as Record<string, Json>) }\n}\n","/**\n * `sink`: upserts its input on `key` into the internal model. Every input field is written to\n * the target path it names (`product.sku`, or a bare `sku` on the sink's own `target`), or\n * to the path `columns` renames it to. Types are enforced here against the host's\n * `TargetSchema`: an unknown path, a wrong type, or a nullable value for a required field\n * fails at save, blamed on the `map` field that produced it.\n *\n * A reference field listed in `refs` is written as a natural key of the entity it references\n * (`product_id` as a SKU, a lane as its `(from, to)` pair) and typed by those fields, so a\n * key of the wrong shape fails at save; the host resolves it to an id when it writes. Key\n * fields must be non-null, except a nullable identity field of an entity whose identity\n * matches NULLs as equal (the inbound supplier lane, `from_warehouse_id = NULL`).\n *\n * `mode: 'replace'` makes the rows the complete set of the target for the company: the host\n * reconciles with `synchronize_all`, deleting rows this run no longer produces. That is what a\n * presence-only entity needs (an exclusion row *is* the rule). Because a short source read\n * would then delete real rows, `in` must carry a `count` expectation with a lower bound\n * (`min` or `shiftRatio.min`) whose action is `stop` or `skip_downstream`.\n *\n * The library performs no write: a run returns the rows, sorted by key, for the host.\n */\n\nimport { z } from 'zod'\nimport type { TargetEntity, TargetField, TargetSchema } from '../../schema'\nimport { resolveAction } from '../expect'\nimport { err, ok, type Result } from '../result'\nimport { type Instant, toDateString } from '../time'\nimport {\n assignable,\n fromLogicalType,\n type MType,\n mayBeNull,\n nullableIf,\n show,\n stripNull,\n t,\n} from '../types'\nimport { compareVals, type Json, keyOf, type Rec, toJson, type Val } from '../values'\nimport {\n defineNode,\n nodeId,\n type NodeIssue,\n type Origin,\n type SinkRef,\n type WritePolicy,\n} from './def'\n\nconst params = z.strictObject({\n in: nodeId,\n target: z.string().min(1),\n key: z.array(z.string().min(1)).min(1),\n columns: z.record(z.string(), z.string().min(1)).optional(),\n write: z.record(z.string(), z.enum(['overwrite', 'fill_if_null', 'never'])).optional(),\n refs: z.record(z.string(), z.strictObject({ by: z.array(z.string().min(1)).min(1) })).optional(),\n mode: z.enum(['upsert', 'replace']).optional(),\n})\n\ninterface Resolved {\n readonly entity: TargetEntity\n readonly field: TargetField\n readonly type: MType\n}\n\n/** `entity.field` names any entity; a bare name is a field of the sink's own target. */\nexport function resolveTarget(\n targets: TargetSchema,\n target: string,\n path: string,\n): Result<Resolved, string> {\n const dot = path.indexOf('.')\n const [entityName, fieldName] =\n dot < 0 ? [target, path] : [path.slice(0, dot), path.slice(dot + 1)]\n const entity = targets.entities.find((e) => e.name === entityName)\n if (!entity) return err(`target has no entity '${entityName}'`)\n const field = entity.fields.find((f) => f.name === fieldName)\n if (!field) return err(`${entityName} has no field '${fieldName}'`)\n return ok({ entity, field, type: nullableIf(fromLogicalType(field.logicalType), field.nullable) })\n}\n\n/**\n * The type of a reference field written as a natural key: the type of its one `by` field of\n * the referenced entity, or a tuple of them in `by` order (each with its own nullability).\n */\nexport function refType(\n targets: TargetSchema,\n field: TargetField,\n by: readonly string[],\n): Result<{ entity: string; type: MType }, string> {\n if (!field.references) return err(`${field.name} is not a reference`)\n const entity = targets.entities.find((e) => e.name === field.references)\n if (!entity) return err(`target has no entity '${field.references}'`)\n const parts: MType[] = []\n for (const name of by) {\n const part = entity.fields.find((f) => f.name === name)\n if (!part) return err(`${entity.name} has no field '${name}'`)\n parts.push(nullableIf(fromLogicalType(part.logicalType), part.nullable))\n }\n const value = parts.length === 1 ? stripNull(parts[0] as MType) : t.tuple(parts)\n return ok({ entity: entity.name, type: nullableIf(value, field.nullable) })\n}\n\n/** A nullable key field is allowed where the target identity matches NULLs as equal. */\nconst nullsEqual = ({ entity, field }: Resolved) =>\n field.nullable && entity.nullsNotDistinct === true && entity.identity.includes(field.name)\n\nexport const sinkNode = defineNode({\n op: 'sink',\n label: 'Write to target',\n category: 'target',\n description: 'Writes rows into a Spherecast entity, updating records with the same key.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: false,\n effect: 'sink',\n defaults: () => ({ in: '', target: '', key: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const issues: NodeIssue[] = []\n const targets = env.graph.targets\n if (!targets.entities.some((e) => e.name === p.target)) {\n return { ok: false, error: [{ message: `target has no entity '${p.target}'` }] }\n }\n const fieldNames = Object.keys(input.type.fields)\n for (const name of [\n ...Object.keys(p.columns ?? {}),\n ...Object.keys(p.write ?? {}),\n ...Object.keys(p.refs ?? {}),\n ]) {\n if (!fieldNames.includes(name))\n issues.push({ message: `'${name}' is not a field of ${p.in}` })\n }\n\n const paths: Record<string, string> = {}\n const logical: Record<string, TargetField['logicalType']> = {}\n const resolvedOf: Record<string, Resolved> = {}\n const refs: Record<string, SinkRef> = {}\n const entities = new Set([p.target])\n for (const name of fieldNames) {\n const path = p.columns?.[name] ?? name\n const origin = input.origins[name] as Origin\n const blame = { node: origin.node, field: origin.field }\n const resolved = resolveTarget(targets, p.target, path)\n if (!resolved.ok) {\n issues.push({ message: resolved.error, ...blame })\n continue\n }\n let expected = resolved.value.type\n const ref = p.refs?.[name]\n if (ref) {\n const typed = refType(targets, resolved.value.field, ref.by)\n if (!typed.ok) {\n issues.push({ message: `refs.${name}: ${typed.error}` })\n continue\n }\n expected = typed.value.type\n refs[path] = { entity: typed.value.entity, by: ref.by }\n }\n const type = input.type.fields[name] as MType\n const present = origin.present ?? type\n if (!assignable(present, expected)) {\n issues.push({\n message: `${path} expects ${show(expected)}, got ${show(present)}`,\n ...blame,\n })\n }\n paths[name] = path\n logical[name] = resolved.value.field.logicalType\n resolvedOf[name] = resolved.value\n entities.add(resolved.value.entity.name)\n }\n for (const k of p.key) {\n const type = input.type.fields[k]\n const resolved = resolvedOf[k]\n if (!type) issues.push({ message: `key '${k}' is not a field of ${p.in}` })\n else if (\n mayBeNull(type) &&\n ((input.origins[k] as Origin).omittable || !resolved || !nullsEqual(resolved))\n ) {\n issues.push({ message: `key '${k}' must be non-null, got ${show(type)}` })\n }\n }\n if (p.mode === 'replace') {\n const exp = env.version.expect[p.in]\n const lower = exp?.count?.min !== undefined || exp?.count?.shiftRatio?.min !== undefined\n const action = resolveAction(exp?.onFail, 'count')\n if (!lower || (action !== 'stop' && action !== 'skip_downstream')) {\n issues.push({\n message: `mode 'replace' deletes rows this run does not produce; give ${p.in} a count expectation with a lower bound and onFail stop or skip_downstream`,\n })\n }\n }\n if (issues.length) return { ok: false, error: issues }\n\n const keyPaths = p.key.map((k) => paths[k] as string)\n const write = p.write\n ? Object.fromEntries(\n Object.entries(p.write).map(([f, w]) => [paths[f] as string, w as WritePolicy]),\n )\n : undefined\n\n return ok({\n output: null,\n writes: [...entities].sort(),\n run: (inputs, ctx) => {\n // Key fields are never omittable, so every row has them (null only where allowed).\n const rows = [...inputs(p.in)].sort((a, b) => {\n for (const k of p.key) {\n const c = compareVals(a[k] as Val, b[k] as Val)\n if (c !== 0) return c\n }\n return 0\n })\n for (let i = 1; i < rows.length; i++) {\n if (keyOf(rows[i] as Rec, p.key) === keyOf(rows[i - 1] as Rec, p.key)) {\n const sample = p.key.map((k) => toJson((rows[i] as Rec)[k] as Val))\n return err({\n code: 'duplicate_key',\n message: `${p.key.join(', ')} ${JSON.stringify(sample)} is written twice`,\n samples: [sample],\n })\n }\n }\n const out = rows.map((row) => {\n const target: Record<string, Json> = {}\n for (const name of fieldNames) {\n if (!Object.hasOwn(row, name)) continue\n const v = row[name] ?? null\n const kind = logical[name]\n target[paths[name] as string] =\n v !== null && kind === 'date' ? toDateString(v as Instant, ctx.tz) : toJson(v)\n }\n return target\n })\n return ok({\n rows: out,\n write: {\n sink: env.id,\n target: p.target,\n key: keyPaths,\n rows: out,\n ...(write ? { write } : {}),\n ...(Object.keys(refs).length ? { refs } : {}),\n ...(p.mode === 'replace' ? { mode: 'replace' as const } : {}),\n },\n })\n },\n })\n },\n})\n","/**\n * `transform`: the collection-scope escape hatch. Calls reviewed, version-pinned code the host\n * registers in `GraphEnv.transforms`; its declared output `schema` (JSON Schema of one record)\n * keeps the rest of the graph type-checked, and its rows are checked against it at runtime.\n */\n\nimport { z } from 'zod'\nimport type { TransformDef } from '../context'\nimport { JsonSchema } from '../document'\nimport { sourceRecordType } from '../jsonschema'\nimport { err, ok } from '../result'\nimport { defineNode, fail, nodeId, ownOrigins } from './def'\nimport { loadRows } from './source'\n\nconst params = z.strictObject({\n ref: z.string().min(1),\n inputs: z.array(nodeId).min(1),\n schema: JsonSchema,\n})\n\nexport const transformNode = defineNode({\n op: 'transform',\n label: 'Transform (code)',\n category: 'transform',\n description: 'Reviewed, version-pinned code with a declared output schema.',\n slots: [{ id: 'inputs', label: 'Inputs', path: ['inputs'], multiple: true }],\n output: true,\n defaults: () => ({ ref: '', inputs: [], schema: { type: 'object', properties: {} } }),\n params,\n compile: (p, env) => {\n for (const id of p.inputs) env.input(id)\n const transforms = env.graph.transforms ?? {}\n if (!Object.hasOwn(transforms, p.ref)) return fail(`unknown transform '${p.ref}'`)\n const type = sourceRecordType(p.schema)\n if (!type.ok) return fail(`schema: ${type.error}`)\n const record = type.value\n const transform = transforms[p.ref] as TransformDef\n return ok({\n output: { type: record, origins: ownOrigins(env.id, record) },\n run: (inputs, ctx) => {\n const result = transform.run(p.inputs.map(inputs), ctx)\n if (!result.ok) return err({ code: 'transform_failed', message: result.error })\n const loaded = loadRows(env.id, result.value, record)\n return loaded.ok ? ok({ rows: loaded.value }) : loaded\n },\n })\n },\n})\n","/**\n * `union`: set union of inputs with the same fields. Field types must agree up to\n * nullability (a field nullable in any input is nullable in the output); project with a\n * `map` first otherwise. Duplicates collapse.\n */\n\nimport { z } from 'zod'\nimport { expectOk, ok } from '../result'\nimport { type MType, show, t, unify } from '../types'\nimport { keyOf, type Rec } from '../values'\nimport { defineNode, fail, nodeId, type NodeIssue, type Origin } from './def'\n\nconst params = z.strictObject({ inputs: z.array(nodeId).min(2) })\n\nexport const unionNode = defineNode({\n op: 'union',\n label: 'Union',\n category: 'transform',\n description: 'All records of several inputs with the same fields; duplicates collapse.',\n slots: [{ id: 'inputs', label: 'Inputs', path: ['inputs'], multiple: true }],\n output: true,\n defaults: () => ({ inputs: [] }),\n params,\n compile: (p, env) => {\n const outputs = p.inputs.map((id) => env.input(id))\n const first = outputs[0] as (typeof outputs)[number]\n const names = Object.keys(first.type.fields).sort()\n const issues: NodeIssue[] = []\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const [i, out] of outputs.entries()) {\n const other = Object.keys(out.type.fields).sort()\n if (other.join('\\u0000') !== names.join('\\u0000')) {\n return fail(\n `${p.inputs[i]} has fields ${other.join(', ')}; ${p.inputs[0]} has ${names.join(', ')}`,\n )\n }\n }\n for (const name of names) {\n let type: MType = t.never\n let present: MType = t.never\n let omittable = false\n for (const [i, out] of outputs.entries()) {\n const field = out.type.fields[name] as MType\n const u = unify(type, field)\n if (!u.ok) {\n issues.push({\n message: `${name}: ${p.inputs[i]} gives ${show(field)}, earlier inputs ${show(type)}`,\n })\n break\n }\n type = u.value\n const origin = out.origins[name] as Origin\n omittable ||= origin.omittable\n present = expectOk(unify(present, origin.present ?? field))\n }\n fields[name] = type\n origins[name] = { node: env.id, field: name, omittable, ...(omittable ? { present } : {}) }\n }\n if (issues.length) return { ok: false, error: issues }\n return ok({\n output: { type: t.record(fields), origins },\n run: (inputs) => {\n const seen = new Set<string>()\n const rows: Rec[] = []\n for (const id of p.inputs) {\n for (const row of inputs(id)) {\n const k = keyOf(row, names)\n if (seen.has(k)) continue\n seen.add(k)\n rows.push(row)\n }\n }\n return ok({ rows })\n },\n })\n },\n})\n","/** The collection node registry, and the catalog the editor builds its palette from. */\n\nimport { aggregateNode } from './aggregate'\nimport { assertNode } from './assert'\nimport type { NodeCategory, NodeDef, Slot } from './def'\nimport { distinctNode } from './distinct'\nimport { filterNode } from './filter'\nimport { joinNode } from './join'\nimport { mapNode } from './map'\nimport { metricsNode } from './metrics'\nimport { sinkNode } from './sink'\nimport { sourceNode } from './source'\nimport { transformNode } from './transform'\nimport { unionNode } from './union'\n\nexport type * from './def'\nexport { defineNode } from './def'\nexport { refType, resolveTarget } from './sink'\nexport { findCycle } from './assert'\n\nconst all = [\n sourceNode,\n mapNode,\n filterNode,\n joinNode,\n aggregateNode,\n distinctNode,\n unionNode,\n sinkNode,\n metricsNode,\n assertNode,\n transformNode,\n]\n\nexport const nodeRegistry: Readonly<Record<string, NodeDef<unknown>>> = Object.fromEntries(\n all.map((def) => [def.op, def as unknown as NodeDef<unknown>]),\n)\n\n/** What the editor needs to place a node and draw its handles. */\nexport interface CatalogEntry {\n readonly op: string\n readonly label: string\n readonly category: NodeCategory\n readonly description: string\n readonly slots: readonly Slot[]\n readonly output: boolean\n readonly defaults: () => Record<string, unknown>\n}\n\nexport const nodeCatalog: readonly CatalogEntry[] = all.map(\n ({ op, label, category, description, slots, output, defaults }) => ({\n op,\n label,\n category,\n description,\n slots,\n output,\n defaults,\n }),\n)\n","/**\n * Edges are implied by input references (`in`, `left`, `right`, `inputs`, and an assert's\n * `per.in` / `remove.in`); each node definition's `slots` name them. Everything that walks the\n * graph (ordering, dead nodes, lineage, freeing edges, the editor's edges) reads them here.\n */\n\nimport type { NodeJson } from './document'\nimport { nodeRegistry } from './nodes'\n\nexport interface Ref {\n /** Slot id on the consuming node. */\n readonly slot: string\n /** Id of the referenced (upstream) node. */\n readonly source: string\n /** Position within a `multiple` slot. */\n readonly index?: number\n}\n\nfunction at(node: Readonly<Record<string, unknown>>, path: readonly string[]): unknown {\n let value: unknown = node\n for (const key of path) {\n if (typeof value !== 'object' || value === null) return undefined\n value = (value as Record<string, unknown>)[key]\n }\n return value\n}\n\n/** The input references of a node, slot by slot. Unknown ops have none. */\nexport function nodeRefs(node: NodeJson): Ref[] {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) return []\n const refs: Ref[] = []\n for (const slot of def.slots) {\n const value = at(node, slot.path)\n if (slot.multiple && Array.isArray(value)) {\n for (const [index, source] of value.entries()) {\n if (typeof source === 'string' && source !== '') refs.push({ slot: slot.id, source, index })\n }\n } else if (typeof value === 'string' && value !== '') {\n refs.push({ slot: slot.id, source: value })\n }\n }\n return refs\n}\n\n/** Distinct upstream ids of a node, in slot order. */\nexport function inputIds(node: NodeJson): string[] {\n return [...new Set(nodeRefs(node).map((r) => r.source))]\n}\n\n/** Downstream neighbours of every node (only references to existing nodes). */\nexport function consumers(nodes: readonly NodeJson[]): Map<string, string[]> {\n const ids = new Set(nodes.map((n) => n.id))\n const next = new Map<string, string[]>(nodes.map((n) => [n.id, []]))\n for (const node of nodes) {\n for (const source of inputIds(node)) {\n if (ids.has(source)) (next.get(source) as string[]).push(node.id)\n }\n }\n return next\n}\n\nfunction reach(start: string, next: ReadonlyMap<string, readonly string[]>): Set<string> {\n const seen = new Set<string>()\n const stack = [...(next.get(start) ?? [])]\n while (stack.length > 0) {\n const id = stack.pop() as string\n if (seen.has(id)) continue\n seen.add(id)\n stack.push(...(next.get(id) as readonly string[]))\n }\n return seen\n}\n\n/** Every node fed by `id`, directly or not (not including `id`). */\nexport function downstream(nodes: readonly NodeJson[], id: string): Set<string> {\n return reach(id, consumers(nodes))\n}\n\n/** Every node feeding `id`, directly or not (not including `id`). */\nexport function upstream(nodes: readonly NodeJson[], id: string): Set<string> {\n const ids = new Set(nodes.map((n) => n.id))\n const prev = new Map(nodes.map((n) => [n.id, inputIds(n).filter((s) => ids.has(s))]))\n return reach(id, prev)\n}\n\n/** One cycle as node ids (first repeated at the end), or null if acyclic. */\nexport function findGraphCycle(nodes: readonly NodeJson[]): string[] | null {\n const next = consumers(nodes)\n const state = new Map<string, 'open' | 'done'>()\n const path: string[] = []\n const visit = (id: string): string[] | null => {\n state.set(id, 'open')\n path.push(id)\n for (const to of next.get(id) as string[]) {\n if (state.get(to) === 'open') return [...path.slice(path.indexOf(to)), to]\n if (!state.has(to)) {\n const cycle = visit(to)\n if (cycle) return cycle\n }\n }\n path.pop()\n state.set(id, 'done')\n return null\n }\n for (const node of nodes) {\n if (state.has(node.id)) continue\n const cycle = visit(node.id)\n if (cycle) return cycle\n }\n return null\n}\n\n/**\n * Node ids with every node after the nodes it reads; ties keep document order, so the result\n * is stable. Nodes on a cycle are left out (check `findGraphCycle` first).\n */\nexport function topologicalOrder(nodes: readonly NodeJson[]): string[] {\n const next = consumers(nodes)\n const indegree = new Map(nodes.map((n) => [n.id, 0]))\n for (const targets of next.values())\n for (const t of targets) indegree.set(t, (indegree.get(t) as number) + 1)\n const position = new Map(nodes.map((n, i) => [n.id, i]))\n const ready = nodes.filter((n) => indegree.get(n.id) === 0).map((n) => n.id)\n const order: string[] = []\n while (ready.length > 0) {\n ready.sort((a, b) => (position.get(a) as number) - (position.get(b) as number))\n const id = ready.shift() as string\n order.push(id)\n for (const to of next.get(id) as string[]) {\n const remaining = (indegree.get(to) as number) - 1\n indegree.set(to, remaining)\n if (remaining === 0) ready.push(to)\n }\n }\n return order\n}\n","/**\n * The graph compiler (arch.md, \"The compiler\"): walks nodes in topological order, threading\n * record types along edges, and compiles each node into a closure in the same pass. The\n * result is one plan per version; a run never touches JSON.\n *\n * Every problem is collected in one pass and located by node, field and step. A node whose\n * inputs failed to compile is skipped silently, so one mistake does not cascade.\n */\n\nimport { type GraphEnv, recordEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { type Checker, compileExpectation } from './expect'\nimport { consumers, findGraphCycle, inputIds, nodeRefs, topologicalOrder } from './graph'\nimport { type CompiledNode, nodeRegistry, type NodeEnv, type NodeOutput } from './nodes'\nimport type { CompileIssue } from './result'\nimport { normalizeVersion } from './sugar'\nimport type { RecordType } from './types'\n\nexport interface PlannedNode {\n readonly id: string\n readonly op: string\n /** Parsed params. */\n readonly params: Readonly<Record<string, unknown>>\n readonly inputs: readonly string[]\n readonly output: NodeOutput | null\n readonly effect?: 'sink' | 'metrics' | 'check'\n readonly run: CompiledNode['run']\n /** The node's `expect` entry, compiled. */\n readonly check?: Checker\n /** Sinks downstream of this node, itself included: the reach of `skip_downstream`. */\n readonly sinks: readonly string[]\n /** Upstream of (or is) a `metrics` node: keeps running after a `stop`. */\n readonly feedsMetrics: boolean\n}\n\nexport interface Plan {\n /** The normalized version the plan was compiled from. */\n readonly version: MappingVersion\n readonly nodes: readonly PlannedNode[]\n /** Index of the last node reading each node's output; the edge is freed after it. */\n readonly lastUse: ReadonlyMap<string, number>\n /** Some predicate reads the run clock (`today`, `now`). */\n readonly usesClock: boolean\n}\n\n/**\n * `types` holds the output record type of every node that compiled, also when others did\n * not, so an editor can offer the fields reaching a node while the graph is half built.\n */\nexport type CompileResult =\n | {\n readonly ok: true\n readonly plan: Plan\n readonly issues: readonly []\n readonly types: Readonly<Record<string, RecordType>>\n }\n | {\n readonly ok: false\n readonly issues: readonly CompileIssue[]\n readonly types: Readonly<Record<string, RecordType>>\n }\n\nfunction paramsOf(node: NodeJson): Record<string, unknown> {\n const { id: _i, op: _o, label: _l, ...rest } = node\n return rest\n}\n\n/**\n * Structural rules that need no types: unique ids, known ops, resolvable references,\n * acyclic, no dead nodes, addressable `expect` keys. Checked in the browser too.\n */\nexport function structuralIssues(version: MappingVersion): CompileIssue[] {\n const issues: CompileIssue[] = []\n const byId = new Map<string, NodeJson>()\n for (const node of version.nodes) {\n if (byId.has(node.id))\n issues.push({ code: 'duplicate_id', message: `id '${node.id}' is used twice`, node: node.id })\n byId.set(node.id, node)\n }\n for (const node of version.nodes) {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) {\n issues.push({ code: 'unknown_op', message: `unknown node op '${node.op}'`, node: node.id })\n continue\n }\n const refs = nodeRefs(node)\n for (const slot of def.slots) {\n if (!slot.optional && !refs.some((r) => r.slot === slot.id)) {\n issues.push({\n code: 'missing_input',\n message: `input '${slot.label}' is not connected`,\n node: node.id,\n })\n }\n }\n for (const ref of refs) {\n const source = byId.get(ref.source)\n if (!source) {\n issues.push({\n code: 'dangling_ref',\n message: `'${ref.slot}' refers to unknown node '${ref.source}'`,\n node: node.id,\n })\n } else if (nodeRegistry[source.op] && !nodeRegistry[source.op]?.output) {\n issues.push({\n code: 'dangling_ref',\n message: `'${ref.source}' (${source.op}) has no output to read`,\n node: node.id,\n })\n }\n }\n }\n const cycle = findGraphCycle(version.nodes)\n if (cycle) issues.push({ code: 'cycle', message: `cycle: ${cycle.join(' -> ')}`, node: cycle[0] })\n\n // No dead nodes: every node must reach a sink, metrics or assert.\n const live = new Set<string>()\n const effectful = (n: NodeJson) => nodeRegistry[n.op]?.effect !== undefined\n const stack = version.nodes.filter(effectful).map((n) => n.id)\n const prev = new Map(version.nodes.map((n) => [n.id, inputIds(n)]))\n while (stack.length > 0) {\n const id = stack.pop() as string\n if (live.has(id)) continue\n live.add(id)\n stack.push(...(prev.get(id) ?? []))\n }\n for (const node of version.nodes) {\n if (!live.has(node.id) && nodeRegistry[node.op]) {\n issues.push({\n code: 'dead_node',\n message: 'reaches no sink, metrics or assert',\n node: node.id,\n })\n }\n }\n for (const id of Object.keys(version.expect)) {\n if (!byId.has(id))\n issues.push({\n code: 'unknown_reference',\n message: `expect names unknown node '${id}'`,\n field: id,\n })\n }\n return issues\n}\n\n/** Compile a version against the host's environment. */\nexport function compileVersion(input: MappingVersion, env: GraphEnv): CompileResult {\n const normalized = normalizeVersion(input, env)\n const version = normalized.version\n const issues: CompileIssue[] = [...normalized.issues, ...structuralIssues(version)]\n if (issues.some((i) => i.code === 'cycle' || i.code === 'duplicate_id'))\n return { ok: false, issues, types: {} }\n\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const clock = { used: false }\n const outputs = new Map<string, NodeOutput>()\n const compiled = new Map<string, CompiledEntry>()\n const renv = (record: RecordType) =>\n recordEnv(record, {\n params: version.params,\n tables: version.tables,\n functions: env.functions ?? {},\n clock,\n })\n\n for (const id of topologicalOrder(version.nodes)) {\n const node = byId.get(id) as NodeJson\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) continue\n const refs = inputIds(node)\n if (refs.some((r) => !outputs.has(r))) continue // blocked by an upstream problem\n\n const parsed = def.params.safeParse(paramsOf(node))\n if (!parsed.success) {\n for (const x of parsed.error.issues) {\n issues.push({\n code: 'invalid_params',\n message: `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`,\n node: id,\n })\n }\n continue\n }\n const exp = version.expect[id]\n const nodeEnv: NodeEnv = {\n id,\n graph: env,\n version,\n ...(exp ? { expect: exp } : {}),\n clock,\n input: (ref) => outputs.get(ref) as NodeOutput,\n recordEnv: renv,\n }\n const result = def.compile(parsed.data, nodeEnv)\n if (!result.ok) {\n for (const x of result.error) {\n issues.push({\n code: x.code ?? 'type_error',\n message: x.message,\n node: x.node ?? id,\n ...(x.field === undefined ? {} : { field: x.field }),\n ...(x.step === undefined ? {} : { step: x.step }),\n })\n }\n continue\n }\n let output = result.value.output\n let check: Checker | undefined\n if (exp) {\n if (!output) {\n issues.push({\n code: 'invalid_expectation',\n message: `${node.op} has no output to expect on`,\n node: id,\n })\n continue\n }\n const e = compileExpectation(id, exp, output, renv)\n if (!e.ok) {\n for (const x of e.error) {\n // Every expectation issue names its clause.\n issues.push({\n code: 'invalid_expectation',\n message: x.message,\n node: id,\n field: x.field as string,\n })\n }\n continue\n }\n output = e.value.output\n check = e.value.check\n }\n if (output) outputs.set(id, output)\n compiled.set(id, {\n node: { ...result.value, output },\n params: parsed.data as Record<string, unknown>,\n ...(check ? { check } : {}),\n })\n }\n\n issues.push(...sinkIssues(compiled), ...skipIssues(version, compiled))\n const types = Object.fromEntries([...outputs].map(([id, output]) => [id, output.type]))\n if (issues.length > 0) return { ok: false, issues: dedupe(issues), types }\n return { ok: true, plan: plan(version, compiled, clock.used), issues: [], types }\n}\n\ninterface CompiledEntry {\n readonly node: CompiledNode\n readonly params: Record<string, unknown>\n readonly check?: Checker\n}\n\ntype Compiled = ReadonlyMap<string, CompiledEntry>\n\n/** Sugar that fails to expand is reported by normalization and again by the step compiler. */\nfunction dedupe(issues: readonly CompileIssue[]): CompileIssue[] {\n const seen = new Set<string>()\n return issues.filter((i) => {\n const key = JSON.stringify([i.node, i.field, i.step, i.message])\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/** One sink per target entity (structural rule 3): resolve overlaps with a union. */\nfunction sinkIssues(compiled: Compiled): CompileIssue[] {\n const writers = new Map<string, string[]>()\n for (const [id, c] of compiled) {\n for (const entity of c.node.writes ?? [])\n writers.set(entity, [...(writers.get(entity) ?? []), id])\n }\n return [...writers]\n .filter(([, sinks]) => sinks.length > 1)\n .map(([entity, sinks]) => ({\n code: 'duplicate_sink' as const,\n message: `${sinks.join(' and ')} both write ${entity}; union their inputs into one sink`,\n node: sinks[1] as string,\n }))\n}\n\n/**\n * Limitation #20: a map that can drop records upstream of a join or aggregate can flip its\n * result, so the first join or aggregate on every path from it must declare `tolerate_skips`.\n */\nfunction skipIssues(version: MappingVersion, compiled: Compiled): CompileIssue[] {\n const next = consumers(version.nodes)\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const issues: CompileIssue[] = []\n for (const [id, c] of compiled) {\n // Only a map drops records; nodes downstream of it may carry its `canSkip` along.\n if (byId.get(id)?.op !== 'map' || !c.node.output?.canSkip) continue\n const seen = new Set<string>()\n const stack = [...(next.get(id) as string[])]\n while (stack.length > 0) {\n const n = stack.pop() as string\n if (seen.has(n)) continue\n seen.add(n)\n const node = byId.get(n) as NodeJson\n const def = nodeRegistry[node.op]\n if (def?.toleratesSkips) {\n const params = compiled.get(n)?.params\n if (params && !def.toleratesSkips(params)) {\n issues.push({\n code: 'skip_tolerance',\n message: `${id} can drop records (on_error skip_record with a fallible field); set tolerate_skips: true here or change ${id}'s on_error`,\n node: n,\n })\n }\n continue\n }\n stack.push(...(next.get(n) as string[]))\n }\n }\n return issues\n}\n\nfunction plan(version: MappingVersion, compiled: Compiled, usesClock: boolean): Plan {\n const order = topologicalOrder(version.nodes)\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const next = consumers(version.nodes)\n const lastUse = new Map<string, number>()\n for (const [i, id] of order.entries()) {\n for (const ref of inputIds(byId.get(id) as NodeJson)) lastUse.set(ref, i)\n }\n const sinksBelow = new Map<string, string[]>()\n const metricsBelow = new Map<string, boolean>()\n for (const id of [...order].reverse()) {\n const op = (byId.get(id) as NodeJson).op\n // Reverse topological order: every consumer is done before the node it reads.\n const below = next.get(id) as string[]\n const sinks = below.flatMap((b) => sinksBelow.get(b) as string[])\n sinksBelow.set(id, [...new Set(op === 'sink' ? [id, ...sinks] : sinks)].sort())\n metricsBelow.set(id, op === 'metrics' || below.some((b) => metricsBelow.get(b)))\n }\n const nodes: PlannedNode[] = order.map((id) => {\n const node = byId.get(id) as NodeJson\n const c = compiled.get(id) as CompiledEntry\n const def = nodeRegistry[node.op]\n return {\n id,\n op: node.op,\n params: c.params,\n inputs: inputIds(node),\n output: c.node.output,\n ...(def?.effect ? { effect: def.effect } : {}),\n run: c.node.run,\n ...(c.check ? { check: c.check } : {}),\n sinks: sinksBelow.get(id) as string[],\n feedsMetrics: metricsBelow.get(id) as boolean,\n }\n })\n return { version, nodes, lastUse, usesClock }\n}\n","/**\n * The executor (arch.md, \"Execution\"). Runs a compiled plan over a frozen snapshot: every node\n * once, in topological order, each edge held only until its last consumer has run. Nothing is\n * written: sinks return their rows, and the host writes those with status `write`.\n *\n * Failure stays as local as lineage allows. A failed node skips what depends on it while\n * independent branches proceed; `skip_downstream` holds back exactly the sinks below a node;\n * `stop` (or `on_error: fail_sync`) holds back every sink, but nodes feeding `metrics` still\n * run, because metrics describe the run and matter most when it stops.\n */\n\nimport type { RunContext } from './context'\nimport type { Plan } from './compile'\nimport type { Metric, NodeRun, RunIssue, SinkWrite } from './nodes'\nimport { Instant } from './time'\nimport { type Relation, toJson } from './values'\n\nexport interface RunInput {\n /** The run's frozen clock: an instant, or an ISO string with an offset. */\n readonly now: Instant | string\n /** IANA time zone for calendar math; defaults to UTC. */\n readonly tz?: string\n readonly locale?: string\n readonly syncRunId?: string\n /** Previous output counts per node id, for `count.shiftRatio`. */\n readonly baseline?: Readonly<Record<string, number>>\n}\n\nexport interface ExecuteOptions {\n /** Keep every node's output in the result (previews, fixtures). */\n readonly retain?: boolean\n /** Fixture mode: run every node even after a stop, skip production `count` envelopes. */\n readonly fixture?: boolean\n /** Elapsed-time clock for statistics; defaults to `performance.now`. */\n readonly clock?: () => number\n}\n\nexport type NodeStatus = 'ok' | 'failed' | 'upstream_failed' | 'stopped'\n\nexport interface NodeStats {\n readonly node: string\n readonly op: string\n readonly status: NodeStatus\n readonly rowsIn: number\n readonly rowsOut: number\n readonly skipped: number\n readonly changed: number\n readonly ms: number\n}\n\nexport type SinkStatus = 'write' | 'held' | 'stopped' | 'failed' | 'upstream_failed'\n\nexport interface SinkResult {\n readonly sink: string\n readonly status: SinkStatus\n /** Present only with status `write`. */\n readonly write?: SinkWrite\n}\n\nexport interface RunResult {\n /** `stopped`: nothing may be written. `partial`: some sink is not `write`. */\n readonly status: 'ok' | 'partial' | 'stopped'\n readonly sinks: readonly SinkResult[]\n readonly metrics: readonly Metric[]\n readonly stats: readonly NodeStats[]\n readonly issues: readonly RunIssue[]\n /** Every node's output, with `retain`. Sinks hold the rows they would write. */\n readonly outputs?: Readonly<Record<string, Relation>>\n}\n\nexport type Snapshot = Readonly<Record<string, readonly Readonly<Record<string, unknown>>[]>>\n\n/** Sources the host must read, once each, before a run. */\nexport function readPlan(plan: Plan): { node: string; system: string; entity: string }[] {\n return plan.nodes\n .filter((n) => n.op === 'source')\n .map((n) => ({ node: n.id, system: String(n.params.system), entity: String(n.params.entity) }))\n}\n\n/** Read every source once and freeze the result into a snapshot. */\nexport async function readSnapshot(\n plan: Plan,\n read: (source: {\n node: string\n system: string\n entity: string\n }) => Promise<readonly Readonly<Record<string, unknown>>[]>,\n): Promise<Snapshot> {\n const snapshot: Record<string, readonly Readonly<Record<string, unknown>>[]> = {}\n for (const source of readPlan(plan))\n snapshot[source.node] = Object.freeze([...(await read(source))])\n return Object.freeze(snapshot)\n}\n\nexport function execute(\n plan: Plan,\n snapshot: Snapshot,\n run: RunInput,\n options: ExecuteOptions = {},\n): RunResult {\n const now = typeof run.now === 'string' ? Instant.parse(run.now) : run.now\n if (!now) throw new Error(`run.now '${String(run.now)}' is not an ISO instant`)\n const clock = options.clock ?? (() => performance.now())\n const ctx: RunContext = Object.freeze({\n now,\n tz: run.tz ?? 'UTC',\n locale: run.locale ?? 'en',\n snapshot: snapshot as RunContext['snapshot'],\n params: plan.version.params,\n tables: plan.version.tables,\n run: {\n syncRunId: run.syncRunId ?? '',\n mappingVersionId: `${plan.version.id}@${plan.version.version}`,\n },\n })\n\n const outputs = new Map<string, Relation>()\n const retained: Record<string, Relation> = {}\n const status = new Map<string, NodeStatus>()\n const stats: NodeStats[] = []\n const issues: RunIssue[] = []\n const writes = new Map<string, SinkWrite>()\n const metrics: Metric[] = []\n const held = new Set<string>()\n let stopped = false\n\n for (const [i, node] of plan.nodes.entries()) {\n const record = (s: NodeStatus, extra: Partial<NodeStats> = {}) => {\n status.set(node.id, s)\n stats.push({\n node: node.id,\n op: node.op,\n status: s,\n rowsIn: 0,\n rowsOut: 0,\n skipped: 0,\n changed: 0,\n ms: 0,\n ...extra,\n })\n }\n // Nodes feeding metrics read only nodes feeding metrics, so never a stopped input.\n if (stopped && !options.fixture && !node.feedsMetrics) record('stopped')\n else if (node.inputs.some((id) => status.get(id) !== 'ok')) record('upstream_failed')\n else {\n const rowsIn = node.inputs.reduce((n, id) => n + (outputs.get(id) as Relation).length, 0)\n const start = clock()\n const result = node.run((id) => outputs.get(id) as Relation, ctx, {\n ...(run.baseline?.[node.id] === undefined ? {} : { baseline: run.baseline[node.id] }),\n ...(options.fixture ? { skipCount: true } : {}),\n })\n if (!result.ok) {\n const e = result.error\n issues.push({\n node: node.id,\n code: e.code,\n message: e.message,\n ...(e.samples ? { samples: e.samples } : {}),\n })\n issues.push(...(e.issues ?? []))\n if (e.stop) stopped = true\n record('failed', { rowsIn, ms: clock() - start })\n } else {\n let out: NodeRun = result.value\n if (node.check) {\n const checked = node.check(out.rows, ctx, {\n ...(run.baseline?.[node.id] === undefined ? {} : { baseline: run.baseline[node.id] }),\n ...(options.fixture ? { skipCount: true } : {}),\n })\n out = {\n ...out,\n rows: checked.rows,\n changed: (out.changed ?? 0) + checked.changed,\n issues: [...(out.issues ?? []), ...checked.issues],\n stop: out.stop || checked.stop,\n skipDownstream: out.skipDownstream || checked.skipDownstream,\n }\n }\n issues.push(...(out.issues ?? []))\n if (out.stop) stopped = true\n if (out.skipDownstream) for (const s of node.sinks) held.add(s)\n if (out.write) writes.set(node.id, out.write)\n // A metric reports its rows as the node's checks left them.\n if (out.metric) {\n metrics.push(\n node.check\n ? { ...out.metric, rows: out.rows.map((r) => toJson(r) as Metric['rows'][number]) }\n : out.metric,\n )\n }\n outputs.set(node.id, out.rows)\n if (options.retain) retained[node.id] = out.rows\n record('ok', {\n rowsIn,\n rowsOut: out.rows.length,\n skipped: out.skipped ?? 0,\n changed: out.changed ?? 0,\n ms: clock() - start,\n })\n }\n }\n for (const id of node.inputs) if (plan.lastUse.get(id) === i) outputs.delete(id)\n }\n\n const sinks: SinkResult[] = plan.nodes\n .filter((n) => n.effect === 'sink')\n .map((n) => {\n const s = status.get(n.id)\n const write = writes.get(n.id)\n if (stopped) return { sink: n.id, status: 'stopped' }\n if (s === 'failed') return { sink: n.id, status: 'failed' }\n if (s !== 'ok' || !write) return { sink: n.id, status: 'upstream_failed' }\n if (held.has(n.id)) return { sink: n.id, status: 'held' }\n return { sink: n.id, status: 'write', write }\n })\n\n return {\n status: stopped\n ? 'stopped'\n : sinks.every((s) => s.status === 'write') && [...status.values()].every((s) => s === 'ok')\n ? 'ok'\n : 'partial',\n sinks,\n metrics,\n stats,\n issues,\n ...(options.retain ? { outputs: retained } : {}),\n }\n}\n","/**\n * Fixtures (arch.md limitation #14): relations in, keyed by source node id, and relations\n * out, keyed by any node id, so a multi-step graph is tested at the step that matters. An\n * expected relation is compared as a set on the fields it lists. A fixture also fails when\n * its run stops (an `assert` or expectation with `stop`) or a node fails.\n *\n * Fixtures run at sample scale, so production `count` envelopes are skipped. Dates compare\n * as ISO instants; sink rows hold what would be written (`YYYY-MM-DD` for date fields).\n */\n\nimport type { Plan } from './compile'\nimport { execute, type RunResult } from './execute'\nimport type { RunIssue } from './nodes'\nimport { Instant, isTimeZone } from './time'\nimport { canonicalKey, type Json, toJson, type Val } from './values'\n\nexport interface NodeDiff {\n readonly node: string\n /** Expected records the run did not produce. */\n readonly missing: readonly Json[]\n /** Produced records the fixture does not list. */\n readonly unexpected: readonly Json[]\n}\n\nexport interface ExampleResult {\n readonly index: number\n readonly name?: string\n readonly passed: boolean\n /** Why the fixture failed, apart from relation differences. */\n readonly failures: readonly string[]\n readonly diffs: readonly NodeDiff[]\n readonly issues: readonly RunIssue[]\n readonly run?: RunResult\n}\n\nconst DEFAULT_NOW = '2000-01-01T00:00:00Z'\n\nexport function runExamples(plan: Plan): ExampleResult[] {\n return plan.version.examples.map((example, index) => {\n const failures: string[] = []\n const head = { index, ...(example.name ? { name: example.name } : {}) }\n const sources = new Set(plan.nodes.filter((n) => n.op === 'source').map((n) => n.id))\n const nodes = new Set(plan.nodes.map((n) => n.id))\n for (const id of Object.keys(example.sources)) {\n if (!sources.has(id)) failures.push(`sources names '${id}', which is not a source node`)\n }\n for (const id of Object.keys(example.expect)) {\n if (!nodes.has(id)) failures.push(`expect names unknown node '${id}'`)\n }\n if (plan.usesClock && example.now === undefined) {\n failures.push('the graph reads the clock (today/now), so the example needs \"now\"')\n }\n const now = Instant.parse(example.now ?? DEFAULT_NOW)\n if (!now) failures.push(`now '${example.now}' is not an ISO instant`)\n const tz = example.tz ?? 'UTC'\n if (!isTimeZone(tz)) failures.push(`unknown time zone '${tz}'`)\n if (failures.length) return { ...head, passed: false, failures, diffs: [], issues: [] }\n\n const run = execute(\n plan,\n example.sources,\n { now: now as Instant, tz },\n { retain: true, fixture: true },\n )\n if (run.status === 'stopped') {\n const why = run.issues\n .filter((i) => i.action === 'stop')\n .map((i) => `${i.node}: ${i.message}`)\n failures.push(`run stopped${why.length ? `: ${why.join('; ')}` : ''}`)\n }\n for (const s of run.stats) {\n if (s.status === 'failed') {\n const why = run.issues.filter((i) => i.node === s.node).map((i) => i.message)\n failures.push(`${s.node} failed: ${why.join('; ')}`)\n }\n }\n\n const diffs: NodeDiff[] = []\n for (const [id, expected] of Object.entries(example.expect)) {\n const actual = run.outputs?.[id]\n if (!actual) {\n failures.push(`${id} produced no output`)\n continue\n }\n if (expected.length === 0) {\n if (actual.length) diffs.push({ node: id, missing: [], unexpected: actual.map(toJson) })\n continue\n }\n const fields = Object.keys(expected[0] as object).sort()\n if (expected.some((r) => Object.keys(r).sort().join('\\u0000') !== fields.join('\\u0000'))) {\n failures.push(`expected rows of ${id} must all list the same fields`)\n continue\n }\n const project = (r: Readonly<Record<string, Val>>) =>\n Object.fromEntries(fields.map((f) => [f, toJson(r[f] ?? null)])) as Json\n const want = new Map(\n expected.map((r) => [\n canonicalKey(project(r as Record<string, Val>) as Val),\n project(r as Record<string, Val>),\n ]),\n )\n const got = new Map(actual.map((r) => [canonicalKey(project(r) as Val), project(r)]))\n const missing = [...want].filter(([k]) => !got.has(k)).map(([, r]) => r)\n const unexpected = [...got].filter(([k]) => !want.has(k)).map(([, r]) => r)\n if (missing.length || unexpected.length) diffs.push({ node: id, missing, unexpected })\n }\n return {\n ...head,\n passed: failures.length === 0 && diffs.length === 0,\n failures,\n diffs,\n issues: run.issues,\n run,\n }\n })\n}\n","/**\n * The draft-save gate: everything that must hold before a version may be published, as one\n * list of located issues. `validateStructure` is the subset that needs no host environment,\n * cheap enough to run in the editor on every change.\n */\n\nimport { compileVersion, type Plan, structuralIssues } from './compile'\nimport type { GraphEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { type ExampleResult, runExamples } from './examples'\nimport { nodeRegistry } from './nodes'\nimport type { CompileIssue } from './result'\n\nexport interface CheckResult {\n readonly ok: boolean\n readonly issues: readonly CompileIssue[]\n readonly plan?: Plan\n readonly examples?: readonly ExampleResult[]\n}\n\n/** Compile, then run every example; publishable only if `ok`. */\nexport function checkVersion(version: MappingVersion, env: GraphEnv): CheckResult {\n const compiled = compileVersion(version, env)\n if (!compiled.ok) return { ok: false, issues: compiled.issues }\n const examples = runExamples(compiled.plan)\n const issues: CompileIssue[] = examples.flatMap((e) => {\n const label = `example ${e.name ?? e.index}`\n return [\n ...e.failures.map((f) => ({ code: 'example_failed' as const, message: `${label}: ${f}` })),\n ...e.diffs.map((d) => ({\n code: 'example_failed' as const,\n node: d.node,\n message: `${label}: ${d.node} is missing ${d.missing.length} and has ${d.unexpected.length} unexpected records`,\n })),\n ]\n })\n return { ok: issues.length === 0, issues, plan: compiled.plan, examples }\n}\n\n/** Structure and params only: no types, no target schema. */\nexport function validateStructure(version: MappingVersion): CompileIssue[] {\n const issues = structuralIssues(version)\n for (const node of version.nodes) {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) continue\n const { id: _id, op: _op, label: _label, ...params } = node as NodeJson\n const parsed = def.params.safeParse(params)\n if (parsed.success) continue\n for (const x of parsed.error.issues) {\n issues.push({\n code: 'invalid_params',\n message: `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`,\n node: node.id,\n })\n }\n }\n return issues\n}\n","/**\n * Pure, immutable edits of a version's graph, for the editor. Every edit returns a new\n * version. `canConnect` is the single rule book for edges, so live feedback while dragging\n * and validation on save agree. Edges are derived from input references (`edgesOf`).\n */\n\nimport type { MappingVersion, NodeJson, Position } from './document'\nimport { downstream, nodeRefs } from './graph'\nimport { nodeCatalog, nodeRegistry, type Slot } from './nodes'\n\nexport { nodeCatalog }\n\nexport interface Edge {\n /** Stable id: `source->target:slot[index]`. */\n readonly id: string\n readonly source: string\n readonly target: string\n /** Slot id on the target node, used as the React Flow target handle. */\n readonly slot: string\n readonly index?: number\n}\n\n/** A prospective edge. */\nexport interface Connection {\n readonly source: string\n readonly target: string\n readonly slot: string\n}\n\nexport type ConnectResult = { ok: true } | { ok: false; reason: string }\n\nlet counter = 0\n\n/** A short unique id; `crypto.randomUUID` where available, a counter otherwise. */\nexport function createId(prefix: string): string {\n counter += 1\n const random = globalThis.crypto?.randomUUID?.().slice(0, 8)\n return `${prefix}_${random ?? counter.toString(36)}`\n}\n\nexport function getNode(version: MappingVersion, id: string): NodeJson | undefined {\n return version.nodes.find((n) => n.id === id)\n}\n\nconst defOf = (op: string) => (Object.hasOwn(nodeRegistry, op) ? nodeRegistry[op] : undefined)\n\nexport function edgesOf(version: MappingVersion): Edge[] {\n return version.nodes.flatMap((node) =>\n nodeRefs(node).map((r) => ({\n id: `${r.source}->${node.id}:${r.slot}${r.index === undefined ? '' : `[${r.index}]`}`,\n source: r.source,\n target: node.id,\n slot: r.slot,\n ...(r.index === undefined ? {} : { index: r.index }),\n })),\n )\n}\n\n/** Add a node of a known op with its default params. */\nexport function addNode(\n version: MappingVersion,\n op: string,\n init: { id?: string; label?: string; params?: Record<string, unknown>; position?: Position } = {},\n): { version: MappingVersion; node: NodeJson } {\n const def = defOf(op)\n if (!def) throw new Error(`Unknown node op '${op}'`)\n const id = init.id ?? createId(op)\n if (getNode(version, id)) throw new Error(`Node id '${id}' already exists`)\n const node: NodeJson = {\n ...def.defaults(),\n ...init.params,\n id,\n op,\n ...(init.label === undefined ? {} : { label: init.label }),\n }\n return {\n version: {\n ...version,\n nodes: [...version.nodes, node],\n ...(init.position ? { layout: { ...version.layout, [id]: init.position } } : {}),\n },\n node,\n }\n}\n\nfunction setPath(node: NodeJson, path: readonly string[], value: unknown): NodeJson {\n const [head, ...rest] = path as [string, ...string[]]\n if (rest.length === 0) {\n const copy: Record<string, unknown> = { ...node }\n if (value === undefined) delete copy[head]\n else copy[head] = value\n return copy as NodeJson\n }\n const child = (node as Record<string, unknown>)[head]\n const inner = typeof child === 'object' && child !== null ? child : {}\n return { ...node, [head]: setPath(inner as NodeJson, rest, value) } as NodeJson\n}\n\nfunction getPath(node: NodeJson, path: readonly string[]): unknown {\n let value: unknown = node\n for (const key of path) value = (value as Record<string, unknown> | undefined)?.[key]\n return value\n}\n\nfunction slotOf(node: NodeJson, slot: string): Slot | undefined {\n return defOf(node.op)?.slots.find((s) => s.id === slot)\n}\n\n/** Remove a node, every reference to it, and its layout entry. */\nexport function removeNode(version: MappingVersion, id: string): MappingVersion {\n const nodes = version.nodes\n .filter((n) => n.id !== id)\n .map((n) => {\n let next = n\n for (const ref of nodeRefs(n)\n .filter((r) => r.source === id)\n .reverse()) {\n next = unlink(next, ref.slot, id)\n }\n return next\n })\n const layout = version.layout ? { ...version.layout } : undefined\n if (layout) delete layout[id]\n const expect = { ...version.expect }\n delete expect[id]\n return { ...version, nodes, expect, ...(layout ? { layout } : {}) }\n}\n\n/** Drop `node`'s reference to `source` in `slotId`; anything else is left as it is. */\nfunction unlink(node: NodeJson, slotId: string, source: string): NodeJson {\n const slot = slotOf(node, slotId)\n if (!slot) return node\n const value = getPath(node, slot.path)\n if (Array.isArray(value))\n return setPath(\n node,\n slot.path,\n value.filter((v) => v !== source),\n )\n return value === source ? setPath(node, slot.path, undefined) : node\n}\n\n/**\n * Replace a node's label and/or params; `id` and `op` cannot change. A `label` key set to\n * undefined clears the label.\n */\nexport function updateNode(\n version: MappingVersion,\n id: string,\n patch: { label?: string | undefined; params?: Record<string, unknown> },\n): MappingVersion {\n return {\n ...version,\n nodes: version.nodes.map((n) => {\n if (n.id !== id) return n\n const label = 'label' in patch ? patch.label : n.label\n const params = patch.params ?? (({ id: _i, op: _o, label: _l, ...rest }) => rest)(n)\n return { ...params, id: n.id, op: n.op, ...(label === undefined ? {} : { label }) }\n }),\n }\n}\n\nexport function moveNode(version: MappingVersion, id: string, position: Position): MappingVersion {\n return { ...version, layout: { ...version.layout, [id]: position } }\n}\n\n/** Every rule a new edge must satisfy, checked against the current version. */\nexport function canConnect(version: MappingVersion, connection: Connection): ConnectResult {\n const source = getNode(version, connection.source)\n const target = getNode(version, connection.target)\n if (!source || !target) return { ok: false, reason: 'Both ends must be nodes in the graph.' }\n if (source.id === target.id) return { ok: false, reason: 'A node cannot feed itself.' }\n const from = defOf(source.op)\n if (!from || !defOf(target.op)) return { ok: false, reason: 'Unknown node op.' }\n if (!from.output) return { ok: false, reason: `${from.label} has no output.` }\n const slot = slotOf(target, connection.slot)\n if (!slot) return { ok: false, reason: `${target.op} has no input '${connection.slot}'.` }\n const refs = nodeRefs(target).filter((r) => r.slot === slot.id)\n if (refs.some((r) => r.source === source.id))\n return { ok: false, reason: 'These nodes are already connected.' }\n if (refs.length > 0 && !slot.multiple)\n return { ok: false, reason: `Input '${slot.label}' already has a connection.` }\n if (downstream(version.nodes, target.id).has(source.id)) {\n return { ok: false, reason: 'This connection would create a cycle; mappings must be acyclic.' }\n }\n return { ok: true }\n}\n\n/** Add an edge by setting the target's input reference, or throw with `canConnect`'s reason. */\nexport function connect(version: MappingVersion, connection: Connection): MappingVersion {\n const verdict = canConnect(version, connection)\n if (!verdict.ok) throw new Error(verdict.reason)\n return {\n ...version,\n nodes: version.nodes.map((n) => {\n if (n.id !== connection.target) return n\n const slot = slotOf(n, connection.slot) as Slot\n const current = getPath(n, slot.path)\n const value = slot.multiple\n ? [...(Array.isArray(current) ? current : []), connection.source]\n : connection.source\n return setPath(n, slot.path, value)\n }),\n }\n}\n\n/** Remove an edge by clearing the target's reference to its source. */\nexport function disconnect(\n version: MappingVersion,\n edge: Pick<Edge, 'source' | 'target' | 'slot'>,\n): MappingVersion {\n return {\n ...version,\n nodes: version.nodes.map((n) => (n.id === edge.target ? unlink(n, edge.slot, edge.source) : n)),\n }\n}\n","/**\n * Descriptions of source and target schemas.\n *\n * These are the nouns every other part of hockeymask speaks: connectors describe what a\n * source contains as `Table`s of `Column`s, the host application describes what it wants\n * to receive as a `TargetSchema`, and mapping graphs work between the two.\n *\n * Every type is a zod schema plus its inferred TypeScript type, so the same definition\n * validates data on the wire and types it in code.\n */\n\nimport { z } from 'zod'\n\n/** A single decoded value. Dates are ISO strings ('2026-10-04'), decimals are numbers. */\nexport const Value = z.union([z.string(), z.number(), z.boolean(), z.null()])\nexport type Value = z.infer<typeof Value>\n\n/** One record as a source returns it: column name -> decoded value. */\nexport const Row = z.record(z.string(), Value)\nexport type Row = z.infer<typeof Row>\n\n/**\n * Source-independent type of a column or field.\n *\n * Connectors translate each system's declared types into one of these. The declared type\n * is kept alongside (`Column.sourceType`), because it often carries meaning the logical\n * type loses, e.g. NetSuite declares checkboxes `boolean` but SuiteQL returns 'T' / 'F'.\n */\nexport const LogicalType = z.enum([\n 'string',\n 'integer',\n 'decimal',\n 'boolean',\n 'date',\n 'timestamp',\n 'reference',\n 'unknown',\n])\nexport type LogicalType = z.infer<typeof LogicalType>\n\nexport const Column = z.object({\n name: z.string(),\n logicalType: LogicalType,\n sourceType: z.string().describe('Type exactly as the source declares it.'),\n nullable: z.boolean().default(true),\n label: z.string().nullable().default(null).describe('Human label shown in the source UI.'),\n description: z.string().nullable().default(null),\n isCustom: z.boolean().default(false).describe('Customer-added field, e.g. custitem_*.'),\n references: z\n .string()\n .nullable()\n .default(null)\n .describe('Table this column points at, when the source declares it.'),\n})\nexport type Column = z.infer<typeof Column>\n\nexport const TableRef = z.object({\n name: z.string().describe(\"Name in the source's own notation, e.g. ANALYTICS.PLANNING.X.\"),\n label: z.string().nullable().default(null),\n description: z.string().nullable().default(null),\n rowCount: z.number().int().nullable().default(null),\n})\nexport type TableRef = z.infer<typeof TableRef>\n\nexport const Table = TableRef.extend({ columns: z.array(Column) })\nexport type Table = z.infer<typeof Table>\n\n/** A batch of rows together with the columns that describe them. */\nexport const RowSet = z.object({\n columns: z.array(Column),\n rows: z.array(Row),\n totalRows: z\n .number()\n .int()\n .nullable()\n .default(null)\n .describe('Rows the query would return without a limit, if known.'),\n})\nexport type RowSet = z.infer<typeof RowSet>\n\nexport const TargetField = z.object({\n name: z.string(),\n logicalType: LogicalType,\n nullable: z.boolean().default(true),\n description: z.string().nullable().default(null),\n unit: z.string().nullable().default(null).describe(\"Unit the target stores, e.g. 'g' or 'm'.\"),\n references: z.string().nullable().default(null).describe('Target entity of a foreign key.'),\n})\nexport type TargetField = z.infer<typeof TargetField>\n\nexport const TargetEntity = z.object({\n name: z.string(),\n description: z.string().nullable().default(null),\n identity: z\n .array(z.string())\n .default([])\n .describe('Fields a re-import uses to find the row it wrote last time.'),\n nullsNotDistinct: z\n .boolean()\n .optional()\n .describe(\n 'The identity matches NULLs as equal (NULLS NOT DISTINCT), so a nullable identity field may be part of an upsert key.',\n ),\n fields: z.array(TargetField),\n})\nexport type TargetEntity = z.infer<typeof TargetEntity>\n\nexport const TargetSchema = z.object({\n name: z.string(),\n entities: z.array(TargetEntity),\n})\nexport type TargetSchema = z.infer<typeof TargetSchema>\n\n/** Column of `table` named `name`, ignoring case (source systems differ on case). */\nexport function findColumn(table: Table, name: string): Column {\n const wanted = name.toLowerCase()\n const column = table.columns.find((c) => c.name.toLowerCase() === wanted)\n if (!column) throw new Error(`${table.name} has no column '${name}'`)\n return column\n}\n\nexport function findEntity(schema: TargetSchema, name: string): TargetEntity {\n const entity = schema.entities.find((e) => e.name === name)\n if (!entity) throw new Error(`${schema.name} has no entity '${name}'`)\n return entity\n}\n\nexport function findField(entity: TargetEntity, name: string): TargetField {\n const field = entity.fields.find((f) => f.name === name)\n if (!field) throw new Error(`${entity.name} has no field '${name}'`)\n return field\n}\n\n/** Build a Column with the defaults filled in. */\nexport function column(\n input: Pick<Column, 'name' | 'logicalType' | 'sourceType'> & Partial<Column>,\n): Column {\n return Column.parse(input)\n}\n"],"mappings":";;;AA0BA,IAAa,iBAAb,cAAoC,MAAM;CACxC,OAAgB;AAClB;;AAGA,IAAa,oBAAb,cAAuC,eAAe;CACpD,OAAgB;AAClB;;;;ACqCA,SAAgB,UAAU,QAAoB,MAAqC;CACjF,MAAM,OAAO,OAAO,OAAO,OAAO,QAAQ,IAAI,IAAI,OAAO,OAAO,QAAQ,KAAA;CACxE,OAAO,OAC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EAAE;CACpE,OAAO;AACT;AAEA,SAAgB,WAAW,QAAsB,MAA4B;CAC3E,MAAM,SAAS,OAAO,SAAS,MAAM,MAAM,EAAE,SAAS,IAAI;CAC1D,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,GAAG,OAAO,KAAK,kBAAkB,KAAK,EAAE;CACrE,OAAO;AACT;AAEA,SAAgB,UAAU,QAAsB,MAA2B;CACzE,MAAM,QAAQ,OAAO,OAAO,MAAM,MAAM,EAAE,SAAS,IAAI;CACvD,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,GAAG,OAAO,KAAK,iBAAiB,KAAK,EAAE;CACnE,OAAO;AACT;;AAGA,SAAgB,OACd,OACQ;CACR,OAAO,OAAO,MAAM,KAAK;AAC3B"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["pad","SAMPLES","params","params","params","params","scalar","params","params","params","index","params","params","params","params","params","SCALAR","params","params","params","params","truncate","params","all","truncate","params","params","params","params"],"sources":["../src/connector.ts","../src/mapping/context.ts","../src/mapping/result.ts","../src/mapping/time.ts","../src/mapping/types.ts","../src/mapping/values.ts","../src/mapping/predicate.ts","../src/mapping/expect.ts","../src/mapping/nodes/def.ts","../src/mapping/nodes/aggregate.ts","../src/mapping/ops/def.ts","../src/mapping/document.ts","../src/mapping/nodes/assert.ts","../src/mapping/nodes/distinct.ts","../src/mapping/jsonschema.ts","../src/mapping/nodes/source.ts","../src/mapping/nodes/filter.ts","../src/mapping/nodes/join.ts","../src/mapping/ops/access.ts","../src/mapping/ops/convert.ts","../src/mapping/ops/date.ts","../src/mapping/ops/fn.ts","../src/mapping/ops/list.ts","../src/mapping/ops/lookup.ts","../src/mapping/ops/nulls.ts","../src/mapping/units.ts","../src/mapping/ops/numeric.ts","../src/mapping/ops/string.ts","../src/mapping/ops/when.ts","../src/mapping/ops/index.ts","../src/mapping/sugar.ts","../src/mapping/pipeline.ts","../src/mapping/nodes/map.ts","../src/mapping/nodes/metrics.ts","../src/mapping/nodes/sink.ts","../src/mapping/nodes/transform.ts","../src/mapping/nodes/union.ts","../src/mapping/nodes/index.ts","../src/mapping/graph.ts","../src/mapping/compile.ts","../src/mapping/execute.ts","../src/mapping/examples.ts","../src/mapping/check.ts","../src/mapping/edit.ts","../src/schema.ts"],"sourcesContent":["/**\n * The contract every source connector fulfils: list tables, read column names and types,\n * sample rows, plus a full `read` and a native `query`. Concrete connectors live with the\n * host that reaches its systems (the demo's NetSuite and Snowflake clients are in apps/api);\n * the mapping engine only ever sees rows.\n *\n * Connectors decode the wire format (numbers sent as strings, dates as epoch days or in the\n * account's date format) but never interpret values: a NetSuite checkbox still arrives as\n * 'T' / 'F', a placeholder date still arrives as '9999-01-01'. Interpretation is the mapping's job.\n */\n\nimport type { Row, RowSet, Table, TableRef } from './schema'\n\nexport interface Connector {\n /** Name of the source system, e.g. \"NetSuite\"; becomes `source_system` on imported rows. */\n readonly system: string\n /** Language `query` accepts, e.g. \"suiteql\" or \"snowflake\". */\n readonly dialect: string\n listTables(): Promise<TableRef[]>\n describe(table: string): Promise<Table>\n sample(table: string, limit?: number): Promise<RowSet>\n read(table: string, options?: { batchSize?: number }): AsyncIterable<Row[]>\n query(sql: string, options?: { limit?: number }): Promise<RowSet>\n}\n\n/** The source rejected a request; the message is safe to show to the user. */\nexport class ConnectorError extends Error {\n override name = 'ConnectorError'\n}\n\n/** The source could not be reached at all (network, DNS, timeout). */\nexport class SourceUnavailable extends ConnectorError {\n override name = 'SourceUnavailable'\n}\n","/**\n * Contexts: the only channel through which a node or step learns anything not in its input.\n * They hold frozen data, never clocks, clients or handles.\n *\n * `RunContext` / `RecordContext` exist at sync time. `GraphEnv` (from the host) and\n * `RecordEnv` (built by the compiler) exist at compile time.\n */\n\nimport type { TargetSchema } from '../schema'\nimport type { Result, StepError } from './result'\nimport type { Instant } from './time'\nimport type { MType, RecordType } from './types'\nimport type { Json, Rec, Relation, Val } from './values'\n\nexport interface RunContext {\n /** Clock frozen at the start of the run. The only source of \"now\". */\n readonly now: Instant\n readonly tz: string\n readonly locale: string\n /** Every source, read once at run start and frozen, keyed by `source` node id. */\n readonly snapshot: Readonly<Record<string, Relation>>\n /** Named constants of the version. */\n readonly params: Readonly<Record<string, Json>>\n /** Static lookup tables of the version, for the `lookup` op. */\n readonly tables: Readonly<Record<string, Readonly<Record<string, Json>>>>\n readonly run: { readonly syncRunId: string; readonly mappingVersionId: string }\n}\n\nexport interface RecordContext extends RunContext {\n /** The record under mapping inside a `map` node. */\n readonly record: Rec\n}\n\n/** A reviewed, version-pinned record function for the `fn` op (escape hatch). */\nexport interface FnDef {\n /** Accepted input type; omitted means any. */\n readonly input?: MType\n readonly output: MType\n /** Whether it can return an error. Defaults to true. */\n readonly fallible?: boolean\n readonly run: (value: Val, ctx: RecordContext) => Result<Val, StepError>\n}\n\n/** A reviewed, version-pinned collection function for the `transform` node (escape hatch). */\nexport interface TransformDef {\n readonly run: (inputs: readonly Relation[], ctx: RunContext) => Result<Relation, string>\n}\n\n/** What the host supplies to compile a version. */\nexport interface GraphEnv {\n /** The internal model sinks write to; also the schema of `system: \"internal\"` sources. */\n readonly targets: TargetSchema\n readonly functions?: Readonly<Record<string, FnDef>>\n readonly transforms?: Readonly<Record<string, TransformDef>>\n}\n\n/** Compile-time view of a record scope: field pipelines, predicates. */\nexport interface RecordEnv {\n /** Type of the current record, against which `extract` and `path` are checked. */\n readonly record: RecordType\n readonly params: Readonly<Record<string, Json>>\n readonly tables: Readonly<Record<string, Readonly<Record<string, Json>>>>\n readonly functions: Readonly<Record<string, FnDef>>\n /** `each` nesting depth; capped at 1. */\n readonly depth: number\n /** Set when anything resolves against the run clock (`today`, `now`). */\n readonly clock: { used: boolean }\n}\n\n/** Type of a record field, or an error naming the missing field. */\nexport function fieldType(record: RecordType, path: string): Result<MType, string> {\n const type = Object.hasOwn(record.fields, path) ? record.fields[path] : undefined\n return type\n ? { ok: true, value: type }\n : {\n ok: false,\n error: `unknown field '${path}' (record has ${Object.keys(record.fields).join(', ') || 'no fields'})`,\n }\n}\n\nexport function recordEnv(\n record: RecordType,\n from: Partial<Omit<RecordEnv, 'record'>> = {},\n): RecordEnv {\n return {\n record,\n params: from.params ?? {},\n tables: from.tables ?? {},\n functions: from.functions ?? {},\n depth: from.depth ?? 0,\n clock: from.clock ?? { used: false },\n }\n}\n","/**\n * Failure as a value. Steps, nodes and the compiler return `Result` instead of throwing, so\n * the executor can apply each node's failure policy (arch.md,\n * \"Failure policy and partial results\").\n */\n\nexport type Result<T, E> =\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: E }\n\nexport function ok<T>(value: T): { readonly ok: true; readonly value: T } {\n return { ok: true, value }\n}\n\n/** The value of a result the caller has already checked, e.g. by `signature` before `run`. */\nexport function expectOk<T>(result: Result<T, unknown>): T {\n if (!result.ok) throw new Error(`unexpected failure: ${JSON.stringify(result.error)}`)\n return result.value\n}\n\nexport function err<E>(error: E): { readonly ok: false; readonly error: E } {\n return { ok: false, error }\n}\n\n/** What a failing record op reports. The pipeline adds the op and step, the map the node. */\nexport type ErrorCode =\n | 'type_mismatch'\n | 'parse_failed'\n | 'unknown_unit'\n | 'lookup_miss'\n | 'required_null'\n | 'domain_error'\n | 'fn_failed'\n\nexport interface StepError {\n readonly code: ErrorCode\n readonly detail: string\n}\n\n/** A runtime failure located in the graph. */\nexport interface MappingError extends StepError {\n readonly node: string\n readonly op: string\n readonly step?: number\n readonly key?: string\n}\n\nexport function stepError(code: ErrorCode, detail: string): { ok: false; error: StepError } {\n return err({ code, detail })\n}\n\n/** A problem found while checking a version, located as precisely as possible. */\nexport interface CompileIssue {\n readonly code: CompileCode\n readonly message: string\n readonly node?: string\n /** The `map` field key, aggregate field name, or expectation clause. */\n readonly field?: string\n /** Index of the step inside the field pipeline. */\n readonly step?: number\n}\n\nexport type CompileCode =\n | 'invalid_params'\n | 'unknown_op'\n | 'type_error'\n | 'duplicate_id'\n | 'dangling_ref'\n | 'missing_input'\n | 'cycle'\n | 'dead_node'\n | 'missing_schema'\n | 'duplicate_sink'\n | 'skip_tolerance'\n | 'missing_expectation'\n | 'invalid_expectation'\n | 'unknown_reference'\n | 'example_failed'\n","/**\n * Dates without a wall clock.\n *\n * The runtime value of the `date` type is an `Instant`: a frozen point in time in epoch\n * milliseconds. Calendar math (\"+10y\", \"start of day\") happens in an IANA time zone, using\n * `Intl.DateTimeFormat` to move between instants and wall-clock time. \"now\" only ever comes\n * from the run context (arch.md, \"Time\"), never from `Date.now()`.\n */\n\nimport { err, ok, type Result } from './result'\n\nexport class Instant {\n private constructor(readonly epochMs: number) {\n Object.freeze(this)\n }\n\n static ofEpochMs(epochMs: number): Instant {\n if (!Number.isFinite(epochMs)) throw new RangeError(`invalid epoch milliseconds ${epochMs}`)\n return new Instant(epochMs)\n }\n\n /** Strict ISO 8601 with an offset or `Z`, e.g. `2026-10-04T12:00:00Z`. */\n static parse(iso: string): Instant | undefined {\n if (!ISO_INSTANT.test(iso)) return undefined\n const ms = Date.parse(iso)\n return Number.isNaN(ms) ? undefined : new Instant(ms)\n }\n\n toISOString(): string {\n return new Date(this.epochMs).toISOString()\n }\n\n toJSON(): string {\n return this.toISOString()\n }\n\n toString(): string {\n return this.toISOString()\n }\n}\n\nconst ISO_INSTANT = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,3})?)?(Z|[+-]\\d{2}:\\d{2})$/\n\n// --- time zones ---------------------------------------------------------------------------\n\n/** Wall-clock fields in some time zone. Months are 1-12. */\nexport interface WallClock {\n readonly year: number\n readonly month: number\n readonly day: number\n readonly hour: number\n readonly minute: number\n readonly second: number\n readonly ms: number\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>()\n\nfunction formatter(tz: string): Intl.DateTimeFormat {\n let f = formatters.get(tz)\n if (!f) {\n f = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n })\n formatters.set(tz, f)\n }\n return f\n}\n\nexport function isTimeZone(tz: string): boolean {\n try {\n formatter(tz)\n return true\n } catch {\n return false\n }\n}\n\n/** The wall clock in `tz` at `instant`. */\nexport function toWallClock(instant: Instant, tz: string): WallClock {\n const parts: Record<string, number> = {}\n for (const p of formatter(tz).formatToParts(new Date(instant.epochMs))) {\n if (p.type !== 'literal') parts[p.type] = Number(p.value)\n }\n return {\n year: parts.year as number,\n month: parts.month as number,\n day: parts.day as number,\n hour: parts.hour as number,\n minute: parts.minute as number,\n second: parts.second as number,\n ms: ((instant.epochMs % 1000) + 1000) % 1000,\n }\n}\n\nfunction wallAsUtc(w: WallClock): number {\n // Date.UTC maps years 0-99 to 1900-1999; setUTCFullYear does not.\n const d = new Date(Date.UTC(2000, w.month - 1, w.day, w.hour, w.minute, w.second, w.ms))\n d.setUTCFullYear(w.year)\n return d.getTime()\n}\n\n/** Offset of `tz` from UTC at `epochMs`, in milliseconds. */\nfunction offsetAt(epochMs: number, tz: string): number {\n return wallAsUtc(toWallClock(Instant.ofEpochMs(epochMs), tz)) - epochMs\n}\n\n/**\n * The instant at which the wall clock in `tz` shows `w`. A wall time skipped by a DST\n * transition resolves after the gap; an ambiguous one resolves to the earlier instant.\n */\nexport function fromWallClock(w: WallClock, tz: string): Instant {\n const local = wallAsUtc(w)\n // The offsets in force a day before and a day after cover both sides of any transition.\n const before = offsetAt(local - 86_400_000, tz)\n const after = offsetAt(local + 86_400_000, tz)\n const shows = (c: number) => wallAsUtc(toWallClock(Instant.ofEpochMs(c), tz)) === local\n const candidates = [local - before, local - after].filter(shows)\n // Inside a gap neither matches: keep the earlier offset, which lands after the gap.\n return Instant.ofEpochMs(candidates.length > 0 ? Math.min(...candidates) : local - before)\n}\n\nexport function daysInMonth(year: number, month: number): number {\n if (month === 2) return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28\n return [4, 6, 9, 11].includes(month) ? 30 : 31\n}\n\n// --- calendar math --------------------------------------------------------------------------\n\nexport type DurationUnit = 'y' | 'mo' | 'w' | 'd' | 'h'\n\nexport interface Duration {\n readonly amount: number\n readonly unit: DurationUnit\n}\n\nconst DURATION_PART = /([+-])(\\d+)(y|mo|w|d|h)/gy\n\n/** `+10y`, `-30d`, `+1y-2mo`: one or more signed amounts. */\nexport function parseDuration(text: string): Result<readonly Duration[], string> {\n const parts: Duration[] = []\n DURATION_PART.lastIndex = 0\n let at = 0\n while (at < text.length) {\n DURATION_PART.lastIndex = at\n const m = DURATION_PART.exec(text)\n if (!m) return err(`invalid duration '${text}', expected e.g. '+10y' or '-30d'`)\n const [, sign, digits, unit] = m\n parts.push({ amount: Number(digits) * (sign === '-' ? -1 : 1), unit: unit as DurationUnit })\n at = DURATION_PART.lastIndex\n }\n if (parts.length === 0) return err(`invalid duration '${text}', expected e.g. '+10y' or '-30d'`)\n return ok(parts)\n}\n\n/** A duration already validated by `parseDuration` (e.g. by a params schema). */\nexport function duration(text: string): readonly Duration[] {\n const parsed = parseDuration(text)\n if (!parsed.ok) throw new Error(parsed.error)\n return parsed.value\n}\n\n/** Shift by calendar units in `tz`. Month ends clamp: Feb 29 + 1y is Feb 28. */\nexport function shift(instant: Instant, by: readonly Duration[], tz: string): Instant {\n let current = instant\n for (const { amount, unit } of by) {\n if (unit === 'h') {\n current = Instant.ofEpochMs(current.epochMs + amount * 3_600_000)\n continue\n }\n const w = toWallClock(current, tz)\n if (unit === 'y' || unit === 'mo') {\n const months = w.year * 12 + (w.month - 1) + (unit === 'y' ? amount * 12 : amount)\n const year = Math.floor(months / 12)\n const month = (months % 12) + 1\n current = fromWallClock(\n { ...w, year, month, day: Math.min(w.day, daysInMonth(year, month)) },\n tz,\n )\n } else {\n const days = unit === 'w' ? amount * 7 : amount\n const d = new Date(wallAsUtc({ ...w, hour: 0, minute: 0, second: 0, ms: 0 }))\n d.setUTCDate(d.getUTCDate() + days)\n current = fromWallClock(\n { ...w, year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() },\n tz,\n )\n }\n }\n return current\n}\n\nexport type TruncateUnit = 'day' | 'month' | 'year'\n\n/** Start of the day, month or year containing `instant`, in `tz`. */\nexport function truncate(instant: Instant, unit: TruncateUnit, tz: string): Instant {\n const w = toWallClock(instant, tz)\n return fromWallClock(\n {\n year: w.year,\n month: unit === 'year' ? 1 : w.month,\n day: unit === 'day' ? w.day : 1,\n hour: 0,\n minute: 0,\n second: 0,\n ms: 0,\n },\n tz,\n )\n}\n\n// --- date expressions -------------------------------------------------------------------------\n\n/**\n * A comparison date in a predicate: `today` or `now` plus durations (resolved against the\n * run's frozen clock), or a literal ISO date or instant.\n */\nexport type DateExpr =\n | {\n readonly kind: 'relative'\n readonly anchor: 'today' | 'now'\n readonly by: readonly Duration[]\n }\n | { readonly kind: 'date'; readonly wall: WallClock }\n | { readonly kind: 'instant'; readonly instant: Instant }\n\nconst RELATIVE = /^(today|now)(.*)$/\n\nexport function parseDateExpr(text: string): Result<DateExpr, string> {\n const rel = RELATIVE.exec(text)\n if (rel) {\n const anchor = rel[1] as 'today' | 'now'\n if (rel[2] === '') return ok({ kind: 'relative', anchor, by: [] })\n const by = parseDuration(rel[2] as string)\n return by.ok ? ok({ kind: 'relative', anchor, by: by.value }) : by\n }\n const wall = parseWithFormat(text, DATE_ONLY)\n if (wall) return ok({ kind: 'date', wall })\n const instant = Instant.parse(text)\n if (instant) return ok({ kind: 'instant', instant })\n return err(\n `invalid date '${text}', expected 'today+10y', 'now-1d', 'YYYY-MM-DD' or an ISO instant`,\n )\n}\n\n/** Whether the expression reads the run clock (fixtures must then pin `now`). */\nexport function usesClock(expr: DateExpr): boolean {\n return expr.kind === 'relative'\n}\n\nexport function resolveDateExpr(expr: DateExpr, clock: { now: Instant; tz: string }): Instant {\n switch (expr.kind) {\n case 'instant':\n return expr.instant\n case 'date':\n return fromWallClock(expr.wall, clock.tz)\n case 'relative': {\n const anchor = expr.anchor === 'today' ? truncate(clock.now, 'day', clock.tz) : clock.now\n return shift(anchor, expr.by, clock.tz)\n }\n }\n}\n\n// --- formats ------------------------------------------------------------------------------------\n\n/**\n * A date format: `iso`, `epoch_ms`, `epoch_s`, or a pattern of the tokens `YYYY MM DD HH mm ss`\n * with any other characters taken literally.\n */\nexport type DateFormat =\n | { readonly kind: 'iso' }\n | { readonly kind: 'epoch'; readonly unit: 'ms' | 's' }\n | { readonly kind: 'pattern'; readonly tokens: readonly string[]; readonly regex: RegExp }\n\nconst TOKENS = ['YYYY', 'MM', 'DD', 'HH', 'mm', 'ss'] as const\nconst TOKEN_SPLIT = /(YYYY|MM|DD|HH|mm|ss)/\n\nexport function parseDateFormat(text: string): Result<DateFormat, string> {\n if (text === 'iso') return ok({ kind: 'iso' })\n if (text === 'epoch_ms') return ok({ kind: 'epoch', unit: 'ms' })\n if (text === 'epoch_s') return ok({ kind: 'epoch', unit: 's' })\n const tokens = text.split(TOKEN_SPLIT).filter((p) => p !== '')\n const used = tokens.filter((p) => (TOKENS as readonly string[]).includes(p))\n if (used.length === 0) return err(`date format '${text}' has none of ${TOKENS.join(' ')}`)\n if (new Set(used).size !== used.length) return err(`date format '${text}' repeats a token`)\n const source = tokens\n .map((p) => {\n if (p === 'YYYY') return '(\\\\d{4})'\n if ((TOKENS as readonly string[]).includes(p)) return '(\\\\d{2})'\n return p.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n })\n .join('')\n return ok({ kind: 'pattern', tokens, regex: new RegExp(`^${source}$`) })\n}\n\n/** A format already validated by `parseDateFormat` (e.g. by a params schema). */\nexport function dateFormat(text: string): DateFormat {\n const format = parseDateFormat(text)\n if (!format.ok) throw new Error(format.error)\n return format.value\n}\n\nconst DATE_ONLY = parseDateFormat('YYYY-MM-DD')\nconst DATE_TIME = parseDateFormat('YYYY-MM-DDTHH:mm:ss')\n\n/** Whether a pattern format names a full calendar date (needed to parse, not to format). */\nexport function hasFullDate(format: DateFormat): boolean {\n return format.kind !== 'pattern' || ['YYYY', 'MM', 'DD'].every((x) => format.tokens.includes(x))\n}\n\nfunction parseWithFormat(text: string, format: Result<DateFormat, string>): WallClock | undefined {\n if (!format.ok || format.value.kind !== 'pattern') return undefined\n const m = format.value.regex.exec(text)\n if (!m) return undefined\n const fields: Record<string, number> = { YYYY: 1970, MM: 1, DD: 1, HH: 0, mm: 0, ss: 0 }\n let group = 1\n for (const token of format.value.tokens) {\n if ((TOKENS as readonly string[]).includes(token)) fields[token] = Number(m[group++])\n }\n const w: WallClock = {\n year: fields.YYYY as number,\n month: fields.MM as number,\n day: fields.DD as number,\n hour: fields.HH as number,\n minute: fields.mm as number,\n second: fields.ss as number,\n ms: 0,\n }\n const valid =\n w.month >= 1 &&\n w.month <= 12 &&\n w.day >= 1 &&\n w.day <= daysInMonth(w.year, w.month) &&\n w.hour <= 23 &&\n w.minute <= 59 &&\n w.second <= 59\n return valid ? w : undefined\n}\n\n/**\n * Parse a source value. Pattern and ISO strings without an offset are wall-clock times in\n * `tz`; epoch formats take a number or a numeric string. Undefined when it does not parse.\n */\nexport function parseDateValue(\n input: string | number,\n format: DateFormat,\n tz: string,\n): Instant | undefined {\n if (format.kind === 'epoch') {\n const n = typeof input === 'number' ? input : /^-?\\d+$/.test(input) ? Number(input) : Number.NaN\n return Number.isFinite(n) ? Instant.ofEpochMs(format.unit === 's' ? n * 1000 : n) : undefined\n }\n if (typeof input !== 'string') return undefined\n if (format.kind === 'pattern') {\n const w = parseWithFormat(input, ok(format))\n return w && fromWallClock(w, tz)\n }\n const wall = parseWithFormat(input, DATE_ONLY) ?? parseWithFormat(input, DATE_TIME)\n return wall ? fromWallClock(wall, tz) : Instant.parse(input)\n}\n\nconst pad = (n: number, width = 2) => String(n).padStart(width, '0')\n\n/** Format an instant. `iso` is UTC (`...Z`); patterns and epoch formats as named. */\nexport function formatDate(instant: Instant, format: DateFormat, tz: string): string {\n if (format.kind === 'iso') return instant.toISOString()\n if (format.kind === 'epoch') {\n return String(format.unit === 's' ? Math.floor(instant.epochMs / 1000) : instant.epochMs)\n }\n const w = toWallClock(instant, tz)\n const values: Record<string, string> = {\n YYYY: pad(w.year, 4),\n MM: pad(w.month),\n DD: pad(w.day),\n HH: pad(w.hour),\n mm: pad(w.minute),\n ss: pad(w.second),\n }\n return format.tokens.map((p) => values[p] ?? p).join('')\n}\n\n/** `YYYY-MM-DD` of the instant in `tz`, how `date` target fields are written. */\nexport function toDateString(instant: Instant, tz: string): string {\n const w = toWallClock(instant, tz)\n return `${pad(w.year, 4)}-${pad(w.month)}-${pad(w.day)}`\n}\n","/**\n * The mapping language's type algebra (arch.md, \"Type checking\").\n *\n * Nullability is part of the type, so the pipeline compiler (not each op) implements null\n * short-circuiting. `Rel` (a collection) is deliberately not an `MType`: a record field can be\n * a list, never a collection.\n *\n * Three kinds exist only for the checker: `unit` is the input of a pipeline's first step,\n * `unknown` is a value nothing is known about (top), and `never` is the bottom type, used for\n * the element of `[]` and, as `t.null = nullable(never)`, for a literal `null`.\n */\n\nimport type { LogicalType } from '../schema'\nimport { err, ok, type Result } from './result'\n\nexport type NonNull =\n | { readonly kind: 'string' }\n | { readonly kind: 'number' }\n | { readonly kind: 'boolean' }\n | { readonly kind: 'date' }\n | { readonly kind: 'list'; readonly of: MType }\n | { readonly kind: 'tuple'; readonly of: readonly MType[] }\n | { readonly kind: 'record'; readonly fields: Readonly<Record<string, MType>> }\n | { readonly kind: 'unit' }\n | { readonly kind: 'unknown' }\n | { readonly kind: 'never' }\n\nexport type NullableType = { readonly kind: 'nullable'; readonly of: NonNull }\n\nexport type MType = NonNull | NullableType\n\nexport type RecordType = Extract<NonNull, { kind: 'record' }>\nexport type ListType = Extract<NonNull, { kind: 'list' }>\nexport type TupleType = Extract<NonNull, { kind: 'tuple' }>\n\n/** Type constructors. `t.nullable` flattens, so `nullable(nullable(x))` is `nullable(x)`. */\nexport const t = {\n string: { kind: 'string' },\n number: { kind: 'number' },\n boolean: { kind: 'boolean' },\n date: { kind: 'date' },\n unit: { kind: 'unit' },\n unknown: { kind: 'unknown' },\n never: { kind: 'never' },\n null: { kind: 'nullable', of: { kind: 'never' } },\n list: (of: MType): MType => ({ kind: 'list', of }),\n tuple: (of: readonly MType[]): MType => ({ kind: 'tuple', of }),\n record: (fields: Readonly<Record<string, MType>>): RecordType => ({ kind: 'record', fields }),\n nullable: (of: MType): MType => (of.kind === 'nullable' ? of : { kind: 'nullable', of }),\n} as const satisfies Record<string, MType | ((...args: never[]) => MType)>\n\nexport function isNullable(type: MType): type is NullableType {\n return type.kind === 'nullable'\n}\n\n/** The type without its null. */\nexport function stripNull(type: MType): NonNull {\n return type.kind === 'nullable' ? type.of : type\n}\n\n/** Whether a value of this type can be null at runtime (`unknown` can be anything). */\nexport function mayBeNull(type: MType): boolean {\n return type.kind === 'nullable' || type.kind === 'unknown'\n}\n\n/** `nullable(x)` when `when` is true, else `x`. */\nexport function nullableIf(type: MType, when: boolean): MType {\n return when ? t.nullable(type) : type\n}\n\n/** Human-readable form used in every type error: `number?`, `list<string>`, `(number, string)`. */\nexport function show(type: MType): string {\n switch (type.kind) {\n case 'nullable':\n return type.of.kind === 'never' ? 'null' : `${show(type.of)}?`\n case 'list':\n return `list<${show(type.of)}>`\n case 'tuple':\n return `(${type.of.map(show).join(', ')})`\n case 'record':\n return `{ ${Object.entries(type.fields)\n .map(([k, v]) => `${k}: ${show(v)}`)\n .join(', ')} }`\n case 'unit':\n return '()'\n default:\n return type.kind\n }\n}\n\nexport function equalTypes(a: MType, b: MType): boolean {\n return show(a) === show(b)\n}\n\n/** Can a value of type `from` be used where `to` is expected? */\nexport function assignable(from: MType, to: MType): boolean {\n if (to.kind === 'unknown') return true\n if (from.kind === 'never') return true\n if (from.kind === 'nullable') {\n return to.kind === 'nullable' && assignable(from.of, to.of)\n }\n if (to.kind === 'nullable') return assignable(from, to.of)\n switch (from.kind) {\n case 'list':\n return to.kind === 'list' && assignable(from.of, to.of)\n case 'tuple':\n return (\n to.kind === 'tuple' &&\n to.of.length === from.of.length &&\n from.of.every((f, i) => assignable(f, to.of[i] as MType))\n )\n case 'record':\n return (\n to.kind === 'record' &&\n Object.entries(to.fields).every(\n ([k, v]) => k in from.fields && assignable(from.fields[k] as MType, v),\n )\n )\n default:\n return from.kind === to.kind\n }\n}\n\nconst SCALAR_KINDS = new Set(['string', 'number', 'boolean', 'date'])\n\n/** Can values of these types be compared for equality (join keys, `eq`, `in`)? */\nexport function comparable(a: MType, b: MType): boolean {\n const x = stripNull(a)\n const y = stripNull(b)\n if (x.kind === 'unknown' || y.kind === 'unknown') return true\n if (x.kind === 'never' || y.kind === 'never') return true\n if (x.kind === 'list' && y.kind === 'list') return comparable(x.of, y.of)\n return SCALAR_KINDS.has(x.kind) && x.kind === y.kind\n}\n\n/** Can values of this type be ordered (`lt`, `min`, sorting)? */\nexport function orderable(type: MType): boolean {\n const kind = stripNull(type).kind\n return kind === 'number' || kind === 'date' || kind === 'string'\n}\n\n/**\n * The common type of two branches (`when` cases, `coalesce`, `union` inputs): equal modulo\n * nullability, nullable when either side is. `never` unifies with anything.\n */\nexport function unify(a: MType, b: MType): Result<MType, string> {\n const nullable = isNullable(a) || isNullable(b)\n const x = stripNull(a)\n const y = stripNull(b)\n const base = unifyNonNull(x, y)\n if (!base.ok) return base\n return ok(nullableIf(base.value, nullable))\n}\n\nfunction unifyNonNull(x: NonNull, y: NonNull): Result<MType, string> {\n const mismatch = () => err(`${show(x)} and ${show(y)} have no common type`)\n if (x.kind === 'never') return ok(y)\n if (y.kind === 'never') return ok(x)\n if (x.kind === 'unknown' || y.kind === 'unknown') return ok(t.unknown)\n if (x.kind === 'list' && y.kind === 'list') {\n const of = unify(x.of, y.of)\n return of.ok ? ok(t.list(of.value)) : mismatch()\n }\n if (x.kind === 'tuple' && y.kind === 'tuple') {\n if (x.of.length !== y.of.length) return mismatch()\n const of: MType[] = []\n for (const [i, a] of x.of.entries()) {\n const u = unify(a, y.of[i] as MType)\n if (!u.ok) return mismatch()\n of.push(u.value)\n }\n return ok(t.tuple(of))\n }\n if (x.kind === 'record' && y.kind === 'record') {\n const keys = Object.keys(x.fields)\n if (keys.length !== Object.keys(y.fields).length) return mismatch()\n const fields: Record<string, MType> = {}\n for (const k of keys) {\n const other = y.fields[k]\n if (!other) return mismatch()\n const u = unify(x.fields[k] as MType, other)\n if (!u.ok) return mismatch()\n fields[k] = u.value\n }\n return ok(t.record(fields))\n }\n return x.kind === y.kind ? ok(x) : mismatch()\n}\n\n/** Unify a non-empty list of types, left to right. */\nexport function unifyAll(types: readonly MType[]): Result<MType, string> {\n let acc: MType = t.never\n for (const type of types) {\n const u = unify(acc, type)\n if (!u.ok) return u\n acc = u.value\n }\n return ok(acc)\n}\n\n/** Static type of a JSON literal: `null` is `t.null`, `[]` is `list<never>`. */\nexport function typeOfJson(value: unknown): MType {\n if (value === null) return t.null\n switch (typeof value) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n }\n if (Array.isArray(value)) {\n const element = unifyAll(value.map(typeOfJson))\n return t.list(element.ok ? element.value : t.unknown)\n }\n if (typeof value === 'object') {\n return t.record(\n Object.fromEntries(Object.entries(value as object).map(([k, v]) => [k, typeOfJson(v)])),\n )\n }\n return t.unknown\n}\n\n/** A connector/target logical type as an `MType`. References are opaque ids. */\nexport function fromLogicalType(logical: LogicalType): NonNull {\n switch (logical) {\n case 'string':\n return t.string\n case 'integer':\n case 'decimal':\n return t.number\n case 'boolean':\n return t.boolean\n case 'date':\n case 'timestamp':\n return t.date\n default:\n return t.unknown\n }\n}\n\n/**\n * Parse a type name as written in `assert_type`: `string`, `number`, `boolean`, `date`,\n * `list<T>`, and a trailing `?` for nullable.\n */\nexport function parseTypeName(text: string): Result<MType, string> {\n const source = text.replace(/\\s+/g, '')\n const parse = (s: string): MType | undefined => {\n if (s.endsWith('?')) {\n const inner = parse(s.slice(0, -1))\n return inner && inner.kind !== 'nullable' ? t.nullable(inner) : undefined\n }\n if (s.startsWith('list<') && s.endsWith('>')) {\n const inner = parse(s.slice(5, -1))\n return inner && t.list(inner)\n }\n switch (s) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n case 'date':\n return t.date\n default:\n return undefined\n }\n }\n const type = parse(source)\n return type ? ok(type) : err(`unknown type '${text}'`)\n}\n\n/** A type name already validated by `parseTypeName` (e.g. by a params schema). */\nexport function typeName(text: string): MType {\n const type = parseTypeName(text)\n if (!type.ok) throw new Error(type.error)\n return type.value\n}\n","/**\n * Runtime values and the relations that carry them.\n *\n * A record is a plain frozen-by-convention object; an absent key reads as null (that is how\n * `omit_if_null` and `skip_field` leave a field out of a write). Nothing here depends on\n * insertion order: hashing and sorting go through `canonicalKey` and `compareVals`, so two\n * runs over the same snapshot produce identical output (arch.md, \"Execution model\").\n */\n\nimport { Instant } from './time'\n\nexport type Val =\n | null\n | string\n | number\n | boolean\n | Instant\n | readonly Val[]\n | { readonly [key: string]: Val }\n\nexport type Rec = Readonly<Record<string, Val>>\n\n/** A collection: records of one record type, in no meaningful order. */\nexport type Relation = readonly Rec[]\n\n/** JSON as stored in a version (params, tables, literals, fixtures). */\nexport type Json =\n | null\n | string\n | number\n | boolean\n | readonly Json[]\n | { readonly [key: string]: Json }\n\n/** Returned by a step to leave its field out of the record entirely (`omit_if_null`). */\nexport const OMIT: unique symbol = Symbol('omit')\nexport type Omitted = typeof OMIT\n\nexport function isRecordVal(v: Val): v is { readonly [key: string]: Val } {\n return typeof v === 'object' && v !== null && !Array.isArray(v) && !(v instanceof Instant)\n}\n\n/** A string that is equal for equal values, used for hashing (joins, distinct, union, groups). */\nexport function canonicalKey(v: Val): string {\n if (v === null) return 'n'\n switch (typeof v) {\n case 'string':\n return `s${JSON.stringify(v)}`\n case 'number':\n return `d${Object.is(v, -0) ? 0 : v}`\n case 'boolean':\n return v ? 't' : 'f'\n }\n if (v instanceof Instant) return `i${v.epochMs}`\n if (Array.isArray(v)) return `[${(v as readonly Val[]).map(canonicalKey).join(',')}]`\n const rec = v as { readonly [key: string]: Val }\n return `{${Object.keys(rec)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonicalKey(rec[k] as Val)}`)\n .join(',')}}`\n}\n\n/** Canonical key of a tuple of fields of a record; absent fields count as null. */\nexport function keyOf(rec: Rec, fields: readonly string[]): string {\n return canonicalKey(fields.map((f) => rec[f] ?? null))\n}\n\nconst rank = (v: Val): number => {\n if (v === null) return 0\n switch (typeof v) {\n case 'boolean':\n return 1\n case 'number':\n return 2\n case 'string':\n return 3\n }\n if (v instanceof Instant) return 4\n return Array.isArray(v) ? 5 : 6\n}\n\n/**\n * A total order over values: null first, then booleans, numbers, strings (by UTF-16 code\n * unit, never locale), dates, lists (lexicographic), records (by canonical key).\n */\nexport function compareVals(a: Val, b: Val): number {\n const ra = rank(a)\n const rb = rank(b)\n if (ra !== rb) return ra - rb\n switch (ra) {\n case 0:\n return 0\n case 1:\n case 2:\n return Number(a) - Number(b)\n case 3:\n return a === b ? 0 : (a as string) < (b as string) ? -1 : 1\n case 4:\n return (a as Instant).epochMs - (b as Instant).epochMs\n case 5: {\n const x = a as readonly Val[]\n const y = b as readonly Val[]\n for (let i = 0; i < Math.min(x.length, y.length); i++) {\n const c = compareVals(x[i] as Val, y[i] as Val)\n if (c !== 0) return c\n }\n return x.length - y.length\n }\n default: {\n const x = canonicalKey(a)\n const y = canonicalKey(b)\n return x === y ? 0 : x < y ? -1 : 1\n }\n }\n}\n\nexport function valEquals(a: Val, b: Val): boolean {\n return compareVals(a, b) === 0\n}\n\n/** Values as JSON: dates become ISO strings. For fixtures, metrics and diagnostics. */\nexport function toJson(v: Val): Json {\n if (v instanceof Instant) return v.toISOString()\n if (Array.isArray(v)) return (v as readonly Val[]).map(toJson)\n if (isRecordVal(v)) return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, toJson(x)]))\n return v as Json\n}\n\n/** Sort records by the values of `fields`, ties by whole-record canonical key. */\nexport function sortRecords(rows: readonly Rec[], fields: readonly string[]): Rec[] {\n return [...rows].sort((a, b) => {\n for (const f of fields) {\n const c = compareVals(a[f] ?? null, b[f] ?? null)\n if (c !== 0) return c\n }\n const x = canonicalKey(a)\n const y = canonicalKey(b)\n return x === y ? 0 : x < y ? -1 : 1\n })\n}\n","/**\n * The one predicate vocabulary, shared by `when`, `filter_list`, the `filter` node, join\n * `where`, aggregate `where`, and `rows` expectations.\n *\n * Shape: `{ path?, <predicate>: operand }` with exactly one predicate key, or a composition\n * `{ all: { of: [...] } }`, `{ any: { of: [...] } }`, `{ not: cond }`. Without `path` the\n * predicate tests the piped value. An operand is a literal, `{ ref: field }` or\n * `{ param: name }`.\n *\n * Null never compares: ordering and equality with a null side are false, `neq` and `not_in`\n * are their negations and so hold for null (arch.md, \"Null semantics\").\n */\n\nimport { fieldType, type RecordEnv, type RunContext } from './context'\nimport { err, ok, type Result } from './result'\nimport { type DateExpr, Instant, parseDateExpr, resolveDateExpr, usesClock } from './time'\nimport { comparable, type MType, orderable, show, stripNull, t, typeOfJson } from './types'\nimport { compareVals, type Json, type Rec, type Val } from './values'\n\nexport type Test = (piped: Val, record: Rec, ctx: RunContext) => boolean\n\nconst COMPARISONS = ['eq', 'neq', 'lt', 'lte', 'gt', 'gte', 'before', 'after'] as const\nconst MEMBERSHIP = ['in', 'not_in'] as const\nconst PRESENCE = ['is_null', 'is_blank'] as const\nconst COMPOSITION = ['all', 'any', 'not'] as const\n\n/** Every predicate name; the `if_<name>` sugar is derived from the non-composite ones. */\nexport const PREDICATES = [\n ...COMPARISONS,\n ...MEMBERSHIP,\n 'matches',\n ...PRESENCE,\n ...COMPOSITION,\n] as const\nexport type PredicateName = (typeof PREDICATES)[number]\n\n/** Predicate JSON, loosely typed: validated by `compilePredicate`. */\nexport type Predicate = { readonly [key: string]: unknown }\n\nexport type Getter = (piped: Val, record: Rec, ctx: RunContext) => Val\n\nexport interface Operand {\n readonly type: MType\n readonly get: Getter\n}\n\n/**\n * Compile a predicate. `piped` is the type of the piped value, or undefined where there is\n * none (`filter`, join `where`, aggregate `where`), in which case `path` is required.\n */\nexport function compilePredicate(\n raw: unknown,\n env: RecordEnv,\n piped?: MType,\n): Result<Test, string> {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return err('a condition must be an object such as { \"eq\": 1 }')\n }\n const cond = raw as Predicate\n const keys = Object.keys(cond).filter((k) => k !== 'path')\n if (keys.length !== 1) {\n return err(\n `a condition needs exactly one predicate, got ${keys.length ? keys.join(', ') : 'none'}`,\n )\n }\n const name = keys[0] as string\n if (!(PREDICATES as readonly string[]).includes(name)) return err(`unknown predicate '${name}'`)\n const value = cond[name]\n\n if ((COMPOSITION as readonly string[]).includes(name)) {\n if ('path' in cond) return err(`'${name}' does not take a path; put paths on its conditions`)\n return compileComposition(name as (typeof COMPOSITION)[number], value, env, piped)\n }\n\n const subject = compileSubject(cond.path, env, piped)\n if (!subject.ok) return subject\n const { type, get } = subject.value\n const base = stripNull(type)\n\n switch (name) {\n case 'is_null':\n case 'is_blank': {\n if (typeof value !== 'boolean') return err(`'${name}' takes true or false`)\n if (name === 'is_blank' && base.kind !== 'string' && base.kind !== 'unknown') {\n return err(`is_blank applies to strings, not ${show(type)}`)\n }\n const blank =\n name === 'is_null'\n ? (v: Val) => v === null\n : (v: Val) => v === null || (typeof v === 'string' && v.trim() === '')\n return ok((p, r, c) => blank(get(p, r, c)) === value)\n }\n case 'matches': {\n if (typeof value !== 'string') return err('matches takes a regular expression string')\n if (base.kind !== 'string' && base.kind !== 'unknown') {\n return err(`matches applies to strings, not ${show(type)}`)\n }\n const regex = compileRegex(value)\n if (!regex.ok) return regex\n const re = regex.value\n return ok((p, r, c) => {\n const v = get(p, r, c)\n return typeof v === 'string' && re.test(v)\n })\n }\n case 'in':\n case 'not_in': {\n const operand = compileOperand(value, env, base.kind === 'date')\n if (!operand.ok) return operand\n const listType = stripNull(operand.value.type)\n if (listType.kind !== 'list')\n return err(`'${name}' takes a list, got ${show(operand.value.type)}`)\n if (!comparable(type, listType.of)) {\n return err(`cannot test ${show(type)} for membership in ${show(listType)}`)\n }\n const list = operand.value.get\n const member: Test = (p, r, c) => {\n const v = get(p, r, c)\n const values = list(p, r, c)\n if (v === null || !Array.isArray(values)) return false\n return (values as readonly Val[]).some((x) => x !== null && compareVals(v, x) === 0)\n }\n return ok(name === 'in' ? member : (p, r, c) => !member(p, r, c))\n }\n }\n\n // Comparisons.\n const isDate = name === 'before' || name === 'after'\n if (isDate && base.kind !== 'date' && base.kind !== 'unknown') {\n return err(`'${name}' applies to dates, not ${show(type)}`)\n }\n if (!isDate && name !== 'eq' && name !== 'neq' && !orderable(base) && base.kind !== 'unknown') {\n return err(`'${name}' applies to numbers, strings and dates, not ${show(type)}`)\n }\n if (value === null) return err(`'${name}' cannot compare with null; use is_null`)\n const operand = compileOperand(value, env, base.kind === 'date' || isDate)\n if (!operand.ok) return operand\n if (!comparable(type, operand.value.type)) {\n return err(`cannot compare ${show(type)} with ${show(operand.value.type)}`)\n }\n const other = operand.value.get\n const test = COMPARE[name as (typeof COMPARISONS)[number]]\n return ok((p, r, c) => {\n const a = get(p, r, c)\n const b = other(p, r, c)\n const holds = a !== null && b !== null && test(compareVals(a, b))\n return name === 'neq' ? !holds : holds\n })\n}\n\nconst COMPARE: Record<(typeof COMPARISONS)[number], (c: number) => boolean> = {\n eq: (c) => c === 0,\n neq: (c) => c === 0, // negated by the caller, so null sides make `neq` true\n lt: (c) => c < 0,\n lte: (c) => c <= 0,\n gt: (c) => c > 0,\n gte: (c) => c >= 0,\n before: (c) => c < 0,\n after: (c) => c > 0,\n}\n\nfunction compileComposition(\n name: (typeof COMPOSITION)[number],\n value: unknown,\n env: RecordEnv,\n piped: MType | undefined,\n): Result<Test, string> {\n if (name === 'not') {\n const inner = compilePredicate(value, env, piped)\n if (!inner.ok) return inner\n const test = inner.value\n return ok((p, r, c) => !test(p, r, c))\n }\n const of = (value as { of?: unknown } | null)?.of\n if (\n typeof value !== 'object' ||\n value === null ||\n Object.keys(value).length !== 1 ||\n !Array.isArray(of)\n ) {\n return err(`'${name}' takes { \"of\": [conditions] }`)\n }\n const tests: Test[] = []\n for (const [i, c] of of.entries()) {\n const compiled = compilePredicate(c, env, piped)\n if (!compiled.ok) return err(`${name}.of[${i}]: ${compiled.error}`)\n tests.push(compiled.value)\n }\n return ok(\n name === 'all'\n ? (p, r, c) => tests.every((x) => x(p, r, c))\n : (p, r, c) => tests.some((x) => x(p, r, c)),\n )\n}\n\nfunction compileSubject(\n path: unknown,\n env: RecordEnv,\n piped: MType | undefined,\n): Result<{ type: MType; get: Getter }, string> {\n if (path !== undefined) {\n if (typeof path !== 'string') return err('path must be a field name')\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n return ok({ type: type.value, get: (_p, r) => r[path] ?? null })\n }\n if (!piped || piped.kind === 'unit') {\n return err('this condition has no piped value to test; give it a \"path\"')\n }\n return ok({ type: piped, get: (p) => p })\n}\n\n/** Literal, `{ ref }` or `{ param }`. Strings compared with a date are date expressions. */\nexport function compileOperand(\n value: unknown,\n env: RecordEnv,\n asDate: boolean,\n): Result<Operand, string> {\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const keys = Object.keys(value)\n const o = value as { ref?: unknown; param?: unknown }\n if (keys.length === 1 && typeof o.ref === 'string') {\n const ref = o.ref\n const type = fieldType(env.record, ref)\n if (!type.ok) return type\n return ok({ type: type.value, get: (_p, r) => r[ref] ?? null })\n }\n if (keys.length === 1 && typeof o.param === 'string') {\n const name = o.param\n if (!Object.hasOwn(env.params, name)) return err(`unknown param '${name}'`)\n return literal(env.params[name] as Json, env, asDate)\n }\n return err('a comparison value is a literal, { \"ref\": field } or { \"param\": name }')\n }\n return literal(value as Json, env, asDate)\n}\n\nfunction literal(value: Json, env: RecordEnv, asDate: boolean): Result<Operand, string> {\n if (asDate && typeof value === 'string') {\n const expr = parseDateExpr(value)\n if (!expr.ok) return expr\n if (usesClock(expr.value)) env.clock.used = true\n return ok({ type: t.date, get: dateGetter(expr.value) })\n }\n if (asDate && Array.isArray(value) && value.every((v) => typeof v === 'string')) {\n const exprs: DateExpr[] = []\n for (const v of value as string[]) {\n const expr = parseDateExpr(v)\n if (!expr.ok) return expr\n if (usesClock(expr.value)) env.clock.used = true\n exprs.push(expr.value)\n }\n const getters = exprs.map(dateGetter)\n return ok({ type: t.list(t.date), get: (p, r, c) => getters.map((g) => g(p, r, c)) })\n }\n const constant = value as Val\n return ok({ type: typeOfJson(value), get: () => constant })\n}\n\n/** Resolve a date expression against the run clock, once per distinct clock. */\nfunction dateGetter(expr: DateExpr): Getter {\n let key = ''\n let cached: Instant = Instant.ofEpochMs(0)\n return (_p, _r, ctx) => {\n const k = `${ctx.now.epochMs}|${ctx.tz}`\n if (k !== key) {\n cached = resolveDateExpr(expr, ctx)\n key = k\n }\n return cached\n }\n}\n\nexport function compileRegex(pattern: string): Result<RegExp, string> {\n try {\n return ok(new RegExp(pattern, 'u'))\n } catch (e) {\n return err(`invalid regular expression: ${(e as Error).message}`)\n }\n}\n\n/**\n * Fields a passing record is known to have non-null: `{ path, is_null: false }` at the top\n * level or inside `all`. The `filter` node narrows its output type with these.\n */\nexport function nonNullPaths(raw: unknown): string[] {\n if (typeof raw !== 'object' || raw === null) return []\n const cond = raw as Predicate\n if (typeof cond.path === 'string' && cond.is_null === false) return [cond.path]\n const of = (cond.all as { of?: unknown } | undefined)?.of\n return Array.isArray(of) ? of.flatMap(nonNullPaths) : []\n}\n","/**\n * Node expectations and the action building blocks (arch.md, \"Failure policy and\n * partial results\"), shared by the version's `expect` block and `assert` nodes.\n *\n * Every clause is detected on the node's raw output first; then `drop_rows` removes the\n * rows it names, then `set_null` / `set_default` repair the remaining violating rows. So\n * the order clauses are written in never matters. Every breach is reported as an issue,\n * whatever its action.\n */\n\nimport type { RecordEnv, RunContext } from './context'\nimport type { Action, ActionSpec, Bound, Clause, NodeExpectation } from './document'\nimport type { NodeIssue, NodeOutput, RunIssue } from './nodes/def'\nimport { compilePredicate, type Test } from './predicate'\nimport { err, ok, type Result } from './result'\nimport {\n assignable,\n comparable,\n type MType,\n type RecordType,\n show,\n stripNull,\n t,\n typeOfJson,\n} from './types'\nimport { type Json, keyOf, type Rec, type Relation, toJson, type Val } from './values'\n\ntype ActionName = 'alert' | 'drop_rows' | 'set_null' | 'set_default' | 'skip_downstream' | 'stop'\n\nconst VALID: Readonly<Record<Clause | 'acyclic', readonly ActionName[]>> = {\n count: ['alert', 'skip_downstream', 'stop'],\n unique: ['alert', 'drop_rows', 'skip_downstream', 'stop'],\n keyed: ['alert', 'skip_downstream', 'stop'],\n rows: ['alert', 'drop_rows', 'set_null', 'set_default', 'skip_downstream', 'stop'],\n acyclic: ['alert', 'skip_downstream', 'stop'],\n}\n\nexport function actionName(action: Action): ActionName {\n if (typeof action === 'string') return action\n return 'set_null' in action ? 'set_null' : 'set_default'\n}\n\n/** Precedence: a bound's own action, then the clause's, then `default`, then the plain spec. */\nexport function resolveAction(spec: ActionSpec | undefined, clause: Clause, own?: Action): Action {\n if (own !== undefined) return own\n if (spec === undefined) return 'alert'\n if (typeof spec === 'string' || 'set_null' in spec || 'set_default' in spec) return spec as Action\n const keyed = spec as Partial<Record<Clause | 'default', Action>>\n return keyed[clause] ?? keyed.default ?? 'alert'\n}\n\n/** Check an action fits its check and the output type; returns the repaired output type. */\nexport function checkAction(\n action: Action,\n check: Clause | 'acyclic',\n output: NodeOutput,\n): Result<NodeOutput, string> {\n const name = actionName(action)\n if (!VALID[check].includes(name)) return err(`action ${name} does not apply to ${check}`)\n if (typeof action === 'string') return ok(output)\n const fields = 'set_null' in action ? action.set_null : Object.keys(action.set_default)\n const unknown = fields.filter((f) => !Object.hasOwn(output.type.fields, f))\n if (unknown.length) return err(`${name} names unknown fields: ${unknown.join(', ')}`)\n if ('set_default' in action) {\n for (const [f, v] of Object.entries(action.set_default)) {\n const type = output.type.fields[f] as MType\n if (v === null || !assignable(typeOfJson(v), stripNull(type))) {\n return err(`set_default ${f}: ${JSON.stringify(v)} is not a ${show(stripNull(type))}`)\n }\n }\n return ok(output)\n }\n // set_null widens the repaired fields, so every consumer is checked against nulls there.\n const widened = { ...output.type.fields }\n for (const f of action.set_null) widened[f] = t.nullable(widened[f] as MType)\n return ok({ ...output, type: t.record(widened) })\n}\n\nexport interface Violation {\n readonly clause: string\n readonly action: Action\n readonly message: string\n readonly count: number\n readonly samples: readonly Json[]\n /** Positions of the violating rows, for row actions. */\n readonly rows?: readonly number[]\n}\n\nexport interface Outcome {\n readonly rows: Relation\n readonly changed: number\n readonly issues: readonly RunIssue[]\n readonly stop: boolean\n readonly skipDownstream: boolean\n}\n\n/** Apply the actions of the detected violations to `rows`, reporting each as an issue. */\nexport function applyViolations(\n node: string,\n code: string,\n rows: Relation,\n violations: readonly Violation[],\n): Outcome {\n const dropped = new Set<number>()\n for (const v of violations) {\n if (actionName(v.action) === 'drop_rows') for (const i of v.rows ?? []) dropped.add(i)\n }\n const patches = new Map<number, Record<string, Val>>()\n for (const v of violations) {\n if (typeof v.action === 'string') continue\n const patch: Record<string, Val> =\n 'set_null' in v.action\n ? Object.fromEntries(v.action.set_null.map((f) => [f, null]))\n : (v.action.set_default as Record<string, Val>)\n for (const i of v.rows ?? []) {\n if (!dropped.has(i)) patches.set(i, { ...patches.get(i), ...patch })\n }\n }\n const out: Rec[] = []\n for (const [i, row] of rows.entries()) {\n if (dropped.has(i)) continue\n const patch = patches.get(i)\n out.push(patch ? { ...row, ...patch } : row)\n }\n const affected = (v: Violation) =>\n actionName(v.action) === 'drop_rows'\n ? (v.rows ?? []).length\n : typeof v.action === 'string'\n ? undefined\n : (v.rows ?? []).filter((i) => !dropped.has(i)).length\n return {\n rows: out,\n changed: dropped.size + patches.size,\n stop: violations.some((v) => v.action === 'stop'),\n skipDownstream: violations.some((v) => v.action === 'skip_downstream'),\n issues: violations.map((v) => ({\n node,\n code,\n clause: v.clause,\n action: v.action,\n message: v.message,\n count: v.count,\n samples: v.samples,\n ...(affected(v) === undefined ? {} : { rowsAffected: affected(v) }),\n })),\n }\n}\n\nconst SAMPLES = 5\n\nexport function countViolation(\n count: number,\n bound: Bound & { readonly shiftRatio?: Bound },\n action: Action,\n baseline: number | undefined,\n): Violation | undefined {\n const problems: string[] = []\n if (bound.min !== undefined && count < bound.min)\n problems.push(`count ${count} below ${bound.min}`)\n if (bound.max !== undefined && count > bound.max)\n problems.push(`count ${count} above ${bound.max}`)\n const shift = bound.shiftRatio\n if (shift && baseline !== undefined && baseline > 0) {\n const ratio = count / baseline\n if (\n (shift.min !== undefined && ratio < shift.min) ||\n (shift.max !== undefined && ratio > shift.max)\n ) {\n problems.push(`count ${count} is ${ratio.toFixed(2)}x the baseline ${baseline}`)\n }\n }\n return problems.length\n ? { clause: 'count', action, message: problems.join('; '), count: 1, samples: [count] }\n : undefined\n}\n\nexport function uniqueViolation(\n rows: Relation,\n keys: readonly string[],\n action: Action,\n): Violation | undefined {\n const groups = new Map<string, number[]>()\n for (const [i, row] of rows.entries()) {\n const k = keyOf(row, keys)\n const g = groups.get(k)\n if (g) g.push(i)\n else groups.set(k, [i])\n }\n const duplicates = [...groups.values()].filter((g) => g.length > 1)\n if (duplicates.length === 0) return undefined\n return {\n clause: 'unique',\n action,\n message: `${keys.join(', ')} not unique: ${duplicates.length} duplicated keys`,\n count: duplicates.length,\n samples: duplicates\n .slice(0, SAMPLES)\n .map((g) => keys.map((k) => toJson((rows[g[0] as number] as Rec)[k] ?? null))),\n rows: duplicates.flat(),\n }\n}\n\nexport function rowsViolation(\n rows: Relation,\n test: Test,\n ctx: RunContext,\n action: Action,\n): Violation | undefined {\n const bad: number[] = []\n for (const [i, row] of rows.entries()) if (!test(null, row, ctx)) bad.push(i)\n if (bad.length === 0) return undefined\n return {\n clause: 'rows',\n action,\n message: `${bad.length} rows fail the row condition`,\n count: bad.length,\n samples: bad.slice(0, SAMPLES).map((i) => toJson(rows[i] as Rec)),\n rows: bad,\n }\n}\n\ntype Keyed = NonNullable<NodeExpectation['keyed']>\n\n/** A key with no row counts as 0, so it fails a positive `min` and passes any `max`. */\nexport function keyedViolations(\n rows: Relation,\n keyed: Keyed,\n spec: ActionSpec | undefined,\n): Violation[] {\n const values = new Map<string, Val>()\n for (const row of rows) {\n const by = row[keyed.by] ?? null\n const k = typeof by === 'string' ? by : JSON.stringify(toJson(by))\n if (!values.has(k)) values.set(k, row[keyed.value] ?? null)\n }\n const out: Violation[] = []\n for (const [key, bound] of Object.entries(keyed.bounds)) {\n const raw = values.get(key)\n const value = typeof raw === 'number' ? raw : 0\n const low = bound.min !== undefined && value < bound.min\n const high = bound.max !== undefined && value > bound.max\n if (low || high) {\n out.push({\n clause: 'keyed',\n action: resolveAction(spec, 'keyed', bound.onFail),\n message: `${keyed.by} ${key}: ${keyed.value} ${value} ${low ? `below ${bound.min}` : `above ${bound.max}`}`,\n count: 1,\n samples: [key],\n })\n }\n }\n return out\n}\n\nexport interface CheckOptions {\n /** Previous count of this node, for `count.shiftRatio`. */\n readonly baseline?: number\n /** Fixtures run at sample scale, so production `count` envelopes are skipped. */\n readonly skipCount?: boolean\n}\n\nexport type Checker = (rows: Relation, ctx: RunContext, options: CheckOptions) => Outcome\n\n/** Compile a node's `expect` entry against its output; returns the repaired output type. */\nexport function compileExpectation(\n node: string,\n exp: NodeExpectation,\n output: NodeOutput,\n renv: (record: RecordType) => RecordEnv,\n): Result<{ output: NodeOutput; check: Checker }, readonly NodeIssue[]> {\n const issues: NodeIssue[] = []\n const issue = (field: Clause, message: string) =>\n issues.push({ message, field, code: 'invalid_expectation' })\n let repaired = output\n const fields = output.type.fields\n const missing = (names: readonly string[]) => names.filter((f) => !Object.hasOwn(fields, f))\n\n for (const clause of ['count', 'unique', 'keyed', 'rows'] as const) {\n if (exp[clause] === undefined) continue\n const action = resolveAction(exp.onFail, clause)\n const checked = checkAction(action, clause, repaired)\n if (checked.ok) repaired = checked.value\n else issue(clause, checked.error)\n }\n if (exp.unique && missing(exp.unique).length) {\n issue('unique', `unknown fields: ${missing(exp.unique).join(', ')}`)\n }\n if (exp.keyed) {\n const keyed = exp.keyed\n if (missing([keyed.by, keyed.value]).length) {\n issue('keyed', `unknown fields: ${missing([keyed.by, keyed.value]).join(', ')}`)\n } else if (!comparable(fields[keyed.value] as MType, t.number)) {\n issue('keyed', `${keyed.value} must be a number`)\n }\n for (const bound of Object.values(keyed.bounds)) {\n if (bound.onFail === undefined) continue\n const checked = checkAction(bound.onFail, 'keyed', repaired)\n if (!checked.ok) issue('keyed', checked.error)\n }\n }\n let test: Test | undefined\n if (exp.rows) {\n const compiled = compilePredicate(exp.rows.cond, renv(output.type))\n if (compiled.ok) test = compiled.value\n else issue('rows', compiled.error)\n }\n if (issues.length) return { ok: false, error: issues }\n\n const check: Checker = (rows, ctx, options) => {\n const violations: Violation[] = []\n const push = (v: Violation | undefined) => v && violations.push(v)\n if (exp.count && !options.skipCount) {\n push(\n countViolation(\n rows.length,\n exp.count,\n resolveAction(exp.onFail, 'count'),\n options.baseline,\n ),\n )\n }\n if (exp.unique) push(uniqueViolation(rows, exp.unique, resolveAction(exp.onFail, 'unique')))\n if (exp.keyed) violations.push(...keyedViolations(rows, exp.keyed, exp.onFail))\n if (test) push(rowsViolation(rows, test, ctx, resolveAction(exp.onFail, 'rows')))\n return applyViolations(node, 'expectation', rows, violations)\n }\n return ok({ output: repaired, check })\n}\n","/**\n * Collection node definitions.\n *\n * A node definition compiles itself: from its params and the types of its inputs it returns\n * its output type and a closure, in one step, so type checking and compilation stay the same\n * pass. Nodes reference their inputs by id; `slots` say which params hold those ids, which is\n * all the graph utilities and the editor need to know about edges.\n */\n\nimport { z } from 'zod'\nimport type { GraphEnv, RecordEnv, RunContext } from '../context'\nimport type { Action, JsonSchema, MappingVersion, NodeExpectation } from '../document'\nimport type { CompileCode, Result } from '../result'\nimport type { MType, RecordType } from '../types'\nimport type { Json, Relation } from '../values'\n\n/** Where a field's value was produced, so a sink can blame the right `map` field. */\nexport interface Origin {\n readonly node: string\n readonly field: string\n /** The field may be absent from a record (`omit_if_null`, `on_error: skip_field`). */\n readonly omittable: boolean\n /** Type of the value when present; set exactly for omittable fields. */\n readonly present?: MType\n}\n\n/**\n * Compile-time output of a node: its record type plus per-field provenance. Invariants: every\n * field has an origin, and an omittable field is typed nullable (an absent field reads null).\n */\nexport interface NodeOutput {\n readonly type: RecordType\n readonly origins: Readonly<Record<string, Origin>>\n /** Can drop records on a failed field. */\n readonly canSkip?: boolean\n}\n\n/** An input slot: the param path that holds an upstream node id. */\nexport interface Slot {\n readonly id: string\n readonly label: string\n readonly path: readonly string[]\n /** Holds a list of ids (`union.inputs`). */\n readonly multiple?: boolean\n readonly optional?: boolean\n}\n\nexport type NodeCategory = 'source' | 'transform' | 'target' | 'check'\n\n/** What a node definition sees while compiling. */\nexport interface NodeEnv {\n readonly id: string\n readonly graph: GraphEnv\n readonly version: Pick<\n MappingVersion,\n 'params' | 'tables' | 'expectedSchema' | 'onError' | 'expect'\n >\n /** This node's entry in the version's `expect` block. */\n readonly expect?: NodeExpectation\n readonly clock: { used: boolean }\n /** Output of an upstream node; the compiler only calls `compile` once all inputs exist. */\n input(id: string): NodeOutput\n recordEnv(record: RecordType): RecordEnv\n}\n\nexport interface NodeIssue {\n readonly message: string\n readonly code?: CompileCode\n /** Blame another node, e.g. the `map` that produced a field a sink rejects. */\n readonly node?: string\n readonly field?: string\n readonly step?: number\n}\n\n/** A problem found while running, reported on the run rather than failing it. */\nexport interface RunIssue {\n readonly node: string\n readonly code: string\n readonly message: string\n readonly field?: string\n readonly clause?: string\n readonly action?: Action\n readonly count?: number\n readonly rowsAffected?: number\n readonly samples?: readonly Json[]\n}\n\nexport interface SinkWrite {\n readonly sink: string\n readonly target: string\n /** Target paths of the upsert key. */\n readonly key: readonly string[]\n /** Rows by target path, sorted by key. Dates are `YYYY-MM-DD`, timestamps ISO. */\n readonly rows: readonly Readonly<Record<string, Json>>[]\n readonly write?: Readonly<Record<string, WritePolicy>>\n /**\n * Reference fields written as natural keys, by target path. The host resolves each value\n * (one field of `by`, or a list in `by` order) to the id of the `entity` row it names.\n */\n readonly refs?: Readonly<Record<string, SinkRef>>\n /**\n * The rows are the complete set of the target for the company (and source system, where\n * the identity has one): the host calls `synchronize_all(rows, scope)`, deleting rows not\n * written. Writes of one run go in one transaction, inserts parent-first and deletes\n * child-first (join-table rows before the entities they reference). A sink that does not write\n * (held, stopped, failed) deletes nothing.\n */\n readonly mode?: 'replace'\n}\n\nexport type WritePolicy = 'overwrite' | 'fill_if_null' | 'never'\n\nexport interface SinkRef {\n readonly entity: string\n readonly by: readonly string[]\n}\n\nexport interface Metric {\n readonly node: string\n readonly name: string\n readonly rows: readonly Readonly<Record<string, Json>>[]\n}\n\nexport interface NodeRun {\n readonly rows: Relation\n /** Records a `map` dropped under `skip_record`. */\n readonly skipped?: number\n /** Rows dropped or repaired by an action. */\n readonly changed?: number\n readonly issues?: readonly RunIssue[]\n readonly stop?: boolean\n readonly skipDownstream?: boolean\n readonly write?: SinkWrite\n readonly metric?: Metric\n}\n\nexport interface NodeFailure {\n readonly code: string\n readonly message: string\n /** Halts the run (`on_error: fail_sync`). */\n readonly stop?: boolean\n readonly issues?: readonly RunIssue[]\n readonly samples?: readonly Json[]\n}\n\nexport type Inputs = (id: string) => Relation\n\nexport interface RunOptions {\n /** Previous output count of this node, for `count.shiftRatio`. */\n readonly baseline?: number\n /** Fixture runs are sample-sized, so production `count` envelopes are skipped. */\n readonly skipCount?: boolean\n}\n\nexport interface CompiledNode {\n /** Null for a node without an output relation (`sink`); `metrics` types what it reports. */\n readonly output: NodeOutput | null\n /** Target entities a sink writes (one sink per entity, structural rule 4). */\n readonly writes?: readonly string[]\n readonly run: (\n inputs: Inputs,\n ctx: RunContext,\n options?: RunOptions,\n ) => Result<NodeRun, NodeFailure>\n}\n\nexport interface NodeDef<P = unknown> {\n readonly op: string\n readonly label: string\n readonly category: NodeCategory\n readonly description: string\n readonly slots: readonly Slot[]\n /** Has an output edge. */\n readonly output: boolean\n /** Has an effect: a write, a metric, or a check. Every node must reach one. */\n readonly effect?: 'sink' | 'metrics' | 'check'\n /** Params a new node starts with in the editor. */\n readonly defaults: () => Record<string, unknown>\n /** Parses the node object without `id`, `op` and `label`. */\n readonly params: z.ZodType<P>\n /** Accepts `tolerate_skips` (arch.md, \"Failure policy and partial results\"). */\n readonly toleratesSkips?: (params: P) => boolean\n readonly compile: (params: P, env: NodeEnv) => Result<CompiledNode, readonly NodeIssue[]>\n}\n\nexport function defineNode<P>(def: NodeDef<P>): NodeDef<P> {\n return def\n}\n\nexport const nodeId = z.string().min(1)\n\n/** Origins for fields a node produces itself. */\nexport function ownOrigins(node: string, type: RecordType): Record<string, Origin> {\n return Object.fromEntries(\n Object.keys(type.fields).map((field) => [field, { node, field, omittable: false }]),\n )\n}\n\n/** Shorthand for a single issue result. */\nexport function fail(message: string, extra: Omit<NodeIssue, 'message'> = {}) {\n return { ok: false as const, error: [{ message, ...extra }] as readonly NodeIssue[] }\n}\n\nexport type { JsonSchema }\n","/**\n * `aggregate`: one record per group of `group_by` (one record overall for `group_by: []`,\n * even on empty input). Every aggregation takes an optional `where`, making it a filtered\n * aggregate. Results never depend on input order: `sum` adds in sorted order, `collect_set`\n * is sorted, and `collect_list`, `first`, `last` require `order_by`.\n */\n\nimport { z } from 'zod'\nimport type { RunContext } from '../context'\nimport { compilePredicate, type Test } from '../predicate'\nimport { ok } from '../result'\nimport { type MType, orderable, type RecordType, show, stripNull, t } from '../types'\nimport {\n canonicalKey,\n compareVals,\n keyOf,\n type Rec,\n type Relation,\n sortRecords,\n type Val,\n} from '../values'\nimport { defineNode, type NodeEnv, nodeId, type NodeIssue, type Origin, ownOrigins } from './def'\n\nconst orderBy = z\n .array(\n z.union([\n z.string().min(1),\n z.strictObject({ path: z.string().min(1), desc: z.boolean().optional() }),\n ]),\n )\n .min(1)\n\nconst agg = z.strictObject({\n agg: z.enum([\n 'count',\n 'count_distinct',\n 'sum',\n 'min',\n 'max',\n 'collect_set',\n 'collect_list',\n 'first',\n 'last',\n 'any',\n 'all',\n ]),\n path: z.string().min(1).optional(),\n where: z.unknown().optional(),\n order_by: orderBy.optional(),\n cond: z.unknown().optional(),\n})\ntype Agg = z.infer<typeof agg>\n\nconst params = z.strictObject({\n in: nodeId,\n group_by: z.array(z.string().min(1)),\n fields: z\n .record(z.string().min(1), agg)\n .refine((f) => Object.keys(f).length > 0, 'needs at least one field'),\n tolerate_skips: z.boolean().optional(),\n})\n\nconst NEEDS_PATH = new Set([\n 'count_distinct',\n 'sum',\n 'min',\n 'max',\n 'collect_set',\n 'collect_list',\n 'first',\n 'last',\n])\nconst NEEDS_ORDER = new Set(['collect_list', 'first', 'last'])\nconst NEEDS_COND = new Set(['any', 'all'])\n\ntype Compute = (rows: Relation, ctx: RunContext) => Val\n\nfunction compileAgg(\n name: string,\n spec: Agg,\n input: RecordType,\n env: NodeEnv,\n): { type: MType; compute: Compute } | NodeIssue {\n const issue = (message: string): NodeIssue => ({ message, field: name })\n const renv = env.recordEnv(input)\n if (NEEDS_PATH.has(spec.agg) !== (spec.path !== undefined)) {\n return issue(\n NEEDS_PATH.has(spec.agg) ? `${spec.agg} needs a path` : `${spec.agg} takes no path`,\n )\n }\n if (NEEDS_ORDER.has(spec.agg) !== (spec.order_by !== undefined)) {\n return issue(\n NEEDS_ORDER.has(spec.agg) ? `${spec.agg} needs order_by` : `${spec.agg} takes no order_by`,\n )\n }\n if (NEEDS_COND.has(spec.agg) !== (spec.cond !== undefined)) {\n return issue(\n NEEDS_COND.has(spec.agg) ? `${spec.agg} needs a cond` : `${spec.agg} takes no cond`,\n )\n }\n const path = spec.path\n const fieldType = path === undefined ? undefined : input.fields[path]\n if (path !== undefined && !fieldType) return issue(`unknown field '${path}'`)\n const order = (spec.order_by ?? []).map((o) =>\n typeof o === 'string' ? { path: o, desc: false } : { desc: false, ...o },\n )\n const unknownOrder = order.filter((o) => !Object.hasOwn(input.fields, o.path))\n if (unknownOrder.length)\n return issue(`order_by: unknown field '${(unknownOrder[0] as { path: string }).path}'`)\n\n let where: Test | undefined\n if (spec.where !== undefined) {\n const w = compilePredicate(spec.where, renv)\n if (!w.ok) return issue(`where: ${w.error}`)\n where = w.value\n }\n let cond: Test | undefined\n if (spec.cond !== undefined) {\n const c = compilePredicate(spec.cond, renv)\n if (!c.ok) return issue(`cond: ${c.error}`)\n cond = c.value\n }\n\n const values = (rows: Relation) => rows.map((r) => r[path as string] ?? null)\n const nonNull = (rows: Relation) => values(rows).filter((v) => v !== null)\n const sorted = (rows: Relation) =>\n [...rows].sort((a, b) => {\n for (const o of order) {\n const c = compareVals(a[o.path] ?? null, b[o.path] ?? null)\n if (c !== 0) return o.desc ? -c : c\n }\n return compareVals(canonicalKey(a), canonicalKey(b))\n })\n const base = fieldType ? stripNull(fieldType) : t.unknown\n\n let type: MType\n let compute: Compute\n switch (spec.agg) {\n case 'count':\n type = t.number\n compute = (rows) => rows.length\n break\n case 'count_distinct':\n type = t.number\n compute = (rows) => new Set(nonNull(rows).map(canonicalKey)).size\n break\n case 'sum':\n if (base.kind !== 'number')\n return issue(`sum needs a number field, ${path} is ${show(fieldType as MType)}`)\n type = t.nullable(t.number)\n compute = (rows) => {\n const xs = (nonNull(rows) as number[]).sort((a, b) => a - b)\n return xs.length === 0 ? null : xs.reduce((a, b) => a + b, 0)\n }\n break\n case 'min':\n case 'max': {\n if (!orderable(base))\n return issue(\n `${spec.agg} needs a number, string or date field, ${path} is ${show(fieldType as MType)}`,\n )\n type = t.nullable(base)\n const sign = spec.agg === 'min' ? 1 : -1\n compute = (rows) => nonNull(rows).sort((a, b) => sign * compareVals(a, b))[0] ?? null\n break\n }\n case 'collect_set':\n type = t.list(base)\n compute = (rows) => {\n const seen = new Map<string, Val>()\n for (const v of nonNull(rows)) seen.set(canonicalKey(v), v)\n return [...seen.values()].sort(compareVals)\n }\n break\n case 'collect_list':\n type = t.list(fieldType as MType)\n compute = (rows) => sorted(rows).map((r) => r[path as string] ?? null)\n break\n case 'first':\n case 'last': {\n type = t.nullable(fieldType as MType)\n const pick = spec.agg === 'first' ? 0 : -1\n compute = (rows) => sorted(rows).at(pick)?.[path as string] ?? null\n break\n }\n default: {\n type = t.boolean\n const test = cond as Test\n compute =\n spec.agg === 'any'\n ? (rows, ctx) => rows.some((r) => test(null, r, ctx))\n : (rows, ctx) => rows.every((r) => test(null, r, ctx))\n }\n }\n if (where) {\n const w = where\n const inner = compute\n compute = (rows, ctx) =>\n inner(\n rows.filter((r) => w(null, r, ctx)),\n ctx,\n )\n }\n return { type, compute }\n}\n\nexport const aggregateNode = defineNode({\n op: 'aggregate',\n label: 'Aggregate',\n category: 'transform',\n description: 'One record per group, with counts, sums, sets and other aggregates.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', group_by: [], fields: {} }),\n params,\n toleratesSkips: (p) => p.tolerate_skips === true,\n compile: (p, env) => {\n const input = env.input(p.in)\n const issues: NodeIssue[] = []\n const fields: Record<string, MType> = {}\n for (const g of p.group_by) {\n const type = input.type.fields[g]\n if (type) fields[g] = type\n else issues.push({ message: `group_by: unknown field '${g}'` })\n }\n const aggs: { name: string; compute: Compute }[] = []\n for (const [name, spec] of Object.entries(p.fields)) {\n if (p.group_by.includes(name)) {\n issues.push({ message: `'${name}' is both a group key and an aggregate`, field: name })\n continue\n }\n const compiled = compileAgg(name, spec, input.type, env)\n if ('message' in compiled) issues.push(compiled)\n else {\n fields[name] = compiled.type\n aggs.push({ name, compute: compiled.compute })\n }\n }\n if (issues.length) return { ok: false, error: issues }\n\n const type = t.record(fields)\n return ok({\n output: {\n type,\n origins: {\n ...ownOrigins(env.id, type),\n ...Object.fromEntries(p.group_by.map((g) => [g, input.origins[g] as Origin])),\n },\n },\n run: (inputs, ctx) => {\n const groups = new Map<string, Rec[]>()\n // `group_by: []` yields one record even for empty input.\n if (p.group_by.length === 0) groups.set(keyOf({}, []), [])\n for (const row of inputs(p.in)) {\n const k = keyOf(row, p.group_by)\n const g = groups.get(k)\n if (g) g.push(row)\n else groups.set(k, [row])\n }\n const rows: Rec[] = []\n for (const members of groups.values()) {\n const out: Record<string, Val> = {}\n const sample = members[0]\n for (const g of p.group_by) out[g] = (sample as Rec)[g] ?? null\n for (const a of aggs) out[a.name] = a.compute(members, ctx)\n rows.push(out)\n }\n return ok({ rows: sortRecords(rows, p.group_by) })\n },\n })\n },\n})\n","/**\n * Record op definitions.\n *\n * An op is a params schema, a type function and a curried implementation. `signature` is\n * the validator's half; `run` binds params once per compiled version and returns the\n * per-record step. With `nulls: 'propagate'` the pipeline compiler handles a null input, so\n * `run` never sees null and `signature` never sees a nullable type.\n */\n\nimport { z } from 'zod'\nimport type { RecordContext, RecordEnv } from '../context'\nimport { err, ok, type Result, type StepError } from '../result'\nimport type { MType } from '../types'\nimport type { Omitted, Val } from '../values'\n\nexport type StepResult = Result<Val | Omitted, StepError>\n\nexport type Step = (input: Val, ctx: RecordContext) => StepResult\n\nexport interface OpDef<P = unknown> {\n readonly name: string\n /** Parses the step object without its `op` key. Unknown keys are rejected. */\n readonly params: z.ZodType<P>\n /** Who handles a null input: the compiler ('propagate') or this op ('consume'). */\n readonly nulls: 'propagate' | 'consume'\n /**\n * What the op reads: 'value' (default) needs a piped value; 'none' starts a pipeline and\n * takes no piped input; 'any' accepts either (`when`).\n */\n readonly input?: 'value' | 'none' | 'any'\n /** Must be the last step (`omit_if_null`). */\n readonly terminal?: boolean\n /** Whether this op can return an error at runtime, given its params. */\n readonly fallible: (params: P, env: RecordEnv, input: MType) => boolean\n /** Output type for an input type; an error message when the input is not accepted. */\n readonly signature: (input: MType, params: P, env: RecordEnv) => Result<MType, string>\n /** Bind params once; `input` is the (null-stripped) input type `signature` accepted. */\n readonly run: (params: P, env: RecordEnv, input: MType) => Step\n}\n\n/** Identity function that keeps `P` inferred from the params schema. */\nexport function defineOp<P>(def: OpDef<P>): OpDef<P> {\n return def\n}\n\nexport const never = () => false\nexport const always = () => true\n\n/** Expect an exact non-null kind. */\nexport function expectKind(\n input: MType,\n kinds: readonly MType['kind'][],\n op: string,\n): Result<MType, string> {\n return kinds.includes(input.kind)\n ? ok(input)\n : err(`${op} expects ${kinds.join(' or ')}, got ${showKind(input)}`)\n}\n\nfunction showKind(input: MType): string {\n return input.kind === 'nullable'\n ? `${input.of.kind}?`\n : input.kind === 'unit'\n ? 'no input'\n : input.kind\n}\n\n/** JSON literal accepted in params. */\nexport const json: z.ZodType<import('../values').Json> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(json),\n z.record(z.string(), json),\n ]),\n)\n\n/** Strict object schema, so a typo'd param is an error rather than ignored. */\nexport const params = <S extends z.ZodRawShape>(shape: S) => z.strictObject(shape)\n","/**\n * The mapping document (arch.md, \"The mapping document\"): one version of a mapping, stored as\n * JSON. It carries the graph (`nodes`), the assumptions about each source (`expectedSchema`,\n * which is also the type environment), expectations about what nodes produce (`expect`),\n * named constants (`params`), lookup tables (`tables`) and fixtures (`examples`).\n *\n * Nodes are flat objects, `{ id, op, ...params }`, and reference their inputs by id; there is\n * no edge list. Node params are validated by the node's definition when the version compiles,\n * so a draft with a half-edited node still parses. `layout` is editor state only.\n */\n\nimport { z } from 'zod'\nimport { json } from './ops/def'\n\nexport const OnError = z.enum(['null', 'skip_field', 'skip_record', 'fail_sync'])\nexport type OnError = z.infer<typeof OnError>\n\nexport const Action = z.union([\n z.enum(['alert', 'drop_rows', 'skip_downstream', 'stop']),\n z.strictObject({ set_null: z.array(z.string().min(1)).min(1) }),\n z.strictObject({ set_default: z.record(z.string(), json) }),\n])\nexport type Action = z.infer<typeof Action>\n\nexport const CLAUSES = ['count', 'unique', 'keyed', 'rows'] as const\nexport type Clause = (typeof CLAUSES)[number]\n\n/** One action for every clause, or one per clause with a fallback. */\nexport const ActionSpec = z.union([\n Action,\n z.strictObject({\n default: Action.optional(),\n count: Action.optional(),\n unique: Action.optional(),\n keyed: Action.optional(),\n rows: Action.optional(),\n }),\n])\nexport type ActionSpec = z.infer<typeof ActionSpec>\n\nexport const Bound = z.strictObject({ min: z.number().optional(), max: z.number().optional() })\nexport type Bound = z.infer<typeof Bound>\n\nexport const NodeExpectation = z.strictObject({\n /** Absolute bounds, and drift relative to a baseline the host passes per run. */\n count: Bound.extend({ shiftRatio: Bound.optional() }).optional(),\n /** Fields whose combination must be unique in the node's output. */\n unique: z.array(z.string().min(1)).min(1).optional(),\n /** Bounds on individual rows of a small keyed relation, typically counters. */\n keyed: z\n .strictObject({\n by: z.string().min(1),\n value: z.string().min(1),\n bounds: z.record(z.string(), Bound.extend({ onFail: Action.optional() })),\n })\n .optional(),\n /** A predicate every row must satisfy. */\n rows: z.strictObject({ cond: z.unknown() }).optional(),\n onFail: ActionSpec.optional(),\n note: z.string().optional(),\n})\nexport type NodeExpectation = z.infer<typeof NodeExpectation>\n\nconst Rows = z.array(z.record(z.string(), json))\n\n/** A fixture: relations in, keyed by source node id; relations out, keyed by any node id. */\nexport const Example = z.strictObject({\n name: z.string().optional(),\n sources: z.record(z.string(), Rows).default({}),\n expect: z.record(z.string(), Rows).default({}),\n /** Frozen clock for the fixture run (ISO instant); required if the graph reads the clock. */\n now: z.string().optional(),\n tz: z.string().optional(),\n})\nexport type Example = z.infer<typeof Example>\n\nexport const NodeJson = z.looseObject({\n id: z.string().min(1),\n op: z.string().min(1),\n label: z.string().optional(),\n})\nexport type NodeJson = z.infer<typeof NodeJson>\n\nexport const Position = z.object({ x: z.number(), y: z.number() })\nexport type Position = z.infer<typeof Position>\n\n/** One JSON Schema document per source node, describing one record of that source. */\nexport const JsonSchema = z.record(z.string(), z.unknown())\nexport type JsonSchema = Readonly<Record<string, unknown>>\n\nexport const MappingVersion = z.object({\n id: z.string().min(1),\n name: z.string().optional(),\n version: z.number().int().min(1).default(1),\n status: z.enum(['draft', 'published']).default('draft'),\n /** Default `on_error` of `map` nodes; a node's own `on_error` overrides it. */\n onError: OnError.optional(),\n unknownFields: z.enum(['ignore', 'notify']).optional(),\n params: z.record(z.string(), json).default({}),\n tables: z.record(z.string(), z.record(z.string(), json)).default({}),\n expectedSchema: z.record(z.string(), JsonSchema).default({}),\n nodes: z.array(NodeJson).default([]),\n expect: z.record(z.string(), NodeExpectation).default({}),\n examples: z.array(Example).default([]),\n layout: z.record(z.string(), Position).optional(),\n})\nexport type MappingVersion = z.infer<typeof MappingVersion>\n/** A version as authored, before defaults are filled in. */\nexport type MappingVersionInput = z.input<typeof MappingVersion>\n\n/** Parse untrusted JSON into a version; throws a zod error with paths on failure. */\nexport function parseVersion(input: unknown): MappingVersion {\n return MappingVersion.parse(input)\n}\n\nexport function emptyVersion(id: string, name?: string): MappingVersion {\n return parseVersion(name === undefined ? { id } : { id, name })\n}\n\n/** JSON Schema of the mapping document, for tools and models that produce mappings. */\nexport function versionJsonSchema(): Record<string, unknown> {\n return z.toJSONSchema(MappingVersion, { io: 'input' }) as Record<string, unknown>\n}\n","/**\n * `assert`: a named built-in check on its `in` relation, which it passes through (repaired, if\n * the chosen action repairs rows), so it can guard a flow or end a branch. `on_fail` is one\n * of the expectation actions, `alert` by default.\n *\n * - `count`: `min` / `max` rows.\n * - `unique`: `keys` unique.\n * - `rows`: every row satisfies `cond`.\n * - `acyclic`: the edges `edge.from -> edge.to` of `in` contain no cycle. With `edge.key` the\n * edges belong to groups (each product's own supply graph) and each group is checked on its\n * own; with `per`, every distinct `per.key` of `per.in` is checked against all edges. Either\n * way a group's rows of `remove.in` are taken out first. Cycle detection is iterative, so\n * it is engine code rather than a composition of DAG nodes.\n */\n\nimport { z } from 'zod'\nimport type { RunContext } from '../context'\nimport { Action } from '../document'\nimport {\n applyViolations,\n checkAction,\n countViolation,\n rowsViolation,\n uniqueViolation,\n type Violation,\n} from '../expect'\nimport { compilePredicate, type Test } from '../predicate'\nimport { ok } from '../result'\nimport { comparable, type MType, show } from '../types'\nimport { canonicalKey, compareVals, type Json, type Relation, toJson, type Val } from '../values'\nimport { defineNode, type NodeEnv, nodeId, type NodeIssue, type NodeOutput } from './def'\n\nconst common = { in: nodeId, on_fail: Action.optional() }\n\nconst params = z.discriminatedUnion('check', [\n z.strictObject({\n ...common,\n check: z.literal('count'),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n z.strictObject({\n ...common,\n check: z.literal('unique'),\n keys: z.array(z.string().min(1)).min(1),\n }),\n z.strictObject({ ...common, check: z.literal('rows'), cond: z.unknown() }),\n z.strictObject({\n ...common,\n check: z.literal('acyclic'),\n edge: z.strictObject({\n from: z.string().min(1),\n to: z.string().min(1),\n key: z.string().min(1).optional(),\n }),\n per: z.strictObject({ in: nodeId, key: z.string().min(1) }).optional(),\n remove: z\n .strictObject({\n in: nodeId,\n key: z.string().min(1),\n from: z.string().min(1),\n to: z.string().min(1),\n where: z.unknown().optional(),\n })\n .optional(),\n }),\n])\ntype Params = z.infer<typeof params>\ntype Acyclic = Extract<Params, { check: 'acyclic' }>\n\n/** One cycle as a path (first node repeated at the end), or undefined. */\nexport function findCycle(edges: readonly (readonly [string, string])[]): string[] | undefined {\n const next = new Map<string, string[]>()\n for (const [from, to] of edges) next.set(from, [...(next.get(from) ?? []), to])\n const state = new Map<string, 'open' | 'done'>()\n const path: string[] = []\n const visit = (node: string): string[] | undefined => {\n state.set(node, 'open')\n path.push(node)\n for (const to of next.get(node) ?? []) {\n if (state.get(to) === 'open') return [...path.slice(path.indexOf(to)), to]\n if (!state.has(to)) {\n const cycle = visit(to)\n if (cycle) return cycle\n }\n }\n path.pop()\n state.set(node, 'done')\n return undefined\n }\n for (const node of [...next.keys()].sort()) {\n if (state.has(node)) continue\n const cycle = visit(node)\n if (cycle) return cycle\n }\n return undefined\n}\n\nfunction fieldIssues(output: NodeOutput, fields: readonly string[], where: string): NodeIssue[] {\n return fields\n .filter((f) => !Object.hasOwn(output.type.fields, f))\n .map((f) => ({ message: `${where}: unknown field '${f}'` }))\n}\n\nfunction compileAcyclic(p: Acyclic, input: NodeOutput, env: NodeEnv) {\n const issues = fieldIssues(\n input,\n [p.edge.from, p.edge.to, ...(p.edge.key ? [p.edge.key] : [])],\n 'edge',\n )\n const edgeType = input.type.fields[p.edge.from]\n let removeWhere: Test | undefined\n if (p.per) issues.push(...fieldIssues(env.input(p.per.in), [p.per.key], 'per'))\n // A group without edges cannot have a cycle, so per adds nothing to grouped edges.\n if (p.edge.key && p.per) issues.push({ message: 'edge.key groups the edges itself; drop per' })\n const groupType = p.edge.key\n ? input.type.fields[p.edge.key]\n : p.per && env.input(p.per.in).type.fields[p.per.key]\n if (p.remove) {\n if (!p.per && !p.edge.key) issues.push({ message: 'remove needs per or edge.key' })\n const removal = env.input(p.remove.in)\n issues.push(...fieldIssues(removal, [p.remove.key, p.remove.from, p.remove.to], 'remove'))\n const checks: [string, MType | undefined, MType | undefined][] = [\n [`remove.from`, removal.type.fields[p.remove.from], edgeType],\n [`remove.to`, removal.type.fields[p.remove.to], edgeType],\n [`remove.key`, removal.type.fields[p.remove.key], groupType],\n ]\n for (const [name, a, b] of checks) {\n if (a && b && !comparable(a, b)) issues.push({ message: `${name}: ${show(a)} vs ${show(b)}` })\n }\n if (p.remove.where !== undefined) {\n const w = compilePredicate(p.remove.where, env.recordEnv(removal.type))\n if (w.ok) removeWhere = w.value\n else issues.push({ message: `remove.where: ${w.error}` })\n }\n }\n const toType = input.type.fields[p.edge.to]\n if (edgeType && toType && !comparable(edgeType, toType)) {\n issues.push({ message: `edge: ${show(edgeType)} vs ${show(toType)}` })\n }\n return { issues, removeWhere }\n}\n\nconst str = (v: Val) => (typeof v === 'string' ? v : canonicalKey(v))\n\ntype Edge = readonly [string, string]\n\nfunction acyclicViolation(\n p: Acyclic,\n inputs: (id: string) => Relation,\n ctx: RunContext,\n removeWhere: Test | undefined,\n action: Action,\n): Violation | undefined {\n const keyed = p.edge.key\n const grouped = keyed !== undefined || p.per !== undefined\n // Edges by canonical group key: by `edge.key`, or one set every group shares under null.\n const edgesOf = new Map<string, Map<string, Edge>>()\n const keys = new Map<string, Val>()\n for (const row of inputs(p.in)) {\n const from = row[p.edge.from] ?? null\n const to = row[p.edge.to] ?? null\n const k = keyed ? (row[keyed] ?? null) : null\n if (from === null || to === null || (keyed && k === null)) continue\n const g = canonicalKey(k)\n keys.set(g, k)\n const edges = edgesOf.get(g) ?? new Map<string, Edge>()\n edges.set(canonicalKey([from, to]), [str(from), str(to)])\n edgesOf.set(g, edges)\n }\n let groups: Val[] = [null]\n if (keyed) groups = [...keys.values()].sort(compareVals)\n else if (p.per) {\n const seen = new Map<string, Val>()\n for (const row of inputs(p.per.in)) {\n const k = row[p.per.key] ?? null\n if (k !== null) seen.set(canonicalKey(k), k)\n }\n groups = [...seen.values()].sort(compareVals)\n }\n const removals = new Map<string, Set<string>>()\n if (p.remove) {\n for (const row of inputs(p.remove.in)) {\n if (removeWhere && !removeWhere(null, row, ctx)) continue\n const g = canonicalKey(row[p.remove.key] ?? null)\n const set = removals.get(g) ?? new Set<string>()\n set.add(canonicalKey([row[p.remove.from] ?? null, row[p.remove.to] ?? null]))\n removals.set(g, set)\n }\n }\n // With shared edges most groups remove the same ones (often none), so cycles are cached\n // by removal set; a group with edges of its own is small and checked directly.\n const cache = new Map<string, string[] | undefined>()\n const failing: Json[] = []\n let count = 0\n for (const g of groups) {\n const removed = removals.get(canonicalKey(g)) ?? new Set<string>()\n const edges = edgesOf.get(canonicalKey(keyed ? g : null)) ?? new Map<string, Edge>()\n const kept = () => [...edges].filter(([k]) => !removed.has(k)).map(([, e]) => e)\n let cycle: string[] | undefined\n if (keyed) cycle = findCycle(kept())\n else {\n const signature = [...removed].sort().join('|')\n if (!cache.has(signature)) cache.set(signature, findCycle(kept()))\n cycle = cache.get(signature)\n }\n if (cycle) {\n count += 1\n if (failing.length < 5) failing.push({ group: toJson(g), cycle })\n }\n }\n if (count === 0) return undefined\n const first = failing[0] as { group: Json; cycle: string[] }\n return {\n clause: 'acyclic',\n action,\n message: `${count} ${grouped ? 'groups have' : 'graph has'} a cycle, e.g. ${grouped ? `${typeof first.group === 'string' ? first.group : JSON.stringify(first.group)}: ` : ''}${first.cycle.join(' -> ')}`,\n count,\n samples: failing,\n }\n}\n\nexport const assertNode = defineNode({\n op: 'assert',\n label: 'Assert',\n category: 'check',\n description: 'A built-in check (count, unique, rows, acyclic) that passes its input through.',\n slots: [\n { id: 'in', label: 'In', path: ['in'] },\n { id: 'per', label: 'Per', path: ['per', 'in'], optional: true },\n { id: 'remove', label: 'Remove', path: ['remove', 'in'], optional: true },\n ],\n output: true,\n effect: 'check',\n defaults: () => ({ in: '', check: 'count' }),\n params,\n compile: (p: Params, env) => {\n const input = env.input(p.in)\n const action = p.on_fail ?? 'alert'\n const checked = checkAction(action, p.check, input)\n const issues: NodeIssue[] = checked.ok ? [] : [{ message: `on_fail: ${checked.error}` }]\n let test: Test | undefined\n let removeWhere: Test | undefined\n switch (p.check) {\n case 'unique':\n issues.push(...fieldIssues(input, p.keys, 'keys'))\n break\n case 'rows': {\n const compiled = compilePredicate(p.cond, env.recordEnv(input.type))\n if (compiled.ok) test = compiled.value\n else issues.push({ message: `cond: ${compiled.error}` })\n break\n }\n case 'acyclic': {\n const compiled = compileAcyclic(p, input, env)\n issues.push(...compiled.issues)\n removeWhere = compiled.removeWhere\n break\n }\n }\n if (!checked.ok || issues.length > 0) return { ok: false, error: issues }\n\n return ok({\n output: checked.value,\n run: (inputs, ctx, options = {}) => {\n const rows = inputs(p.in)\n let violation: Violation | undefined\n switch (p.check) {\n case 'count':\n violation = options.skipCount\n ? undefined\n : countViolation(rows.length, p, action, undefined)\n break\n case 'unique':\n violation = uniqueViolation(rows, p.keys, action)\n break\n case 'rows':\n violation = rowsViolation(rows, test as Test, ctx, action)\n break\n default:\n violation = acyclicViolation(p, inputs, ctx, removeWhere, action)\n }\n return ok(applyViolations(env.id, 'assert', rows, violation ? [violation] : []))\n },\n })\n },\n})\n","/** `distinct`: deduplicates on `keys` and projects to them. */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport { type MType, t } from '../types'\nimport { keyOf, type Rec, type Val } from '../values'\nimport { defineNode, fail, nodeId, type Origin } from './def'\n\nconst params = z.strictObject({ in: nodeId, keys: z.array(z.string().min(1)).min(1) })\n\nexport const distinctNode = defineNode({\n op: 'distinct',\n label: 'Distinct',\n category: 'transform',\n description: 'One record per distinct combination of the key fields.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', keys: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const unknown = p.keys.filter((k) => !Object.hasOwn(input.type.fields, k))\n if (unknown.length) return fail(`unknown keys: ${unknown.join(', ')}`)\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const k of p.keys) {\n fields[k] = input.type.fields[k] as MType\n origins[k] = input.origins[k] as Origin\n }\n return ok({\n output: { type: t.record(fields), origins },\n run: (inputs) => {\n const seen = new Set<string>()\n const rows: Rec[] = []\n for (const row of inputs(p.in)) {\n const k = keyOf(row, p.keys)\n if (seen.has(k)) continue\n seen.add(k)\n rows.push(Object.fromEntries(p.keys.map((f) => [f, (row[f] ?? null) as Val])))\n }\n return ok({ rows })\n },\n })\n },\n})\n","/**\n * `expectedSchema` as JSON Schema (arch.md, \"expectedSchema is the type environment\").\n *\n * The stored schema of a source is its type environment: `sourceRecordType` derives the\n * record type a `source` node emits. `format` stays a validation constraint, never a type: a\n * `{ \"type\": \"string\", \"format\": \"date\" }` field is a `string`, and `to_date` makes a date.\n *\n * Until per-record contract validation (Ajv) exists, `conformRows` is the runtime guard: it\n * projects rows onto the declared fields and checks every value against its declared type.\n */\n\nimport type { Column, LogicalType, Table, TargetEntity } from '../schema'\nimport type { JsonSchema } from './document'\nimport { err, ok, type Result } from './result'\nimport { Instant } from './time'\nimport { type MType, type NonNull, type RecordType, show, t } from './types'\nimport { isRecordVal, type Json, type Rec, type Val } from './values'\n\ntype Node = Readonly<Record<string, unknown>>\n\nconst DIALECT = 'https://json-schema.org/draft/2020-12/schema'\n\n/** The record type of a source's schema. Optional fields read as null, so are nullable. */\nexport function sourceRecordType(schema: JsonSchema): Result<RecordType, string> {\n const properties = schema.properties as Readonly<Record<string, Node>> | undefined\n if (schema.type !== 'object' || typeof properties !== 'object' || properties === null) {\n return err(\n 'a source schema must describe one object record (\"type\": \"object\" with \"properties\")',\n )\n }\n const required = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : [])\n const fields: Record<string, MType> = {}\n for (const [name, node] of Object.entries(properties)) {\n const type = toMType(node)\n fields[name] = required.has(name) ? type : t.nullable(type)\n }\n return ok(t.record(fields))\n}\n\nfunction toMType(node: Node): MType {\n const union = (node.anyOf ?? node.oneOf) as readonly Node[] | undefined\n if (Array.isArray(union)) {\n const nonNull = union.filter((m) => m.type !== 'null')\n const inner = nonNull.length === 1 ? toMType(nonNull[0] as Node) : t.unknown\n return union.length > nonNull.length ? t.nullable(inner) : inner\n }\n if (Array.isArray(node.type)) {\n const types = node.type as readonly string[]\n const nonNull = types.filter((x) => x !== 'null')\n const inner = nonNull.length === 1 ? toMType({ ...node, type: nonNull[0] }) : t.unknown\n return nonNull.length < types.length ? t.nullable(inner) : inner\n }\n if (Array.isArray(node.enum)) {\n const kinds = new Set(\n (node.enum as readonly unknown[]).map((v) => (v === null ? 'null' : typeof v)),\n )\n const hasNull = kinds.delete('null')\n const inner: MType = kinds.size === 1 ? scalar([...kinds][0] as string) : t.unknown\n return hasNull ? t.nullable(inner) : inner\n }\n switch (node.type) {\n case 'string':\n case 'number':\n case 'boolean':\n return scalar(node.type)\n case 'integer':\n return t.number\n case 'array':\n return t.list(\n typeof node.items === 'object' && node.items ? toMType(node.items as Node) : t.unknown,\n )\n case 'object': {\n const props = (node.properties ?? {}) as Readonly<Record<string, Node>>\n return t.record(Object.fromEntries(Object.entries(props).map(([k, v]) => [k, toMType(v)])))\n }\n default:\n return t.unknown\n }\n}\n\nfunction scalar(kind: string): NonNull {\n switch (kind) {\n case 'string':\n return t.string\n case 'number':\n return t.number\n case 'boolean':\n return t.boolean\n default:\n return t.unknown\n }\n}\n\nfunction logicalSchema(logical: LogicalType): Record<string, Json> {\n switch (logical) {\n case 'string':\n return { type: 'string' }\n case 'integer':\n return { type: 'integer' }\n case 'decimal':\n return { type: 'number' }\n case 'boolean':\n return { type: 'boolean' }\n case 'date':\n return { type: 'string', format: 'date' }\n case 'timestamp':\n return { type: 'string', format: 'date-time' }\n default:\n return {}\n }\n}\n\nfunction fieldSchema(logical: LogicalType, nullable: boolean, description?: string | null) {\n const base = logicalSchema(logical)\n const typed =\n nullable && typeof base.type === 'string' ? { ...base, type: [base.type, 'null'] } : base\n return description ? { ...typed, description } : typed\n}\n\nfunction objectSchema(\n id: string,\n fields: readonly {\n name: string\n logical: LogicalType\n nullable: boolean\n description?: string | null\n }[],\n): JsonSchema {\n return {\n $schema: DIALECT,\n $id: id,\n type: 'object',\n required: fields.filter((f) => !f.nullable).map((f) => f.name),\n properties: Object.fromEntries(\n fields.map((f) => [f.name, fieldSchema(f.logical, f.nullable, f.description)]),\n ),\n additionalProperties: true,\n }\n}\n\n/** A starting `expectedSchema` for a source table, from what its connector describes. */\nexport function tableJsonSchema(table: Table, system?: string): JsonSchema {\n return objectSchema(\n system ? `${system}.${table.name}` : table.name,\n table.columns.map((c: Column) => ({\n name: c.name,\n logical: c.logicalType,\n nullable: c.nullable,\n description: c.description,\n })),\n )\n}\n\n/** The pinned schema of an internal entity read as a source. */\nexport function entityJsonSchema(entity: TargetEntity): JsonSchema {\n return objectSchema(\n `internal.${entity.name}`,\n entity.fields.map((f) => ({\n name: f.name,\n logical: f.logicalType,\n nullable: f.nullable,\n description: f.description,\n })),\n )\n}\n\n/** Does a runtime value inhabit this type? */\nexport function conforms(value: Val, type: MType): boolean {\n if (value === null) return type.kind === 'nullable' || type.kind === 'unknown'\n switch (type.kind) {\n case 'nullable':\n return conforms(value, type.of)\n case 'unknown':\n return true\n case 'string':\n return typeof value === 'string'\n case 'number':\n return typeof value === 'number' && Number.isFinite(value)\n case 'boolean':\n return typeof value === 'boolean'\n case 'date':\n return value instanceof Instant\n case 'list':\n return Array.isArray(value) && (value as readonly Val[]).every((v) => conforms(v, type.of))\n case 'tuple':\n return (\n Array.isArray(value) &&\n value.length === type.of.length &&\n type.of.every((x, i) => conforms((value as readonly Val[])[i] as Val, x))\n )\n case 'record':\n return (\n isRecordVal(value) &&\n Object.entries(type.fields).every(([k, v]) => conforms(value[k] ?? null, v))\n )\n default:\n return false\n }\n}\n\nexport interface FieldViolation {\n readonly field: string\n readonly expected: string\n readonly count: number\n /** Row positions of the first violations. */\n readonly samples: readonly number[]\n}\n\n/** Project rows onto the declared fields and check each value; one violation per field. */\nexport function conformRows(\n rows: readonly Readonly<Record<string, unknown>>[],\n type: RecordType,\n): { rows: Rec[]; violations: FieldViolation[] } {\n const fields = Object.entries(type.fields)\n const counts = new Map<string, { count: number; samples: number[] }>()\n const out: Rec[] = []\n for (const [i, row] of rows.entries()) {\n const rec: Record<string, Val> = {}\n for (const [name, fieldType] of fields) {\n const value = (row[name] ?? null) as Val\n if (!conforms(value, fieldType)) {\n const v = counts.get(name) ?? { count: 0, samples: [] }\n v.count += 1\n if (v.samples.length < 5) v.samples.push(i)\n counts.set(name, v)\n }\n rec[name] = value\n }\n out.push(rec)\n }\n return {\n rows: out,\n violations: [...counts].map(([field, v]) => ({\n field,\n expected: show(type.fields[field] as MType),\n ...v,\n })),\n }\n}\n","/**\n * `source`: one entity of an external or internal system, read once per run into the\n * snapshot. Its record type comes from the version's `expectedSchema` entry for this node.\n * Loading checks every value against that type; a violation fails the node, so nothing\n * downstream runs on data the version never claimed to handle.\n */\n\nimport { z } from 'zod'\nimport { conformRows, type FieldViolation, sourceRecordType } from '../jsonschema'\nimport { compilePredicate, nonNullPaths, type Test } from '../predicate'\nimport { err, ok, type Result } from '../result'\nimport { type MType, type RecordType, stripNull, t } from '../types'\nimport type { Rec, Relation } from '../values'\nimport {\n defineNode,\n fail,\n type NodeFailure,\n type NodeIssue,\n type NodeOutput,\n type Origin,\n ownOrigins,\n type RunIssue,\n} from './def'\n\nconst params = z.strictObject({\n system: z.string().min(1),\n entity: z.string().min(1),\n filter: z.unknown().optional(),\n})\n\n/**\n * Narrow the fields a passing filter guarantees are non-null (and so present). The condition\n * has compiled against `output`, so every path it names exists.\n */\nexport function narrow(output: NodeOutput, cond: unknown): NodeOutput {\n const fields = { ...output.type.fields }\n const origins = { ...output.origins }\n for (const path of nonNullPaths(cond)) {\n fields[path] = stripNull(fields[path] as MType)\n const origin = origins[path] as Origin\n origins[path] = { node: origin.node, field: origin.field, omittable: false }\n }\n return { ...output, type: t.record(fields), origins }\n}\n\n/** Shared by `source` and `transform`: conform rows, or fail with one issue per field. */\nexport function loadRows(\n node: string,\n rows: readonly Readonly<Record<string, unknown>>[],\n type: RecordType,\n): Result<Rec[], NodeFailure> {\n const loaded = conformRows(rows, type)\n if (loaded.violations.length === 0) return ok(loaded.rows)\n const issues: RunIssue[] = loaded.violations.map((v: FieldViolation) => ({\n node,\n code: 'schema_violation',\n field: v.field,\n message: `${v.field}: ${v.count} values are not ${v.expected}`,\n count: v.count,\n samples: v.samples,\n }))\n return err({\n code: 'schema_violation',\n message: `${loaded.violations.length} fields do not match the declared schema`,\n issues,\n })\n}\n\nexport const sourceNode = defineNode({\n op: 'source',\n label: 'Source',\n category: 'source',\n description: 'Reads one entity of a source system into the run snapshot.',\n slots: [],\n output: true,\n defaults: () => ({ system: '', entity: '' }),\n params,\n compile: (p, env) => {\n const schema = env.version.expectedSchema[env.id]\n if (!schema) {\n return fail(`no expectedSchema for source '${env.id}'`, { code: 'missing_schema' })\n }\n const declared = sourceRecordType(schema)\n if (!declared.ok) return fail(declared.error, { code: 'missing_schema' })\n const type = declared.value\n\n let test: Test | undefined\n if (p.filter !== undefined) {\n const compiled = compilePredicate(p.filter, env.recordEnv(type))\n if (!compiled.ok)\n return { ok: false, error: [{ message: `filter: ${compiled.error}` }] as NodeIssue[] }\n test = compiled.value\n }\n const declaredOutput: NodeOutput = { type, origins: ownOrigins(env.id, type) }\n const output = test ? narrow(declaredOutput, p.filter) : declaredOutput\n\n return ok({\n output,\n run: (_inputs, ctx) => {\n const loaded = loadRows(env.id, ctx.snapshot[env.id] ?? [], type)\n if (!loaded.ok) return loaded\n const rows: Relation = test\n ? loaded.value.filter((r) => (test as Test)(null, r, ctx))\n : loaded.value\n return ok({ rows })\n },\n })\n },\n})\n","/**\n * `filter`: keeps records where the predicate holds. A `{ path, is_null: false }` condition\n * (alone or inside `all`) narrows that field to non-null in the output type.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate } from '../predicate'\nimport { ok } from '../result'\nimport { defineNode, fail, nodeId } from './def'\nimport { narrow } from './source'\n\nconst params = z.strictObject({ in: nodeId, cond: z.unknown() })\n\nexport const filterNode = defineNode({\n op: 'filter',\n label: 'Filter',\n category: 'transform',\n description: 'Keeps the records where a condition holds.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', cond: {} }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const test = compilePredicate(p.cond, env.recordEnv(input.type))\n if (!test.ok) return fail(`cond: ${test.error}`)\n const cond = test.value\n return ok({\n output: narrow(input, p.cond),\n run: (inputs, ctx) => ok({ rows: inputs(p.in).filter((r) => cond(null, r, ctx)) }),\n })\n },\n})\n","/**\n * `join`: equi-join on key pairs plus an optional residual `where`, part of the match (as in\n * SQL `ON`). `left` makes every right field nullable; `semi` / `anti` keep left records with\n * at least one / no match and return the left schema.\n *\n * `select` picks and renames right fields; without it every right field is kept, a join key\n * with the same name on both sides merges, and any other collision is a save error. Null keys\n * never match.\n *\n * `cardinality` is declared and enforced while the hash table is built:\n * `n:1` right keys unique, `1:n` left keys unique, `1:1` both, `n:m` unrestricted but needs a\n * `count` expectation on this node.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate, type Test } from '../predicate'\nimport { err, ok } from '../result'\nimport { comparable, type MType, show, t } from '../types'\nimport { type Json, keyOf, type Rec, type Relation, toJson, type Val } from '../values'\nimport { defineNode, nodeId, type NodeIssue, type Origin } from './def'\n\nconst params = z.strictObject({\n left: nodeId,\n right: nodeId,\n on: z.array(z.tuple([z.string().min(1), z.string().min(1)])).min(1),\n type: z.enum(['inner', 'left', 'semi', 'anti']).optional(),\n cardinality: z.enum(['1:1', 'n:1', '1:n', 'n:m']),\n select: z.record(z.string().min(1), z.string().min(1)).optional(),\n where: z.unknown().optional(),\n tolerate_skips: z.boolean().optional(),\n})\n\n/** Index of rows by key, skipping null keys; reports the first duplicate when `unique`. */\nfunction index(rows: Relation, keys: readonly string[], unique: boolean) {\n const byKey = new Map<string, Rec[]>()\n for (const row of rows) {\n if (keys.some((k) => (row[k] ?? null) === null)) continue\n const k = keyOf(row, keys)\n const bucket = byKey.get(k)\n if (!bucket) byKey.set(k, [row])\n else if (unique) return { duplicate: keys.map((f) => toJson(row[f] as Val)) }\n else bucket.push(row)\n }\n return { byKey }\n}\n\nexport const joinNode = defineNode({\n op: 'join',\n label: 'Join',\n category: 'transform',\n description: 'Combines two inputs on matching keys, with a declared cardinality.',\n slots: [\n { id: 'left', label: 'Left', path: ['left'] },\n { id: 'right', label: 'Right', path: ['right'] },\n ],\n output: true,\n defaults: () => ({ left: '', right: '', on: [], type: 'inner', cardinality: 'n:1' }),\n params,\n toleratesSkips: (p) => p.tolerate_skips === true,\n compile: (p, env) => {\n const left = env.input(p.left)\n const right = env.input(p.right)\n const kind = p.type ?? 'inner'\n const issues: NodeIssue[] = []\n\n for (const [lk, rk] of p.on) {\n const lt = left.type.fields[lk]\n const rt = right.type.fields[rk]\n if (!lt) issues.push({ message: `left has no field '${lk}'` })\n if (!rt) issues.push({ message: `right has no field '${rk}'` })\n if (lt && rt && !comparable(lt, rt)) {\n issues.push({ message: `join key ${lk}: ${show(lt)} vs ${rk}: ${show(rt)}` })\n }\n }\n if (p.cardinality === 'n:m' && env.expect?.count === undefined) {\n issues.push({\n message: \"an n:m join needs a count expectation in the version's expect block\",\n code: 'missing_expectation',\n })\n }\n\n // Right fields carried into the output: `select`ed and renamed, or all but merged keys.\n const carried: [string, string][] = []\n if (p.select) {\n for (const [from, to] of Object.entries(p.select)) {\n if (Object.hasOwn(right.type.fields, from)) carried.push([from, to])\n else issues.push({ message: `select: right has no field '${from}'` })\n }\n } else {\n const merged = new Set(p.on.filter(([l, r]) => l === r).map(([l]) => l))\n for (const name of Object.keys(right.type.fields))\n if (!merged.has(name)) carried.push([name, name])\n }\n const needsMerge = kind === 'inner' || kind === 'left' || p.where !== undefined\n const fields: Record<string, MType> = { ...left.type.fields }\n const origins: Record<string, Origin> = { ...left.origins }\n if (needsMerge) {\n for (const [from, to] of carried) {\n if (Object.hasOwn(fields, to)) {\n issues.push({ message: `field '${to}' exists on both sides; rename it with select` })\n continue\n }\n const type = right.type.fields[from] as MType\n fields[to] = kind === 'left' ? t.nullable(type) : type\n origins[to] =\n kind === 'left'\n ? { node: env.id, field: to, omittable: false }\n : (right.origins[from] as Origin)\n }\n }\n let where: Test | undefined\n if (p.where !== undefined && issues.length === 0) {\n const compiled = compilePredicate(p.where, env.recordEnv(t.record(fields)))\n if (compiled.ok) where = compiled.value\n else issues.push({ message: `where: ${compiled.error}` })\n }\n if (issues.length) return { ok: false, error: issues }\n\n const leftKeys = p.on.map(([l]) => l)\n const rightKeys = p.on.map(([, r]) => r)\n const leftUnique = p.cardinality === '1:1' || p.cardinality === '1:n'\n const rightUnique = p.cardinality === '1:1' || p.cardinality === 'n:1'\n const nullRight = Object.fromEntries(carried.map(([, to]) => [to, null]))\n const project = (r: Rec): Rec => {\n const out: Record<string, Val> = {}\n for (const [from, to] of carried) out[to] = r[from] ?? null\n return out\n }\n const violated = (side: 'left' | 'right', key: readonly Json[]) =>\n err({\n code: 'cardinality_violated',\n message: `${p.cardinality} join: ${side} key ${JSON.stringify(key)} is not unique`,\n samples: [key],\n })\n\n return ok({\n output: kind === 'inner' || kind === 'left' ? { type: t.record(fields), origins } : left,\n run: (inputs, ctx) => {\n const lrows = inputs(p.left)\n const built = index(inputs(p.right), rightKeys, rightUnique)\n if (built.duplicate) return violated('right', built.duplicate)\n if (leftUnique) {\n const checked = index(lrows, leftKeys, true)\n if (checked.duplicate) return violated('left', checked.duplicate)\n }\n const byKey = built.byKey as Map<string, Rec[]>\n const rows: Rec[] = []\n for (const l of lrows) {\n const nullKey = leftKeys.some((k) => (l[k] ?? null) === null)\n const candidates = nullKey ? [] : (byKey.get(keyOf(l, leftKeys)) ?? [])\n const matches: Rec[] = []\n for (const r of candidates) {\n const merged = { ...l, ...project(r) }\n if (!where || where(null, merged, ctx)) matches.push(merged)\n }\n if (kind === 'semi') {\n if (matches.length > 0) rows.push(l)\n } else if (kind === 'anti') {\n if (matches.length === 0) rows.push(l)\n } else if (matches.length > 0) rows.push(...matches)\n else if (kind === 'left') rows.push({ ...l, ...nullRight })\n }\n return ok({ rows })\n },\n })\n },\n})\n","/** Access ops, the pipeline entry points: `extract`, `const`, `coalesce`. */\n\nimport { z } from 'zod'\nimport { fieldType } from '../context'\nimport { ok, type Result } from '../result'\nimport { isNullable, type MType, stripNull, t, typeOfJson, unifyAll } from '../types'\nimport type { Val } from '../values'\nimport { defineOp, json, never, params } from './def'\n\n/** Reads one field of the current record, or a tuple of fields. A missing field is null. */\nexport const extract = defineOp({\n name: 'extract',\n params: params({ path: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]) }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p, env): Result<MType, string> => {\n if (typeof p.path === 'string') return fieldType(env.record, p.path)\n const types: MType[] = []\n for (const path of p.path) {\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n types.push(type.value)\n }\n return ok(t.tuple(types))\n },\n run: (p) => {\n if (typeof p.path === 'string') {\n const path = p.path\n return (_input, ctx) => ok(ctx.record[path] ?? null)\n }\n const paths = p.path\n return (_input, ctx) => ok(paths.map((x) => ctx.record[x] ?? null))\n },\n})\n\n/** A literal value. */\nexport const constant = defineOp({\n name: 'const',\n params: params({ value: json }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p) => ok(typeOfJson(p.value)),\n run: (p) => {\n const value = p.value as Val\n return () => ok(value)\n },\n})\n\n/** The first non-null of several fields. Nullable only if every field is. */\nexport const coalesce = defineOp({\n name: 'coalesce',\n params: params({ paths: z.array(z.string().min(1)).min(2) }),\n nulls: 'consume',\n input: 'none',\n fallible: never,\n signature: (_input, p, env): Result<MType, string> => {\n const types: MType[] = []\n for (const path of p.paths) {\n const type = fieldType(env.record, path)\n if (!type.ok) return type\n types.push(type.value)\n }\n const common = unifyAll(types)\n if (!common.ok) return common\n return ok(types.every(isNullable) ? common.value : stripNull(common.value))\n },\n run: (p) => {\n const paths = p.paths\n return (_input, ctx) => {\n for (const path of paths) {\n const v = ctx.record[path] ?? null\n if (v !== null) return ok(v)\n }\n return ok(null)\n }\n },\n})\n","/** Type conversion: `to_number`, `to_string`, `to_bool`, `to_date`, `assert_type`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport {\n dateFormat,\n formatDate,\n hasFullDate,\n type Instant,\n isTimeZone,\n parseDateValue,\n parseDateFormat,\n} from '../time'\nimport { assignable, parseTypeName, show, t, typeName } from '../types'\nimport { toJson, type Val } from '../values'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst NUMBER = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/\n\nconst dateFormatParam = z.string().superRefine((s, ctx) => {\n const f = parseDateFormat(s)\n if (!f.ok) ctx.addIssue({ code: 'custom', message: f.error })\n})\n\nconst timeZone = z.string().refine(isTimeZone, 'unknown time zone')\n\n/** Parses a number from a string (a boolean gives 1 or 0). Strict raises, else null. */\nexport const toNumber = defineOp({\n name: 'to_number',\n params: params({ strict: z.boolean().optional() }),\n nulls: 'propagate',\n fallible: (p) => p.strict === true,\n signature: (input, p) => {\n const s = expectKind(input, ['string', 'boolean'], 'to_number')\n if (!s.ok) return s\n return ok(input.kind === 'boolean' || p.strict ? t.number : t.nullable(t.number))\n },\n run: (p) => (input) => {\n if (typeof input === 'boolean') return ok(input ? 1 : 0)\n const text = (input as string).trim()\n if (NUMBER.test(text)) return ok(Number(text))\n return p.strict ? stepError('parse_failed', `'${input as string}' is not a number`) : ok(null)\n },\n})\n\n/** Canonical string form. `format` applies to dates, in the run time zone. */\nexport const toString = defineOp({\n name: 'to_string',\n params: params({ format: dateFormatParam.optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p) => {\n if (input.kind === 'unknown') return err('to_string needs a known input type')\n if (p.format !== undefined && input.kind !== 'date') {\n return err('to_string format applies to dates only')\n }\n return ok(t.string)\n },\n run: (p, _env, input) => {\n if (input.kind === 'date') {\n const format = dateFormat(p.format ?? 'iso')\n return (v, ctx) => ok(formatDate(v as Instant, format, ctx.tz))\n }\n return (v) => ok(stringify(v))\n },\n})\n\nfunction stringify(v: Val): string {\n if (typeof v === 'string') return v\n if (typeof v === 'number' || typeof v === 'boolean') return String(v)\n return JSON.stringify(toJson(v))\n}\n\nconst TRUE_VALUES = ['true', '1']\nconst FALSE_VALUES = ['false', '0']\n\n/** Explicit truthiness: only the listed values convert, anything else is an error. */\nexport const toBool = defineOp({\n name: 'to_bool',\n params: params({\n true_values: z.array(z.string()).min(1).optional(),\n false_values: z.array(z.string()).min(1).optional(),\n }).refine(\n (p) =>\n !(p.true_values ?? TRUE_VALUES).some((v) => (p.false_values ?? FALSE_VALUES).includes(v)),\n 'true_values and false_values overlap',\n ),\n nulls: 'propagate',\n fallible: () => true,\n signature: (input) => {\n const s = expectKind(input, ['string', 'number'], 'to_bool')\n return s.ok ? ok(t.boolean) : s\n },\n run: (p) => {\n const yes = new Set(p.true_values ?? TRUE_VALUES)\n const no = new Set(p.false_values ?? FALSE_VALUES)\n return (input) => {\n const text = typeof input === 'number' ? String(input) : (input as string).trim()\n if (yes.has(text)) return ok(true)\n if (no.has(text)) return ok(false)\n return stepError('parse_failed', `'${text}' is not a listed boolean value`)\n }\n },\n})\n\n/**\n * Parses to an instant: `iso`, `epoch_ms`, `epoch_s`, or a `YYYY MM DD HH mm ss` pattern.\n * Wall-clock values are read in `tz`, by default the run's frozen time zone.\n */\nexport const toDate = defineOp({\n name: 'to_date',\n params: params({ format: dateFormatParam, tz: timeZone.optional() }).refine((p) => {\n const format = parseDateFormat(p.format)\n return !format.ok || hasFullDate(format.value)\n }, 'to_date format needs YYYY, MM and DD'),\n nulls: 'propagate',\n fallible: () => true,\n signature: (input, p) => {\n const epoch = dateFormat(p.format).kind === 'epoch'\n const s = expectKind(input, epoch ? ['string', 'number'] : ['string'], 'to_date')\n return s.ok ? ok(t.date) : s\n },\n run: (p) => {\n const format = dateFormat(p.format)\n return (input, ctx) => {\n const instant = parseDateValue(input as string | number, format, p.tz ?? ctx.tz)\n return instant\n ? ok(instant)\n : stepError(\n 'parse_failed',\n `'${String(input as string | number)}' does not match date format ${p.format}`,\n )\n }\n },\n})\n\n/** A runtime no-op and a checkpoint for the validator: the input must have this type. */\nexport const assertType = defineOp({\n name: 'assert_type',\n params: params({\n type: z.string().superRefine((s, ctx) => {\n const parsed = parseTypeName(s)\n if (!parsed.ok) ctx.addIssue({ code: 'custom', message: parsed.error })\n }),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p) => {\n const declared = typeName(p.type)\n return assignable(input, declared)\n ? ok(declared)\n : err(`expected ${p.type}, got ${show(input)}`)\n },\n run: () => (input) => ok(input),\n})\n","/**\n * Date ops: `format_date`, `shift_date`, `truncate_date`, `to_utc`. Calendar math happens in\n * the run's frozen time zone unless a `tz` is given.\n */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport {\n dateFormat,\n duration,\n formatDate,\n type Instant,\n isTimeZone,\n parseDateFormat,\n parseDuration,\n shift,\n truncate,\n} from '../time'\nimport { type MType, t } from '../types'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst dateIn =\n (op: string, out: MType = t.date) =>\n (input: MType) => {\n const s = expectKind(input, ['date'], op)\n return s.ok ? ok(out) : s\n }\n\nexport const formatDateOp = defineOp({\n name: 'format_date',\n params: params({\n format: z.string().superRefine((s, ctx) => {\n const f = parseDateFormat(s)\n if (!f.ok) ctx.addIssue({ code: 'custom', message: f.error })\n }),\n tz: z.string().refine(isTimeZone, 'unknown time zone').optional(),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('format_date', t.string),\n run: (p) => {\n const format = dateFormat(p.format)\n return (input, ctx) => ok(formatDate(input as Instant, format, p.tz ?? ctx.tz))\n },\n})\n\n/** Shift by a duration such as `+10y` or `-30d`. */\nexport const shiftDate = defineOp({\n name: 'shift_date',\n params: params({\n by: z.string().superRefine((s, ctx) => {\n const d = parseDuration(s)\n if (!d.ok) ctx.addIssue({ code: 'custom', message: d.error })\n }),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('shift_date'),\n run: (p) => {\n const by = duration(p.by)\n return (input, ctx) => ok(shift(input as Instant, by, ctx.tz))\n },\n})\n\nexport const truncateDate = defineOp({\n name: 'truncate_date',\n params: params({ unit: z.enum(['day', 'month', 'year']) }),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('truncate_date'),\n run: (p) => (input, ctx) => ok(truncate(input as Instant, p.unit, ctx.tz)),\n})\n\n/** Instants carry no zone, so this is the identity; kept as an explicit normalisation step. */\nexport const toUtc = defineOp({\n name: 'to_utc',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: dateIn('to_utc'),\n run: () => (input) => ok(input),\n})\n","/**\n * `fn`: the record-scope escape hatch. Calls a named, reviewed, version-pinned function the\n * host registers in `GraphEnv.functions`, with a declared input and output type.\n */\n\nimport { z } from 'zod'\nimport type { FnDef } from '../context'\nimport { err, ok } from '../result'\nimport { assignable, show } from '../types'\nimport { defineOp, params } from './def'\n\nexport const fn = defineOp({\n name: 'fn',\n params: params({ ref: z.string().min(1) }),\n nulls: 'consume',\n fallible: (p, env) => env.functions[p.ref]?.fallible ?? true,\n signature: (input, p, env) => {\n const def = Object.hasOwn(env.functions, p.ref) ? env.functions[p.ref] : undefined\n if (!def) return err(`unknown function '${p.ref}'`)\n if (def.input && !assignable(input, def.input)) {\n return err(`function '${p.ref}' takes ${show(def.input)}, got ${show(input)}`)\n }\n return ok(def.output)\n },\n run: (p, env) => {\n const def = env.functions[p.ref] as FnDef\n return (input, ctx) => def.run(input, ctx)\n },\n})\n","/**\n * List ops for list-typed fields within one record: `each`, `filter_list`, `index`, `first`,\n * `last`, `len`, `unique`, `sum`, `min`, `max`, `contains`. Collection-wide work belongs to\n * collection nodes.\n */\n\nimport { z } from 'zod'\nimport { compileOperand, compilePredicate } from '../predicate'\nimport { compileSteps } from '../pipeline'\nimport { err, expectOk, ok, type Result } from '../result'\nimport { comparable, type ListType, type MType, orderable, show, stripNull, t } from '../types'\nimport { canonicalKey, compareVals, type Val } from '../values'\nimport { defineOp, never, params } from './def'\n\nconst listIn = (input: MType, op: string): Result<MType, string> =>\n input.kind === 'list' ? ok(input.of) : err(`${op} expects a list, got ${show(input)}`)\n\n/** Applies a nested pipeline to every element. Nesting depth is capped at 1. */\nexport const each = defineOp({\n name: 'each',\n params: params({ pipeline: z.array(z.unknown()).min(1) }),\n nulls: 'propagate',\n fallible: (p, env, input) =>\n expectOk(compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, (input as ListType).of))\n .fallible,\n signature: (input, p, env) => {\n if (env.depth >= 1) return err('each cannot be nested inside each')\n const element = listIn(input, 'each')\n if (!element.ok) return element\n const nested = compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, element.value)\n if (!nested.ok) return err(`each step ${nested.error.step}: ${nested.error.message}`)\n if (nested.value.omittable) return err('each cannot end in omit_if_null')\n return ok(t.list(nested.value.type))\n },\n run: (p, env, input) => {\n const { run } = expectOk(\n compileSteps(p.pipeline, { ...env, depth: env.depth + 1 }, (input as ListType).of),\n )\n return (list, ctx) => {\n const out: Val[] = []\n for (const [i, element] of (list as readonly Val[]).entries()) {\n const r = run(element, ctx)\n if (!r.ok)\n return err({\n code: r.error.code,\n detail: `element ${i}, ${r.error.op}: ${r.error.detail}`,\n })\n out.push(r.value as Val)\n }\n return ok(out)\n }\n },\n})\n\nexport const filterList = defineOp({\n name: 'filter_list',\n params: params({ cond: z.unknown() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p, env) => {\n const element = listIn(input, 'filter_list')\n if (!element.ok) return element\n const test = compilePredicate(p.cond, env, element.value)\n return test.ok ? ok(input) : test\n },\n run: (p, env, input) => {\n const test = expectOk(compilePredicate(p.cond, env, (input as ListType).of))\n return (list, ctx) => ok((list as readonly Val[]).filter((e) => test(e, ctx.record, ctx)))\n },\n})\n\nconst pick = (name: string, at: (length: number) => number) =>\n defineOp({\n name,\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, name)\n return element.ok ? ok(t.nullable(element.value)) : element\n },\n run: () => (list) => ok((list as readonly Val[])[at((list as readonly Val[]).length)] ?? null),\n })\n\nexport const first = pick('first', () => 0)\nexport const last = pick('last', (n) => n - 1)\n\n/** Element at `at`; a negative index counts from the end. Out of range gives null. */\nexport const index = defineOp({\n name: 'index',\n params: params({ at: z.number().int() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'index')\n return element.ok ? ok(t.nullable(element.value)) : element\n },\n run: (p) => (list) => ok((list as readonly Val[]).at(p.at) ?? null),\n})\n\n/** Length of a list, or of a string in code points. */\nexport const len = defineOp({\n name: 'len',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) =>\n input.kind === 'list' || input.kind === 'string'\n ? ok(t.number)\n : err(`len expects a list or string, got ${show(input)}`),\n run: () => (v) => ok(typeof v === 'string' ? Array.from(v).length : (v as readonly Val[]).length),\n})\n\n/** Drops repeated elements, keeping the first occurrence. */\nexport const unique = defineOp({\n name: 'unique',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'unique')\n return element.ok ? ok(input) : element\n },\n run: () => (list) => {\n const seen = new Set<string>()\n return ok(\n (list as readonly Val[]).filter((e) => {\n const k = canonicalKey(e)\n if (seen.has(k)) return false\n seen.add(k)\n return true\n }),\n )\n },\n})\n\n/** Null elements are skipped; an empty list gives null. */\nexport const sum = defineOp({\n name: 'sum',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, 'sum')\n if (!element.ok) return element\n return stripNull(element.value).kind === 'number'\n ? ok(t.nullable(t.number))\n : err(`sum expects list<number>, got ${show(input)}`)\n },\n // Sorted first, so floating-point results do not depend on element order.\n run: () => (list) => {\n const numbers = (list as readonly Val[])\n .filter((x): x is number => x !== null)\n .sort((a, b) => a - b)\n return ok(numbers.length === 0 ? null : numbers.reduce((a, b) => a + b, 0))\n },\n})\n\nconst extreme = (name: 'min' | 'max') =>\n defineOp({\n name,\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const element = listIn(input, name)\n if (!element.ok) return element\n return orderable(element.value)\n ? ok(t.nullable(stripNull(element.value)))\n : err(`${name} expects a list of numbers, strings or dates, got ${show(input)}`)\n },\n run: () => (list) => {\n let best: Val = null\n for (const x of list as readonly Val[]) {\n if (x === null) continue\n if (best === null || (name === 'min' ? compareVals(x, best) < 0 : compareVals(x, best) > 0))\n best = x\n }\n return ok(best)\n },\n })\n\nexport const min = extreme('min')\nexport const max = extreme('max')\n\n/** Membership of a literal, `{ ref }` or `{ param }` value. Null is never a member. */\nexport const contains = defineOp({\n name: 'contains',\n params: params({ value: z.unknown().refine((v) => v !== undefined, 'contains needs a value') }),\n nulls: 'propagate',\n fallible: never,\n signature: (input, p, env) => {\n const element = listIn(input, 'contains')\n if (!element.ok) return element\n const operand = compileOperand(p.value, env, stripNull(element.value).kind === 'date')\n if (!operand.ok) return operand\n return comparable(element.value, operand.value.type)\n ? ok(t.boolean)\n : err(`cannot look for ${show(operand.value.type)} in ${show(input)}`)\n },\n run: (p, env, input) => {\n const element = (input as ListType).of\n const { get } = expectOk(compileOperand(p.value, env, stripNull(element).kind === 'date'))\n return (list, ctx) => {\n const v = get(list, ctx.record, ctx)\n return ok(\n v !== null && (list as readonly Val[]).some((x) => x !== null && compareVals(x, v) === 0),\n )\n }\n },\n})\n","/** `lookup`: a static value map stored with the version, for enum and code translation. */\n\nimport { z } from 'zod'\nimport { err, expectOk, ok, stepError } from '../result'\nimport { comparable, show, t, typeOfJson, unify, unifyAll } from '../types'\nimport type { Json, Val } from '../values'\nimport { defineOp, params } from './def'\n\nconst SCALAR = new Set(['string', 'number', 'boolean'])\n\n/**\n * Translate a scalar through `tables[table]` (keys are the value's string form). `on_miss`:\n * `null` (default) yields null, `pass` forwards the input, `error` raises `lookup_miss`.\n */\nexport const lookup = defineOp({\n name: 'lookup',\n params: params({\n table: z.string().min(1),\n on_miss: z.enum(['null', 'pass', 'error']).optional(),\n }),\n nulls: 'propagate',\n fallible: (p) => p.on_miss === 'error',\n signature: (input, p, env) => {\n if (!SCALAR.has(input.kind))\n return err(`lookup expects a string, number or boolean, got ${show(input)}`)\n if (!Object.hasOwn(env.tables, p.table)) return err(`unknown lookup table '${p.table}'`)\n const values = Object.values(env.tables[p.table] as Record<string, Json>)\n const value = unifyAll(values.map(typeOfJson))\n if (!value.ok) return err(`lookup table '${p.table}' mixes value types: ${value.error}`)\n switch (p.on_miss ?? 'null') {\n case 'null':\n return ok(t.nullable(value.value))\n case 'error':\n return ok(value.value)\n default: {\n if (!comparable(input, value.value)) {\n return err(\n `on_miss \"pass\" forwards ${show(input)}, but the table yields ${show(value.value)}`,\n )\n }\n return ok(expectOk(unify(input, value.value)))\n }\n }\n },\n run: (p, env) => {\n const table = env.tables[p.table] as Readonly<Record<string, Json>>\n const miss = p.on_miss ?? 'null'\n return (input) => {\n const key = String(input as string | number | boolean)\n if (Object.hasOwn(table, key)) return ok(table[key] as Val)\n if (miss === 'error') return stepError('lookup_miss', `'${key}' is not in table '${p.table}'`)\n return ok(miss === 'pass' ? input : null)\n }\n },\n})\n","/** Null and blank handling: `blank_to_null`, `default`, `require`, `omit_if_null`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport { assignable, show, stripNull, t, typeOfJson } from '../types'\nimport { OMIT, type Val } from '../values'\nimport { always, defineOp, expectKind, json, never, params } from './def'\n\n/** An empty or whitespace-only string becomes null. */\nexport const blankToNull = defineOp({\n name: 'blank_to_null',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'blank_to_null')\n return s.ok ? ok(t.nullable(t.string)) : s\n },\n run: () => (input) => ok((input as string).trim() === '' ? null : input),\n})\n\n/** Replaces null with a literal of the input's type. */\nexport const defaultOp = defineOp({\n name: 'default',\n params: params({ value: json }),\n nulls: 'consume',\n fallible: never,\n signature: (input, p) => {\n if (p.value === null) return err('default needs a non-null value')\n const base = stripNull(input)\n const literal = typeOfJson(p.value)\n if (base.kind === 'unknown') return ok(literal)\n return assignable(literal, base)\n ? ok(base)\n : err(`default value is ${show(literal)}, input is ${show(input)}`)\n },\n run: (p) => {\n const value = p.value as Val\n return (input) => ok(input ?? value)\n },\n})\n\n/** Null triggers the node's `on_error` policy. */\nexport const requireOp = defineOp({\n name: 'require',\n params: params({ message: z.string().optional() }),\n nulls: 'consume',\n fallible: always,\n signature: (input) => ok(stripNull(input)),\n run: (p) => {\n const message = p.message ?? 'required value is null'\n return (input) => (input === null ? stepError('required_null', message) : ok(input))\n },\n})\n\n/**\n * Terminal. A null leaves the field out of the record (and so out of the write) instead of\n * setting it to null. Readers downstream see the field as nullable.\n */\nexport const omitIfNull = defineOp({\n name: 'omit_if_null',\n params: params({}),\n nulls: 'consume',\n terminal: true,\n fallible: never,\n signature: (input) => ok(t.nullable(stripNull(input))),\n run: () => (input) => ok(input === null ? OMIT : input),\n})\n","/**\n * The unit table behind `convert_unit`: mass, length and volume, each against one base unit.\n * Unit names are matched case-insensitively. Anything else, and any conversion across\n * dimensions, is unknown.\n */\n\ntype Dimension = 'mass' | 'length' | 'volume'\n\nconst UNITS: Readonly<Record<string, { readonly dimension: Dimension; readonly factor: number }>> =\n {\n // mass, in grams\n mg: { dimension: 'mass', factor: 0.001 },\n g: { dimension: 'mass', factor: 1 },\n kg: { dimension: 'mass', factor: 1000 },\n t: { dimension: 'mass', factor: 1_000_000 },\n oz: { dimension: 'mass', factor: 28.349523125 },\n lb: { dimension: 'mass', factor: 453.59237 },\n // length, in metres\n mm: { dimension: 'length', factor: 0.001 },\n cm: { dimension: 'length', factor: 0.01 },\n m: { dimension: 'length', factor: 1 },\n km: { dimension: 'length', factor: 1000 },\n in: { dimension: 'length', factor: 0.0254 },\n ft: { dimension: 'length', factor: 0.3048 },\n // volume, in litres\n ml: { dimension: 'volume', factor: 0.001 },\n l: { dimension: 'volume', factor: 1 },\n m3: { dimension: 'volume', factor: 1000 },\n }\n\nconst unit = (name: string) => UNITS[name.trim().toLowerCase()]\n\nexport function isUnit(name: string): boolean {\n return unit(name) !== undefined\n}\n\n/** Multiply by this to convert `from` into `to`; undefined if unknown or across dimensions. */\nexport function conversionFactor(from: string, to: string): number | undefined {\n const a = unit(from)\n const b = unit(to)\n if (!a || !b || a.dimension !== b.dimension) return undefined\n // Divide instead of multiplying by a reciprocal, so kg -> g is exactly 1000.\n return a.factor / b.factor\n}\n","/** Numeric ops: `add`, `subtract`, `multiply`, `divide`, `round`, `abs`, `clamp`, `convert_unit`. */\n\nimport { z } from 'zod'\nimport { err, ok, stepError } from '../result'\nimport { isNullable, type MType, nullableIf, show, stripNull, t } from '../types'\nimport { conversionFactor, isUnit } from '../units'\nimport { defineOp, expectKind, never, params } from './def'\n\n// Zod 4 numbers are finite: Infinity and NaN are rejected.\nconst finite = z.number()\n\nconst numberIn = (op: string) => (input: MType) => {\n const s = expectKind(input, ['number'], op)\n return s.ok ? ok(t.number) : s\n}\n\nconst arithmetic = <K extends string>(\n name: string,\n key: K,\n apply: (a: number, b: number) => number,\n) =>\n defineOp({\n name,\n params: params({ [key]: finite } as { [P in K]: typeof finite }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn(name),\n run: (p) => {\n const operand = (p as Record<K, number>)[key]\n return (input) => ok(apply(input as number, operand))\n },\n })\n\nexport const add = arithmetic('add', 'value', (a, b) => a + b)\nexport const subtract = arithmetic('subtract', 'value', (a, b) => a - b)\nexport const multiply = arithmetic('multiply', 'by', (a, b) => a * b)\n\n/** `by: 0` is rejected when the version is saved, never at runtime. */\nexport const divide = defineOp({\n name: 'divide',\n params: params({ by: finite.refine((n) => n !== 0, 'divide by zero') }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('divide'),\n run: (p) => (input) => ok((input as number) / p.by),\n})\n\n/** Shift the decimal point by `places` without floating-point drift (1.005 stays 1.005). */\nfunction shiftDecimal(n: number, places: number): number {\n const [mantissa, exponent = '0'] = String(n).split('e')\n return Number(`${mantissa}e${Number(exponent) + places}`)\n}\n\ntype RoundMode = 'half_up' | 'half_even' | 'floor' | 'ceil'\n\nfunction roundScaled(x: number, mode: RoundMode): number {\n switch (mode) {\n case 'floor':\n return Math.floor(x)\n case 'ceil':\n return Math.ceil(x)\n case 'half_up':\n return Math.sign(x) * Math.round(Math.abs(x))\n case 'half_even': {\n const a = Math.abs(x)\n const floor = Math.floor(a)\n const diff = a - floor\n const r = diff > 0.5 || (diff === 0.5 && floor % 2 === 1) ? floor + 1 : floor\n return Math.sign(x) * r\n }\n }\n}\n\n/** Round to `precision` decimals. `half_up` rounds halves away from zero. */\nexport const round = defineOp({\n name: 'round',\n params: params({\n precision: z.number().int().min(0).max(15).optional(),\n mode: z.enum(['half_up', 'half_even', 'floor', 'ceil']).optional(),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('round'),\n run: (p) => {\n const precision = p.precision ?? 0\n const mode = p.mode ?? 'half_up'\n // The final shift goes through String(), which also turns -0 into 0.\n return (input) =>\n ok(shiftDecimal(roundScaled(shiftDecimal(input as number, precision), mode), -precision))\n },\n})\n\nexport const abs = defineOp({\n name: 'abs',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('abs'),\n run: () => (input) => ok(Math.abs(input as number)),\n})\n\nexport const clamp = defineOp({\n name: 'clamp',\n params: params({ min: finite.optional(), max: finite.optional() })\n .refine((p) => p.min !== undefined || p.max !== undefined, 'clamp needs min or max')\n .refine(\n (p) => p.min === undefined || p.max === undefined || p.min <= p.max,\n 'min is above max',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: numberIn('clamp'),\n run: (p) => {\n const min = p.min ?? -Infinity\n const max = p.max ?? Infinity\n return (input) => ok(Math.min(max, Math.max(min, input as number)))\n },\n})\n\nconst unitName = z.string().refine(isUnit, 'unknown unit')\n\n/**\n * Convert over the unit table. The source unit is `from`, or the second element of an\n * extracted `(value, unit)` tuple. With a static `from` the conversion is checked at save\n * and cannot fail; with a unit read from the record an unknown unit raises.\n */\nexport const convertUnit = defineOp({\n name: 'convert_unit',\n params: params({ to: unitName, from: unitName.optional() }).refine(\n (p) =>\n p.from === undefined ||\n !isUnit(p.from) ||\n !isUnit(p.to) ||\n conversionFactor(p.from, p.to) !== undefined,\n 'from and to measure different things',\n ),\n nulls: 'propagate',\n fallible: (p) => p.from === undefined,\n signature: (input, p) => {\n if (input.kind === 'tuple') {\n if (p.from !== undefined)\n return err('convert_unit takes a unit from the record or from \"from\", not both')\n const [value, unit] = input.of as readonly [MType, MType]\n const pair =\n input.of.length === 2 &&\n stripNull(value).kind === 'number' &&\n stripNull(unit).kind === 'string'\n if (!pair) return err(`convert_unit expects (number, string), got ${show(input)}`)\n return ok(nullableIf(t.number, isNullable(value)))\n }\n if (p.from === undefined) return err('convert_unit needs a unit input or a \"from\" param')\n return numberIn('convert_unit')(input)\n },\n run: (p, _env, input) => {\n const to = p.to\n if (input.kind !== 'tuple') {\n const factor = conversionFactor(p.from as string, to) as number\n return (v) => ok((v as number) * factor)\n }\n return (v) => {\n const [value, from] = v as readonly [number | null, string | null]\n if (value === null) return ok(null)\n if (from === null) return stepError('unknown_unit', `no unit given for ${value}`)\n const factor = conversionFactor(from, to)\n return factor === undefined\n ? stepError('unknown_unit', `cannot convert ${from} to ${to}`)\n : ok(value * factor)\n }\n },\n})\n","/**\n * String ops: `trim`, `lower`, `upper`, `truncate`, `pad`, `replace`, `regex_extract`,\n * `split`, `join`, `concat`, `slug`. Lengths count code points, not UTF-16 units.\n */\n\nimport { z } from 'zod'\nimport { compileRegex } from '../predicate'\nimport { err, ok } from '../result'\nimport { type MType, show, stripNull, t } from '../types'\nimport type { Val } from '../values'\nimport { defineOp, expectKind, never, params } from './def'\n\nconst stringIn = (op: string) => (input: MType) => {\n const s = expectKind(input, ['string'], op)\n return s.ok ? ok(t.string) : s\n}\n\nconst regex = z.string().superRefine((s, ctx) => {\n const r = compileRegex(s)\n if (!r.ok) ctx.addIssue({ code: 'custom', message: r.error })\n})\n\nconst escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\nexport const trim = defineOp({\n name: 'trim',\n params: params({ chars: z.string().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('trim'),\n run: (p) => {\n if (p.chars === undefined) return (input) => ok((input as string).trim())\n const set = `[${p.chars.replace(/[\\\\\\]^-]/g, '\\\\$&')}]+`\n const edges = new RegExp(`^${set}|${set}$`, 'gu')\n return (input) => ok((input as string).replace(edges, ''))\n },\n})\n\nexport const lower = defineOp({\n name: 'lower',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('lower'),\n run: () => (input) => ok((input as string).toLowerCase()),\n})\n\nexport const upper = defineOp({\n name: 'upper',\n params: params({}),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('upper'),\n run: () => (input) => ok((input as string).toUpperCase()),\n})\n\n/** Lossy, no inverse. With `ellipsis` the result, ellipsis included, fits `length`. */\nexport const truncate = defineOp({\n name: 'truncate',\n params: params({ length: z.number().int().min(0), ellipsis: z.boolean().optional() }).refine(\n (p) => !p.ellipsis || p.length >= 1,\n 'truncate with ellipsis needs length >= 1',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('truncate'),\n run: (p) => (input) => {\n const chars = Array.from(input as string)\n if (chars.length <= p.length) return ok(input)\n return ok(\n p.ellipsis ? `${chars.slice(0, p.length - 1).join('')}…` : chars.slice(0, p.length).join(''),\n )\n },\n})\n\n/** Fixed-width codes, zero-padded SKUs. Strings already as long are unchanged. */\nexport const pad = defineOp({\n name: 'pad',\n params: params({\n length: z.number().int().min(1),\n with: z.string().min(1),\n side: z.enum(['left', 'right']),\n }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('pad'),\n run: (p) => (input) => {\n const s = input as string\n return ok(p.side === 'left' ? s.padStart(p.length, p.with) : s.padEnd(p.length, p.with))\n },\n})\n\n/** Replace every occurrence; `regex: true` treats `pattern` as a regular expression. */\nexport const replace = defineOp({\n name: 'replace',\n params: params({\n pattern: z.string().min(1),\n with: z.string(),\n regex: z.boolean().optional(),\n }).superRefine((p, ctx) => {\n if (!p.regex || typeof p.pattern !== 'string') return\n const r = compileRegex(p.pattern)\n if (!r.ok) ctx.addIssue({ code: 'custom', path: ['pattern'], message: r.error })\n }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('replace'),\n run: (p) => {\n const pattern = new RegExp(p.regex ? p.pattern : escapeRegex(p.pattern), 'gu')\n // Literal replacement: `$` in `with` has no special meaning.\n return (input) => ok((input as string).replace(pattern, () => p.with))\n },\n})\n\nfunction groupCount(pattern: string): number {\n return (new RegExp(`${pattern}|`, 'u').exec('') as RegExpExecArray).length - 1\n}\n\n/** The match (or capture `group`) of the first match; no match gives null. */\nexport const regexExtract = defineOp({\n name: 'regex_extract',\n params: params({ pattern: regex, group: z.number().int().min(0).optional() }).refine(\n (p) => !compileRegex(p.pattern).ok || (p.group ?? 0) <= groupCount(p.pattern),\n 'group is larger than the number of capture groups',\n ),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'regex_extract')\n return s.ok ? ok(t.nullable(t.string)) : s\n },\n run: (p) => {\n const re = new RegExp(p.pattern, 'u')\n const group = p.group ?? 0\n return (input) => ok(re.exec(input as string)?.[group] ?? null)\n },\n})\n\n/** Split on a separator. With `limit`, at most that many parts; the last keeps the rest. */\nexport const split = defineOp({\n name: 'split',\n params: params({ separator: z.string().min(1), limit: z.number().int().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n const s = expectKind(input, ['string'], 'split')\n return s.ok ? ok(t.list(t.string)) : s\n },\n run: (p) => (input) => {\n const parts = (input as string).split(p.separator)\n if (p.limit === undefined || parts.length <= p.limit) return ok(parts)\n return ok([...parts.slice(0, p.limit - 1), parts.slice(p.limit - 1).join(p.separator)])\n },\n})\n\n/** String join of a list; null elements are skipped. Unrelated to the `join` node. */\nexport const join = defineOp({\n name: 'join',\n params: params({ separator: z.string() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n if (input.kind !== 'list' || stripNull(input.of).kind !== 'string') {\n return err(`join expects list<string>, got ${show(input)}`)\n }\n return ok(t.string)\n },\n run: (p) => (input) =>\n ok((input as readonly (string | null)[]).filter((x) => x !== null).join(p.separator)),\n})\n\nconst SCALAR = new Set(['string', 'number', 'boolean'])\n\n/** Join the parts of a multi-path `extract`; null parts are skipped. */\nexport const concat = defineOp({\n name: 'concat',\n params: params({ separator: z.string().optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: (input) => {\n if (input.kind !== 'tuple' || !input.of.every((x) => SCALAR.has(stripNull(x).kind))) {\n return err(`concat expects a tuple of strings, numbers or booleans, got ${show(input)}`)\n }\n return ok(t.string)\n },\n run: (p) => (input) =>\n ok(\n (input as readonly Val[])\n .filter((x) => x !== null)\n .map((x) => String(x as string | number | boolean))\n .join(p.separator ?? ''),\n ),\n})\n\n/** URL-safe form: ASCII letters and digits, lowercase, runs of anything else to `separator`. */\nexport const slug = defineOp({\n name: 'slug',\n params: params({ separator: z.string().min(1).optional() }),\n nulls: 'propagate',\n fallible: never,\n signature: stringIn('slug'),\n run: (p) => {\n const sep = p.separator ?? '-'\n return (input) =>\n ok(\n (input as string)\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((x) => x !== '')\n .join(sep),\n )\n },\n})\n","/**\n * `when`: the one general conditional. First matching case wins;\n * `then` and `else` are a literal, `null`, or `{ \"pass\": true }` to forward the input. `else`\n * defaults to pass-through. As a pipeline's first step there is no input: every case must\n * test a `path`, and `else` is required.\n */\n\nimport { z } from 'zod'\nimport { compilePredicate } from '../predicate'\nimport { err, expectOk, ok, type Result } from '../result'\nimport { type MType, show, typeOfJson, unifyAll } from '../types'\nimport type { Json, Val } from '../values'\nimport { defineOp, json, never, params } from './def'\n\nconst pass = z.strictObject({ pass: z.literal(true) })\nconst scalar = z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(json)])\nconst branch = z.union([pass, scalar])\n\ntype Branch = z.infer<typeof branch>\n\nconst isPass = (b: Branch): b is { pass: true } =>\n typeof b === 'object' && b !== null && !Array.isArray(b)\n\nexport const when = defineOp({\n name: 'when',\n params: params({\n cases: z.array(z.strictObject({ cond: z.unknown(), then: branch })).min(1),\n else: branch.optional(),\n }),\n nulls: 'consume',\n input: 'any',\n fallible: never,\n signature: (input, p, env): Result<MType, string> => {\n const first = input.kind === 'unit'\n const branches = [...p.cases.map((c) => c.then), ...(p.else === undefined ? [] : [p.else])]\n if (first && p.else === undefined) return err('when as the first step needs an \"else\"')\n if (first && branches.some(isPass)) return err('when as the first step has no input to pass')\n for (const [i, c] of p.cases.entries()) {\n const test = compilePredicate(c.cond, env, input)\n if (!test.ok) return err(`case ${i}: ${test.error}`)\n }\n const types = branches.map((b) => (isPass(b) ? input : typeOfJson(b)))\n if (p.else === undefined) types.push(input)\n const out = unifyAll(types)\n return out.ok ? out : err(`when branches disagree: ${types.map(show).join(', ')}`)\n },\n run: (p, env, input) => {\n const cases = p.cases.map((c) => ({\n test: expectOk(compilePredicate(c.cond, env, input)),\n then: c.then,\n }))\n const otherwise = p.else ?? { pass: true as const }\n const resolve = (b: Branch, v: Val): Val => (isPass(b) ? v : (b as Json as Val))\n return (v, ctx) => {\n for (const c of cases) if (c.test(v, ctx.record, ctx)) return ok(resolve(c.then, v))\n return ok(resolve(otherwise, v))\n }\n },\n})\n","/** The record op registry: every op a `map` field pipeline may use, by name. */\n\nimport { coalesce, constant, extract } from './access'\nimport { assertType, toBool, toDate, toNumber, toString } from './convert'\nimport { formatDateOp, shiftDate, toUtc, truncateDate } from './date'\nimport type { OpDef } from './def'\nimport { fn } from './fn'\nimport { contains, each, filterList, first, index, last, len, max, min, sum, unique } from './list'\nimport { lookup } from './lookup'\nimport { blankToNull, defaultOp, omitIfNull, requireOp } from './nulls'\nimport { abs, add, clamp, convertUnit, divide, multiply, round, subtract } from './numeric'\nimport {\n concat,\n join,\n lower,\n pad,\n regexExtract,\n replace,\n slug,\n split,\n trim,\n truncate,\n upper,\n} from './string'\nimport { when } from './when'\n\nexport type { OpDef, Step, StepResult } from './def'\nexport { defineOp } from './def'\n\nconst all = [\n extract,\n constant,\n coalesce,\n blankToNull,\n defaultOp,\n requireOp,\n omitIfNull,\n toNumber,\n toString,\n toBool,\n toDate,\n assertType,\n add,\n subtract,\n multiply,\n divide,\n round,\n abs,\n clamp,\n convertUnit,\n trim,\n lower,\n upper,\n truncate,\n pad,\n replace,\n regexExtract,\n split,\n join,\n concat,\n slug,\n formatDateOp,\n shiftDate,\n truncateDate,\n toUtc,\n when,\n each,\n filterList,\n index,\n first,\n last,\n len,\n unique,\n sum,\n min,\n max,\n contains,\n lookup,\n fn,\n]\n\nexport const opRegistry: Readonly<Record<string, OpDef<unknown>>> = Object.fromEntries(\n all.map((op) => [op.name, op as unknown as OpDef<unknown>]),\n)\n","/**\n * Sugar, kept for readability and expanded on save.\n *\n * - `{ op: \"if_<predicate>\", <operand>, then, else? }` expands to a one-case `when`, e.g.\n * `{ op: \"if_lte\", value: 0, then: null }` to\n * `{ op: \"when\", cases: [{ cond: { lte: 0 }, then: null }] }`.\n * - `{ op: \"lookup_entity\", entity, by, field, on_miss? }` expands into a `source` for the\n * internal entity, an `n:1` left `join` on `by`, and an `extract` of `field` (see\n * `normalizeVersion`).\n */\n\nimport { z } from 'zod'\nimport type { GraphEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { entityJsonSchema } from './jsonschema'\nimport { PREDICATES } from './predicate'\nimport { type CompileIssue, err, ok, type Result } from './result'\n\nconst OPERAND_KEYS = ['value', 'values', 'date', 'pattern'] as const\nconst SUGAR_PREDICATES = new Set<string>(\n PREDICATES.filter((p) => !['all', 'any', 'not'].includes(p)),\n)\n\nexport type StepJson = { readonly op: string } & { readonly [key: string]: unknown }\n\n/** Expand one step if it is sugar; other steps pass through unchanged. */\nexport function expandStep(raw: StepJson): Result<StepJson, string> {\n const m = /^if_(.+)$/.exec(raw.op)\n if (!m) return ok(raw)\n const predicate = m[1] as string\n if (!SUGAR_PREDICATES.has(predicate)) return err(`unknown op '${raw.op}'`)\n const { op: _op, then, else: otherwise, path, ...rest } = raw\n if (!('then' in raw)) return err(`${raw.op} needs \"then\"`)\n\n const extra = Object.keys(rest).filter((k) => !(OPERAND_KEYS as readonly string[]).includes(k))\n if (extra.length) return err(`${raw.op} does not take ${extra.join(', ')}`)\n const given = OPERAND_KEYS.filter((k) => k in rest)\n const presence = predicate === 'is_null' || predicate === 'is_blank'\n if (presence ? given.length > 0 : given.length !== 1) {\n return err(\n presence\n ? `${raw.op} takes no comparison value`\n : `${raw.op} takes exactly one of ${OPERAND_KEYS.join(', ')}`,\n )\n }\n const operand = presence ? true : rest[given[0] as string]\n const cond = { ...(path === undefined ? {} : { path }), [predicate]: operand }\n return ok({\n op: 'when',\n cases: [{ cond, then }],\n ...(otherwise === undefined ? {} : { else: otherwise }),\n })\n}\n\nconst LookupEntity = z.strictObject({\n op: z.literal('lookup_entity'),\n entity: z.string().min(1),\n by: z.string().min(1),\n field: z.string().min(1).default('id'),\n on_miss: z.enum(['null', 'pass', 'error']).optional(),\n})\n\nconst isStep = (v: unknown): v is StepJson =>\n typeof v === 'object' && v !== null && typeof (v as StepJson).op === 'string'\n\n/** Expand `if_*` steps (also inside `each`); report `lookup_entity` where it cannot go. */\nfunction expandPipeline(\n steps: readonly unknown[],\n nested: boolean,\n issue: (message: string, step: number) => void,\n): unknown[] {\n return steps.map((step, i) => {\n if (!isStep(step)) return step\n if (nested && step.op === 'lookup_entity') {\n issue('lookup_entity cannot be used inside each', i)\n return step\n }\n if (step.op === 'each' && Array.isArray(step.pipeline)) {\n return {\n ...step,\n pipeline: expandPipeline(step.pipeline, true, (m) => issue(`each: ${m}`, i)),\n }\n }\n const expanded = expandStep(step)\n if (expanded.ok) return expanded.value\n issue(expanded.error, i)\n return step\n })\n}\n\ninterface Rewrite {\n readonly generated: NodeJson[]\n readonly node: NodeJson\n}\n\n/** Rewrite the `lookup_entity` steps of one map node into generated nodes. */\nfunction rewriteLookups(\n node: NodeJson,\n env: Pick<GraphEnv, 'targets'>,\n sources: Set<string>,\n issues: CompileIssue[],\n): Rewrite {\n const generated: NodeJson[] = []\n let input = node.in\n const drop = Array.isArray(node.drop) ? [...(node.drop as string[])] : []\n let n = 0\n const fields = (node.fields as unknown[]).map((raw) => {\n const f = raw as { key?: unknown; pipeline?: unknown }\n if (typeof f !== 'object' || f === null || !Array.isArray(f.pipeline)) return raw\n const key = String(f.key)\n const issue = (message: string, step: number) =>\n issues.push({ code: 'invalid_params', message, node: node.id, field: key, step })\n const pipeline = expandPipeline(f.pipeline, false, issue)\n const at = pipeline.findIndex((s) => isStep(s) && s.op === 'lookup_entity')\n if (at < 0) return { ...f, pipeline }\n if (pipeline.findLastIndex((s) => isStep(s) && s.op === 'lookup_entity') !== at) {\n issue('use one lookup_entity per field; resolve the others in an upstream map', at)\n return { ...f, pipeline }\n }\n const parsed = LookupEntity.safeParse(pipeline[at])\n if (!parsed.success) {\n issue(\n `lookup_entity: ${parsed.error.issues.map((x) => `${x.path.join('.')}: ${x.message}`).join('; ')}`,\n at,\n )\n return { ...f, pipeline }\n }\n if (at === 0) {\n issue('lookup_entity needs a key; extract it first', at)\n return { ...f, pipeline }\n }\n const { entity, by, field, on_miss: onMiss } = parsed.data\n if (!env.targets.entities.some((e) => e.name === entity)) {\n issue(`lookup_entity: unknown entity '${entity}'`, at)\n return { ...f, pipeline }\n }\n n += 1\n const prefix = pipeline.slice(0, at) as StepJson[]\n const only = prefix[0] as StepJson\n let keyField: string\n if (prefix.length === 1 && only.op === 'extract' && typeof only.path === 'string') {\n keyField = only.path\n } else {\n // A computed key is materialised as a field of a preceding map first.\n keyField = `__${key}__key`\n const helper: NodeJson = {\n id: `${node.id}__key${n}`,\n op: 'map',\n in: input,\n keep: 'all',\n fields: [{ key: keyField, pipeline: prefix }],\n ...(node.on_error === undefined ? {} : { on_error: node.on_error }),\n }\n generated.push(helper)\n input = helper.id\n drop.push(keyField)\n }\n const source = `__internal_${entity}`\n if (!sources.has(source)) {\n sources.add(source)\n generated.push({ id: source, op: 'source', system: 'internal', entity })\n }\n const valueField = `__${key}__lookup`\n const join: NodeJson = {\n id: `${node.id}__lookup${n}`,\n op: 'join',\n left: input,\n right: source,\n on: [[keyField, by]],\n type: 'left',\n cardinality: 'n:1',\n select: { [field]: valueField },\n tolerate_skips: true,\n }\n generated.push(join)\n input = join.id\n drop.push(valueField)\n const head: StepJson[] =\n onMiss === 'pass'\n ? [{ op: 'coalesce', paths: [valueField, keyField] }]\n : onMiss === 'error'\n ? [\n { op: 'extract', path: valueField },\n { op: 'require', message: `no ${entity} with ${by} equal to the key` },\n ]\n : [{ op: 'extract', path: valueField }]\n return { ...f, pipeline: [...head, ...pipeline.slice(at + 1)] }\n })\n if (n === 0) return { generated, node: { ...node, fields } }\n const keepAll = node.keep === 'all'\n return {\n generated,\n node: { ...node, in: input, fields, ...(keepAll ? { drop } : {}) },\n }\n}\n\n/**\n * The form a version is stored and compiled in: sugar expanded, `lookup_entity` rewritten\n * into graph nodes, and every internal source's schema pinned from the target model.\n * Idempotent.\n */\nexport function normalizeVersion(\n version: MappingVersion,\n env: Pick<GraphEnv, 'targets'>,\n): { version: MappingVersion; issues: CompileIssue[] } {\n const issues: CompileIssue[] = []\n const sources = new Set(version.nodes.filter((n) => n.op === 'source').map((n) => n.id))\n const nodes: NodeJson[] = []\n for (const node of version.nodes) {\n if (node.op !== 'map' || !Array.isArray(node.fields)) {\n nodes.push(node)\n continue\n }\n const rewrite = rewriteLookups(node, env, sources, issues)\n nodes.push(...rewrite.generated, rewrite.node)\n }\n const expectedSchema = { ...version.expectedSchema }\n for (const node of nodes) {\n if (node.op !== 'source' || node.system !== 'internal' || expectedSchema[node.id]) continue\n const entity = env.targets.entities.find((e) => e.name === node.entity)\n if (entity) expectedSchema[node.id] = entityJsonSchema(entity)\n }\n return { version: { ...version, nodes, expectedSchema }, issues }\n}\n","/**\n * The step compiler (arch.md, \"Type checking\"): a fold over the steps of one field pipeline\n * that threads a value type and a closure. Nullability is lifted here, so an op marked\n * `nulls: 'propagate'` never sees null: a null input skips it and stays null.\n */\n\nimport type { RecordContext, RecordEnv } from './context'\nimport { opRegistry } from './ops'\nimport type { Step } from './ops/def'\nimport { err, ok, type Result, type StepError } from './result'\nimport { expandStep, type StepJson } from './sugar'\nimport { mayBeNull, type MType, stripNull, t } from './types'\nimport type { Omitted, Val } from './values'\n\nexport interface PipelineError extends StepError {\n readonly step: number\n readonly op: string\n}\n\nexport interface CompiledPipeline {\n readonly type: MType\n /** Can return an error at runtime. */\n readonly fallible: boolean\n /** Ends in `omit_if_null`: the field may be left out of the record. */\n readonly omittable: boolean\n readonly run: (input: Val, ctx: RecordContext) => Result<Val | Omitted, PipelineError>\n}\n\nexport interface StepIssue {\n readonly step: number\n readonly message: string\n}\n\nconst NULL_RESULT = ok(null)\n\n/** Compile a pipeline. Top-level pipelines start from `t.unit`; `each` passes the element type. */\nexport function compileSteps(\n raw: readonly unknown[],\n env: RecordEnv,\n input: MType = t.unit,\n): Result<CompiledPipeline, StepIssue> {\n if (raw.length === 0) return err({ step: 0, message: 'a pipeline needs at least one step' })\n\n let type = input\n let fallible = false\n let omittable = false\n const steps: Step[] = []\n const names: string[] = []\n\n for (const [i, value] of raw.entries()) {\n const issue = (message: string) => err({ step: i, message })\n if (typeof value !== 'object' || value === null || typeof (value as StepJson).op !== 'string') {\n return issue('a step is an object with an \"op\"')\n }\n const expanded = expandStep(value as StepJson)\n if (!expanded.ok) return issue(expanded.error)\n const { op, ...rest } = expanded.value\n const def = Object.hasOwn(opRegistry, op) ? opRegistry[op] : undefined\n if (!def) return issue(`unknown op '${op}'`)\n if (omittable) return issue(`${names.at(-1)} must be the last step`)\n\n const params = def.params.safeParse(rest)\n if (!params.success) {\n return issue(\n `${op}: ${params.error.issues.map((x) => `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`).join('; ')}`,\n )\n }\n\n const mode = def.input ?? 'value'\n if (mode === 'none' && type.kind !== 'unit') {\n return issue(`${op} starts a pipeline; it cannot follow another step`)\n }\n if (mode === 'value' && type.kind === 'unit') {\n return issue(`${op} needs an input; start the pipeline with extract, const, coalesce or when`)\n }\n\n // Nullability is lifted here, so the op only ever sees a non-null input.\n const propagate = def.nulls === 'propagate'\n const lifted = propagate && mayBeNull(type)\n const inner = propagate ? stripNull(type) : type\n if (inner.kind === 'never') return issue(`${op} receives only null; nothing to do`)\n\n const out = def.signature(inner, params.data, env)\n if (!out.ok) return issue(out.error)\n\n const bound = def.run(params.data, env, inner)\n steps.push(lifted ? (v, ctx) => (v === null ? NULL_RESULT : bound(v, ctx)) : bound)\n names.push(op)\n type = lifted ? t.nullable(out.value) : out.value\n fallible ||= def.fallible(params.data, env, inner)\n omittable = def.terminal === true\n }\n\n return ok({\n type,\n fallible,\n omittable,\n run: (input, ctx) => {\n let v: Val | Omitted = input\n for (let i = 0; i < steps.length; i++) {\n const r = (steps[i] as Step)(v as Val, ctx)\n if (!r.ok) return err({ ...r.error, step: i, op: names[i] as string })\n v = r.value\n }\n return ok(v)\n },\n })\n}\n","/**\n * `map`: where the scopes meet. Splits a collection into records, runs one field pipeline per\n * target field with the record as the `extract` scope, and collects the results.\n *\n * `keep: \"all\"` passes the input fields through alongside the new ones, except those listed in\n * `drop` (the `lookup_entity` rewrite drops its helper fields that way). A failing field\n * applies `on_error`:\n * `null` writes null, `skip_field` leaves the field out, `skip_record` (default) drops the\n * record, `fail_sync` fails the node and stops the run.\n */\n\nimport { z } from 'zod'\nimport { OnError } from '../document'\nimport { type CompiledPipeline, compileSteps } from '../pipeline'\nimport { err, ok } from '../result'\nimport { type MType, stripNull, t } from '../types'\nimport { OMIT, type Rec, type Val } from '../values'\nimport { defineNode, nodeId, type NodeIssue, type Origin, type RunIssue } from './def'\n\nconst field = z.strictObject({ key: z.string().min(1), pipeline: z.array(z.unknown()).min(1) })\n\nconst params = z.strictObject({\n in: nodeId,\n fields: z.array(field).min(1),\n keep: z.enum(['none', 'all']).optional(),\n drop: z.array(z.string().min(1)).optional(),\n on_error: OnError.optional(),\n})\n\nconst SAMPLES = 5\n\nexport const mapNode = defineNode({\n op: 'map',\n label: 'Map fields',\n category: 'transform',\n description: 'One output field per pipeline, computed from each input record.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: true,\n defaults: () => ({ in: '', fields: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const renv = env.recordEnv(input.type)\n const policy = p.on_error ?? env.version.onError ?? 'skip_record'\n const issues: NodeIssue[] = []\n\n const drop = new Set(p.drop ?? [])\n if (drop.size > 0 && p.keep !== 'all')\n issues.push({ message: 'drop applies only with keep: \"all\"' })\n for (const name of drop) {\n if (!Object.hasOwn(input.type.fields, name))\n issues.push({ message: `drop: unknown field '${name}'` })\n }\n const keep = p.keep === 'all' ? Object.keys(input.type.fields).filter((f) => !drop.has(f)) : []\n\n const seen = new Set<string>()\n const compiled: { key: string; pipeline: CompiledPipeline }[] = []\n for (const f of p.fields) {\n if (seen.has(f.key))\n issues.push({ message: `field '${f.key}' is defined twice`, field: f.key })\n seen.add(f.key)\n const c = compileSteps(f.pipeline, renv)\n if (c.ok) compiled.push({ key: f.key, pipeline: c.value })\n else issues.push({ message: c.error.message, field: f.key, step: c.error.step })\n }\n if (issues.length) return { ok: false, error: issues }\n\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const name of keep) {\n fields[name] = input.type.fields[name] as MType\n origins[name] = input.origins[name] as Origin\n }\n for (const { key, pipeline } of compiled) {\n const soft = pipeline.fallible && (policy === 'null' || policy === 'skip_field')\n const omittable = pipeline.omittable || (pipeline.fallible && policy === 'skip_field')\n fields[key] = soft ? t.nullable(pipeline.type) : pipeline.type\n origins[key] = {\n node: env.id,\n field: key,\n omittable,\n ...(omittable\n ? { present: pipeline.omittable ? stripNull(pipeline.type) : pipeline.type }\n : {}),\n }\n }\n\n return ok({\n output: {\n type: t.record(fields),\n origins,\n canSkip: policy === 'skip_record' && compiled.some((c) => c.pipeline.fallible),\n },\n run: (inputs, ctx) => {\n const errors = new Map<\n string,\n { field: string; code: string; count: number; samples: string[] }\n >()\n const rows: Rec[] = []\n let skipped = 0\n for (const record of inputs(p.in)) {\n const rc = { ...ctx, record }\n const out: Record<string, Val> = {}\n for (const name of keep) if (Object.hasOwn(record, name)) out[name] = record[name] as Val\n let drop = false\n for (const { key, pipeline } of compiled) {\n const r = pipeline.run(null, rc)\n if (r.ok) {\n if (r.value === OMIT) delete out[key]\n else out[key] = r.value\n continue\n }\n const detail = `step ${r.error.step} ${r.error.op}: ${r.error.detail}`\n if (policy === 'fail_sync') {\n return err({ code: r.error.code, message: `${key} ${detail}`, stop: true })\n }\n const k = `${key}\\u0000${r.error.code}`\n const e = errors.get(k) ?? { field: key, code: r.error.code, count: 0, samples: [] }\n e.count += 1\n if (e.samples.length < SAMPLES) e.samples.push(detail)\n errors.set(k, e)\n if (policy === 'null') out[key] = null\n else if (policy === 'skip_field') delete out[key]\n else {\n drop = true\n break\n }\n }\n if (drop) skipped += 1\n else rows.push(out)\n }\n const issues: RunIssue[] = [...errors.values()].map((e) => ({\n node: env.id,\n code: e.code,\n field: e.field,\n message: `${e.field}: ${e.count} records failed (${policy})`,\n count: e.count,\n samples: e.samples,\n }))\n return ok({ rows, skipped, issues })\n },\n })\n },\n})\n","/**\n * `metrics`: writes a small relation, such as counters, onto the sync run rather than into the\n * domain. Never held back by any check: it describes the run, and matters most when a run\n * is stopped.\n *\n * `count_by` reports one row per distinct combination of those fields with its number of\n * `rows`, the usual counter, so it needs no `aggregate` in front. The reported relation is the\n * node's output for `expect` (a `keyed` bound alerts on one counter); nothing reads it.\n */\n\nimport { z } from 'zod'\nimport { ok } from '../result'\nimport { type MType, t } from '../types'\nimport { type Json, keyOf, type Rec, sortRecords, toJson } from '../values'\nimport { defineNode, fail, nodeId, type Origin, ownOrigins } from './def'\n\nconst params = z.strictObject({\n in: nodeId,\n name: z.string().min(1),\n count_by: z.array(z.string().min(1)).min(1).optional(),\n})\n\n/** The count field `count_by` adds next to the group fields. */\nconst COUNT = 'rows'\n\nexport const metricsNode = defineNode({\n op: 'metrics',\n label: 'Run metrics',\n category: 'target',\n description: 'Reports a small relation (counters) on the run instead of the domain.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: false,\n effect: 'metrics',\n defaults: () => ({ in: '', name: '' }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const by = p.count_by\n if (!by) {\n return ok({\n output: input,\n run: (inputs) => {\n const rows = sortRecords(inputs(p.in), [])\n return ok({ rows, metric: metric(env.id, p.name, rows) })\n },\n })\n }\n const unknown = by.filter((f) => !Object.hasOwn(input.type.fields, f))\n if (unknown.length) return fail(`count_by: unknown fields: ${unknown.join(', ')}`)\n if (by.includes(COUNT)) return fail(`count_by: '${COUNT}' is the count field; rename it first`)\n const fields: Record<string, MType> = Object.fromEntries(\n by.map((f) => [f, input.type.fields[f] as MType]),\n )\n const type = t.record({ ...fields, [COUNT]: t.number })\n return ok({\n output: {\n type,\n origins: {\n ...ownOrigins(env.id, type),\n ...Object.fromEntries(by.map((f) => [f, input.origins[f] as Origin])),\n },\n },\n run: (inputs) => {\n const groups = new Map<string, { first: Rec; n: number }>()\n for (const row of inputs(p.in)) {\n const k = keyOf(row, by)\n const group = groups.get(k)\n if (group) group.n += 1\n else groups.set(k, { first: row, n: 1 })\n }\n const counted = [...groups.values()].map(({ first, n }) => ({\n ...Object.fromEntries(by.map((f) => [f, first[f] ?? null])),\n [COUNT]: n,\n }))\n const rows = sortRecords(counted, by)\n return ok({ rows, metric: metric(env.id, p.name, rows) })\n },\n })\n },\n})\n\nfunction metric(node: string, name: string, rows: readonly Rec[]) {\n return { node, name, rows: rows.map((r) => toJson(r) as Record<string, Json>) }\n}\n","/**\n * `sink`: upserts its input on `key` into the internal model. Every input field is written to\n * the target path it names (`product.sku`, or a bare `sku` on the sink's own `target`), or\n * to the path `columns` renames it to. Types are enforced here against the host's\n * `TargetSchema`: an unknown path, a wrong type, or a nullable value for a required field\n * fails at save, blamed on the `map` field that produced it.\n *\n * A reference field listed in `refs` is written as a natural key of the entity it references\n * (`product_id` as a SKU, a join-table row as its two keys) and typed by those fields, so a\n * key of the wrong shape fails at save; the host resolves it to an id when it writes. Key\n * fields must be non-null, except a nullable identity field of an entity whose identity\n * matches NULLs as equal (a transfer with no origin, `from_warehouse_id = NULL`).\n *\n * `mode: 'replace'` makes the rows the complete set of the target for the company: the host\n * reconciles with `synchronize_all`, deleting rows this run no longer produces. That is what a\n * presence-only entity needs (a join-table row *is* the link). Because a short source read\n * would then delete real rows, `in` must carry a `count` expectation with a lower bound\n * (`min` or `shiftRatio.min`) whose action is `stop` or `skip_downstream`.\n *\n * The library performs no write: a run returns the rows, sorted by key, for the host.\n */\n\nimport { z } from 'zod'\nimport type { TargetEntity, TargetField, TargetSchema } from '../../schema'\nimport { resolveAction } from '../expect'\nimport { err, ok, type Result } from '../result'\nimport { type Instant, toDateString } from '../time'\nimport {\n assignable,\n fromLogicalType,\n type MType,\n mayBeNull,\n nullableIf,\n show,\n stripNull,\n t,\n} from '../types'\nimport { compareVals, type Json, keyOf, type Rec, toJson, type Val } from '../values'\nimport {\n defineNode,\n nodeId,\n type NodeIssue,\n type Origin,\n type SinkRef,\n type WritePolicy,\n} from './def'\n\nconst params = z.strictObject({\n in: nodeId,\n target: z.string().min(1),\n key: z.array(z.string().min(1)).min(1),\n columns: z.record(z.string(), z.string().min(1)).optional(),\n write: z.record(z.string(), z.enum(['overwrite', 'fill_if_null', 'never'])).optional(),\n refs: z.record(z.string(), z.strictObject({ by: z.array(z.string().min(1)).min(1) })).optional(),\n mode: z.enum(['upsert', 'replace']).optional(),\n})\n\ninterface Resolved {\n readonly entity: TargetEntity\n readonly field: TargetField\n readonly type: MType\n}\n\n/** `entity.field` names any entity; a bare name is a field of the sink's own target. */\nexport function resolveTarget(\n targets: TargetSchema,\n target: string,\n path: string,\n): Result<Resolved, string> {\n const dot = path.indexOf('.')\n const [entityName, fieldName] =\n dot < 0 ? [target, path] : [path.slice(0, dot), path.slice(dot + 1)]\n const entity = targets.entities.find((e) => e.name === entityName)\n if (!entity) return err(`target has no entity '${entityName}'`)\n const field = entity.fields.find((f) => f.name === fieldName)\n if (!field) return err(`${entityName} has no field '${fieldName}'`)\n return ok({ entity, field, type: nullableIf(fromLogicalType(field.logicalType), field.nullable) })\n}\n\n/**\n * The type of a reference field written as a natural key: the type of its one `by` field of\n * the referenced entity, or a tuple of them in `by` order (each with its own nullability).\n */\nexport function refType(\n targets: TargetSchema,\n field: TargetField,\n by: readonly string[],\n): Result<{ entity: string; type: MType }, string> {\n if (!field.references) return err(`${field.name} is not a reference`)\n const entity = targets.entities.find((e) => e.name === field.references)\n if (!entity) return err(`target has no entity '${field.references}'`)\n const parts: MType[] = []\n for (const name of by) {\n const part = entity.fields.find((f) => f.name === name)\n if (!part) return err(`${entity.name} has no field '${name}'`)\n parts.push(nullableIf(fromLogicalType(part.logicalType), part.nullable))\n }\n const value = parts.length === 1 ? stripNull(parts[0] as MType) : t.tuple(parts)\n return ok({ entity: entity.name, type: nullableIf(value, field.nullable) })\n}\n\n/** A nullable key field is allowed where the target identity matches NULLs as equal. */\nconst nullsEqual = ({ entity, field }: Resolved) =>\n field.nullable && entity.nullsNotDistinct === true && entity.identity.includes(field.name)\n\nexport const sinkNode = defineNode({\n op: 'sink',\n label: 'Write to target',\n category: 'target',\n description: 'Writes rows into a target entity, updating records with the same key.',\n slots: [{ id: 'in', label: 'In', path: ['in'] }],\n output: false,\n effect: 'sink',\n defaults: () => ({ in: '', target: '', key: [] }),\n params,\n compile: (p, env) => {\n const input = env.input(p.in)\n const issues: NodeIssue[] = []\n const targets = env.graph.targets\n if (!targets.entities.some((e) => e.name === p.target)) {\n return { ok: false, error: [{ message: `target has no entity '${p.target}'` }] }\n }\n const fieldNames = Object.keys(input.type.fields)\n for (const name of [\n ...Object.keys(p.columns ?? {}),\n ...Object.keys(p.write ?? {}),\n ...Object.keys(p.refs ?? {}),\n ]) {\n if (!fieldNames.includes(name))\n issues.push({ message: `'${name}' is not a field of ${p.in}` })\n }\n\n const paths: Record<string, string> = {}\n const logical: Record<string, TargetField['logicalType']> = {}\n const resolvedOf: Record<string, Resolved> = {}\n const refs: Record<string, SinkRef> = {}\n const entities = new Set([p.target])\n for (const name of fieldNames) {\n const path = p.columns?.[name] ?? name\n const origin = input.origins[name] as Origin\n const blame = { node: origin.node, field: origin.field }\n const resolved = resolveTarget(targets, p.target, path)\n if (!resolved.ok) {\n issues.push({ message: resolved.error, ...blame })\n continue\n }\n let expected = resolved.value.type\n const ref = p.refs?.[name]\n if (ref) {\n const typed = refType(targets, resolved.value.field, ref.by)\n if (!typed.ok) {\n issues.push({ message: `refs.${name}: ${typed.error}` })\n continue\n }\n expected = typed.value.type\n refs[path] = { entity: typed.value.entity, by: ref.by }\n }\n const type = input.type.fields[name] as MType\n const present = origin.present ?? type\n if (!assignable(present, expected)) {\n issues.push({\n message: `${path} expects ${show(expected)}, got ${show(present)}`,\n ...blame,\n })\n }\n paths[name] = path\n logical[name] = resolved.value.field.logicalType\n resolvedOf[name] = resolved.value\n entities.add(resolved.value.entity.name)\n }\n for (const k of p.key) {\n const type = input.type.fields[k]\n const resolved = resolvedOf[k]\n if (!type) issues.push({ message: `key '${k}' is not a field of ${p.in}` })\n else if (\n mayBeNull(type) &&\n ((input.origins[k] as Origin).omittable || !resolved || !nullsEqual(resolved))\n ) {\n issues.push({ message: `key '${k}' must be non-null, got ${show(type)}` })\n }\n }\n if (p.mode === 'replace') {\n const exp = env.version.expect[p.in]\n const lower = exp?.count?.min !== undefined || exp?.count?.shiftRatio?.min !== undefined\n const action = resolveAction(exp?.onFail, 'count')\n if (!lower || (action !== 'stop' && action !== 'skip_downstream')) {\n issues.push({\n message: `mode 'replace' deletes rows this run does not produce; give ${p.in} a count expectation with a lower bound and onFail stop or skip_downstream`,\n })\n }\n }\n if (issues.length) return { ok: false, error: issues }\n\n const keyPaths = p.key.map((k) => paths[k] as string)\n const write = p.write\n ? Object.fromEntries(\n Object.entries(p.write).map(([f, w]) => [paths[f] as string, w as WritePolicy]),\n )\n : undefined\n\n return ok({\n output: null,\n writes: [...entities].sort(),\n run: (inputs, ctx) => {\n // Key fields are never omittable, so every row has them (null only where allowed).\n const rows = [...inputs(p.in)].sort((a, b) => {\n for (const k of p.key) {\n const c = compareVals(a[k] as Val, b[k] as Val)\n if (c !== 0) return c\n }\n return 0\n })\n for (let i = 1; i < rows.length; i++) {\n if (keyOf(rows[i] as Rec, p.key) === keyOf(rows[i - 1] as Rec, p.key)) {\n const sample = p.key.map((k) => toJson((rows[i] as Rec)[k] as Val))\n return err({\n code: 'duplicate_key',\n message: `${p.key.join(', ')} ${JSON.stringify(sample)} is written twice`,\n samples: [sample],\n })\n }\n }\n const out = rows.map((row) => {\n const target: Record<string, Json> = {}\n for (const name of fieldNames) {\n if (!Object.hasOwn(row, name)) continue\n const v = row[name] ?? null\n const kind = logical[name]\n target[paths[name] as string] =\n v !== null && kind === 'date' ? toDateString(v as Instant, ctx.tz) : toJson(v)\n }\n return target\n })\n return ok({\n rows: out,\n write: {\n sink: env.id,\n target: p.target,\n key: keyPaths,\n rows: out,\n ...(write ? { write } : {}),\n ...(Object.keys(refs).length ? { refs } : {}),\n ...(p.mode === 'replace' ? { mode: 'replace' as const } : {}),\n },\n })\n },\n })\n },\n})\n","/**\n * `transform`: the collection-scope escape hatch. Calls reviewed, version-pinned code the host\n * registers in `GraphEnv.transforms`; its declared output `schema` (JSON Schema of one record)\n * keeps the rest of the graph type-checked, and its rows are checked against it at runtime.\n */\n\nimport { z } from 'zod'\nimport type { TransformDef } from '../context'\nimport { JsonSchema } from '../document'\nimport { sourceRecordType } from '../jsonschema'\nimport { err, ok } from '../result'\nimport { defineNode, fail, nodeId, ownOrigins } from './def'\nimport { loadRows } from './source'\n\nconst params = z.strictObject({\n ref: z.string().min(1),\n inputs: z.array(nodeId).min(1),\n schema: JsonSchema,\n})\n\nexport const transformNode = defineNode({\n op: 'transform',\n label: 'Transform (code)',\n category: 'transform',\n description: 'Reviewed, version-pinned code with a declared output schema.',\n slots: [{ id: 'inputs', label: 'Inputs', path: ['inputs'], multiple: true }],\n output: true,\n defaults: () => ({ ref: '', inputs: [], schema: { type: 'object', properties: {} } }),\n params,\n compile: (p, env) => {\n for (const id of p.inputs) env.input(id)\n const transforms = env.graph.transforms ?? {}\n if (!Object.hasOwn(transforms, p.ref)) return fail(`unknown transform '${p.ref}'`)\n const type = sourceRecordType(p.schema)\n if (!type.ok) return fail(`schema: ${type.error}`)\n const record = type.value\n const transform = transforms[p.ref] as TransformDef\n return ok({\n output: { type: record, origins: ownOrigins(env.id, record) },\n run: (inputs, ctx) => {\n const result = transform.run(p.inputs.map(inputs), ctx)\n if (!result.ok) return err({ code: 'transform_failed', message: result.error })\n const loaded = loadRows(env.id, result.value, record)\n return loaded.ok ? ok({ rows: loaded.value }) : loaded\n },\n })\n },\n})\n","/**\n * `union`: set union of inputs with the same fields. Field types must agree up to\n * nullability (a field nullable in any input is nullable in the output); project with a\n * `map` first otherwise. Duplicates collapse.\n */\n\nimport { z } from 'zod'\nimport { expectOk, ok } from '../result'\nimport { type MType, show, t, unify } from '../types'\nimport { keyOf, type Rec } from '../values'\nimport { defineNode, fail, nodeId, type NodeIssue, type Origin } from './def'\n\nconst params = z.strictObject({ inputs: z.array(nodeId).min(2) })\n\nexport const unionNode = defineNode({\n op: 'union',\n label: 'Union',\n category: 'transform',\n description: 'All records of several inputs with the same fields; duplicates collapse.',\n slots: [{ id: 'inputs', label: 'Inputs', path: ['inputs'], multiple: true }],\n output: true,\n defaults: () => ({ inputs: [] }),\n params,\n compile: (p, env) => {\n const outputs = p.inputs.map((id) => env.input(id))\n const first = outputs[0] as (typeof outputs)[number]\n const names = Object.keys(first.type.fields).sort()\n const issues: NodeIssue[] = []\n const fields: Record<string, MType> = {}\n const origins: Record<string, Origin> = {}\n for (const [i, out] of outputs.entries()) {\n const other = Object.keys(out.type.fields).sort()\n if (other.join('\\u0000') !== names.join('\\u0000')) {\n return fail(\n `${p.inputs[i]} has fields ${other.join(', ')}; ${p.inputs[0]} has ${names.join(', ')}`,\n )\n }\n }\n for (const name of names) {\n let type: MType = t.never\n let present: MType = t.never\n let omittable = false\n for (const [i, out] of outputs.entries()) {\n const field = out.type.fields[name] as MType\n const u = unify(type, field)\n if (!u.ok) {\n issues.push({\n message: `${name}: ${p.inputs[i]} gives ${show(field)}, earlier inputs ${show(type)}`,\n })\n break\n }\n type = u.value\n const origin = out.origins[name] as Origin\n omittable ||= origin.omittable\n present = expectOk(unify(present, origin.present ?? field))\n }\n fields[name] = type\n origins[name] = { node: env.id, field: name, omittable, ...(omittable ? { present } : {}) }\n }\n if (issues.length) return { ok: false, error: issues }\n return ok({\n output: { type: t.record(fields), origins },\n run: (inputs) => {\n const seen = new Set<string>()\n const rows: Rec[] = []\n for (const id of p.inputs) {\n for (const row of inputs(id)) {\n const k = keyOf(row, names)\n if (seen.has(k)) continue\n seen.add(k)\n rows.push(row)\n }\n }\n return ok({ rows })\n },\n })\n },\n})\n","/** The collection node registry, and the catalog the editor builds its palette from. */\n\nimport { aggregateNode } from './aggregate'\nimport { assertNode } from './assert'\nimport type { NodeCategory, NodeDef, Slot } from './def'\nimport { distinctNode } from './distinct'\nimport { filterNode } from './filter'\nimport { joinNode } from './join'\nimport { mapNode } from './map'\nimport { metricsNode } from './metrics'\nimport { sinkNode } from './sink'\nimport { sourceNode } from './source'\nimport { transformNode } from './transform'\nimport { unionNode } from './union'\n\nexport type * from './def'\nexport { defineNode } from './def'\nexport { refType, resolveTarget } from './sink'\nexport { findCycle } from './assert'\n\nconst all = [\n sourceNode,\n mapNode,\n filterNode,\n joinNode,\n aggregateNode,\n distinctNode,\n unionNode,\n sinkNode,\n metricsNode,\n assertNode,\n transformNode,\n]\n\nexport const nodeRegistry: Readonly<Record<string, NodeDef<unknown>>> = Object.fromEntries(\n all.map((def) => [def.op, def as unknown as NodeDef<unknown>]),\n)\n\n/** What the editor needs to place a node and draw its handles. */\nexport interface CatalogEntry {\n readonly op: string\n readonly label: string\n readonly category: NodeCategory\n readonly description: string\n readonly slots: readonly Slot[]\n readonly output: boolean\n readonly defaults: () => Record<string, unknown>\n}\n\nexport const nodeCatalog: readonly CatalogEntry[] = all.map(\n ({ op, label, category, description, slots, output, defaults }) => ({\n op,\n label,\n category,\n description,\n slots,\n output,\n defaults,\n }),\n)\n","/**\n * Edges are implied by input references (`in`, `left`, `right`, `inputs`, and an assert's\n * `per.in` / `remove.in`); each node definition's `slots` name them. Everything that walks the\n * graph (ordering, dead nodes, lineage, freeing edges, the editor's edges) reads them here.\n */\n\nimport type { NodeJson } from './document'\nimport { nodeRegistry } from './nodes'\n\nexport interface Ref {\n /** Slot id on the consuming node. */\n readonly slot: string\n /** Id of the referenced (upstream) node. */\n readonly source: string\n /** Position within a `multiple` slot. */\n readonly index?: number\n}\n\nfunction at(node: Readonly<Record<string, unknown>>, path: readonly string[]): unknown {\n let value: unknown = node\n for (const key of path) {\n if (typeof value !== 'object' || value === null) return undefined\n value = (value as Record<string, unknown>)[key]\n }\n return value\n}\n\n/** The input references of a node, slot by slot. Unknown ops have none. */\nexport function nodeRefs(node: NodeJson): Ref[] {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) return []\n const refs: Ref[] = []\n for (const slot of def.slots) {\n const value = at(node, slot.path)\n if (slot.multiple && Array.isArray(value)) {\n for (const [index, source] of value.entries()) {\n if (typeof source === 'string' && source !== '') refs.push({ slot: slot.id, source, index })\n }\n } else if (typeof value === 'string' && value !== '') {\n refs.push({ slot: slot.id, source: value })\n }\n }\n return refs\n}\n\n/** Distinct upstream ids of a node, in slot order. */\nexport function inputIds(node: NodeJson): string[] {\n return [...new Set(nodeRefs(node).map((r) => r.source))]\n}\n\n/** Downstream neighbours of every node (only references to existing nodes). */\nexport function consumers(nodes: readonly NodeJson[]): Map<string, string[]> {\n const ids = new Set(nodes.map((n) => n.id))\n const next = new Map<string, string[]>(nodes.map((n) => [n.id, []]))\n for (const node of nodes) {\n for (const source of inputIds(node)) {\n if (ids.has(source)) (next.get(source) as string[]).push(node.id)\n }\n }\n return next\n}\n\nfunction reach(start: string, next: ReadonlyMap<string, readonly string[]>): Set<string> {\n const seen = new Set<string>()\n const stack = [...(next.get(start) ?? [])]\n while (stack.length > 0) {\n const id = stack.pop() as string\n if (seen.has(id)) continue\n seen.add(id)\n stack.push(...(next.get(id) as readonly string[]))\n }\n return seen\n}\n\n/** Every node fed by `id`, directly or not (not including `id`). */\nexport function downstream(nodes: readonly NodeJson[], id: string): Set<string> {\n return reach(id, consumers(nodes))\n}\n\n/** Every node feeding `id`, directly or not (not including `id`). */\nexport function upstream(nodes: readonly NodeJson[], id: string): Set<string> {\n const ids = new Set(nodes.map((n) => n.id))\n const prev = new Map(nodes.map((n) => [n.id, inputIds(n).filter((s) => ids.has(s))]))\n return reach(id, prev)\n}\n\n/** One cycle as node ids (first repeated at the end), or null if acyclic. */\nexport function findGraphCycle(nodes: readonly NodeJson[]): string[] | null {\n const next = consumers(nodes)\n const state = new Map<string, 'open' | 'done'>()\n const path: string[] = []\n const visit = (id: string): string[] | null => {\n state.set(id, 'open')\n path.push(id)\n for (const to of next.get(id) as string[]) {\n if (state.get(to) === 'open') return [...path.slice(path.indexOf(to)), to]\n if (!state.has(to)) {\n const cycle = visit(to)\n if (cycle) return cycle\n }\n }\n path.pop()\n state.set(id, 'done')\n return null\n }\n for (const node of nodes) {\n if (state.has(node.id)) continue\n const cycle = visit(node.id)\n if (cycle) return cycle\n }\n return null\n}\n\n/**\n * Node ids with every node after the nodes it reads; ties keep document order, so the result\n * is stable. Nodes on a cycle are left out (check `findGraphCycle` first).\n */\nexport function topologicalOrder(nodes: readonly NodeJson[]): string[] {\n const next = consumers(nodes)\n const indegree = new Map(nodes.map((n) => [n.id, 0]))\n for (const targets of next.values())\n for (const t of targets) indegree.set(t, (indegree.get(t) as number) + 1)\n const position = new Map(nodes.map((n, i) => [n.id, i]))\n const ready = nodes.filter((n) => indegree.get(n.id) === 0).map((n) => n.id)\n const order: string[] = []\n while (ready.length > 0) {\n ready.sort((a, b) => (position.get(a) as number) - (position.get(b) as number))\n const id = ready.shift() as string\n order.push(id)\n for (const to of next.get(id) as string[]) {\n const remaining = (indegree.get(to) as number) - 1\n indegree.set(to, remaining)\n if (remaining === 0) ready.push(to)\n }\n }\n return order\n}\n","/**\n * The graph compiler (arch.md, \"Type checking\"): walks nodes in topological order, threading\n * record types along edges, and compiles each node into a closure in the same pass. The\n * result is one plan per version; a run never touches JSON.\n *\n * Every problem is collected in one pass and located by node, field and step. A node whose\n * inputs failed to compile is skipped silently, so one mistake does not cascade.\n */\n\nimport { type GraphEnv, recordEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { type Checker, compileExpectation } from './expect'\nimport { consumers, findGraphCycle, inputIds, nodeRefs, topologicalOrder } from './graph'\nimport { type CompiledNode, nodeRegistry, type NodeEnv, type NodeOutput } from './nodes'\nimport type { CompileIssue } from './result'\nimport { normalizeVersion } from './sugar'\nimport type { RecordType } from './types'\n\nexport interface PlannedNode {\n readonly id: string\n readonly op: string\n /** Parsed params. */\n readonly params: Readonly<Record<string, unknown>>\n readonly inputs: readonly string[]\n readonly output: NodeOutput | null\n readonly effect?: 'sink' | 'metrics' | 'check'\n readonly run: CompiledNode['run']\n /** The node's `expect` entry, compiled. */\n readonly check?: Checker\n /** Sinks downstream of this node, itself included: the reach of `skip_downstream`. */\n readonly sinks: readonly string[]\n /** Upstream of (or is) a `metrics` node: keeps running after a `stop`. */\n readonly feedsMetrics: boolean\n}\n\nexport interface Plan {\n /** The normalized version the plan was compiled from. */\n readonly version: MappingVersion\n readonly nodes: readonly PlannedNode[]\n /** Index of the last node reading each node's output; the edge is freed after it. */\n readonly lastUse: ReadonlyMap<string, number>\n /** Some predicate reads the run clock (`today`, `now`). */\n readonly usesClock: boolean\n}\n\n/**\n * `types` holds the output record type of every node that compiled, also when others did\n * not, so an editor can offer the fields reaching a node while the graph is half built.\n */\nexport type CompileResult =\n | {\n readonly ok: true\n readonly plan: Plan\n readonly issues: readonly []\n readonly types: Readonly<Record<string, RecordType>>\n }\n | {\n readonly ok: false\n readonly issues: readonly CompileIssue[]\n readonly types: Readonly<Record<string, RecordType>>\n }\n\nfunction paramsOf(node: NodeJson): Record<string, unknown> {\n const { id: _i, op: _o, label: _l, ...rest } = node\n return rest\n}\n\n/**\n * Structural rules that need no types: unique ids, known ops, resolvable references,\n * acyclic, no dead nodes, addressable `expect` keys. Checked in the browser too.\n */\nexport function structuralIssues(version: MappingVersion): CompileIssue[] {\n const issues: CompileIssue[] = []\n const byId = new Map<string, NodeJson>()\n for (const node of version.nodes) {\n if (byId.has(node.id))\n issues.push({ code: 'duplicate_id', message: `id '${node.id}' is used twice`, node: node.id })\n byId.set(node.id, node)\n }\n for (const node of version.nodes) {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) {\n issues.push({ code: 'unknown_op', message: `unknown node op '${node.op}'`, node: node.id })\n continue\n }\n const refs = nodeRefs(node)\n for (const slot of def.slots) {\n if (!slot.optional && !refs.some((r) => r.slot === slot.id)) {\n issues.push({\n code: 'missing_input',\n message: `input '${slot.label}' is not connected`,\n node: node.id,\n })\n }\n }\n for (const ref of refs) {\n const source = byId.get(ref.source)\n if (!source) {\n issues.push({\n code: 'dangling_ref',\n message: `'${ref.slot}' refers to unknown node '${ref.source}'`,\n node: node.id,\n })\n } else if (nodeRegistry[source.op] && !nodeRegistry[source.op]?.output) {\n issues.push({\n code: 'dangling_ref',\n message: `'${ref.source}' (${source.op}) has no output to read`,\n node: node.id,\n })\n }\n }\n }\n const cycle = findGraphCycle(version.nodes)\n if (cycle) issues.push({ code: 'cycle', message: `cycle: ${cycle.join(' -> ')}`, node: cycle[0] })\n\n // No dead nodes: every node must reach a sink, metrics or assert.\n const live = new Set<string>()\n const effectful = (n: NodeJson) => nodeRegistry[n.op]?.effect !== undefined\n const stack = version.nodes.filter(effectful).map((n) => n.id)\n const prev = new Map(version.nodes.map((n) => [n.id, inputIds(n)]))\n while (stack.length > 0) {\n const id = stack.pop() as string\n if (live.has(id)) continue\n live.add(id)\n stack.push(...(prev.get(id) ?? []))\n }\n for (const node of version.nodes) {\n if (!live.has(node.id) && nodeRegistry[node.op]) {\n issues.push({\n code: 'dead_node',\n message: 'reaches no sink, metrics or assert',\n node: node.id,\n })\n }\n }\n for (const id of Object.keys(version.expect)) {\n if (!byId.has(id))\n issues.push({\n code: 'unknown_reference',\n message: `expect names unknown node '${id}'`,\n field: id,\n })\n }\n return issues\n}\n\n/** Compile a version against the host's environment. */\nexport function compileVersion(input: MappingVersion, env: GraphEnv): CompileResult {\n const normalized = normalizeVersion(input, env)\n const version = normalized.version\n const issues: CompileIssue[] = [...normalized.issues, ...structuralIssues(version)]\n if (issues.some((i) => i.code === 'cycle' || i.code === 'duplicate_id'))\n return { ok: false, issues, types: {} }\n\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const clock = { used: false }\n const outputs = new Map<string, NodeOutput>()\n const compiled = new Map<string, CompiledEntry>()\n const renv = (record: RecordType) =>\n recordEnv(record, {\n params: version.params,\n tables: version.tables,\n functions: env.functions ?? {},\n clock,\n })\n\n for (const id of topologicalOrder(version.nodes)) {\n const node = byId.get(id) as NodeJson\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) continue\n const refs = inputIds(node)\n if (refs.some((r) => !outputs.has(r))) continue // blocked by an upstream problem\n\n const parsed = def.params.safeParse(paramsOf(node))\n if (!parsed.success) {\n for (const x of parsed.error.issues) {\n issues.push({\n code: 'invalid_params',\n message: `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`,\n node: id,\n })\n }\n continue\n }\n const exp = version.expect[id]\n const nodeEnv: NodeEnv = {\n id,\n graph: env,\n version,\n ...(exp ? { expect: exp } : {}),\n clock,\n input: (ref) => outputs.get(ref) as NodeOutput,\n recordEnv: renv,\n }\n const result = def.compile(parsed.data, nodeEnv)\n if (!result.ok) {\n for (const x of result.error) {\n issues.push({\n code: x.code ?? 'type_error',\n message: x.message,\n node: x.node ?? id,\n ...(x.field === undefined ? {} : { field: x.field }),\n ...(x.step === undefined ? {} : { step: x.step }),\n })\n }\n continue\n }\n let output = result.value.output\n let check: Checker | undefined\n if (exp) {\n if (!output) {\n issues.push({\n code: 'invalid_expectation',\n message: `${node.op} has no output to expect on`,\n node: id,\n })\n continue\n }\n const e = compileExpectation(id, exp, output, renv)\n if (!e.ok) {\n for (const x of e.error) {\n // Every expectation issue names its clause.\n issues.push({\n code: 'invalid_expectation',\n message: x.message,\n node: id,\n field: x.field as string,\n })\n }\n continue\n }\n output = e.value.output\n check = e.value.check\n }\n if (output) outputs.set(id, output)\n compiled.set(id, {\n node: { ...result.value, output },\n params: parsed.data as Record<string, unknown>,\n ...(check ? { check } : {}),\n })\n }\n\n issues.push(...sinkIssues(compiled), ...skipIssues(version, compiled))\n const types = Object.fromEntries([...outputs].map(([id, output]) => [id, output.type]))\n if (issues.length > 0) return { ok: false, issues: dedupe(issues), types }\n return { ok: true, plan: plan(version, compiled, clock.used), issues: [], types }\n}\n\ninterface CompiledEntry {\n readonly node: CompiledNode\n readonly params: Record<string, unknown>\n readonly check?: Checker\n}\n\ntype Compiled = ReadonlyMap<string, CompiledEntry>\n\n/** Sugar that fails to expand is reported by normalization and again by the step compiler. */\nfunction dedupe(issues: readonly CompileIssue[]): CompileIssue[] {\n const seen = new Set<string>()\n return issues.filter((i) => {\n const key = JSON.stringify([i.node, i.field, i.step, i.message])\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/** One sink per target entity (structural rule 4): resolve overlaps with a union. */\nfunction sinkIssues(compiled: Compiled): CompileIssue[] {\n const writers = new Map<string, string[]>()\n for (const [id, c] of compiled) {\n for (const entity of c.node.writes ?? [])\n writers.set(entity, [...(writers.get(entity) ?? []), id])\n }\n return [...writers]\n .filter(([, sinks]) => sinks.length > 1)\n .map(([entity, sinks]) => ({\n code: 'duplicate_sink' as const,\n message: `${sinks.join(' and ')} both write ${entity}; union their inputs into one sink`,\n node: sinks[1] as string,\n }))\n}\n\n/**\n * A map that can drop records upstream of a join or aggregate can flip its result, so the\n * first join or aggregate on every path from it must declare `tolerate_skips`.\n */\nfunction skipIssues(version: MappingVersion, compiled: Compiled): CompileIssue[] {\n const next = consumers(version.nodes)\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const issues: CompileIssue[] = []\n for (const [id, c] of compiled) {\n // Only a map drops records; nodes downstream of it may carry its `canSkip` along.\n if (byId.get(id)?.op !== 'map' || !c.node.output?.canSkip) continue\n const seen = new Set<string>()\n const stack = [...(next.get(id) as string[])]\n while (stack.length > 0) {\n const n = stack.pop() as string\n if (seen.has(n)) continue\n seen.add(n)\n const node = byId.get(n) as NodeJson\n const def = nodeRegistry[node.op]\n if (def?.toleratesSkips) {\n const params = compiled.get(n)?.params\n if (params && !def.toleratesSkips(params)) {\n issues.push({\n code: 'skip_tolerance',\n message: `${id} can drop records (on_error skip_record with a fallible field); set tolerate_skips: true here or change ${id}'s on_error`,\n node: n,\n })\n }\n continue\n }\n stack.push(...(next.get(n) as string[]))\n }\n }\n return issues\n}\n\nfunction plan(version: MappingVersion, compiled: Compiled, usesClock: boolean): Plan {\n const order = topologicalOrder(version.nodes)\n const byId = new Map(version.nodes.map((n) => [n.id, n]))\n const next = consumers(version.nodes)\n const lastUse = new Map<string, number>()\n for (const [i, id] of order.entries()) {\n for (const ref of inputIds(byId.get(id) as NodeJson)) lastUse.set(ref, i)\n }\n const sinksBelow = new Map<string, string[]>()\n const metricsBelow = new Map<string, boolean>()\n for (const id of [...order].reverse()) {\n const op = (byId.get(id) as NodeJson).op\n // Reverse topological order: every consumer is done before the node it reads.\n const below = next.get(id) as string[]\n const sinks = below.flatMap((b) => sinksBelow.get(b) as string[])\n sinksBelow.set(id, [...new Set(op === 'sink' ? [id, ...sinks] : sinks)].sort())\n metricsBelow.set(id, op === 'metrics' || below.some((b) => metricsBelow.get(b)))\n }\n const nodes: PlannedNode[] = order.map((id) => {\n const node = byId.get(id) as NodeJson\n const c = compiled.get(id) as CompiledEntry\n const def = nodeRegistry[node.op]\n return {\n id,\n op: node.op,\n params: c.params,\n inputs: inputIds(node),\n output: c.node.output,\n ...(def?.effect ? { effect: def.effect } : {}),\n run: c.node.run,\n ...(c.check ? { check: c.check } : {}),\n sinks: sinksBelow.get(id) as string[],\n feedsMetrics: metricsBelow.get(id) as boolean,\n }\n })\n return { version, nodes, lastUse, usesClock }\n}\n","/**\n * The executor (arch.md, \"Execution model\"). Runs a compiled plan over a frozen snapshot:\n * every node once, in topological order, each edge held only until its last consumer has run.\n * Nothing is written: sinks return their rows, and the host writes those with status `write`.\n *\n * Failure stays as local as lineage allows. A failed node skips what depends on it while\n * independent branches proceed; `skip_downstream` holds back exactly the sinks below a node;\n * `stop` (or `on_error: fail_sync`) holds back every sink, but nodes feeding `metrics` still\n * run, because metrics describe the run and matter most when it stops.\n */\n\nimport type { RunContext } from './context'\nimport type { Plan } from './compile'\nimport type { Metric, NodeRun, RunIssue, SinkWrite } from './nodes'\nimport { Instant } from './time'\nimport { type Relation, toJson } from './values'\n\nexport interface RunInput {\n /** The run's frozen clock: an instant, or an ISO string with an offset. */\n readonly now: Instant | string\n /** IANA time zone for calendar math; defaults to UTC. */\n readonly tz?: string\n readonly locale?: string\n readonly syncRunId?: string\n /** Previous output counts per node id, for `count.shiftRatio`. */\n readonly baseline?: Readonly<Record<string, number>>\n}\n\nexport interface ExecuteOptions {\n /** Keep every node's output in the result (previews, fixtures). */\n readonly retain?: boolean\n /** Fixture mode: run every node even after a stop, skip production `count` envelopes. */\n readonly fixture?: boolean\n /** Elapsed-time clock for statistics; defaults to `performance.now`. */\n readonly clock?: () => number\n}\n\nexport type NodeStatus = 'ok' | 'failed' | 'upstream_failed' | 'stopped'\n\nexport interface NodeStats {\n readonly node: string\n readonly op: string\n readonly status: NodeStatus\n readonly rowsIn: number\n readonly rowsOut: number\n readonly skipped: number\n readonly changed: number\n readonly ms: number\n}\n\nexport type SinkStatus = 'write' | 'held' | 'stopped' | 'failed' | 'upstream_failed'\n\nexport interface SinkResult {\n readonly sink: string\n readonly status: SinkStatus\n /** Present only with status `write`. */\n readonly write?: SinkWrite\n}\n\nexport interface RunResult {\n /** `stopped`: nothing may be written. `partial`: some sink is not `write`. */\n readonly status: 'ok' | 'partial' | 'stopped'\n readonly sinks: readonly SinkResult[]\n readonly metrics: readonly Metric[]\n readonly stats: readonly NodeStats[]\n readonly issues: readonly RunIssue[]\n /** Every node's output, with `retain`. Sinks hold the rows they would write. */\n readonly outputs?: Readonly<Record<string, Relation>>\n}\n\nexport type Snapshot = Readonly<Record<string, readonly Readonly<Record<string, unknown>>[]>>\n\n/** Sources the host must read, once each, before a run. */\nexport function readPlan(plan: Plan): { node: string; system: string; entity: string }[] {\n return plan.nodes\n .filter((n) => n.op === 'source')\n .map((n) => ({ node: n.id, system: String(n.params.system), entity: String(n.params.entity) }))\n}\n\n/** Read every source once and freeze the result into a snapshot. */\nexport async function readSnapshot(\n plan: Plan,\n read: (source: {\n node: string\n system: string\n entity: string\n }) => Promise<readonly Readonly<Record<string, unknown>>[]>,\n): Promise<Snapshot> {\n const snapshot: Record<string, readonly Readonly<Record<string, unknown>>[]> = {}\n for (const source of readPlan(plan))\n snapshot[source.node] = Object.freeze([...(await read(source))])\n return Object.freeze(snapshot)\n}\n\nexport function execute(\n plan: Plan,\n snapshot: Snapshot,\n run: RunInput,\n options: ExecuteOptions = {},\n): RunResult {\n const now = typeof run.now === 'string' ? Instant.parse(run.now) : run.now\n if (!now) throw new Error(`run.now '${String(run.now)}' is not an ISO instant`)\n const clock = options.clock ?? (() => performance.now())\n const ctx: RunContext = Object.freeze({\n now,\n tz: run.tz ?? 'UTC',\n locale: run.locale ?? 'en',\n snapshot: snapshot as RunContext['snapshot'],\n params: plan.version.params,\n tables: plan.version.tables,\n run: {\n syncRunId: run.syncRunId ?? '',\n mappingVersionId: `${plan.version.id}@${plan.version.version}`,\n },\n })\n\n const outputs = new Map<string, Relation>()\n const retained: Record<string, Relation> = {}\n const status = new Map<string, NodeStatus>()\n const stats: NodeStats[] = []\n const issues: RunIssue[] = []\n const writes = new Map<string, SinkWrite>()\n const metrics: Metric[] = []\n const held = new Set<string>()\n let stopped = false\n\n for (const [i, node] of plan.nodes.entries()) {\n const record = (s: NodeStatus, extra: Partial<NodeStats> = {}) => {\n status.set(node.id, s)\n stats.push({\n node: node.id,\n op: node.op,\n status: s,\n rowsIn: 0,\n rowsOut: 0,\n skipped: 0,\n changed: 0,\n ms: 0,\n ...extra,\n })\n }\n // Nodes feeding metrics read only nodes feeding metrics, so never a stopped input.\n if (stopped && !options.fixture && !node.feedsMetrics) record('stopped')\n else if (node.inputs.some((id) => status.get(id) !== 'ok')) record('upstream_failed')\n else {\n const rowsIn = node.inputs.reduce((n, id) => n + (outputs.get(id) as Relation).length, 0)\n const start = clock()\n const result = node.run((id) => outputs.get(id) as Relation, ctx, {\n ...(run.baseline?.[node.id] === undefined ? {} : { baseline: run.baseline[node.id] }),\n ...(options.fixture ? { skipCount: true } : {}),\n })\n if (!result.ok) {\n const e = result.error\n issues.push({\n node: node.id,\n code: e.code,\n message: e.message,\n ...(e.samples ? { samples: e.samples } : {}),\n })\n issues.push(...(e.issues ?? []))\n if (e.stop) stopped = true\n record('failed', { rowsIn, ms: clock() - start })\n } else {\n let out: NodeRun = result.value\n if (node.check) {\n const checked = node.check(out.rows, ctx, {\n ...(run.baseline?.[node.id] === undefined ? {} : { baseline: run.baseline[node.id] }),\n ...(options.fixture ? { skipCount: true } : {}),\n })\n out = {\n ...out,\n rows: checked.rows,\n changed: (out.changed ?? 0) + checked.changed,\n issues: [...(out.issues ?? []), ...checked.issues],\n stop: out.stop || checked.stop,\n skipDownstream: out.skipDownstream || checked.skipDownstream,\n }\n }\n issues.push(...(out.issues ?? []))\n if (out.stop) stopped = true\n if (out.skipDownstream) for (const s of node.sinks) held.add(s)\n if (out.write) writes.set(node.id, out.write)\n // A metric reports its rows as the node's checks left them.\n if (out.metric) {\n metrics.push(\n node.check\n ? { ...out.metric, rows: out.rows.map((r) => toJson(r) as Metric['rows'][number]) }\n : out.metric,\n )\n }\n outputs.set(node.id, out.rows)\n if (options.retain) retained[node.id] = out.rows\n record('ok', {\n rowsIn,\n rowsOut: out.rows.length,\n skipped: out.skipped ?? 0,\n changed: out.changed ?? 0,\n ms: clock() - start,\n })\n }\n }\n for (const id of node.inputs) if (plan.lastUse.get(id) === i) outputs.delete(id)\n }\n\n const sinks: SinkResult[] = plan.nodes\n .filter((n) => n.effect === 'sink')\n .map((n) => {\n const s = status.get(n.id)\n const write = writes.get(n.id)\n if (stopped) return { sink: n.id, status: 'stopped' }\n if (s === 'failed') return { sink: n.id, status: 'failed' }\n if (s !== 'ok' || !write) return { sink: n.id, status: 'upstream_failed' }\n if (held.has(n.id)) return { sink: n.id, status: 'held' }\n return { sink: n.id, status: 'write', write }\n })\n\n return {\n status: stopped\n ? 'stopped'\n : sinks.every((s) => s.status === 'write') && [...status.values()].every((s) => s === 'ok')\n ? 'ok'\n : 'partial',\n sinks,\n metrics,\n stats,\n issues,\n ...(options.retain ? { outputs: retained } : {}),\n }\n}\n","/**\n * Fixtures (arch.md, \"examples\"): relations in, keyed by source node id, and relations\n * out, keyed by any node id, so a multi-step graph is tested at the step that matters. An\n * expected relation is compared as a set on the fields it lists. A fixture also fails when\n * its run stops (an `assert` or expectation with `stop`) or a node fails.\n *\n * Fixtures run at sample scale, so production `count` envelopes are skipped. Dates compare\n * as ISO instants; sink rows hold what would be written (`YYYY-MM-DD` for date fields).\n */\n\nimport type { Plan } from './compile'\nimport { execute, type RunResult } from './execute'\nimport type { RunIssue } from './nodes'\nimport { Instant, isTimeZone } from './time'\nimport { canonicalKey, type Json, toJson, type Val } from './values'\n\nexport interface NodeDiff {\n readonly node: string\n /** Expected records the run did not produce. */\n readonly missing: readonly Json[]\n /** Produced records the fixture does not list. */\n readonly unexpected: readonly Json[]\n}\n\nexport interface ExampleResult {\n readonly index: number\n readonly name?: string\n readonly passed: boolean\n /** Why the fixture failed, apart from relation differences. */\n readonly failures: readonly string[]\n readonly diffs: readonly NodeDiff[]\n readonly issues: readonly RunIssue[]\n readonly run?: RunResult\n}\n\nconst DEFAULT_NOW = '2000-01-01T00:00:00Z'\n\nexport function runExamples(plan: Plan): ExampleResult[] {\n return plan.version.examples.map((example, index) => {\n const failures: string[] = []\n const head = { index, ...(example.name ? { name: example.name } : {}) }\n const sources = new Set(plan.nodes.filter((n) => n.op === 'source').map((n) => n.id))\n const nodes = new Set(plan.nodes.map((n) => n.id))\n for (const id of Object.keys(example.sources)) {\n if (!sources.has(id)) failures.push(`sources names '${id}', which is not a source node`)\n }\n for (const id of Object.keys(example.expect)) {\n if (!nodes.has(id)) failures.push(`expect names unknown node '${id}'`)\n }\n if (plan.usesClock && example.now === undefined) {\n failures.push('the graph reads the clock (today/now), so the example needs \"now\"')\n }\n const now = Instant.parse(example.now ?? DEFAULT_NOW)\n if (!now) failures.push(`now '${example.now}' is not an ISO instant`)\n const tz = example.tz ?? 'UTC'\n if (!isTimeZone(tz)) failures.push(`unknown time zone '${tz}'`)\n if (failures.length) return { ...head, passed: false, failures, diffs: [], issues: [] }\n\n const run = execute(\n plan,\n example.sources,\n { now: now as Instant, tz },\n { retain: true, fixture: true },\n )\n if (run.status === 'stopped') {\n const why = run.issues\n .filter((i) => i.action === 'stop')\n .map((i) => `${i.node}: ${i.message}`)\n failures.push(`run stopped${why.length ? `: ${why.join('; ')}` : ''}`)\n }\n for (const s of run.stats) {\n if (s.status === 'failed') {\n const why = run.issues.filter((i) => i.node === s.node).map((i) => i.message)\n failures.push(`${s.node} failed: ${why.join('; ')}`)\n }\n }\n\n const diffs: NodeDiff[] = []\n for (const [id, expected] of Object.entries(example.expect)) {\n const actual = run.outputs?.[id]\n if (!actual) {\n failures.push(`${id} produced no output`)\n continue\n }\n if (expected.length === 0) {\n if (actual.length) diffs.push({ node: id, missing: [], unexpected: actual.map(toJson) })\n continue\n }\n const fields = Object.keys(expected[0] as object).sort()\n if (expected.some((r) => Object.keys(r).sort().join('\\u0000') !== fields.join('\\u0000'))) {\n failures.push(`expected rows of ${id} must all list the same fields`)\n continue\n }\n const project = (r: Readonly<Record<string, Val>>) =>\n Object.fromEntries(fields.map((f) => [f, toJson(r[f] ?? null)])) as Json\n const want = new Map(\n expected.map((r) => [\n canonicalKey(project(r as Record<string, Val>) as Val),\n project(r as Record<string, Val>),\n ]),\n )\n const got = new Map(actual.map((r) => [canonicalKey(project(r) as Val), project(r)]))\n const missing = [...want].filter(([k]) => !got.has(k)).map(([, r]) => r)\n const unexpected = [...got].filter(([k]) => !want.has(k)).map(([, r]) => r)\n if (missing.length || unexpected.length) diffs.push({ node: id, missing, unexpected })\n }\n return {\n ...head,\n passed: failures.length === 0 && diffs.length === 0,\n failures,\n diffs,\n issues: run.issues,\n run,\n }\n })\n}\n","/**\n * The draft-save gate: everything that must hold before a version may be published, as one\n * list of located issues. `validateStructure` is the subset that needs no host environment,\n * cheap enough to run in the editor on every change.\n */\n\nimport { compileVersion, type Plan, structuralIssues } from './compile'\nimport type { GraphEnv } from './context'\nimport type { MappingVersion, NodeJson } from './document'\nimport { type ExampleResult, runExamples } from './examples'\nimport { nodeRegistry } from './nodes'\nimport type { CompileIssue } from './result'\n\nexport interface CheckResult {\n readonly ok: boolean\n readonly issues: readonly CompileIssue[]\n readonly plan?: Plan\n readonly examples?: readonly ExampleResult[]\n}\n\n/** Compile, then run every example; publishable only if `ok`. */\nexport function checkVersion(version: MappingVersion, env: GraphEnv): CheckResult {\n const compiled = compileVersion(version, env)\n if (!compiled.ok) return { ok: false, issues: compiled.issues }\n const examples = runExamples(compiled.plan)\n const issues: CompileIssue[] = examples.flatMap((e) => {\n const label = `example ${e.name ?? e.index}`\n return [\n ...e.failures.map((f) => ({ code: 'example_failed' as const, message: `${label}: ${f}` })),\n ...e.diffs.map((d) => ({\n code: 'example_failed' as const,\n node: d.node,\n message: `${label}: ${d.node} is missing ${d.missing.length} and has ${d.unexpected.length} unexpected records`,\n })),\n ]\n })\n return { ok: issues.length === 0, issues, plan: compiled.plan, examples }\n}\n\n/** Structure and params only: no types, no target schema. */\nexport function validateStructure(version: MappingVersion): CompileIssue[] {\n const issues = structuralIssues(version)\n for (const node of version.nodes) {\n const def = Object.hasOwn(nodeRegistry, node.op) ? nodeRegistry[node.op] : undefined\n if (!def) continue\n const { id: _id, op: _op, label: _label, ...params } = node as NodeJson\n const parsed = def.params.safeParse(params)\n if (parsed.success) continue\n for (const x of parsed.error.issues) {\n issues.push({\n code: 'invalid_params',\n message: `${x.path.length ? `${x.path.join('.')}: ` : ''}${x.message}`,\n node: node.id,\n })\n }\n }\n return issues\n}\n","/**\n * Pure, immutable edits of a version's graph, for the editor. Every edit returns a new\n * version. `canConnect` is the single rule book for edges, so live feedback while dragging\n * and validation on save agree. Edges are derived from input references (`edgesOf`).\n */\n\nimport type { MappingVersion, NodeJson, Position } from './document'\nimport { downstream, nodeRefs } from './graph'\nimport { nodeCatalog, nodeRegistry, type Slot } from './nodes'\n\nexport { nodeCatalog }\n\nexport interface Edge {\n /** Stable id: `source->target:slot[index]`. */\n readonly id: string\n readonly source: string\n readonly target: string\n /** Slot id on the target node, used as the React Flow target handle. */\n readonly slot: string\n readonly index?: number\n}\n\n/** A prospective edge. */\nexport interface Connection {\n readonly source: string\n readonly target: string\n readonly slot: string\n}\n\nexport type ConnectResult = { ok: true } | { ok: false; reason: string }\n\nlet counter = 0\n\n/** A short unique id; `crypto.randomUUID` where available, a counter otherwise. */\nexport function createId(prefix: string): string {\n counter += 1\n const random = globalThis.crypto?.randomUUID?.().slice(0, 8)\n return `${prefix}_${random ?? counter.toString(36)}`\n}\n\nexport function getNode(version: MappingVersion, id: string): NodeJson | undefined {\n return version.nodes.find((n) => n.id === id)\n}\n\nconst defOf = (op: string) => (Object.hasOwn(nodeRegistry, op) ? nodeRegistry[op] : undefined)\n\nexport function edgesOf(version: MappingVersion): Edge[] {\n return version.nodes.flatMap((node) =>\n nodeRefs(node).map((r) => ({\n id: `${r.source}->${node.id}:${r.slot}${r.index === undefined ? '' : `[${r.index}]`}`,\n source: r.source,\n target: node.id,\n slot: r.slot,\n ...(r.index === undefined ? {} : { index: r.index }),\n })),\n )\n}\n\n/** Add a node of a known op with its default params. */\nexport function addNode(\n version: MappingVersion,\n op: string,\n init: { id?: string; label?: string; params?: Record<string, unknown>; position?: Position } = {},\n): { version: MappingVersion; node: NodeJson } {\n const def = defOf(op)\n if (!def) throw new Error(`Unknown node op '${op}'`)\n const id = init.id ?? createId(op)\n if (getNode(version, id)) throw new Error(`Node id '${id}' already exists`)\n const node: NodeJson = {\n ...def.defaults(),\n ...init.params,\n id,\n op,\n ...(init.label === undefined ? {} : { label: init.label }),\n }\n return {\n version: {\n ...version,\n nodes: [...version.nodes, node],\n ...(init.position ? { layout: { ...version.layout, [id]: init.position } } : {}),\n },\n node,\n }\n}\n\nfunction setPath(node: NodeJson, path: readonly string[], value: unknown): NodeJson {\n const [head, ...rest] = path as [string, ...string[]]\n if (rest.length === 0) {\n const copy: Record<string, unknown> = { ...node }\n if (value === undefined) delete copy[head]\n else copy[head] = value\n return copy as NodeJson\n }\n const child = (node as Record<string, unknown>)[head]\n const inner = typeof child === 'object' && child !== null ? child : {}\n return { ...node, [head]: setPath(inner as NodeJson, rest, value) } as NodeJson\n}\n\nfunction getPath(node: NodeJson, path: readonly string[]): unknown {\n let value: unknown = node\n for (const key of path) value = (value as Record<string, unknown> | undefined)?.[key]\n return value\n}\n\nfunction slotOf(node: NodeJson, slot: string): Slot | undefined {\n return defOf(node.op)?.slots.find((s) => s.id === slot)\n}\n\n/** Remove a node, every reference to it, and its layout entry. */\nexport function removeNode(version: MappingVersion, id: string): MappingVersion {\n const nodes = version.nodes\n .filter((n) => n.id !== id)\n .map((n) => {\n let next = n\n for (const ref of nodeRefs(n)\n .filter((r) => r.source === id)\n .reverse()) {\n next = unlink(next, ref.slot, id)\n }\n return next\n })\n const layout = version.layout ? { ...version.layout } : undefined\n if (layout) delete layout[id]\n const expect = { ...version.expect }\n delete expect[id]\n return { ...version, nodes, expect, ...(layout ? { layout } : {}) }\n}\n\n/** Drop `node`'s reference to `source` in `slotId`; anything else is left as it is. */\nfunction unlink(node: NodeJson, slotId: string, source: string): NodeJson {\n const slot = slotOf(node, slotId)\n if (!slot) return node\n const value = getPath(node, slot.path)\n if (Array.isArray(value))\n return setPath(\n node,\n slot.path,\n value.filter((v) => v !== source),\n )\n return value === source ? setPath(node, slot.path, undefined) : node\n}\n\n/**\n * Replace a node's label and/or params; `id` and `op` cannot change. A `label` key set to\n * undefined clears the label.\n */\nexport function updateNode(\n version: MappingVersion,\n id: string,\n patch: { label?: string | undefined; params?: Record<string, unknown> },\n): MappingVersion {\n return {\n ...version,\n nodes: version.nodes.map((n) => {\n if (n.id !== id) return n\n const label = 'label' in patch ? patch.label : n.label\n const params = patch.params ?? (({ id: _i, op: _o, label: _l, ...rest }) => rest)(n)\n return { ...params, id: n.id, op: n.op, ...(label === undefined ? {} : { label }) }\n }),\n }\n}\n\nexport function moveNode(version: MappingVersion, id: string, position: Position): MappingVersion {\n return { ...version, layout: { ...version.layout, [id]: position } }\n}\n\n/** Every rule a new edge must satisfy, checked against the current version. */\nexport function canConnect(version: MappingVersion, connection: Connection): ConnectResult {\n const source = getNode(version, connection.source)\n const target = getNode(version, connection.target)\n if (!source || !target) return { ok: false, reason: 'Both ends must be nodes in the graph.' }\n if (source.id === target.id) return { ok: false, reason: 'A node cannot feed itself.' }\n const from = defOf(source.op)\n if (!from || !defOf(target.op)) return { ok: false, reason: 'Unknown node op.' }\n if (!from.output) return { ok: false, reason: `${from.label} has no output.` }\n const slot = slotOf(target, connection.slot)\n if (!slot) return { ok: false, reason: `${target.op} has no input '${connection.slot}'.` }\n const refs = nodeRefs(target).filter((r) => r.slot === slot.id)\n if (refs.some((r) => r.source === source.id))\n return { ok: false, reason: 'These nodes are already connected.' }\n if (refs.length > 0 && !slot.multiple)\n return { ok: false, reason: `Input '${slot.label}' already has a connection.` }\n if (downstream(version.nodes, target.id).has(source.id)) {\n return { ok: false, reason: 'This connection would create a cycle; mappings must be acyclic.' }\n }\n return { ok: true }\n}\n\n/** Add an edge by setting the target's input reference, or throw with `canConnect`'s reason. */\nexport function connect(version: MappingVersion, connection: Connection): MappingVersion {\n const verdict = canConnect(version, connection)\n if (!verdict.ok) throw new Error(verdict.reason)\n return {\n ...version,\n nodes: version.nodes.map((n) => {\n if (n.id !== connection.target) return n\n const slot = slotOf(n, connection.slot) as Slot\n const current = getPath(n, slot.path)\n const value = slot.multiple\n ? [...(Array.isArray(current) ? current : []), connection.source]\n : connection.source\n return setPath(n, slot.path, value)\n }),\n }\n}\n\n/** Remove an edge by clearing the target's reference to its source. */\nexport function disconnect(\n version: MappingVersion,\n edge: Pick<Edge, 'source' | 'target' | 'slot'>,\n): MappingVersion {\n return {\n ...version,\n nodes: version.nodes.map((n) => (n.id === edge.target ? unlink(n, edge.slot, edge.source) : n)),\n }\n}\n","/**\n * Descriptions of source and target schemas.\n *\n * These are the nouns every other part of hockeymask speaks: connectors describe what a\n * source contains as `Table`s of `Column`s, the host application describes what it wants\n * to receive as a `TargetSchema`, and mapping graphs work between the two.\n *\n * Every type is a zod schema plus its inferred TypeScript type, so the same definition\n * validates data on the wire and types it in code.\n */\n\nimport { z } from 'zod'\n\n/** A single decoded value. Dates are ISO strings ('2026-10-04'), decimals are numbers. */\nexport const Value = z.union([z.string(), z.number(), z.boolean(), z.null()])\nexport type Value = z.infer<typeof Value>\n\n/** One record as a source returns it: column name -> decoded value. */\nexport const Row = z.record(z.string(), Value)\nexport type Row = z.infer<typeof Row>\n\n/**\n * Source-independent type of a column or field.\n *\n * Connectors translate each system's declared types into one of these. The declared type\n * is kept alongside (`Column.sourceType`), because it often carries meaning the logical\n * type loses, e.g. NetSuite declares checkboxes `boolean` but SuiteQL returns 'T' / 'F'.\n */\nexport const LogicalType = z.enum([\n 'string',\n 'integer',\n 'decimal',\n 'boolean',\n 'date',\n 'timestamp',\n 'reference',\n 'unknown',\n])\nexport type LogicalType = z.infer<typeof LogicalType>\n\nexport const Column = z.object({\n name: z.string(),\n logicalType: LogicalType,\n sourceType: z.string().describe('Type exactly as the source declares it.'),\n nullable: z.boolean().default(true),\n label: z.string().nullable().default(null).describe('Human label shown in the source UI.'),\n description: z.string().nullable().default(null),\n isCustom: z.boolean().default(false).describe('Customer-added field, e.g. custitem_*.'),\n references: z\n .string()\n .nullable()\n .default(null)\n .describe('Table this column points at, when the source declares it.'),\n})\nexport type Column = z.infer<typeof Column>\n\nexport const TableRef = z.object({\n name: z.string().describe(\"Name in the source's own notation, e.g. ANALYTICS.PLANNING.X.\"),\n label: z.string().nullable().default(null),\n description: z.string().nullable().default(null),\n rowCount: z.number().int().nullable().default(null),\n})\nexport type TableRef = z.infer<typeof TableRef>\n\nexport const Table = TableRef.extend({ columns: z.array(Column) })\nexport type Table = z.infer<typeof Table>\n\n/** A batch of rows together with the columns that describe them. */\nexport const RowSet = z.object({\n columns: z.array(Column),\n rows: z.array(Row),\n totalRows: z\n .number()\n .int()\n .nullable()\n .default(null)\n .describe('Rows the query would return without a limit, if known.'),\n})\nexport type RowSet = z.infer<typeof RowSet>\n\nexport const TargetField = z.object({\n name: z.string(),\n logicalType: LogicalType,\n nullable: z.boolean().default(true),\n description: z.string().nullable().default(null),\n unit: z.string().nullable().default(null).describe(\"Unit the target stores, e.g. 'g' or 'm'.\"),\n references: z.string().nullable().default(null).describe('Target entity of a foreign key.'),\n})\nexport type TargetField = z.infer<typeof TargetField>\n\nexport const TargetEntity = z.object({\n name: z.string(),\n description: z.string().nullable().default(null),\n identity: z\n .array(z.string())\n .default([])\n .describe('Fields a re-import uses to find the row it wrote last time.'),\n nullsNotDistinct: z\n .boolean()\n .optional()\n .describe(\n 'The identity matches NULLs as equal (NULLS NOT DISTINCT), so a nullable identity field may be part of an upsert key.',\n ),\n fields: z.array(TargetField),\n})\nexport type TargetEntity = z.infer<typeof TargetEntity>\n\nexport const TargetSchema = z.object({\n name: z.string(),\n entities: z.array(TargetEntity),\n})\nexport type TargetSchema = z.infer<typeof TargetSchema>\n\n/** Column of `table` named `name`, ignoring case (source systems differ on case). */\nexport function findColumn(table: Table, name: string): Column {\n const wanted = name.toLowerCase()\n const column = table.columns.find((c) => c.name.toLowerCase() === wanted)\n if (!column) throw new Error(`${table.name} has no column '${name}'`)\n return column\n}\n\nexport function findEntity(schema: TargetSchema, name: string): TargetEntity {\n const entity = schema.entities.find((e) => e.name === name)\n if (!entity) throw new Error(`${schema.name} has no entity '${name}'`)\n return entity\n}\n\nexport function findField(entity: TargetEntity, name: string): TargetField {\n const field = entity.fields.find((f) => f.name === name)\n if (!field) throw new Error(`${entity.name} has no field '${name}'`)\n return field\n}\n\n/** Build a Column with the defaults filled in. */\nexport function column(\n input: Pick<Column, 'name' | 'logicalType' | 'sourceType'> & Partial<Column>,\n): Column {\n return Column.parse(input)\n}\n"],"mappings":";;;AA0BA,IAAa,iBAAb,cAAoC,MAAM;CACxC,OAAgB;AAClB;;AAGA,IAAa,oBAAb,cAAuC,eAAe;CACpD,OAAgB;AAClB;;;;ACqCA,SAAgB,UAAU,QAAoB,MAAqC;CACjF,MAAM,OAAO,OAAO,OAAO,OAAO,QAAQ,I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