@kurotako/ir 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/builder.ts","../src/schemas.ts","../src/validate.ts","../src/version.ts","../src/helpers.ts"],"sourcesContent":["/**\n * `@kurotako/ir` — the intermediate representation: Valibot schemas (source of\n * truth), inferred types, runtime validation, the `SourceIR` fluent builder and\n * traversal helpers. Single entry point; every export is pure.\n */\nexport * from './builder.js';\nexport * from './helpers.js';\nexport * from './schemas.js';\nexport * from './types.js';\nexport * from './validate.js';\nexport * from './version.js';\n","/**\n * Fluent `SourceIR` builder with incremental validation.\n *\n * A parser builds one `SourceIR`; `@kurotako/core` merges them. Incremental\n * checks throw immediately with a located path (`pg.User.email`); `build()` runs\n * the full `assertSourceIR` as the final gate.\n */\nimport * as v from 'valibot';\nimport { ScalarTypeSchema } from './schemas.js';\nimport type {\n DefaultValue,\n Entity,\n EnumDef,\n EnumValue,\n Field,\n IndexDef,\n IndexType,\n ReferentialAction,\n Relation,\n ScalarType,\n SourceIR,\n StringFormat,\n} from './types.js';\nimport { assertSourceIR, type IrIssue, IrValidationError } from './validate.js';\n\nexport class IrBuildError extends Error {\n readonly path: string;\n readonly issues: IrIssue[] | undefined;\n\n constructor(path: string, message: string, issues?: IrIssue[]) {\n super(`${path}: ${message}`);\n this.name = 'IrBuildError';\n this.path = path;\n this.issues = issues;\n }\n}\n\n// --- public builder interfaces -----------------------------------------------\n\nexport interface EnumBuilder {\n value(name: string, opts?: { dbName?: string; doc?: string }): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\nexport interface FieldBuilder {\n scalar(t: ScalarType): this;\n enum(ref: string): this;\n unknown(hint?: string): this;\n list(): this;\n optional(): this;\n nullable(): this;\n primary(): this;\n unique(): this;\n min(n: number): this;\n max(n: number): this;\n minLength(n: number): this;\n maxLength(n: number): this;\n regex(src: string): this;\n format(f: StringFormat): this;\n default(d: DefaultValue): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\nexport interface RelationBuilder {\n to(namespace: string, entity: string): this;\n one(): this;\n many(): this;\n optional(): this;\n owning(): this;\n backRelation(name: string): this;\n fkFields(...fields: string[]): this;\n references(...fields: string[]): this;\n onDelete(action: ReferentialAction): this;\n onUpdate(action: ReferentialAction): this;\n}\n\nexport interface EntityBuilder {\n field(name: string, def: (f: FieldBuilder) => void): this;\n relation(name: string, def: (r: RelationBuilder) => void): this;\n localEnum(name: string, def: (e: EnumBuilder) => void): this;\n primaryKey(...fields: string[]): this;\n index(fields: string[], opts?: { name?: string; type?: IndexType }): this;\n unique(fields: string[], opts?: { name?: string }): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\nexport interface SourceIrBuilder {\n addEnum(name: string, def: (e: EnumBuilder) => void): this;\n addEntity(name: string, def: (e: EntityBuilder) => void): this;\n build(): SourceIR;\n}\n\n// --- implementations -----------------------------------------------------------\n\nclass EnumBuilderImpl implements EnumBuilder {\n #def: EnumDef;\n\n constructor(name: string) {\n this.#def = { name, values: [] };\n }\n\n value(name: string, opts?: { dbName?: string; doc?: string }): this {\n const entry: EnumValue = { name };\n if (opts?.dbName !== undefined) {\n entry.dbName = opts.dbName;\n }\n if (opts?.doc !== undefined) {\n entry.doc = opts.doc;\n }\n this.#def.values.push(entry);\n return this;\n }\n\n doc(text: string): this {\n this.#def.doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#def.dbName = name;\n return this;\n }\n\n build(): EnumDef {\n return this.#def;\n }\n}\n\nclass FieldBuilderImpl implements FieldBuilder {\n #path: string;\n #field: Field;\n #onPrimary: (name: string) => void;\n\n constructor(path: string, name: string, onPrimary: (name: string) => void) {\n this.#path = path;\n this.#onPrimary = onPrimary;\n this.#field = {\n name,\n type: { kind: 'unknown' },\n list: false,\n optional: false,\n nullable: false,\n constraints: {},\n };\n }\n\n scalar(t: ScalarType): this {\n if (!v.is(ScalarTypeSchema, t)) {\n throw new IrBuildError(this.#path, `unknown scalar type '${t}'`);\n }\n this.#field.type = { kind: 'scalar', scalar: t };\n return this;\n }\n\n enum(ref: string): this {\n this.#field.type = { kind: 'enum', ref };\n return this;\n }\n\n unknown(hint?: string): this {\n this.#field.type =\n hint === undefined ? { kind: 'unknown' } : { kind: 'unknown', hint };\n return this;\n }\n\n list(): this {\n this.#field.list = true;\n return this;\n }\n\n optional(): this {\n this.#field.optional = true;\n return this;\n }\n\n nullable(): this {\n this.#field.nullable = true;\n return this;\n }\n\n primary(): this {\n if (this.#field.list) {\n throw new IrBuildError(\n this.#path,\n 'primary() cannot be used on a list field',\n );\n }\n this.#onPrimary(this.#field.name);\n return this;\n }\n\n unique(): this {\n this.#field.constraints.unique = true;\n return this;\n }\n\n min(n: number): this {\n this.#field.constraints.min = n;\n return this;\n }\n\n max(n: number): this {\n this.#field.constraints.max = n;\n return this;\n }\n\n minLength(n: number): this {\n this.#field.constraints.minLength = n;\n return this;\n }\n\n maxLength(n: number): this {\n this.#field.constraints.maxLength = n;\n return this;\n }\n\n regex(src: string): this {\n this.#field.constraints.regex = src;\n return this;\n }\n\n format(f: StringFormat): this {\n if (\n this.#field.type.kind !== 'scalar' ||\n this.#field.type.scalar !== 'string'\n ) {\n throw new IrBuildError(\n this.#path,\n 'format() requires a string scalar field',\n );\n }\n this.#field.constraints.format = f;\n return this;\n }\n\n default(d: DefaultValue): this {\n this.#field.default = d;\n return this;\n }\n\n doc(text: string): this {\n this.#field.doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#field.dbName = name;\n return this;\n }\n\n build(): Field {\n return this.#field;\n }\n}\n\nclass RelationBuilderImpl implements RelationBuilder {\n #rel: Relation;\n\n constructor(name: string) {\n this.#rel = {\n name,\n target: { namespace: '', entity: '' },\n cardinality: 'one',\n optional: false,\n owning: false,\n };\n }\n\n to(namespace: string, entity: string): this {\n this.#rel.target = { namespace, entity };\n return this;\n }\n\n one(): this {\n this.#rel.cardinality = 'one';\n return this;\n }\n\n many(): this {\n this.#rel.cardinality = 'many';\n return this;\n }\n\n optional(): this {\n this.#rel.optional = true;\n return this;\n }\n\n owning(): this {\n this.#rel.owning = true;\n return this;\n }\n\n backRelation(name: string): this {\n this.#rel.backRelation = name;\n return this;\n }\n\n fkFields(...fields: string[]): this {\n this.#rel.fkFields = fields;\n return this;\n }\n\n references(...fields: string[]): this {\n this.#rel.references = fields;\n return this;\n }\n\n onDelete(action: ReferentialAction): this {\n this.#rel.onDelete = action;\n return this;\n }\n\n onUpdate(action: ReferentialAction): this {\n this.#rel.onUpdate = action;\n return this;\n }\n\n build(): Relation {\n return this.#rel;\n }\n}\n\nclass EntityBuilderImpl implements EntityBuilder {\n #namespace: string;\n #name: string;\n #fields: FieldBuilderImpl[] = [];\n #fieldNames = new Set<string>();\n #relations: RelationBuilderImpl[] = [];\n #localEnums: Record<string, EnumDef> = {};\n #primaryKey: string[] = [];\n #indexes: IndexDef[] = [];\n #uniques: { fields: string[]; name?: string }[] = [];\n #doc: string | undefined;\n #dbName: string | undefined;\n\n constructor(namespace: string, name: string) {\n this.#namespace = namespace;\n this.#name = name;\n }\n\n #addPrimary(field: string): void {\n if (!this.#primaryKey.includes(field)) {\n this.#primaryKey.push(field);\n }\n }\n\n field(name: string, def: (f: FieldBuilder) => void): this {\n if (this.#fieldNames.has(name)) {\n throw new IrBuildError(\n `${this.#namespace}.${this.#name}.${name}`,\n `duplicate field '${name}'`,\n );\n }\n this.#fieldNames.add(name);\n const builder = new FieldBuilderImpl(\n `${this.#namespace}.${this.#name}.${name}`,\n name,\n (pk) => this.#addPrimary(pk),\n );\n def(builder);\n this.#fields.push(builder);\n return this;\n }\n\n relation(name: string, def: (r: RelationBuilder) => void): this {\n const builder = new RelationBuilderImpl(name);\n def(builder);\n this.#relations.push(builder);\n return this;\n }\n\n localEnum(name: string, def: (e: EnumBuilder) => void): this {\n const builder = new EnumBuilderImpl(name);\n def(builder);\n this.#localEnums[name] = builder.build();\n return this;\n }\n\n primaryKey(...fields: string[]): this {\n for (const field of fields) {\n this.#addPrimary(field);\n }\n return this;\n }\n\n index(fields: string[], opts?: { name?: string; type?: IndexType }): this {\n const idx: IndexDef = { fields };\n if (opts?.name !== undefined) {\n idx.name = opts.name;\n }\n if (opts?.type !== undefined) {\n idx.type = opts.type;\n }\n this.#indexes.push(idx);\n return this;\n }\n\n unique(fields: string[], opts?: { name?: string }): this {\n const entry: { fields: string[]; name?: string } = { fields };\n if (opts?.name !== undefined) {\n entry.name = opts.name;\n }\n this.#uniques.push(entry);\n return this;\n }\n\n doc(text: string): this {\n this.#doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#dbName = name;\n return this;\n }\n\n build(): Entity {\n const entity: Entity = {\n name: this.#name,\n fields: this.#fields.map((f) => f.build()),\n relations: this.#relations.map((r) => r.build()),\n indexes: this.#indexes,\n uniques: this.#uniques,\n };\n if (Object.keys(this.#localEnums).length > 0) {\n entity.enums = this.#localEnums;\n }\n if (this.#primaryKey.length > 0) {\n entity.primaryKey = this.#primaryKey;\n }\n if (this.#doc !== undefined) {\n entity.doc = this.#doc;\n }\n if (this.#dbName !== undefined) {\n entity.dbName = this.#dbName;\n }\n return entity;\n }\n}\n\nclass SourceIrBuilderImpl implements SourceIrBuilder {\n #namespace: string;\n #parser: string;\n #parserVersion: string | undefined;\n #entities: EntityBuilderImpl[] = [];\n #entityNames = new Set<string>();\n #enums: Record<string, EnumDef> = {};\n\n constructor(init: {\n namespace: string;\n parser: string;\n parserVersion?: string;\n }) {\n this.#namespace = init.namespace;\n this.#parser = init.parser;\n this.#parserVersion = init.parserVersion;\n }\n\n addEnum(name: string, def: (e: EnumBuilder) => void): this {\n const builder = new EnumBuilderImpl(name);\n def(builder);\n this.#enums[name] = builder.build();\n return this;\n }\n\n addEntity(name: string, def: (e: EntityBuilder) => void): this {\n if (this.#entityNames.has(name)) {\n throw new IrBuildError(\n `${this.#namespace}.${name}`,\n `duplicate entity '${name}'`,\n );\n }\n this.#entityNames.add(name);\n const builder = new EntityBuilderImpl(this.#namespace, name);\n def(builder);\n this.#entities.push(builder);\n return this;\n }\n\n build(): SourceIR {\n const source: SourceIR = {\n namespace: this.#namespace,\n parser: this.#parser,\n entities: Object.fromEntries(\n this.#entities.map((e) => {\n const built = e.build();\n return [built.name, built];\n }),\n ),\n enums: this.#enums,\n };\n if (this.#parserVersion !== undefined) {\n source.parserVersion = this.#parserVersion;\n }\n\n try {\n assertSourceIR(source);\n } catch (err) {\n if (err instanceof IrValidationError) {\n const first = err.issues[0];\n throw new IrBuildError(\n first?.path ?? this.#namespace,\n first?.message ?? 'invalid SourceIR',\n err.issues,\n );\n }\n throw err;\n }\n return source;\n }\n}\n\nexport function createSourceIR(init: {\n namespace: string;\n parser: string;\n parserVersion?: string;\n}): SourceIrBuilder {\n return new SourceIrBuilderImpl(init);\n}\n","/**\n * Valibot schemas — the single source of truth for the IR format.\n *\n * `types.ts` derives every type alias from these schemas via `v.InferOutput`;\n * `validate.ts` runs `v.safeParse` against them before the cross-reference pass.\n * Every schema stays plain and JSON-serializable by construction: only object,\n * array, record, picklist, variant and primitives — no `Date`, `RegExp`, classes\n * or functions. This is what keeps `--emit-ir` and `parseIR` trivial.\n */\nimport * as v from 'valibot';\n\n/** Recursive JSON value. Hand-written because `v.lazy` needs an explicit type. */\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport const JsonValueSchema: v.GenericSchema<JsonValue> = v.lazy(() =>\n v.union([\n v.null(),\n v.boolean(),\n v.number(),\n v.string(),\n v.array(JsonValueSchema),\n v.record(v.string(), JsonValueSchema),\n ]),\n);\n\n// --- closed unions -----------------------------------------------------------\n\nexport const ScalarTypeSchema = v.picklist([\n 'string',\n 'boolean',\n 'int',\n 'bigint',\n 'float',\n 'decimal',\n 'date',\n 'datetime',\n 'uuid',\n 'bytes',\n 'json',\n]);\n\nexport const StringFormatSchema = v.picklist([\n 'email',\n 'url',\n 'uuid',\n 'cuid',\n 'cuid2',\n 'ulid',\n 'datetime',\n 'date',\n 'time',\n 'duration',\n 'ipv4',\n 'ipv6',\n]);\n\nexport const ReferentialActionSchema = v.picklist([\n 'cascade',\n 'restrict',\n 'setNull',\n 'setDefault',\n 'noAction',\n]);\n\nexport const IndexTypeSchema = v.picklist([\n 'btree',\n 'hash',\n 'gin',\n 'gist',\n 'brin',\n 'spgist',\n]);\n\n// --- field types -----------------------------------------------------------\n\nexport const FieldTypeSchema = v.variant('kind', [\n v.object({ kind: v.literal('scalar'), scalar: ScalarTypeSchema }),\n v.object({ kind: v.literal('enum'), ref: v.string() }),\n v.object({ kind: v.literal('unknown'), hint: v.optional(v.string()) }),\n]);\n\nexport const ConstraintsSchema = v.object({\n min: v.optional(v.number()),\n max: v.optional(v.number()),\n minLength: v.optional(v.number()),\n maxLength: v.optional(v.number()),\n regex: v.optional(v.string()),\n format: v.optional(StringFormatSchema),\n unique: v.optional(v.boolean()),\n});\n\nexport const DefaultValueSchema = v.variant('kind', [\n v.object({ kind: v.literal('value'), value: JsonValueSchema }),\n v.object({\n kind: v.literal('expr'),\n expr: v.string(),\n args: v.optional(v.array(JsonValueSchema)),\n }),\n]);\n\nexport const FieldSchema = v.object({\n name: v.string(),\n type: FieldTypeSchema,\n list: v.boolean(),\n optional: v.boolean(),\n nullable: v.boolean(),\n constraints: ConstraintsSchema,\n default: v.optional(DefaultValueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\n// --- relations -----------------------------------------------------------\n\nexport const RelationTargetSchema = v.object({\n namespace: v.string(),\n entity: v.string(),\n});\n\nexport const RelationSchema = v.object({\n name: v.string(),\n target: RelationTargetSchema,\n cardinality: v.picklist(['one', 'many']),\n optional: v.boolean(),\n owning: v.boolean(),\n backRelation: v.optional(v.string()),\n fkFields: v.optional(v.array(v.string())),\n references: v.optional(v.array(v.string())),\n onDelete: v.optional(ReferentialActionSchema),\n onUpdate: v.optional(ReferentialActionSchema),\n});\n\n// --- enums -----------------------------------------------------------\n\nexport const EnumValueSchema = v.object({\n name: v.string(),\n dbName: v.optional(v.string()),\n doc: v.optional(v.string()),\n});\n\nexport const EnumDefSchema = v.object({\n name: v.string(),\n values: v.array(EnumValueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\n// --- indexes -----------------------------------------------------------\n\nexport const IndexDefSchema = v.object({\n fields: v.array(v.string()),\n name: v.optional(v.string()),\n type: v.optional(IndexTypeSchema),\n});\n\nexport const CompositeUniqueSchema = v.object({\n fields: v.array(v.string()),\n name: v.optional(v.string()),\n});\n\n// --- entities and roots -----------------------------------------------------------\n\nexport const EntitySchema = v.object({\n name: v.string(),\n fields: v.array(FieldSchema),\n relations: v.array(RelationSchema),\n enums: v.optional(v.record(v.string(), EnumDefSchema)),\n primaryKey: v.optional(v.array(v.string())),\n indexes: v.array(IndexDefSchema),\n uniques: v.array(CompositeUniqueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\nexport const SourceIrSchema = v.object({\n namespace: v.string(),\n parser: v.string(),\n parserVersion: v.optional(v.string()),\n entities: v.record(v.string(), EntitySchema),\n enums: v.record(v.string(), EnumDefSchema),\n});\n\nexport const IrSchema = v.object({\n irVersion: v.string(),\n sources: v.record(v.string(), SourceIrSchema),\n});\n","/**\n * Runtime validation of the IR.\n *\n * Schema-first: `v.safeParse` against `schemas.ts` covers structural shape,\n * closed-union membership, required/optional keys and tagged-union narrowing.\n * This module adds the cross-reference pass — the checks Valibot cannot express\n * structurally (enum-ref resolution, relation-target / back-relation resolution,\n * field-name references, `min <= max`, regex compilation, key/name invariants).\n *\n * Valibot issues and cross-ref issues are both normalised to the stable\n * `IrIssue` surface (dotted, located paths) so consumers are unaffected.\n */\nimport * as v from 'valibot';\nimport { IrSchema, SourceIrSchema } from './schemas.js';\nimport type { Constraints, Entity, IR, SourceIR } from './types.js';\nimport { IR_VERSION, isCompatible } from './version.js';\n\nexport type IrIssueCode =\n | 'version_incompatible'\n | 'namespace_key_mismatch'\n | 'entity_key_mismatch'\n | 'duplicate_field'\n | 'duplicate_enum_value'\n | 'unresolved_enum_ref'\n | 'unresolved_field_ref'\n | 'unresolved_relation_target'\n | 'unresolved_back_relation'\n | 'invalid_constraint'\n | 'invalid_regex'\n | 'shape';\n\nexport interface IrIssue {\n path: string;\n code: IrIssueCode;\n message: string;\n}\n\nexport type IrValidation<T> =\n | { ok: true; value: T }\n | { ok: false; issues: IrIssue[] };\n\nexport class IrValidationError extends Error {\n readonly issues: IrIssue[];\n\n constructor(issues: IrIssue[]) {\n const detail = issues\n .map((i) => `${i.path === '' ? '<root>' : i.path}: ${i.message}`)\n .join('; ');\n super(`invalid IR: ${detail}`);\n this.name = 'IrValidationError';\n this.issues = issues;\n }\n}\n\nfunction normaliseValibotIssues(\n issues: readonly v.BaseIssue<unknown>[],\n): IrIssue[] {\n return issues.map((issue) => ({\n path: v.getDotPath(issue) ?? '',\n code: 'shape' as const,\n message: issue.message,\n }));\n}\n\nfunction pushIssue(\n issues: IrIssue[],\n path: string,\n code: IrIssueCode,\n message: string,\n): void {\n issues.push({ path, code, message });\n}\n\nfunction checkConstraints(\n issues: IrIssue[],\n path: string,\n c: Constraints,\n): void {\n if (c.min !== undefined && c.max !== undefined && c.min > c.max) {\n pushIssue(\n issues,\n path,\n 'invalid_constraint',\n `min (${c.min}) is greater than max (${c.max})`,\n );\n }\n if (\n c.minLength !== undefined &&\n c.maxLength !== undefined &&\n c.minLength > c.maxLength\n ) {\n pushIssue(\n issues,\n path,\n 'invalid_constraint',\n `minLength (${c.minLength}) is greater than maxLength (${c.maxLength})`,\n );\n }\n if (c.regex !== undefined) {\n try {\n new RegExp(c.regex);\n } catch {\n pushIssue(\n issues,\n path,\n 'invalid_regex',\n `regex does not compile: ${c.regex}`,\n );\n }\n }\n}\n\nfunction checkEnumValues(\n issues: IrIssue[],\n path: string,\n values: readonly { name: string }[],\n): void {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value.name)) {\n pushIssue(\n issues,\n `${path}.${value.name}`,\n 'duplicate_enum_value',\n `duplicate enum value '${value.name}'`,\n );\n }\n seen.add(value.name);\n }\n}\n\n/**\n * Run every cross-reference check on one source. `lookupEntity` and\n * `isNamespacePresent` give access to the cross-namespace view (full in\n * `validateIR`, this-source-only in `validateSourceIR`).\n */\nfunction checkSource(\n namespace: string,\n source: SourceIR,\n lookupEntity: (ns: string, name: string) => Entity | undefined,\n isNamespacePresent: (ns: string) => boolean,\n issues: IrIssue[],\n): void {\n for (const [key, def] of Object.entries(source.enums)) {\n if (def.name !== key) {\n pushIssue(\n issues,\n `${namespace}.enums.${key}`,\n 'entity_key_mismatch',\n `enum key '${key}' does not match enum name '${def.name}'`,\n );\n }\n checkEnumValues(issues, `${namespace}.enums.${key}`, def.values);\n }\n\n for (const [key, entity] of Object.entries(source.entities)) {\n const ePath = `${namespace}.${key}`;\n if (entity.name !== key) {\n pushIssue(\n issues,\n ePath,\n 'entity_key_mismatch',\n `entity key '${key}' does not match entity name '${entity.name}'`,\n );\n }\n\n const fieldNames = new Set<string>();\n for (const field of entity.fields) {\n const fPath = `${ePath}.${field.name}`;\n if (fieldNames.has(field.name)) {\n pushIssue(\n issues,\n fPath,\n 'duplicate_field',\n `duplicate field '${field.name}'`,\n );\n }\n fieldNames.add(field.name);\n checkConstraints(issues, `${fPath}.constraints`, field.constraints);\n if (field.type.kind === 'enum') {\n const resolved =\n entity.enums?.[field.type.ref] ?? source.enums[field.type.ref];\n if (resolved === undefined) {\n pushIssue(\n issues,\n fPath,\n 'unresolved_enum_ref',\n `field '${field.name}' references unknown enum '${field.type.ref}'`,\n );\n }\n }\n }\n\n for (const [localKey, def] of Object.entries(entity.enums ?? {})) {\n if (def.name !== localKey) {\n pushIssue(\n issues,\n `${ePath}.enums.${localKey}`,\n 'entity_key_mismatch',\n `local enum key '${localKey}' does not match name '${def.name}'`,\n );\n }\n checkEnumValues(issues, `${ePath}.enums.${localKey}`, def.values);\n }\n\n const hasField = (name: string): boolean => fieldNames.has(name);\n\n for (const pk of entity.primaryKey ?? []) {\n if (!hasField(pk)) {\n pushIssue(\n issues,\n `${ePath}.primaryKey`,\n 'unresolved_field_ref',\n `primaryKey references unknown field '${pk}'`,\n );\n }\n }\n entity.indexes.forEach((idx, i) => {\n for (const f of idx.fields) {\n if (!hasField(f)) {\n pushIssue(\n issues,\n `${ePath}.indexes.${i}`,\n 'unresolved_field_ref',\n `index references unknown field '${f}'`,\n );\n }\n }\n });\n entity.uniques.forEach((u, i) => {\n for (const f of u.fields) {\n if (!hasField(f)) {\n pushIssue(\n issues,\n `${ePath}.uniques.${i}`,\n 'unresolved_field_ref',\n `unique references unknown field '${f}'`,\n );\n }\n }\n });\n\n entity.relations.forEach((rel, i) => {\n const rPath = `${ePath}.relations.${rel.name === '' ? i : rel.name}`;\n\n for (const fk of rel.fkFields ?? []) {\n if (!hasField(fk)) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_field_ref',\n `relation '${rel.name}' fkField references unknown field '${fk}'`,\n );\n }\n }\n\n const targetNs = rel.target.namespace;\n // Namespace absent: informational only, v1 drivers ignore cross-source.\n if (targetNs === '') {\n return;\n }\n const sameNs = targetNs === namespace;\n if (!sameNs && !isNamespacePresent(targetNs)) {\n // Other namespace, not present in this view: ignored (shape-level info).\n return;\n }\n\n const targetEntity = lookupEntity(targetNs, rel.target.entity);\n if (targetEntity === undefined) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_relation_target',\n `relation '${rel.name}' target ${targetNs}.${rel.target.entity} does not exist`,\n );\n return;\n }\n if (\n rel.backRelation !== undefined &&\n !targetEntity.relations.some((r) => r.name === rel.backRelation)\n ) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_back_relation',\n `backRelation '${rel.backRelation}' not found on ${targetNs}.${rel.target.entity}`,\n );\n }\n for (const ref of rel.references ?? []) {\n if (!targetEntity.fields.some((f) => f.name === ref)) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_field_ref',\n `relation '${rel.name}' references unknown field '${ref}' on ${targetNs}.${rel.target.entity}`,\n );\n }\n }\n });\n }\n}\n\nexport function validateSourceIR(value: unknown): IrValidation<SourceIR> {\n const parsed = v.safeParse(SourceIrSchema, value);\n if (!parsed.success) {\n return { ok: false, issues: normaliseValibotIssues(parsed.issues) };\n }\n const source = parsed.output;\n const issues: IrIssue[] = [];\n const lookup = (ns: string, name: string): Entity | undefined =>\n ns === source.namespace ? source.entities[name] : undefined;\n const isPresent = (ns: string): boolean => ns === source.namespace;\n checkSource(source.namespace, source, lookup, isPresent, issues);\n return issues.length > 0\n ? { ok: false, issues }\n : { ok: true, value: source };\n}\n\nexport function validateIR(value: unknown): IrValidation<IR> {\n const parsed = v.safeParse(IrSchema, value);\n if (!parsed.success) {\n return { ok: false, issues: normaliseValibotIssues(parsed.issues) };\n }\n const ir = parsed.output;\n const issues: IrIssue[] = [];\n\n if (!isCompatible(ir.irVersion)) {\n pushIssue(\n issues,\n 'irVersion',\n 'version_incompatible',\n `IR version '${ir.irVersion}' is not compatible with supported version '${IR_VERSION}'`,\n );\n }\n\n const lookup = (ns: string, name: string): Entity | undefined =>\n ir.sources[ns]?.entities[name];\n const isPresent = (ns: string): boolean => ns in ir.sources;\n\n for (const [key, source] of Object.entries(ir.sources)) {\n if (source.namespace !== key) {\n pushIssue(\n issues,\n `sources.${key}`,\n 'namespace_key_mismatch',\n `source key '${key}' does not match namespace '${source.namespace}'`,\n );\n }\n checkSource(source.namespace, source, lookup, isPresent, issues);\n }\n\n return issues.length > 0 ? { ok: false, issues } : { ok: true, value: ir };\n}\n\nexport function assertIR(value: unknown): asserts value is IR {\n const result = validateIR(value);\n if (!result.ok) {\n throw new IrValidationError(result.issues);\n }\n}\n\nexport function assertSourceIR(value: unknown): asserts value is SourceIR {\n const result = validateSourceIR(value);\n if (!result.ok) {\n throw new IrValidationError(result.issues);\n }\n}\n\nexport function parseIR(json: string): IR {\n const value = JSON.parse(json) as unknown;\n assertIR(value);\n return value;\n}\n","/**\n * IR format version. Orthogonal to the npm semver of `@kurotako/ir`\n * (independent versioning): a single string, bumped only on a breaking change\n * to the format itself.\n */\nexport const IR_VERSION = '1';\n\n/**\n * Whether an IR produced against `irVersion` can be consumed by this build.\n * v1 rule: strict equality.\n */\nexport function isCompatible(irVersion: string): boolean {\n return irVersion === IR_VERSION;\n}\n","/**\n * Traversal / resolution helpers. All pure, none throw — they return `undefined`\n * on a miss. `resolveEnum` implements the entity-local → source-level precedence\n * in one place so every generator agrees.\n */\nimport type {\n Entity,\n EnumDef,\n Field,\n FieldType,\n IR,\n Relation,\n ScalarType,\n SourceIR,\n} from './types.js';\n\nexport function getSource(ir: IR, namespace: string): SourceIR | undefined {\n return ir.sources[namespace];\n}\n\nexport function resolveEntity(\n ir: IR,\n namespace: string,\n name: string,\n): Entity | undefined {\n return ir.sources[namespace]?.entities[name];\n}\n\n/** Entity-local enums shadow source-level enums of the same name. */\nexport function resolveEnum(\n source: SourceIR,\n entity: Entity | undefined,\n ref: string,\n): EnumDef | undefined {\n return entity?.enums?.[ref] ?? source.enums[ref];\n}\n\n/**\n * A relation is cross-source when its target namespace is anything other than\n * the entity's own namespace — including the \"absent\" (empty) namespace, which\n * v1 drivers treat as an unresolved cross-source reference.\n */\nexport function isCrossSource(fromNamespace: string, rel: Relation): boolean {\n return rel.target.namespace !== fromNamespace;\n}\n\n/**\n * Resolve the target entity of a relation. Returns `undefined` when the target\n * namespace is absent or not present in the IR, or when the entity is missing.\n */\nexport function resolveRelationTarget(\n ir: IR,\n fromNamespace: string,\n rel: Relation,\n): Entity | undefined {\n const ns = isCrossSource(fromNamespace, rel)\n ? rel.target.namespace\n : fromNamespace;\n return ir.sources[ns]?.entities[rel.target.entity];\n}\n\nexport function* iterEntities(\n ir: IR,\n): Iterable<{ namespace: string; entity: Entity }> {\n for (const [namespace, source] of Object.entries(ir.sources)) {\n for (const entity of Object.values(source.entities)) {\n yield { namespace, entity };\n }\n }\n}\n\nexport function* iterFields(entity: Entity): Iterable<Field> {\n yield* entity.fields;\n}\n\n/** Fields named by `entity.primaryKey`, in declaration order. */\nexport function primaryKeyFields(entity: Entity): Field[] {\n const pk = entity.primaryKey;\n if (pk === undefined) {\n return [];\n }\n const byName = new Map(entity.fields.map((f) => [f.name, f]));\n const out: Field[] = [];\n for (const name of pk) {\n const field = byName.get(name);\n if (field !== undefined) {\n out.push(field);\n }\n }\n return out;\n}\n\n// --- shared-decision helpers ------------------------------------------------\n//\n// Principle: any modelling rule that a parser or a generator would otherwise\n// re-implement \"in its own way\" lives here as a pure helper, so the whole\n// pipeline reads it from one place. `generator-zod` (#34) and `generator-angular`\n// (#39) MUST consume these rather than re-encode the create/update payload-shape\n// rules or the scalar -> TS type mapping.\n\n/** Closed set of scalar TS type tokens `scalarTsType` may return for a scalar. */\nexport type ScalarTsType =\n | 'string'\n | 'number'\n | 'bigint'\n | 'boolean'\n | 'Date'\n | 'Uint8Array'\n | 'JsonValue'\n | 'unknown';\n\n/**\n * The value is assigned by the DB/server (an `expr` default: `now()`,\n * `autoincrement()`, `uuid()`, `dbgenerated(\"…\")`, …) and is never supplied on a\n * create payload.\n */\nexport function isDbAssigned(field: Field): boolean {\n return field.default?.kind === 'expr';\n}\n\n/**\n * Fields to include in a \"create\" payload: `entity.fields` minus the ones whose\n * only value source is db-side (a primary-key member that is `isDbAssigned`).\n */\nexport function createFields(entity: Entity): Field[] {\n const pk = new Set(entity.primaryKey ?? []);\n return entity.fields.filter(\n (field) => !(pk.has(field.name) && isDbAssigned(field)),\n );\n}\n\n/**\n * A create-payload field the caller may omit:\n * `field.optional || field.default != null || isDbAssigned(field)`.\n */\nexport function isCreateOptional(field: Field): boolean {\n return field.optional || field.default !== undefined || isDbAssigned(field);\n}\n\n/**\n * Fields to include in an \"update\" payload: `entity.fields` minus primary-key\n * members; the caller treats every one as optional (partial).\n */\nexport function updateFields(entity: Entity): Field[] {\n const pk = new Set(entity.primaryKey ?? []);\n return entity.fields.filter((field) => !pk.has(field.name));\n}\n\n/**\n * The TS type a non-nullable, non-list value of this field maps to, as a source\n * string every generator's typed output must agree on. Returns a `ScalarTsType`\n * token for scalars (`bytes -> 'Uint8Array'`, `json -> 'JsonValue'`, `decimal`\n * kept as `'string'` to preserve precision — runtime representation stays each\n * generator's choice), the enum type name for `{ kind: 'enum' }` (identifiers are\n * never prefixed, ADR-0004), and `'unknown'` for `{ kind: 'unknown' }`.\n */\nexport function scalarTsType(type: FieldType): string {\n switch (type.kind) {\n case 'enum':\n return type.ref;\n case 'unknown':\n return 'unknown';\n case 'scalar':\n return mapScalar(type.scalar);\n }\n}\n\nfunction mapScalar(scalar: ScalarType): ScalarTsType {\n switch (scalar) {\n case 'string':\n case 'uuid':\n case 'decimal':\n return 'string';\n case 'boolean':\n return 'boolean';\n case 'int':\n case 'float':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'date':\n case 'datetime':\n return 'Date';\n case 'bytes':\n return 'Uint8Array';\n case 'json':\n return 'JsonValue';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,IAAAA,KAAmB;;;ACEnB,QAAmB;AAWZ,IAAM,kBAAgD;AAAA,EAAK,MAC9D,QAAM;AAAA,IACJ,OAAK;AAAA,IACL,UAAQ;AAAA,IACR,SAAO;AAAA,IACP,SAAO;AAAA,IACP,QAAM,eAAe;AAAA,IACrB,SAAS,SAAO,GAAG,eAAe;AAAA,EACtC,CAAC;AACH;AAIO,IAAM,mBAAqB,WAAS;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAC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AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;","names":["v","v"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/builder.ts","../src/schemas.ts","../src/validate.ts","../src/version.ts","../src/helpers.ts"],"sourcesContent":["/**\n * `@kurotako/ir` — the intermediate representation: Valibot schemas (source of\n * truth), inferred types, runtime validation, the `SourceIR` fluent builder and\n * traversal helpers. Single entry point; every export is pure.\n */\nexport * from './builder.js';\nexport * from './helpers.js';\nexport * from './schemas.js';\nexport * from './types.js';\nexport * from './validate.js';\nexport * from './version.js';\n","/**\n * Fluent `SourceIR` builder with incremental validation.\n *\n * A parser builds one `SourceIR`; `@kurotako/core` merges them. Incremental\n * checks throw immediately with a located path (`pg.User.email`); `build()` runs\n * the full `assertSourceIR` as the final gate.\n */\nimport * as v from 'valibot';\nimport { ScalarTypeSchema } from './schemas.js';\nimport type {\n DefaultValue,\n Entity,\n EnumDef,\n EnumValue,\n Field,\n FieldType,\n IndexDef,\n IndexType,\n ReferentialAction,\n Relation,\n ScalarType,\n SourceIR,\n StringFormat,\n TypeAlias,\n} from './types.js';\nimport { assertSourceIR, type IrIssue, IrValidationError } from './validate.js';\n\nexport class IrBuildError extends Error {\n readonly path: string;\n readonly issues: IrIssue[] | undefined;\n\n constructor(path: string, message: string, issues?: IrIssue[]) {\n super(`${path}: ${message}`);\n this.name = 'IrBuildError';\n this.path = path;\n this.issues = issues;\n }\n}\n\n// --- public builder interfaces -----------------------------------------------\n\nexport interface EnumBuilder {\n value(name: string, opts?: { dbName?: string; doc?: string }): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\n/** Type-setters shared by `UnionBuilder` and `TypeAliasBuilder`. */\nexport interface TypeVariantBuilder {\n scalar(t: ScalarType): this;\n enum(ref: string): this;\n ref(name: string): this;\n union(build: (u: UnionBuilder) => void): this;\n unknown(hint?: string): this;\n}\n\nexport interface UnionBuilder extends TypeVariantBuilder {\n /** `mapping` values must name a `ref` variant of this union. */\n discriminator(propertyName: string, mapping?: Record<string, string>): this;\n}\n\nexport interface TypeAliasBuilder extends TypeVariantBuilder {\n doc(text: string): this;\n}\n\nexport interface FieldBuilder {\n scalar(t: ScalarType): this;\n enum(ref: string): this;\n ref(name: string): this;\n union(build: (u: UnionBuilder) => void): this;\n unknown(hint?: string): this;\n list(): this;\n optional(): this;\n nullable(): this;\n primary(): this;\n unique(): this;\n min(n: number): this;\n max(n: number): this;\n minLength(n: number): this;\n maxLength(n: number): this;\n regex(src: string): this;\n format(f: StringFormat): this;\n default(d: DefaultValue): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\nexport interface RelationBuilder {\n to(namespace: string, entity: string): this;\n one(): this;\n many(): this;\n optional(): this;\n owning(): this;\n backRelation(name: string): this;\n fkFields(...fields: string[]): this;\n references(...fields: string[]): this;\n onDelete(action: ReferentialAction): this;\n onUpdate(action: ReferentialAction): this;\n}\n\nexport interface EntityBuilder {\n field(name: string, def: (f: FieldBuilder) => void): this;\n relation(name: string, def: (r: RelationBuilder) => void): this;\n localEnum(name: string, def: (e: EnumBuilder) => void): this;\n primaryKey(...fields: string[]): this;\n index(fields: string[], opts?: { name?: string; type?: IndexType }): this;\n unique(fields: string[], opts?: { name?: string }): this;\n doc(text: string): this;\n dbName(name: string): this;\n}\n\nexport interface SourceIrBuilder {\n addEnum(name: string, def: (e: EnumBuilder) => void): this;\n addEntity(name: string, def: (e: EntityBuilder) => void): this;\n addTypeAlias(name: string, def: (t: TypeAliasBuilder) => void): this;\n build(): SourceIR;\n}\n\n// --- implementations -----------------------------------------------------------\n\nclass EnumBuilderImpl implements EnumBuilder {\n #def: EnumDef;\n\n constructor(name: string) {\n this.#def = { name, values: [] };\n }\n\n value(name: string, opts?: { dbName?: string; doc?: string }): this {\n const entry: EnumValue = { name };\n if (opts?.dbName !== undefined) {\n entry.dbName = opts.dbName;\n }\n if (opts?.doc !== undefined) {\n entry.doc = opts.doc;\n }\n this.#def.values.push(entry);\n return this;\n }\n\n doc(text: string): this {\n this.#def.doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#def.dbName = name;\n return this;\n }\n\n build(): EnumDef {\n return this.#def;\n }\n}\n\nfunction checkedScalar(path: string, t: ScalarType): FieldType {\n if (!v.is(ScalarTypeSchema, t)) {\n throw new IrBuildError(path, `unknown scalar type '${t}'`);\n }\n return { kind: 'scalar', scalar: t };\n}\n\nclass UnionBuilderImpl implements UnionBuilder {\n #path: string;\n #variants: FieldType[] = [];\n #discriminator:\n | { propertyName: string; mapping?: Record<string, string> }\n | undefined;\n\n constructor(path: string) {\n this.#path = path;\n }\n\n scalar(t: ScalarType): this {\n this.#variants.push(checkedScalar(this.#path, t));\n return this;\n }\n\n enum(ref: string): this {\n this.#variants.push({ kind: 'enum', ref });\n return this;\n }\n\n ref(name: string): this {\n this.#variants.push({ kind: 'ref', ref: name });\n return this;\n }\n\n union(build: (u: UnionBuilder) => void): this {\n const nested = new UnionBuilderImpl(this.#path);\n build(nested);\n // Nested unions are flattened into this one on build.\n for (const variant of nested.#variants) {\n this.#variants.push(variant);\n }\n return this;\n }\n\n unknown(hint?: string): this {\n this.#variants.push(\n hint === undefined ? { kind: 'unknown' } : { kind: 'unknown', hint },\n );\n return this;\n }\n\n discriminator(propertyName: string, mapping?: Record<string, string>): this {\n this.#discriminator =\n mapping === undefined ? { propertyName } : { propertyName, mapping };\n return this;\n }\n\n build(): Extract<FieldType, { kind: 'union' }> {\n if (this.#variants.length < 2) {\n throw new IrBuildError(\n this.#path,\n `union() needs at least 2 variants, got ${this.#variants.length}`,\n );\n }\n const mapping = this.#discriminator?.mapping;\n if (mapping !== undefined) {\n const refVariants = new Set(\n this.#variants.flatMap((vv) => (vv.kind === 'ref' ? [vv.ref] : [])),\n );\n for (const [key, target] of Object.entries(mapping)) {\n if (!refVariants.has(target)) {\n throw new IrBuildError(\n this.#path,\n `discriminator mapping '${key}' -> '${target}' names no ref variant`,\n );\n }\n }\n }\n const type: Extract<FieldType, { kind: 'union' }> = {\n kind: 'union',\n variants: this.#variants,\n };\n if (this.#discriminator !== undefined) {\n type.discriminator = this.#discriminator;\n }\n return type;\n }\n}\n\nclass TypeAliasBuilderImpl implements TypeAliasBuilder {\n #path: string;\n #name: string;\n #type: FieldType = { kind: 'unknown' };\n #doc: string | undefined;\n\n constructor(path: string, name: string) {\n this.#path = path;\n this.#name = name;\n }\n\n scalar(t: ScalarType): this {\n this.#type = checkedScalar(this.#path, t);\n return this;\n }\n\n enum(ref: string): this {\n this.#type = { kind: 'enum', ref };\n return this;\n }\n\n ref(name: string): this {\n this.#type = { kind: 'ref', ref: name };\n return this;\n }\n\n union(build: (u: UnionBuilder) => void): this {\n const nested = new UnionBuilderImpl(this.#path);\n build(nested);\n this.#type = nested.build();\n return this;\n }\n\n unknown(hint?: string): this {\n this.#type =\n hint === undefined ? { kind: 'unknown' } : { kind: 'unknown', hint };\n return this;\n }\n\n doc(text: string): this {\n this.#doc = text;\n return this;\n }\n\n build(): TypeAlias {\n const alias: TypeAlias = { name: this.#name, type: this.#type };\n if (this.#doc !== undefined) {\n alias.doc = this.#doc;\n }\n return alias;\n }\n}\n\nclass FieldBuilderImpl implements FieldBuilder {\n #path: string;\n #field: Field;\n #onPrimary: (name: string) => void;\n\n constructor(path: string, name: string, onPrimary: (name: string) => void) {\n this.#path = path;\n this.#onPrimary = onPrimary;\n this.#field = {\n name,\n type: { kind: 'unknown' },\n list: false,\n optional: false,\n nullable: false,\n constraints: {},\n };\n }\n\n scalar(t: ScalarType): this {\n if (!v.is(ScalarTypeSchema, t)) {\n throw new IrBuildError(this.#path, `unknown scalar type '${t}'`);\n }\n this.#field.type = { kind: 'scalar', scalar: t };\n return this;\n }\n\n enum(ref: string): this {\n this.#field.type = { kind: 'enum', ref };\n return this;\n }\n\n ref(name: string): this {\n this.#field.type = { kind: 'ref', ref: name };\n return this;\n }\n\n union(build: (u: UnionBuilder) => void): this {\n const builder = new UnionBuilderImpl(this.#path);\n build(builder);\n this.#field.type = builder.build();\n return this;\n }\n\n unknown(hint?: string): this {\n this.#field.type =\n hint === undefined ? { kind: 'unknown' } : { kind: 'unknown', hint };\n return this;\n }\n\n list(): this {\n this.#field.list = true;\n return this;\n }\n\n optional(): this {\n this.#field.optional = true;\n return this;\n }\n\n nullable(): this {\n this.#field.nullable = true;\n return this;\n }\n\n primary(): this {\n if (this.#field.list) {\n throw new IrBuildError(\n this.#path,\n 'primary() cannot be used on a list field',\n );\n }\n this.#onPrimary(this.#field.name);\n return this;\n }\n\n unique(): this {\n this.#field.constraints.unique = true;\n return this;\n }\n\n min(n: number): this {\n this.#field.constraints.min = n;\n return this;\n }\n\n max(n: number): this {\n this.#field.constraints.max = n;\n return this;\n }\n\n minLength(n: number): this {\n this.#field.constraints.minLength = n;\n return this;\n }\n\n maxLength(n: number): this {\n this.#field.constraints.maxLength = n;\n return this;\n }\n\n regex(src: string): this {\n this.#field.constraints.regex = src;\n return this;\n }\n\n format(f: StringFormat): this {\n if (\n this.#field.type.kind !== 'scalar' ||\n this.#field.type.scalar !== 'string'\n ) {\n throw new IrBuildError(\n this.#path,\n 'format() requires a string scalar field',\n );\n }\n this.#field.constraints.format = f;\n return this;\n }\n\n default(d: DefaultValue): this {\n this.#field.default = d;\n return this;\n }\n\n doc(text: string): this {\n this.#field.doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#field.dbName = name;\n return this;\n }\n\n build(): Field {\n return this.#field;\n }\n}\n\nclass RelationBuilderImpl implements RelationBuilder {\n #rel: Relation;\n\n constructor(name: string) {\n this.#rel = {\n name,\n target: { namespace: '', entity: '' },\n cardinality: 'one',\n optional: false,\n owning: false,\n };\n }\n\n to(namespace: string, entity: string): this {\n this.#rel.target = { namespace, entity };\n return this;\n }\n\n one(): this {\n this.#rel.cardinality = 'one';\n return this;\n }\n\n many(): this {\n this.#rel.cardinality = 'many';\n return this;\n }\n\n optional(): this {\n this.#rel.optional = true;\n return this;\n }\n\n owning(): this {\n this.#rel.owning = true;\n return this;\n }\n\n backRelation(name: string): this {\n this.#rel.backRelation = name;\n return this;\n }\n\n fkFields(...fields: string[]): this {\n this.#rel.fkFields = fields;\n return this;\n }\n\n references(...fields: string[]): this {\n this.#rel.references = fields;\n return this;\n }\n\n onDelete(action: ReferentialAction): this {\n this.#rel.onDelete = action;\n return this;\n }\n\n onUpdate(action: ReferentialAction): this {\n this.#rel.onUpdate = action;\n return this;\n }\n\n build(): Relation {\n return this.#rel;\n }\n}\n\nclass EntityBuilderImpl implements EntityBuilder {\n #namespace: string;\n #name: string;\n #fields: FieldBuilderImpl[] = [];\n #fieldNames = new Set<string>();\n #relations: RelationBuilderImpl[] = [];\n #localEnums: Record<string, EnumDef> = {};\n #primaryKey: string[] = [];\n #indexes: IndexDef[] = [];\n #uniques: { fields: string[]; name?: string }[] = [];\n #doc: string | undefined;\n #dbName: string | undefined;\n\n constructor(namespace: string, name: string) {\n this.#namespace = namespace;\n this.#name = name;\n }\n\n #addPrimary(field: string): void {\n if (!this.#primaryKey.includes(field)) {\n this.#primaryKey.push(field);\n }\n }\n\n field(name: string, def: (f: FieldBuilder) => void): this {\n if (this.#fieldNames.has(name)) {\n throw new IrBuildError(\n `${this.#namespace}.${this.#name}.${name}`,\n `duplicate field '${name}'`,\n );\n }\n this.#fieldNames.add(name);\n const builder = new FieldBuilderImpl(\n `${this.#namespace}.${this.#name}.${name}`,\n name,\n (pk) => this.#addPrimary(pk),\n );\n def(builder);\n this.#fields.push(builder);\n return this;\n }\n\n relation(name: string, def: (r: RelationBuilder) => void): this {\n const builder = new RelationBuilderImpl(name);\n def(builder);\n this.#relations.push(builder);\n return this;\n }\n\n localEnum(name: string, def: (e: EnumBuilder) => void): this {\n const builder = new EnumBuilderImpl(name);\n def(builder);\n this.#localEnums[name] = builder.build();\n return this;\n }\n\n primaryKey(...fields: string[]): this {\n for (const field of fields) {\n this.#addPrimary(field);\n }\n return this;\n }\n\n index(fields: string[], opts?: { name?: string; type?: IndexType }): this {\n const idx: IndexDef = { fields };\n if (opts?.name !== undefined) {\n idx.name = opts.name;\n }\n if (opts?.type !== undefined) {\n idx.type = opts.type;\n }\n this.#indexes.push(idx);\n return this;\n }\n\n unique(fields: string[], opts?: { name?: string }): this {\n const entry: { fields: string[]; name?: string } = { fields };\n if (opts?.name !== undefined) {\n entry.name = opts.name;\n }\n this.#uniques.push(entry);\n return this;\n }\n\n doc(text: string): this {\n this.#doc = text;\n return this;\n }\n\n dbName(name: string): this {\n this.#dbName = name;\n return this;\n }\n\n build(): Entity {\n const entity: Entity = {\n name: this.#name,\n fields: this.#fields.map((f) => f.build()),\n relations: this.#relations.map((r) => r.build()),\n indexes: this.#indexes,\n uniques: this.#uniques,\n };\n if (Object.keys(this.#localEnums).length > 0) {\n entity.enums = this.#localEnums;\n }\n if (this.#primaryKey.length > 0) {\n entity.primaryKey = this.#primaryKey;\n }\n if (this.#doc !== undefined) {\n entity.doc = this.#doc;\n }\n if (this.#dbName !== undefined) {\n entity.dbName = this.#dbName;\n }\n return entity;\n }\n}\n\nclass SourceIrBuilderImpl implements SourceIrBuilder {\n #namespace: string;\n #parser: string;\n #parserVersion: string | undefined;\n #entities: EntityBuilderImpl[] = [];\n #entityNames = new Set<string>();\n #enums: Record<string, EnumDef> = {};\n #typeAliases: Record<string, TypeAlias> = {};\n\n constructor(init: {\n namespace: string;\n parser: string;\n parserVersion?: string;\n }) {\n this.#namespace = init.namespace;\n this.#parser = init.parser;\n this.#parserVersion = init.parserVersion;\n }\n\n addEnum(name: string, def: (e: EnumBuilder) => void): this {\n const builder = new EnumBuilderImpl(name);\n def(builder);\n this.#enums[name] = builder.build();\n return this;\n }\n\n addEntity(name: string, def: (e: EntityBuilder) => void): this {\n if (this.#entityNames.has(name)) {\n throw new IrBuildError(\n `${this.#namespace}.${name}`,\n `duplicate entity '${name}'`,\n );\n }\n this.#entityNames.add(name);\n const builder = new EntityBuilderImpl(this.#namespace, name);\n def(builder);\n this.#entities.push(builder);\n return this;\n }\n\n addTypeAlias(name: string, def: (t: TypeAliasBuilder) => void): this {\n if (name in this.#typeAliases) {\n throw new IrBuildError(\n `${this.#namespace}.typeAliases.${name}`,\n `duplicate type alias '${name}'`,\n );\n }\n const builder = new TypeAliasBuilderImpl(\n `${this.#namespace}.typeAliases.${name}`,\n name,\n );\n def(builder);\n this.#typeAliases[name] = builder.build();\n return this;\n }\n\n build(): SourceIR {\n const source: SourceIR = {\n namespace: this.#namespace,\n parser: this.#parser,\n entities: Object.fromEntries(\n this.#entities.map((e) => {\n const built = e.build();\n return [built.name, built];\n }),\n ),\n enums: this.#enums,\n };\n if (this.#parserVersion !== undefined) {\n source.parserVersion = this.#parserVersion;\n }\n if (Object.keys(this.#typeAliases).length > 0) {\n source.typeAliases = this.#typeAliases;\n }\n\n try {\n assertSourceIR(source);\n } catch (err) {\n if (err instanceof IrValidationError) {\n const first = err.issues[0];\n throw new IrBuildError(\n first?.path ?? this.#namespace,\n first?.message ?? 'invalid SourceIR',\n err.issues,\n );\n }\n throw err;\n }\n return source;\n }\n}\n\nexport function createSourceIR(init: {\n namespace: string;\n parser: string;\n parserVersion?: string;\n}): SourceIrBuilder {\n return new SourceIrBuilderImpl(init);\n}\n","/**\n * Valibot schemas — the single source of truth for the IR format.\n *\n * `types.ts` derives every type alias from these schemas via `v.InferOutput`;\n * `validate.ts` runs `v.safeParse` against them before the cross-reference pass.\n * Every schema stays plain and JSON-serializable by construction: only object,\n * array, record, picklist, variant and primitives — no `Date`, `RegExp`, classes\n * or functions. This is what keeps `--emit-ir` and `parseIR` trivial.\n */\nimport * as v from 'valibot';\nimport type { FieldType } from './types.js';\n\n/** Recursive JSON value. Hand-written because `v.lazy` needs an explicit type. */\nexport type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport const JsonValueSchema: v.GenericSchema<JsonValue> = v.lazy(() =>\n v.union([\n v.null(),\n v.boolean(),\n v.number(),\n v.string(),\n v.array(JsonValueSchema),\n v.record(v.string(), JsonValueSchema),\n ]),\n);\n\n// --- closed unions -----------------------------------------------------------\n\nexport const ScalarTypeSchema = v.picklist([\n 'string',\n 'boolean',\n 'int',\n 'bigint',\n 'float',\n 'decimal',\n 'date',\n 'datetime',\n 'uuid',\n 'bytes',\n 'json',\n]);\n\nexport const StringFormatSchema = v.picklist([\n 'email',\n 'url',\n 'uuid',\n 'cuid',\n 'cuid2',\n 'ulid',\n 'datetime',\n 'date',\n 'time',\n 'duration',\n 'ipv4',\n 'ipv6',\n]);\n\nexport const ReferentialActionSchema = v.picklist([\n 'cascade',\n 'restrict',\n 'setNull',\n 'setDefault',\n 'noAction',\n]);\n\nexport const IndexTypeSchema = v.picklist([\n 'btree',\n 'hash',\n 'gin',\n 'gist',\n 'brin',\n 'spgist',\n]);\n\n// --- field types -----------------------------------------------------------\n\n/**\n * Recursive because of the `union` variant — wrapped in `v.lazy` with an explicit\n * `v.GenericSchema<FieldType>` annotation, exactly like `JsonValueSchema`. The\n * schema does **not** enforce `variants.length >= 2`: degenerate unions are\n * tolerated on read and normalised in the cross-reference pass.\n */\nexport const FieldTypeSchema: v.GenericSchema<FieldType> = v.lazy(() =>\n v.variant('kind', [\n v.object({ kind: v.literal('scalar'), scalar: ScalarTypeSchema }),\n v.object({ kind: v.literal('enum'), ref: v.string() }),\n v.object({ kind: v.literal('unknown'), hint: v.optional(v.string()) }),\n v.object({ kind: v.literal('ref'), ref: v.string() }),\n v.object({\n kind: v.literal('union'),\n variants: v.array(FieldTypeSchema),\n discriminator: v.optional(\n v.object({\n propertyName: v.string(),\n mapping: v.optional(v.record(v.string(), v.string())),\n }),\n ),\n }),\n ]),\n);\n\nexport const TypeAliasSchema = v.object({\n name: v.string(),\n type: FieldTypeSchema,\n doc: v.optional(v.string()),\n});\n\nexport const ConstraintsSchema = v.object({\n min: v.optional(v.number()),\n max: v.optional(v.number()),\n minLength: v.optional(v.number()),\n maxLength: v.optional(v.number()),\n regex: v.optional(v.string()),\n format: v.optional(StringFormatSchema),\n unique: v.optional(v.boolean()),\n});\n\nexport const DefaultValueSchema = v.variant('kind', [\n v.object({ kind: v.literal('value'), value: JsonValueSchema }),\n v.object({\n kind: v.literal('expr'),\n expr: v.string(),\n args: v.optional(v.array(JsonValueSchema)),\n }),\n]);\n\nexport const FieldSchema = v.object({\n name: v.string(),\n type: FieldTypeSchema,\n list: v.boolean(),\n optional: v.boolean(),\n nullable: v.boolean(),\n constraints: ConstraintsSchema,\n default: v.optional(DefaultValueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\n// --- relations -----------------------------------------------------------\n\nexport const RelationTargetSchema = v.object({\n namespace: v.string(),\n entity: v.string(),\n});\n\nexport const RelationSchema = v.object({\n name: v.string(),\n target: RelationTargetSchema,\n cardinality: v.picklist(['one', 'many']),\n optional: v.boolean(),\n owning: v.boolean(),\n backRelation: v.optional(v.string()),\n fkFields: v.optional(v.array(v.string())),\n references: v.optional(v.array(v.string())),\n onDelete: v.optional(ReferentialActionSchema),\n onUpdate: v.optional(ReferentialActionSchema),\n});\n\n// --- enums -----------------------------------------------------------\n\nexport const EnumValueSchema = v.object({\n name: v.string(),\n dbName: v.optional(v.string()),\n doc: v.optional(v.string()),\n});\n\nexport const EnumDefSchema = v.object({\n name: v.string(),\n values: v.array(EnumValueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\n// --- indexes -----------------------------------------------------------\n\nexport const IndexDefSchema = v.object({\n fields: v.array(v.string()),\n name: v.optional(v.string()),\n type: v.optional(IndexTypeSchema),\n});\n\nexport const CompositeUniqueSchema = v.object({\n fields: v.array(v.string()),\n name: v.optional(v.string()),\n});\n\n// --- entities and roots -----------------------------------------------------------\n\nexport const EntitySchema = v.object({\n name: v.string(),\n fields: v.array(FieldSchema),\n relations: v.array(RelationSchema),\n enums: v.optional(v.record(v.string(), EnumDefSchema)),\n primaryKey: v.optional(v.array(v.string())),\n indexes: v.array(IndexDefSchema),\n uniques: v.array(CompositeUniqueSchema),\n doc: v.optional(v.string()),\n dbName: v.optional(v.string()),\n});\n\nexport const SourceIrSchema = v.object({\n namespace: v.string(),\n parser: v.string(),\n parserVersion: v.optional(v.string()),\n entities: v.record(v.string(), EntitySchema),\n enums: v.record(v.string(), EnumDefSchema),\n typeAliases: v.optional(v.record(v.string(), TypeAliasSchema)),\n});\n\nexport const IrSchema = v.object({\n irVersion: v.string(),\n sources: v.record(v.string(), SourceIrSchema),\n});\n","/**\n * Runtime validation of the IR.\n *\n * Schema-first: `v.safeParse` against `schemas.ts` covers structural shape,\n * closed-union membership, required/optional keys and tagged-union narrowing.\n * This module adds the cross-reference pass — the checks Valibot cannot express\n * structurally (enum-ref resolution, relation-target / back-relation resolution,\n * field-name references, `min <= max`, regex compilation, key/name invariants).\n *\n * Valibot issues and cross-ref issues are both normalised to the stable\n * `IrIssue` surface (dotted, located paths) so consumers are unaffected.\n */\nimport * as v from 'valibot';\nimport { IrSchema, SourceIrSchema } from './schemas.js';\nimport type { Constraints, Entity, FieldType, IR, SourceIR } from './types.js';\nimport { IR_VERSION, isCompatible } from './version.js';\n\nexport type IrIssueCode =\n | 'version_incompatible'\n | 'namespace_key_mismatch'\n | 'entity_key_mismatch'\n | 'duplicate_field'\n | 'duplicate_enum_value'\n | 'unresolved_enum_ref'\n | 'unresolved_field_ref'\n | 'unresolved_relation_target'\n | 'unresolved_back_relation'\n | 'unresolved_ref'\n | 'unresolved_type_alias'\n | 'type_alias_key_mismatch'\n | 'degenerate_union'\n | 'union_cycle'\n | 'invalid_constraint'\n | 'invalid_regex'\n | 'shape';\n\nexport interface IrIssue {\n path: string;\n code: IrIssueCode;\n message: string;\n}\n\nexport type IrValidation<T> =\n | { ok: true; value: T; info?: IrIssue[] }\n | { ok: false; issues: IrIssue[] };\n\nexport class IrValidationError extends Error {\n readonly issues: IrIssue[];\n\n constructor(issues: IrIssue[]) {\n const detail = issues\n .map((i) => `${i.path === '' ? '<root>' : i.path}: ${i.message}`)\n .join('; ');\n super(`invalid IR: ${detail}`);\n this.name = 'IrValidationError';\n this.issues = issues;\n }\n}\n\nfunction normaliseValibotIssues(\n issues: readonly v.BaseIssue<unknown>[],\n): IrIssue[] {\n return issues.map((issue) => ({\n path: v.getDotPath(issue) ?? '',\n code: 'shape' as const,\n message: issue.message,\n }));\n}\n\nfunction pushIssue(\n issues: IrIssue[],\n path: string,\n code: IrIssueCode,\n message: string,\n): void {\n issues.push({ path, code, message });\n}\n\nfunction checkConstraints(\n issues: IrIssue[],\n path: string,\n c: Constraints,\n): void {\n if (c.min !== undefined && c.max !== undefined && c.min > c.max) {\n pushIssue(\n issues,\n path,\n 'invalid_constraint',\n `min (${c.min}) is greater than max (${c.max})`,\n );\n }\n if (\n c.minLength !== undefined &&\n c.maxLength !== undefined &&\n c.minLength > c.maxLength\n ) {\n pushIssue(\n issues,\n path,\n 'invalid_constraint',\n `minLength (${c.minLength}) is greater than maxLength (${c.maxLength})`,\n );\n }\n if (c.regex !== undefined) {\n try {\n new RegExp(c.regex);\n } catch {\n pushIssue(\n issues,\n path,\n 'invalid_regex',\n `regex does not compile: ${c.regex}`,\n );\n }\n }\n}\n\nfunction checkEnumValues(\n issues: IrIssue[],\n path: string,\n values: readonly { name: string }[],\n): void {\n const seen = new Set<string>();\n for (const value of values) {\n if (seen.has(value.name)) {\n pushIssue(\n issues,\n `${path}.${value.name}`,\n 'duplicate_enum_value',\n `duplicate enum value '${value.name}'`,\n );\n }\n seen.add(value.name);\n }\n}\n\n/**\n * Recursive field-type check. `enum` keeps its entity-local → source-level\n * resolution; `ref` must resolve against `source.entities` then\n * `source.typeAliases`; `union` recurses into every variant and, when it carries\n * a `discriminator.mapping`, every value must name a `ref` variant of the union.\n * A union with fewer than two variants is tolerated on read — it feeds the\n * non-fatal `info` channel (`degenerate_union`), not `issues`.\n */\nfunction walkFieldType(\n type: FieldType,\n path: string,\n entity: Entity | undefined,\n source: SourceIR,\n issues: IrIssue[],\n info: IrIssue[],\n): void {\n switch (type.kind) {\n case 'scalar':\n case 'unknown':\n return;\n case 'enum': {\n const resolved = entity?.enums?.[type.ref] ?? source.enums[type.ref];\n if (resolved === undefined) {\n pushIssue(\n issues,\n path,\n 'unresolved_enum_ref',\n `field type references unknown enum '${type.ref}'`,\n );\n }\n return;\n }\n case 'ref': {\n const known =\n source.entities[type.ref] !== undefined ||\n source.typeAliases?.[type.ref] !== undefined;\n if (!known) {\n pushIssue(\n issues,\n path,\n 'unresolved_ref',\n `ref '${type.ref}' resolves to no entity and no type alias`,\n );\n }\n return;\n }\n case 'union': {\n if (type.variants.length < 2) {\n pushIssue(\n info,\n path,\n 'degenerate_union',\n `union has ${type.variants.length} variant(s); expected at least 2`,\n );\n }\n type.variants.forEach((variant, i) => {\n walkFieldType(\n variant,\n `${path}.variants.${i}`,\n entity,\n source,\n issues,\n info,\n );\n });\n const mapping = type.discriminator?.mapping;\n if (mapping !== undefined) {\n const refVariants = new Set(\n type.variants.flatMap((vv) => (vv.kind === 'ref' ? [vv.ref] : [])),\n );\n for (const [key, target] of Object.entries(mapping)) {\n if (!refVariants.has(target)) {\n pushIssue(\n issues,\n `${path}.discriminator.mapping.${key}`,\n 'unresolved_type_alias',\n `discriminator mapping '${key}' -> '${target}' names no ref variant of the union`,\n );\n }\n }\n }\n return;\n }\n }\n}\n\n/** Every `ref` name reachable from a field type, following nested unions. */\nfunction collectRefs(type: FieldType, out: Set<string>): void {\n if (type.kind === 'ref') {\n out.add(type.ref);\n } else if (type.kind === 'union') {\n for (const variant of type.variants) {\n collectRefs(variant, out);\n }\n }\n}\n\n/**\n * Informational cycle detection over `ref` edges (entity fields, alias types,\n * union variants). Recursion is allowed — a cycle never produces a fatal issue,\n * it only feeds the `info` channel (`union_cycle`) so a generator can log it and\n * fall back to a lazy reference.\n */\nfunction checkRefCycles(\n namespace: string,\n source: SourceIR,\n info: IrIssue[],\n): void {\n const adjacency = new Map<string, Set<string>>();\n for (const [key, alias] of Object.entries(source.typeAliases ?? {})) {\n const refs = new Set<string>();\n collectRefs(alias.type, refs);\n adjacency.set(key, refs);\n }\n for (const [key, entity] of Object.entries(source.entities)) {\n const refs = adjacency.get(key) ?? new Set<string>();\n for (const field of entity.fields) {\n collectRefs(field.type, refs);\n }\n adjacency.set(key, refs);\n }\n\n const state = new Map<string, 'gray' | 'black'>();\n const stack: string[] = [];\n const reported = new Set<string>();\n\n const visit = (node: string): void => {\n state.set(node, 'gray');\n stack.push(node);\n for (const next of adjacency.get(node) ?? []) {\n if (!adjacency.has(next)) {\n continue;\n }\n const seen = state.get(next);\n if (seen === 'gray') {\n const cycle = stack.slice(stack.indexOf(next));\n const signature = [...cycle].sort().join('|');\n if (!reported.has(signature)) {\n reported.add(signature);\n pushIssue(\n info,\n namespace,\n 'union_cycle',\n `reference cycle: ${[...cycle, next].join(' -> ')}`,\n );\n }\n } else if (seen === undefined) {\n visit(next);\n }\n }\n stack.pop();\n state.set(node, 'black');\n };\n\n for (const node of adjacency.keys()) {\n if (state.get(node) === undefined) {\n visit(node);\n }\n }\n}\n\n/**\n * Run every cross-reference check on one source. `lookupEntity` and\n * `isNamespacePresent` give access to the cross-namespace view (full in\n * `validateIR`, this-source-only in `validateSourceIR`). Non-fatal observations\n * (degenerate unions, reference cycles) are collected in `info`.\n */\nfunction checkSource(\n namespace: string,\n source: SourceIR,\n lookupEntity: (ns: string, name: string) => Entity | undefined,\n isNamespacePresent: (ns: string) => boolean,\n issues: IrIssue[],\n info: IrIssue[],\n): void {\n for (const [key, def] of Object.entries(source.enums)) {\n if (def.name !== key) {\n pushIssue(\n issues,\n `${namespace}.enums.${key}`,\n 'entity_key_mismatch',\n `enum key '${key}' does not match enum name '${def.name}'`,\n );\n }\n checkEnumValues(issues, `${namespace}.enums.${key}`, def.values);\n }\n\n for (const [key, entity] of Object.entries(source.entities)) {\n const ePath = `${namespace}.${key}`;\n if (entity.name !== key) {\n pushIssue(\n issues,\n ePath,\n 'entity_key_mismatch',\n `entity key '${key}' does not match entity name '${entity.name}'`,\n );\n }\n\n const fieldNames = new Set<string>();\n for (const field of entity.fields) {\n const fPath = `${ePath}.${field.name}`;\n if (fieldNames.has(field.name)) {\n pushIssue(\n issues,\n fPath,\n 'duplicate_field',\n `duplicate field '${field.name}'`,\n );\n }\n fieldNames.add(field.name);\n checkConstraints(issues, `${fPath}.constraints`, field.constraints);\n walkFieldType(field.type, fPath, entity, source, issues, info);\n }\n\n for (const [localKey, def] of Object.entries(entity.enums ?? {})) {\n if (def.name !== localKey) {\n pushIssue(\n issues,\n `${ePath}.enums.${localKey}`,\n 'entity_key_mismatch',\n `local enum key '${localKey}' does not match name '${def.name}'`,\n );\n }\n checkEnumValues(issues, `${ePath}.enums.${localKey}`, def.values);\n }\n\n const hasField = (name: string): boolean => fieldNames.has(name);\n\n for (const pk of entity.primaryKey ?? []) {\n if (!hasField(pk)) {\n pushIssue(\n issues,\n `${ePath}.primaryKey`,\n 'unresolved_field_ref',\n `primaryKey references unknown field '${pk}'`,\n );\n }\n }\n entity.indexes.forEach((idx, i) => {\n for (const f of idx.fields) {\n if (!hasField(f)) {\n pushIssue(\n issues,\n `${ePath}.indexes.${i}`,\n 'unresolved_field_ref',\n `index references unknown field '${f}'`,\n );\n }\n }\n });\n entity.uniques.forEach((u, i) => {\n for (const f of u.fields) {\n if (!hasField(f)) {\n pushIssue(\n issues,\n `${ePath}.uniques.${i}`,\n 'unresolved_field_ref',\n `unique references unknown field '${f}'`,\n );\n }\n }\n });\n\n entity.relations.forEach((rel, i) => {\n const rPath = `${ePath}.relations.${rel.name === '' ? i : rel.name}`;\n\n for (const fk of rel.fkFields ?? []) {\n if (!hasField(fk)) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_field_ref',\n `relation '${rel.name}' fkField references unknown field '${fk}'`,\n );\n }\n }\n\n const targetNs = rel.target.namespace;\n // Namespace absent: informational only, v1 drivers ignore cross-source.\n if (targetNs === '') {\n return;\n }\n const sameNs = targetNs === namespace;\n if (!sameNs && !isNamespacePresent(targetNs)) {\n // Other namespace, not present in this view: ignored (shape-level info).\n return;\n }\n\n const targetEntity = lookupEntity(targetNs, rel.target.entity);\n if (targetEntity === undefined) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_relation_target',\n `relation '${rel.name}' target ${targetNs}.${rel.target.entity} does not exist`,\n );\n return;\n }\n if (\n rel.backRelation !== undefined &&\n !targetEntity.relations.some((r) => r.name === rel.backRelation)\n ) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_back_relation',\n `backRelation '${rel.backRelation}' not found on ${targetNs}.${rel.target.entity}`,\n );\n }\n for (const ref of rel.references ?? []) {\n if (!targetEntity.fields.some((f) => f.name === ref)) {\n pushIssue(\n issues,\n rPath,\n 'unresolved_field_ref',\n `relation '${rel.name}' references unknown field '${ref}' on ${targetNs}.${rel.target.entity}`,\n );\n }\n }\n });\n }\n\n for (const [key, alias] of Object.entries(source.typeAliases ?? {})) {\n const aPath = `${namespace}.typeAliases.${key}`;\n if (alias.name !== key) {\n pushIssue(\n issues,\n aPath,\n 'type_alias_key_mismatch',\n `type alias key '${key}' does not match name '${alias.name}'`,\n );\n }\n walkFieldType(alias.type, `${aPath}.type`, undefined, source, issues, info);\n }\n\n checkRefCycles(namespace, source, info);\n}\n\nexport function validateSourceIR(value: unknown): IrValidation<SourceIR> {\n const parsed = v.safeParse(SourceIrSchema, value);\n if (!parsed.success) {\n return { ok: false, issues: normaliseValibotIssues(parsed.issues) };\n }\n const source = parsed.output;\n const issues: IrIssue[] = [];\n const info: IrIssue[] = [];\n const lookup = (ns: string, name: string): Entity | undefined =>\n ns === source.namespace ? source.entities[name] : undefined;\n const isPresent = (ns: string): boolean => ns === source.namespace;\n checkSource(source.namespace, source, lookup, isPresent, issues, info);\n if (issues.length > 0) {\n return { ok: false, issues };\n }\n return info.length > 0\n ? { ok: true, value: source, info }\n : { ok: true, value: source };\n}\n\nexport function validateIR(value: unknown): IrValidation<IR> {\n const parsed = v.safeParse(IrSchema, value);\n if (!parsed.success) {\n return { ok: false, issues: normaliseValibotIssues(parsed.issues) };\n }\n const ir = parsed.output;\n const issues: IrIssue[] = [];\n const info: IrIssue[] = [];\n\n if (!isCompatible(ir.irVersion)) {\n pushIssue(\n issues,\n 'irVersion',\n 'version_incompatible',\n `IR version '${ir.irVersion}' is not compatible with supported version '${IR_VERSION}'`,\n );\n }\n\n const lookup = (ns: string, name: string): Entity | undefined =>\n ir.sources[ns]?.entities[name];\n const isPresent = (ns: string): boolean => ns in ir.sources;\n\n for (const [key, source] of Object.entries(ir.sources)) {\n if (source.namespace !== key) {\n pushIssue(\n issues,\n `sources.${key}`,\n 'namespace_key_mismatch',\n `source key '${key}' does not match namespace '${source.namespace}'`,\n );\n }\n checkSource(source.namespace, source, lookup, isPresent, issues, info);\n }\n\n if (issues.length > 0) {\n return { ok: false, issues };\n }\n return info.length > 0\n ? { ok: true, value: ir, info }\n : { ok: true, value: ir };\n}\n\nexport function assertIR(value: unknown): asserts value is IR {\n const result = validateIR(value);\n if (!result.ok) {\n throw new IrValidationError(result.issues);\n }\n}\n\nexport function assertSourceIR(value: unknown): asserts value is SourceIR {\n const result = validateSourceIR(value);\n if (!result.ok) {\n throw new IrValidationError(result.issues);\n }\n}\n\nexport function parseIR(json: string): IR {\n const value = JSON.parse(json) as unknown;\n assertIR(value);\n return value;\n}\n","/**\n * IR format version. Orthogonal to the npm semver of `@kurotako/ir`\n * (independent versioning): a single string, bumped only on a breaking change\n * to the format itself.\n */\nexport const IR_VERSION = '2';\n\n/**\n * Whether an IR produced against `irVersion` can be consumed by this build.\n * v1 rule: strict equality.\n */\nexport function isCompatible(irVersion: string): boolean {\n return irVersion === IR_VERSION;\n}\n","/**\n * Traversal / resolution helpers. All pure, none throw — they return `undefined`\n * on a miss. `resolveEnum` implements the entity-local → source-level precedence\n * in one place so every generator agrees.\n */\nimport type {\n Entity,\n EnumDef,\n Field,\n FieldType,\n IR,\n Relation,\n ScalarType,\n SourceIR,\n TypeAlias,\n} from './types.js';\n\nexport function getSource(ir: IR, namespace: string): SourceIR | undefined {\n return ir.sources[namespace];\n}\n\nexport function resolveEntity(\n ir: IR,\n namespace: string,\n name: string,\n): Entity | undefined {\n return ir.sources[namespace]?.entities[name];\n}\n\n/** Entity-local enums shadow source-level enums of the same name. */\nexport function resolveEnum(\n source: SourceIR,\n entity: Entity | undefined,\n ref: string,\n): EnumDef | undefined {\n return entity?.enums?.[ref] ?? source.enums[ref];\n}\n\n/**\n * Resolve a `{ kind: 'ref' }` name against the same source: an entity first,\n * then a type alias. Same-namespace only — v1 has no namespace qualifier.\n */\nexport function resolveRef(\n source: SourceIR,\n ref: string,\n): Entity | TypeAlias | undefined {\n return source.entities[ref] ?? source.typeAliases?.[ref];\n}\n\nexport function resolveTypeAlias(\n source: SourceIR,\n name: string,\n): TypeAlias | undefined {\n return source.typeAliases?.[name];\n}\n\nexport function* iterTypeAliases(\n ir: IR,\n): Iterable<{ namespace: string; alias: TypeAlias }> {\n for (const [namespace, source] of Object.entries(ir.sources)) {\n for (const alias of Object.values(source.typeAliases ?? {})) {\n yield { namespace, alias };\n }\n }\n}\n\n/** Every `{ kind: 'ref' }` name reachable from a field type (through unions). */\nexport function collectRefNames(\n type: FieldType,\n into: Set<string> = new Set(),\n): Set<string> {\n if (type.kind === 'ref') {\n into.add(type.ref);\n } else if (type.kind === 'union') {\n for (const variant of type.variants) {\n collectRefNames(variant, into);\n }\n }\n return into;\n}\n\n/**\n * Names of entities / type aliases that take part in at least one `ref` cycle\n * within `source` — following field-type `ref`, alias `type` `ref` and union\n * variant `ref` edges. Mirrors the informational `union_cycle` pass in\n * `validate.ts`; a generator consumes this (through `GenerateContext.cycles`)\n * to decide which references must be `z.lazy`-wrapped / widened rather than\n * emitted as a bare forward reference.\n */\nexport function refCycleMembers(source: SourceIR): Set<string> {\n const adjacency = new Map<string, Set<string>>();\n const edgesFor = (key: string): Set<string> => {\n let set = adjacency.get(key);\n if (set === undefined) {\n set = new Set<string>();\n adjacency.set(key, set);\n }\n return set;\n };\n for (const [key, alias] of Object.entries(source.typeAliases ?? {})) {\n collectRefNames(alias.type, edgesFor(key));\n }\n for (const [key, entity] of Object.entries(source.entities)) {\n const set = edgesFor(key);\n for (const field of entity.fields) {\n collectRefNames(field.type, set);\n }\n }\n\n const canReachSelf = (start: string): boolean => {\n const seen = new Set<string>();\n const stack = [...(adjacency.get(start) ?? [])];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) {\n break;\n }\n if (node === start) {\n return true;\n }\n if (seen.has(node) || !adjacency.has(node)) {\n continue;\n }\n seen.add(node);\n for (const next of adjacency.get(node) ?? []) {\n stack.push(next);\n }\n }\n return false;\n };\n\n const members = new Set<string>();\n for (const node of adjacency.keys()) {\n if (canReachSelf(node)) {\n members.add(node);\n }\n }\n return members;\n}\n\n/** Stable structural key for a non-union `FieldType`, for deduplication. */\nfunction fieldTypeKey(type: FieldType): string {\n switch (type.kind) {\n case 'scalar':\n return `scalar:${type.scalar}`;\n case 'enum':\n return `enum:${type.ref}`;\n case 'ref':\n return `ref:${type.ref}`;\n case 'unknown':\n return `unknown:${type.hint ?? ''}`;\n case 'union':\n return `union:${flattenUnion(type).map(fieldTypeKey).join(',')}`;\n }\n}\n\n/**\n * Flatten nested unions into a single variant list and drop\n * structurally-identical duplicates, preserving first-seen order. The\n * discriminator of a nested union is not carried up.\n */\nexport function flattenUnion(\n type: Extract<FieldType, { kind: 'union' }>,\n): FieldType[] {\n const out: FieldType[] = [];\n const seen = new Set<string>();\n const push = (t: FieldType): void => {\n if (t.kind === 'union') {\n for (const variant of t.variants) {\n push(variant);\n }\n return;\n }\n const key = fieldTypeKey(t);\n if (!seen.has(key)) {\n seen.add(key);\n out.push(t);\n }\n };\n for (const variant of type.variants) {\n push(variant);\n }\n return out;\n}\n\n/**\n * A relation is cross-source when its target namespace is anything other than\n * the entity's own namespace — including the \"absent\" (empty) namespace, which\n * v1 drivers treat as an unresolved cross-source reference.\n */\nexport function isCrossSource(fromNamespace: string, rel: Relation): boolean {\n return rel.target.namespace !== fromNamespace;\n}\n\n/**\n * Resolve the target entity of a relation. Returns `undefined` when the target\n * namespace is absent or not present in the IR, or when the entity is missing.\n */\nexport function resolveRelationTarget(\n ir: IR,\n fromNamespace: string,\n rel: Relation,\n): Entity | undefined {\n const ns = isCrossSource(fromNamespace, rel)\n ? rel.target.namespace\n : fromNamespace;\n return ir.sources[ns]?.entities[rel.target.entity];\n}\n\nexport function* iterEntities(\n ir: IR,\n): Iterable<{ namespace: string; entity: Entity }> {\n for (const [namespace, source] of Object.entries(ir.sources)) {\n for (const entity of Object.values(source.entities)) {\n yield { namespace, entity };\n }\n }\n}\n\nexport function* iterFields(entity: Entity): Iterable<Field> {\n yield* entity.fields;\n}\n\n/** Fields named by `entity.primaryKey`, in declaration order. */\nexport function primaryKeyFields(entity: Entity): Field[] {\n const pk = entity.primaryKey;\n if (pk === undefined) {\n return [];\n }\n const byName = new Map(entity.fields.map((f) => [f.name, f]));\n const out: Field[] = [];\n for (const name of pk) {\n const field = byName.get(name);\n if (field !== undefined) {\n out.push(field);\n }\n }\n return out;\n}\n\n// --- shared-decision helpers ------------------------------------------------\n//\n// Principle: any modelling rule that a parser or a generator would otherwise\n// re-implement \"in its own way\" lives here as a pure helper, so the whole\n// pipeline reads it from one place. `generator-zod` (#34) and `generator-angular`\n// (#39) MUST consume these rather than re-encode the create/update payload-shape\n// rules or the scalar -> TS type mapping.\n\n/** Closed set of scalar TS type tokens `scalarTsType` may return for a scalar. */\nexport type ScalarTsType =\n | 'string'\n | 'number'\n | 'bigint'\n | 'boolean'\n | 'Date'\n | 'Uint8Array'\n | 'JsonValue'\n | 'unknown';\n\n/**\n * The value is assigned by the DB/server (an `expr` default: `now()`,\n * `autoincrement()`, `uuid()`, `dbgenerated(\"…\")`, …) and is never supplied on a\n * create payload.\n */\nexport function isDbAssigned(field: Field): boolean {\n return field.default?.kind === 'expr';\n}\n\n/**\n * Fields to include in a \"create\" payload: `entity.fields` minus the ones whose\n * only value source is db-side (a primary-key member that is `isDbAssigned`).\n */\nexport function createFields(entity: Entity): Field[] {\n const pk = new Set(entity.primaryKey ?? []);\n return entity.fields.filter(\n (field) => !(pk.has(field.name) && isDbAssigned(field)),\n );\n}\n\n/**\n * A create-payload field the caller may omit:\n * `field.optional || field.default != null || isDbAssigned(field)`.\n */\nexport function isCreateOptional(field: Field): boolean {\n return field.optional || field.default !== undefined || isDbAssigned(field);\n}\n\n/**\n * Fields to include in an \"update\" payload: `entity.fields` minus primary-key\n * members; the caller treats every one as optional (partial).\n */\nexport function updateFields(entity: Entity): Field[] {\n const pk = new Set(entity.primaryKey ?? []);\n return entity.fields.filter((field) => !pk.has(field.name));\n}\n\n/**\n * The TS type a non-nullable, non-list value of this field maps to, as a source\n * string every generator's typed output must agree on. Returns a `ScalarTsType`\n * token for scalars (`bytes -> 'Uint8Array'`, `json -> 'JsonValue'`, `decimal`\n * kept as `'string'` to preserve precision — runtime representation stays each\n * generator's choice), the enum type name for `{ kind: 'enum' }` (identifiers are\n * never prefixed, ADR-0004), and `'unknown'` for `{ kind: 'unknown' }`.\n */\nexport function scalarTsType(type: FieldType): string {\n switch (type.kind) {\n case 'enum':\n return type.ref;\n case 'ref':\n return type.ref;\n case 'unknown':\n return 'unknown';\n case 'scalar':\n return mapScalar(type.scalar);\n case 'union':\n return flattenUnion(type)\n .map((variant) =>\n variant.kind === 'union'\n ? `(${scalarTsType(variant)})`\n : scalarTsType(variant),\n )\n .join(' | ');\n }\n}\n\nfunction mapScalar(scalar: ScalarType): ScalarTsType {\n switch (scalar) {\n case 'string':\n case 'uuid':\n case 'decimal':\n return 'string';\n case 'boolean':\n return 'boolean';\n case 'int':\n case 'float':\n return 'number';\n case 'bigint':\n return 'bigint';\n case 'date':\n case 'datetime':\n return 'Date';\n case 'bytes':\n return 'Uint8Array';\n case 'json':\n return 'JsonValue';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;","names":["v","v","variant","variant","variant"]}
package/dist/index.d.cts CHANGED
@@ -19,16 +19,18 @@ declare const ScalarTypeSchema: v.PicklistSchema<["string", "boolean", "int", "b
19
19
  declare const StringFormatSchema: v.PicklistSchema<["email", "url", "uuid", "cuid", "cuid2", "ulid", "datetime", "date", "time", "duration", "ipv4", "ipv6"], undefined>;
20
20
  declare const ReferentialActionSchema: v.PicklistSchema<["cascade", "restrict", "setNull", "setDefault", "noAction"], undefined>;
21
21
  declare const IndexTypeSchema: v.PicklistSchema<["btree", "hash", "gin", "gist", "brin", "spgist"], undefined>;
22
- declare const FieldTypeSchema: v.VariantSchema<"kind", [v.ObjectSchema<{
23
- readonly kind: v.LiteralSchema<"scalar", undefined>;
24
- readonly scalar: v.PicklistSchema<["string", "boolean", "int", "bigint", "float", "decimal", "date", "datetime", "uuid", "bytes", "json"], undefined>;
25
- }, undefined>, v.ObjectSchema<{
26
- readonly kind: v.LiteralSchema<"enum", undefined>;
27
- readonly ref: v.StringSchema<undefined>;
28
- }, undefined>, v.ObjectSchema<{
29
- readonly kind: v.LiteralSchema<"unknown", undefined>;
30
- readonly hint: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
31
- }, undefined>], undefined>;
22
+ /**
23
+ * Recursive because of the `union` variant — wrapped in `v.lazy` with an explicit
24
+ * `v.GenericSchema<FieldType>` annotation, exactly like `JsonValueSchema`. The
25
+ * schema does **not** enforce `variants.length >= 2`: degenerate unions are
26
+ * tolerated on read and normalised in the cross-reference pass.
27
+ */
28
+ declare const FieldTypeSchema: v.GenericSchema<FieldType>;
29
+ declare const TypeAliasSchema: v.ObjectSchema<{
30
+ readonly name: v.StringSchema<undefined>;
31
+ readonly type: v.GenericSchema<FieldType>;
32
+ readonly doc: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
33
+ }, undefined>;
32
34
  declare const ConstraintsSchema: v.ObjectSchema<{
33
35
  readonly min: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
34
36
  readonly max: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
@@ -48,16 +50,7 @@ declare const DefaultValueSchema: v.VariantSchema<"kind", [v.ObjectSchema<{
48
50
  }, undefined>], undefined>;
49
51
  declare const FieldSchema: v.ObjectSchema<{
50
52
  readonly name: v.StringSchema<undefined>;
51
- readonly type: v.VariantSchema<"kind", [v.ObjectSchema<{
52
- readonly kind: v.LiteralSchema<"scalar", undefined>;
53
- readonly scalar: v.PicklistSchema<["string", "boolean", "int", "bigint", "float", "decimal", "date", "datetime", "uuid", "bytes", "json"], undefined>;
54
- }, undefined>, v.ObjectSchema<{
55
- readonly kind: v.LiteralSchema<"enum", undefined>;
56
- readonly ref: v.StringSchema<undefined>;
57
- }, undefined>, v.ObjectSchema<{
58
- readonly kind: v.LiteralSchema<"unknown", undefined>;
59
- readonly hint: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
60
- }, undefined>], undefined>;
53
+ readonly type: v.GenericSchema<FieldType>;
61
54
  readonly list: v.BooleanSchema<undefined>;
62
55
  readonly optional: v.BooleanSchema<undefined>;
63
56
  readonly nullable: v.BooleanSchema<undefined>;
@@ -128,16 +121,7 @@ declare const EntitySchema: v.ObjectSchema<{
128
121
  readonly name: v.StringSchema<undefined>;
129
122
  readonly fields: v.ArraySchema<v.ObjectSchema<{
130
123
  readonly name: v.StringSchema<undefined>;
131
- readonly type: v.VariantSchema<"kind", [v.ObjectSchema<{
132
- readonly kind: v.LiteralSchema<"scalar", undefined>;
133
- readonly scalar: v.PicklistSchema<["string", "boolean", "int", "bigint", "float", "decimal", "date", "datetime", "uuid", "bytes", "json"], undefined>;
134
- }, undefined>, v.ObjectSchema<{
135
- readonly kind: v.LiteralSchema<"enum", undefined>;
136
- readonly ref: v.StringSchema<undefined>;
137
- }, undefined>, v.ObjectSchema<{
138
- readonly kind: v.LiteralSchema<"unknown", undefined>;
139
- readonly hint: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
140
- }, undefined>], undefined>;
124
+ readonly type: v.GenericSchema<FieldType>;
141
125
  readonly list: v.BooleanSchema<undefined>;
142
126
  readonly optional: v.BooleanSchema<undefined>;
143
127
  readonly nullable: v.BooleanSchema<undefined>;
@@ -207,16 +191,7 @@ declare const SourceIrSchema: v.ObjectSchema<{
207
191
  readonly name: v.StringSchema<undefined>;
208
192
  readonly fields: v.ArraySchema<v.ObjectSchema<{
209
193
  readonly name: v.StringSchema<undefined>;
210
- readonly type: v.VariantSchema<"kind", [v.ObjectSchema<{
211
- readonly kind: v.LiteralSchema<"scalar", undefined>;
212
- readonly scalar: v.PicklistSchema<["string", "boolean", "int", "bigint", "float", "decimal", "date", "datetime", "uuid", "bytes", "json"], undefined>;
213
- }, undefined>, v.ObjectSchema<{
214
- readonly kind: v.LiteralSchema<"enum", undefined>;
215
- readonly ref: v.StringSchema<undefined>;
216
- }, undefined>, v.ObjectSchema<{
217
- readonly kind: v.LiteralSchema<"unknown", undefined>;
218
- readonly hint: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
219
- }, undefined>], undefined>;
194
+ readonly type: v.GenericSchema<FieldType>;
220
195
  readonly list: v.BooleanSchema<undefined>;
221
196
  readonly optional: v.BooleanSchema<undefined>;
222
197
  readonly nullable: v.BooleanSchema<undefined>;
@@ -288,6 +263,11 @@ declare const SourceIrSchema: v.ObjectSchema<{
288
263
  readonly doc: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
289
264
  readonly dbName: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
290
265
  }, undefined>, undefined>;
266
+ readonly typeAliases: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
267
+ readonly name: v.StringSchema<undefined>;
268
+ readonly type: v.GenericSchema<FieldType>;
269
+ readonly doc: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
270
+ }, undefined>, undefined>, undefined>;
291
271
  }, undefined>;
292
272
  declare const IrSchema: v.ObjectSchema<{
293
273
  readonly irVersion: v.StringSchema<undefined>;
@@ -299,16 +279,7 @@ declare const IrSchema: v.ObjectSchema<{
299
279
  readonly name: v.StringSchema<undefined>;
300
280
  readonly fields: v.ArraySchema<v.ObjectSchema<{
301
281
  readonly name: v.StringSchema<undefined>;
302
- readonly type: v.VariantSchema<"kind", [v.ObjectSchema<{
303
- readonly kind: v.LiteralSchema<"scalar", undefined>;
304
- readonly scalar: v.PicklistSchema<["string", "boolean", "int", "bigint", "float", "decimal", "date", "datetime", "uuid", "bytes", "json"], undefined>;
305
- }, undefined>, v.ObjectSchema<{
306
- readonly kind: v.LiteralSchema<"enum", undefined>;
307
- readonly ref: v.StringSchema<undefined>;
308
- }, undefined>, v.ObjectSchema<{
309
- readonly kind: v.LiteralSchema<"unknown", undefined>;
310
- readonly hint: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
311
- }, undefined>], undefined>;
282
+ readonly type: v.GenericSchema<FieldType>;
312
283
  readonly list: v.BooleanSchema<undefined>;
313
284
  readonly optional: v.BooleanSchema<undefined>;
314
285
  readonly nullable: v.BooleanSchema<undefined>;
@@ -380,6 +351,11 @@ declare const IrSchema: v.ObjectSchema<{
380
351
  readonly doc: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
381
352
  readonly dbName: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
382
353
  }, undefined>, undefined>;
354
+ readonly typeAliases: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ObjectSchema<{
355
+ readonly name: v.StringSchema<undefined>;
356
+ readonly type: v.GenericSchema<FieldType>;
357
+ readonly doc: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
358
+ }, undefined>, undefined>, undefined>;
383
359
  }, undefined>, undefined>;
384
360
  }, undefined>;
385
361
 
@@ -389,12 +365,38 @@ declare const IrSchema: v.ObjectSchema<{
389
365
  * hand-written interface here.
390
366
  */
391
367
 
368
+ /**
369
+ * Hand-written because `FieldTypeSchema` is recursive (`union` variant) and
370
+ * `v.lazy` needs an explicit type — same pattern as `JsonValue`.
371
+ * `ref` is a bare name resolved against the same source (`entities` then
372
+ * `typeAliases`); there is no namespace qualifier in v1.
373
+ */
374
+ type FieldType = {
375
+ kind: 'scalar';
376
+ scalar: ScalarType;
377
+ } | {
378
+ kind: 'enum';
379
+ ref: string;
380
+ } | {
381
+ kind: 'unknown';
382
+ hint?: string;
383
+ } | {
384
+ kind: 'ref';
385
+ ref: string;
386
+ } | {
387
+ kind: 'union';
388
+ variants: FieldType[];
389
+ discriminator?: {
390
+ propertyName: string;
391
+ mapping?: Record<string, string>;
392
+ };
393
+ };
392
394
  type IR = v.InferOutput<typeof IrSchema>;
393
395
  type SourceIR = v.InferOutput<typeof SourceIrSchema>;
394
396
  type Entity = v.InferOutput<typeof EntitySchema>;
395
397
  type Field = v.InferOutput<typeof FieldSchema>;
396
- type FieldType = v.InferOutput<typeof FieldTypeSchema>;
397
398
  type ScalarType = v.InferOutput<typeof ScalarTypeSchema>;
399
+ type TypeAlias = v.InferOutput<typeof TypeAliasSchema>;
398
400
  type StringFormat = v.InferOutput<typeof StringFormatSchema>;
399
401
  type ReferentialAction = v.InferOutput<typeof ReferentialActionSchema>;
400
402
  type IndexType = v.InferOutput<typeof IndexTypeSchema>;
@@ -407,7 +409,7 @@ type EnumValue = v.InferOutput<typeof EnumValueSchema>;
407
409
  type IndexDef = v.InferOutput<typeof IndexDefSchema>;
408
410
  type CompositeUnique = v.InferOutput<typeof CompositeUniqueSchema>;
409
411
 
410
- type IrIssueCode = 'version_incompatible' | 'namespace_key_mismatch' | 'entity_key_mismatch' | 'duplicate_field' | 'duplicate_enum_value' | 'unresolved_enum_ref' | 'unresolved_field_ref' | 'unresolved_relation_target' | 'unresolved_back_relation' | 'invalid_constraint' | 'invalid_regex' | 'shape';
412
+ type IrIssueCode = 'version_incompatible' | 'namespace_key_mismatch' | 'entity_key_mismatch' | 'duplicate_field' | 'duplicate_enum_value' | 'unresolved_enum_ref' | 'unresolved_field_ref' | 'unresolved_relation_target' | 'unresolved_back_relation' | 'unresolved_ref' | 'unresolved_type_alias' | 'type_alias_key_mismatch' | 'degenerate_union' | 'union_cycle' | 'invalid_constraint' | 'invalid_regex' | 'shape';
411
413
  interface IrIssue {
412
414
  path: string;
413
415
  code: IrIssueCode;
@@ -416,6 +418,7 @@ interface IrIssue {
416
418
  type IrValidation<T> = {
417
419
  ok: true;
418
420
  value: T;
421
+ info?: IrIssue[];
419
422
  } | {
420
423
  ok: false;
421
424
  issues: IrIssue[];
@@ -443,9 +446,26 @@ interface EnumBuilder {
443
446
  doc(text: string): this;
444
447
  dbName(name: string): this;
445
448
  }
449
+ /** Type-setters shared by `UnionBuilder` and `TypeAliasBuilder`. */
450
+ interface TypeVariantBuilder {
451
+ scalar(t: ScalarType): this;
452
+ enum(ref: string): this;
453
+ ref(name: string): this;
454
+ union(build: (u: UnionBuilder) => void): this;
455
+ unknown(hint?: string): this;
456
+ }
457
+ interface UnionBuilder extends TypeVariantBuilder {
458
+ /** `mapping` values must name a `ref` variant of this union. */
459
+ discriminator(propertyName: string, mapping?: Record<string, string>): this;
460
+ }
461
+ interface TypeAliasBuilder extends TypeVariantBuilder {
462
+ doc(text: string): this;
463
+ }
446
464
  interface FieldBuilder {
447
465
  scalar(t: ScalarType): this;
448
466
  enum(ref: string): this;
467
+ ref(name: string): this;
468
+ union(build: (u: UnionBuilder) => void): this;
449
469
  unknown(hint?: string): this;
450
470
  list(): this;
451
471
  optional(): this;
@@ -492,6 +512,7 @@ interface EntityBuilder {
492
512
  interface SourceIrBuilder {
493
513
  addEnum(name: string, def: (e: EnumBuilder) => void): this;
494
514
  addEntity(name: string, def: (e: EntityBuilder) => void): this;
515
+ addTypeAlias(name: string, def: (t: TypeAliasBuilder) => void): this;
495
516
  build(): SourceIR;
496
517
  }
497
518
  declare function createSourceIR(init: {
@@ -510,6 +531,35 @@ declare function getSource(ir: IR, namespace: string): SourceIR | undefined;
510
531
  declare function resolveEntity(ir: IR, namespace: string, name: string): Entity | undefined;
511
532
  /** Entity-local enums shadow source-level enums of the same name. */
512
533
  declare function resolveEnum(source: SourceIR, entity: Entity | undefined, ref: string): EnumDef | undefined;
534
+ /**
535
+ * Resolve a `{ kind: 'ref' }` name against the same source: an entity first,
536
+ * then a type alias. Same-namespace only — v1 has no namespace qualifier.
537
+ */
538
+ declare function resolveRef(source: SourceIR, ref: string): Entity | TypeAlias | undefined;
539
+ declare function resolveTypeAlias(source: SourceIR, name: string): TypeAlias | undefined;
540
+ declare function iterTypeAliases(ir: IR): Iterable<{
541
+ namespace: string;
542
+ alias: TypeAlias;
543
+ }>;
544
+ /** Every `{ kind: 'ref' }` name reachable from a field type (through unions). */
545
+ declare function collectRefNames(type: FieldType, into?: Set<string>): Set<string>;
546
+ /**
547
+ * Names of entities / type aliases that take part in at least one `ref` cycle
548
+ * within `source` — following field-type `ref`, alias `type` `ref` and union
549
+ * variant `ref` edges. Mirrors the informational `union_cycle` pass in
550
+ * `validate.ts`; a generator consumes this (through `GenerateContext.cycles`)
551
+ * to decide which references must be `z.lazy`-wrapped / widened rather than
552
+ * emitted as a bare forward reference.
553
+ */
554
+ declare function refCycleMembers(source: SourceIR): Set<string>;
555
+ /**
556
+ * Flatten nested unions into a single variant list and drop
557
+ * structurally-identical duplicates, preserving first-seen order. The
558
+ * discriminator of a nested union is not carried up.
559
+ */
560
+ declare function flattenUnion(type: Extract<FieldType, {
561
+ kind: 'union';
562
+ }>): FieldType[];
513
563
  /**
514
564
  * A relation is cross-source when its target namespace is anything other than
515
565
  * the entity's own namespace — including the "absent" (empty) namespace, which
@@ -566,11 +616,11 @@ declare function scalarTsType(type: FieldType): string;
566
616
  * (independent versioning): a single string, bumped only on a breaking change
567
617
  * to the format itself.
568
618
  */
569
- declare const IR_VERSION = "1";
619
+ declare const IR_VERSION = "2";
570
620
  /**
571
621
  * Whether an IR produced against `irVersion` can be consumed by this build.
572
622
  * v1 rule: strict equality.
573
623
  */
574
624
  declare function isCompatible(irVersion: string): boolean;
575
625
 
576
- export { type CompositeUnique, CompositeUniqueSchema, type Constraints, ConstraintsSchema, type DefaultValue, DefaultValueSchema, type Entity, type EntityBuilder, EntitySchema, type EnumBuilder, type EnumDef, EnumDefSchema, type EnumValue, EnumValueSchema, type Field, type FieldBuilder, FieldSchema, type FieldType, FieldTypeSchema, type IR, IR_VERSION, type IndexDef, IndexDefSchema, type IndexType, IndexTypeSchema, IrBuildError, type IrIssue, type IrIssueCode, IrSchema, type IrValidation, IrValidationError, type JsonValue, JsonValueSchema, type ReferentialAction, ReferentialActionSchema, type Relation, type RelationBuilder, RelationSchema, type RelationTarget, RelationTargetSchema, type ScalarTsType, type ScalarType, ScalarTypeSchema, type SourceIR, type SourceIrBuilder, SourceIrSchema, type StringFormat, StringFormatSchema, assertIR, assertSourceIR, createFields, createSourceIR, getSource, isCompatible, isCreateOptional, isCrossSource, isDbAssigned, iterEntities, iterFields, parseIR, primaryKeyFields, resolveEntity, resolveEnum, resolveRelationTarget, scalarTsType, updateFields, validateIR, validateSourceIR };
626
+ export { type CompositeUnique, CompositeUniqueSchema, type Constraints, ConstraintsSchema, type DefaultValue, DefaultValueSchema, type Entity, type EntityBuilder, EntitySchema, type EnumBuilder, type EnumDef, EnumDefSchema, type EnumValue, EnumValueSchema, type Field, type FieldBuilder, FieldSchema, type FieldType, FieldTypeSchema, type IR, IR_VERSION, type IndexDef, IndexDefSchema, type IndexType, IndexTypeSchema, IrBuildError, type IrIssue, type IrIssueCode, IrSchema, type IrValidation, IrValidationError, type JsonValue, JsonValueSchema, type ReferentialAction, ReferentialActionSchema, type Relation, type RelationBuilder, RelationSchema, type RelationTarget, RelationTargetSchema, type ScalarTsType, type ScalarType, ScalarTypeSchema, type SourceIR, type SourceIrBuilder, SourceIrSchema, type StringFormat, StringFormatSchema, type TypeAlias, type TypeAliasBuilder, TypeAliasSchema, type TypeVariantBuilder, type UnionBuilder, assertIR, assertSourceIR, collectRefNames, createFields, createSourceIR, flattenUnion, getSource, isCompatible, isCreateOptional, isCrossSource, isDbAssigned, iterEntities, iterFields, iterTypeAliases, parseIR, primaryKeyFields, refCycleMembers, resolveEntity, resolveEnum, resolveRef, resolveRelationTarget, resolveTypeAlias, scalarTsType, updateFields, validateIR, validateSourceIR };