@uncutsql/core 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 François Germain (cahnory)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,80 +1,88 @@
1
1
  # @uncutsql/core
2
2
 
3
- Dialect-independent database models, structural comparison and logical migration
4
- procedures. The only runtime dependency is Effect. No SQL parser, codec, dialect,
5
- filesystem or database driver is imported here.
3
+ The dialect-independent heart of [UncutSQL](../../README.md): the database model, schema
4
+ comparison, migration planning, and the contracts that dialects, drivers and code generators
5
+ implement.
6
6
 
7
- `DatabaseSchema` contains tables, standalone indexes, columns, constraints and option properties.
8
- Table identities distinguish catalog and schema. Each dialect adapter supplies
9
- normalized table identities and column keys; core does not infer namespaces or
10
- fold case. Types and constraint properties use serializable structured values.
11
- Namespaced option keys retain dialect features without hardcoding their meaning.
12
- Object property order is ignored, while array order remains significant.
7
+ **You do not need this package to use UncutSQL.** The CLI depends on it. Install it if you want
8
+ to:
13
9
 
14
- ```ts
15
- import { resolveMigrationDecisions, planDatabaseMigration } from "@uncutsql/core";
10
+ - write a **dialect** for another database, or a **driver** for another client;
11
+ - write a **code generator** or a **mapper** for `uncutsql codegen`;
12
+ - compare schemas or plan migrations from your own code.
16
13
 
17
- const { diff } = yield * resolveMigrationDecisions(beforeDatabase, afterDatabase, decisions);
18
- const migration = planDatabaseMigration(diff);
19
- // migration.procedures: CreateTable | DropTable | AlterTable | RenameTable
14
+ ```sh
15
+ npm install @uncutsql/core effect
20
16
  ```
21
17
 
22
- The logical procedures express requested changes. Each dialect chooses physical
23
- operations, dependency order, rebuild strategy and SQL rendering. Cross-dialect
24
- semantic equivalence is not inferred: adapters must agree on normalized values
25
- before comparison. Views carry a query, and triggers carry a target identity and a
26
- dialect-normalized definition. Changes to either trigger field produce a ReplaceTrigger procedure.
18
+ All operations return [Effect](https://effect.website) values. Core has no dependency other
19
+ than Effect: no SQL parser, filesystem or database access.
27
20
 
28
- ```sh
29
- pnpm --filter @uncutsql/core check
30
- pnpm --filter @uncutsql/core build
21
+ ## The pipeline
22
+
23
+ ```mermaid
24
+ flowchart LR
25
+ SQL[Schema SQL] -->|dialect: parse, toDatabaseSchema| Model[DatabaseSchema]
26
+ Model -->|core: diffDatabases, resolveMigrationDecisions| Diff[Diff]
27
+ Diff -->|core: planDatabaseMigration| Procedures[Logical procedures]
28
+ Procedures -->|dialect: lowerMigration, encodeMigration| Migration[Migration SQL]
29
+ Migration -->|driver: MigrationExecutor| DB[(Database)]
30
+ ```
31
+
32
+ - **`DatabaseSchema`** is a serializable description of namespaces, tables, columns,
33
+ constraints, indexes, views and triggers. `decodeDatabaseSchema` validates one restored from
34
+ JSON.
35
+ - **`diffDatabases(before, after)`** reports what changed.
36
+ - **`prepareMigrationDecisions`**, **`mergeMigrationDecisions`** and
37
+ **`resolveMigrationDecisions`** turn removals into explicit questions (drop, drop if empty,
38
+ rename) and validate the answers. Core never guesses a rename.
39
+ - **`planDatabaseMigration(diff)`** produces logical procedures (`CreateTable`, `AlterTable`,
40
+ `RenameTable`, …). Each dialect decides how to carry them out.
41
+
42
+ ```ts
43
+ import { Effect } from "effect";
44
+
45
+ import { planDatabaseMigration, resolveMigrationDecisions } from "@uncutsql/core";
46
+ import { dialect } from "@uncutsql/sqlite";
47
+
48
+ const migrationSql = (beforeSql: string, afterSql: string) =>
49
+ Effect.gen(function* () {
50
+ const before = yield* dialect.toDatabaseSchema(yield* dialect.parse(beforeSql), "before");
51
+ const after = yield* dialect.toDatabaseSchema(yield* dialect.parse(afterSql), "after");
52
+ const { diff } = yield* resolveMigrationDecisions(before, after);
53
+ const plan = yield* dialect.lowerMigration(planDatabaseMigration(diff), before, after);
54
+ return yield* dialect.encodeMigration(plan);
55
+ });
56
+ // migrationSql("create table t (a int)", "create table t (a int, b text)")
57
+ // BEGIN;
58
+ // ALTER TABLE "main"."t" ADD COLUMN "b" text;
59
+ // COMMIT;
31
60
  ```
32
61
 
33
- `Dialect<Ast, PhysicalPlan, E, R>` is the capability contract for interchangeable
34
- adapters: parse/format SQL, convert ASTs to the shared model, lower logical
35
- procedures and render a physical plan. Users own the composition. Core never
36
- selects or imports a dialect, and dialect packages must not run the core diff or
37
- logical planner on behalf of callers. The CLI demonstrates the wiring and tests
38
- its workflow with a separate fixture adapter that has a different AST and plan.
39
-
40
- `decodeDatabaseSchema(unknown)` validates JSON-restored/external model shapes and
41
- serializable semantic values with path-based SchemaModelError failures. Model
42
- validation is separate from duplicate-identity checking in the diff. Lock versions,
43
- dialect IDs, migration history and filesystem persistence remain consumer concerns.
44
-
45
- `MigrationExecutor` is a separate optional runtime contract. Consumers provide the
46
- full ordered MigrationSource history and a schema-verification callback, leaving
47
- core comparison in the application. An executor owns connections, physical
48
- transactions and applied-history recording. It is selected independently from the
49
- syntax dialect; core itself has no database driver or filesystem dependency.
50
-
51
- ## Migration decisions
52
-
53
- `prepareMigrationDecisions(before, after)` returns a versioned JSON document with
54
- both schema snapshots and structured questions for removed tables and columns.
55
- Column questions list all added keys in that table as candidates; no similarity
56
- heuristic selects a rename. Each `resolution` starts as `{ "action": "pending" }`.
57
-
58
- Table questions list added table names in the same namespace. Consumers choose
59
- `drop`, `drop_if_empty`, or `rename` with a listed target. After choosing a table
60
- rename, `mergeMigrationDecisions` adds questions for columns removed from that
61
- table and retains reviewed answers for the same source and target. Then
62
- `resolveMigrationDecisions(before, after, document)` validates the untrusted
63
- answers and snapshots and returns a resolved diff and sanitized decision record.
64
- Missing, stale, duplicate or conflicting answers fail with MigrationDecisionError;
65
- its `pending` field carries the review document. Additions alone need no answers.
66
-
67
- Table renames become RenameTable procedures. Column renames become ColumnRenamed alterations, including separate dataType/constraints
68
- change fields. The desired schema remains authoritative: rename decisions do not
69
- rewrite desired CHECK expressions or foreign-key references. Custom transformations, similarity ranking and automatic approval are not provided.
70
-
71
- Core has no prompts or persistence. `planDatabaseMigration` remains a low-level
72
- primitive for caller-approved intent; user-facing workflows should resolve
73
- choices before calling it. The CLI enforces this sequence for migration/generate.
74
-
75
- ## Roadmap
76
-
77
- - [x] Represent views in serializable database snapshots, validate restored snapshots, and describe view changes in the diff and logical plan.
78
- - [x] Represent trigger snapshots, validate restored models and lower trigger diffs to logical procedures.
79
-
80
- See the [workspace roadmap](../../ROADMAP.md) for cross-project sequencing.
62
+ `resolveMigrationDecisions` fails with a `MigrationDecisionError` listing the questions when a
63
+ table or column was removed; pass the answered document as its third argument.
64
+
65
+ ## Extension contracts
66
+
67
+ | Contract | Implemented by | Loaded by the CLI from |
68
+ | ------------------- | ------------------------------- | ------------------------------------------ |
69
+ | `Dialect` | `@uncutsql/sqlite`, … | the `dialect` export (or default export) |
70
+ | `MigrationExecutor` | `@uncutsql/sqlite-driver`, … | the `executor` export (or default export) |
71
+ | `MapperPlugin` | `@uncutsql/typescript` | the `mapper` export (or default export) |
72
+ | `GeneratorPlugin` | `@uncutsql/generator-kysely`, … | the `generator` export (or default export) |
73
+
74
+ Point the configuration at your own module to use it:
75
+
76
+ ```json
77
+ {
78
+ "dialect": "./my-dialect.mjs",
79
+ "generators": { "docs": { "plugin": "./my-generator.mjs", "mapper": "app", "output": "./docs" } }
80
+ }
81
+ ```
82
+
83
+ A dialect can also provide `resolveSemanticSchema`, which derives the facts code generators
84
+ rely on (types, nullability, defaults, keys), and a `languageService` for the editor.
85
+
86
+ The full contracts, including migration decision documents and executor helpers, are described
87
+ in [DEVELOPMENT.md](DEVELOPMENT.md). The existing dialect and driver packages are the best
88
+ examples.
package/dist/index.cjs CHANGED
@@ -6,6 +6,12 @@ const tableKey = (table) => JSON.stringify([
6
6
  table.schema ?? null,
7
7
  table.name
8
8
  ]);
9
+ const namespaceKey = (namespace) => JSON.stringify([namespace.catalog ?? null, namespace.name]);
10
+ /** The namespace that contains an object, or undefined when its identity has no schema level. */
11
+ const namespaceOf = (identity) => identity.schema === void 0 ? void 0 : identity.catalog === void 0 ? { name: identity.schema } : {
12
+ catalog: identity.catalog,
13
+ name: identity.schema
14
+ };
9
15
  /** Object property insertion order is not semantic; array order is retained. */
10
16
  const schemaValueEqual = (before, after) => {
11
17
  if (before === after) return true;
@@ -85,6 +91,34 @@ const validateDatabase = (database, side) => {
85
91
  });
86
92
  triggers.add(id);
87
93
  }
94
+ const namespaces = /* @__PURE__ */ new Set();
95
+ for (const namespace of database.namespaces ?? []) {
96
+ const id = namespaceKey(namespace.identity);
97
+ if (namespaces.has(id)) diagnostics.push({
98
+ code: "DuplicateNamespace",
99
+ message: `Duplicate namespace ${id}`,
100
+ side,
101
+ table: namespace.identity
102
+ });
103
+ namespaces.add(id);
104
+ }
105
+ if (database.namespaces) {
106
+ const undeclared = (identity, owner, role) => {
107
+ const namespace = namespaceOf(identity);
108
+ if (namespace && !namespaces.has(namespaceKey(namespace))) diagnostics.push({
109
+ code: "UndeclaredNamespace",
110
+ message: `${role} ${tableKey(identity)} belongs to undeclared namespace ${namespaceKey(namespace)}`,
111
+ side,
112
+ table: owner
113
+ });
114
+ };
115
+ for (const table of database.tables) undeclared(table.identity, table.identity, "Table");
116
+ for (const view of database.views ?? []) undeclared(view.identity, view.identity, "View");
117
+ for (const trigger of database.triggers ?? []) {
118
+ undeclared(trigger.identity, trigger.identity, "Trigger");
119
+ undeclared(trigger.target, trigger.identity, "Target of trigger");
120
+ }
121
+ }
88
122
  return diagnostics;
89
123
  };
90
124
  const constraintsEqual = (before, after) => before.length === after.length && before.every((item, index) => item.kind === after[index].kind && schemaValueEqual(item.properties, after[index].properties));
@@ -158,9 +192,27 @@ const compareTable = (before, after) => {
158
192
  const diffDatabases = (before, after) => effect.Effect.gen(function* () {
159
193
  const diagnostics = [...validateDatabase(before, "before"), ...validateDatabase(after, "after")];
160
194
  if (diagnostics.length) return yield* effect.Effect.fail(new SchemaDiffError({ diagnostics }));
195
+ const changes = [];
196
+ const oldNamespaces = new Map((before.namespaces ?? []).map((namespace) => [namespaceKey(namespace.identity), namespace]));
197
+ const newNamespaces = new Map((after.namespaces ?? []).map((namespace) => [namespaceKey(namespace.identity), namespace]));
198
+ for (const [key, namespace] of oldNamespaces) if (!newNamespaces.has(key)) changes.push({
199
+ _tag: "NamespaceRemoved",
200
+ namespace
201
+ });
202
+ for (const [key, namespace] of newNamespaces) {
203
+ const old = oldNamespaces.get(key);
204
+ if (!old) changes.push({
205
+ _tag: "NamespaceAdded",
206
+ namespace
207
+ });
208
+ else if (old.name !== namespace.name || !schemaValueEqual(old.options, namespace.options)) changes.push({
209
+ _tag: "NamespaceChanged",
210
+ after: namespace,
211
+ before: old
212
+ });
213
+ }
161
214
  const previous = new Map(before.tables.map((table) => [tableKey(table.identity), table]));
162
215
  const next = new Map(after.tables.map((table) => [tableKey(table.identity), table]));
163
- const changes = [];
164
216
  for (const [key, table] of previous) if (!next.has(key)) changes.push({
165
217
  _tag: "TableRemoved",
166
218
  definition: table,
@@ -228,6 +280,16 @@ const planDatabaseMigration = (diff) => ({
228
280
  ...diff.dropGuards ? { dropGuards: diff.dropGuards } : {},
229
281
  procedures: diff.changes.map((change) => {
230
282
  switch (change._tag) {
283
+ case "NamespaceAdded":
284
+ case "NamespaceRemoved": return {
285
+ _tag: change._tag === "NamespaceAdded" ? "CreateNamespace" : "DropNamespace",
286
+ namespace: change.namespace
287
+ };
288
+ case "NamespaceChanged": return {
289
+ _tag: "AlterNamespace",
290
+ after: change.after,
291
+ before: change.before
292
+ };
231
293
  case "TriggerAdded":
232
294
  case "TriggerRemoved": return {
233
295
  _tag: change._tag === "TriggerAdded" ? "CreateTrigger" : "DropTrigger",
@@ -293,6 +355,14 @@ const planDownMigration = (up) => {
293
355
  _tag: step._tag === "CreateView" ? "DropView" : "CreateView"
294
356
  });
295
357
  break;
358
+ case "CreateNamespace":
359
+ case "DropNamespace":
360
+ procedures.push({
361
+ ...step,
362
+ _tag: step._tag === "CreateNamespace" ? "DropNamespace" : "CreateNamespace"
363
+ });
364
+ break;
365
+ case "AlterNamespace":
296
366
  case "ReplaceView":
297
367
  case "ReplaceTrigger":
298
368
  procedures.push(swap(step));
@@ -449,6 +519,20 @@ const view = (value, path) => {
449
519
  if (Object.hasOwn(item, "columns")) array(item.columns, `${path}.columns`, text);
450
520
  semanticValue(item.query, `${path}.query`);
451
521
  };
522
+ const namespace = (value, path) => {
523
+ const item = record$1(value, path);
524
+ fields(item, [
525
+ "identity",
526
+ "name",
527
+ "options"
528
+ ], path);
529
+ const identity = record$1(item.identity, `${path}.identity`);
530
+ fields(identity, ["catalog", "name"], `${path}.identity`);
531
+ text(identity.name, `${path}.identity.name`);
532
+ if (Object.hasOwn(identity, "catalog")) text(identity.catalog, `${path}.identity.catalog`);
533
+ text(item.name, `${path}.name`);
534
+ properties(item.options, `${path}.options`);
535
+ };
452
536
  const table = (value, path) => {
453
537
  const item = record$1(value, path);
454
538
  fields(item, [
@@ -475,16 +559,42 @@ const decodeDatabaseSchema = (value) => effect.Effect.try({
475
559
  try: () => {
476
560
  const database = record$1(value, "$database");
477
561
  fields(database, [
562
+ "namespaces",
478
563
  "tables",
479
564
  "views",
480
565
  "triggers"
481
566
  ], "$database");
567
+ if (Object.hasOwn(database, "namespaces")) array(database.namespaces, "$database.namespaces", namespace);
482
568
  array(database.tables, "$database.tables", table);
483
569
  if (Object.hasOwn(database, "views")) array(database.views, "$database.views", view);
484
570
  if (Object.hasOwn(database, "triggers")) array(database.triggers, "$database.triggers", trigger);
485
571
  return value;
486
572
  }
487
573
  });
574
+ // src/executor.ts
575
+ const checksumPattern = /^[a-f0-9]{64}$/;
576
+ /** The run, or `undefined` when IDs, baseline, checkpoint, SQL or checksums are invalid. */
577
+ const migrationRun = (direction, migrations, checkpoint, sha256) => {
578
+ const down = direction === "down";
579
+ const baseline = migrations[0]?.baselineCheckpoint !== void 0 ? migrations[0] : void 0;
580
+ const checkpointId = checkpoint?.id ?? 0;
581
+ const firstUpId = baseline?.id ?? checkpointId + 1;
582
+ const offset = down ? Math.max(0, checkpointId - 1) : firstUpId - 1;
583
+ if (baseline !== void 0 && (down || checkpointId !== 0 || !Number.isSafeInteger(baseline.id) || baseline.id < 2 || !checksumPattern.test(baseline.baselineCheckpoint)) || down && checkpoint !== void 0 && (migrations.length !== (checkpoint.id ? 1 : 0) || checkpoint.id > 0 && migrations[0]?.sha256 !== checkpoint.sha256) || migrations.some((migration, index) => index > 0 && migration.baselineCheckpoint !== void 0 || migration.id !== offset + index + 1 || !migration.sql.trim() || migration.sql.includes("\0") || sha256(migration.sql) !== migration.sha256)) return;
584
+ return {
585
+ ...baseline ? { baseline } : {},
586
+ direction,
587
+ lastId: offset + migrations.length,
588
+ offset
589
+ };
590
+ };
591
+ /** Whether the history tip read under the write transaction is a matching prefix of the run. */
592
+ const continuesRun = (run, migrations, checkpoint, tip) => {
593
+ const applied = migrations[tip.id - run.offset - 1];
594
+ return !((checkpoint && tip.id === checkpoint.id ? checkpoint.sha256 : tip.id === 0 ? null : applied?.baselineCheckpoint ?? applied?.sha256) !== tip.sha256 || tip.id < (checkpoint?.id ?? 0) || run.direction === "down" && checkpoint !== void 0 && tip.id !== checkpoint.id);
595
+ };
596
+ /** The file to execute after the tip, or `undefined` when the run is complete. */
597
+ const nextMigration = (run, migrations, tipId) => run.baseline && tipId === 0 ? run.baseline : migrations[tipId - run.offset - (run.direction === "down" ? 1 : 0)];
488
598
  // src/decisions.ts
489
599
  var MigrationDecisionError = class extends effect.Data.TaggedError("MigrationDecisionError") {};
490
600
  const equal = (a, b) => schemaValueEqual(a, b);
@@ -725,17 +835,192 @@ const resolveMigrationDecisions = (before, after, supplied) => effect.Effect.gen
725
835
  diff: resolved
726
836
  };
727
837
  });
838
+ // src/language-service.ts
839
+ /** Returns the first reference whose half-open span contains `offset`. */
840
+ const referenceAt = (analysis, offset) => analysis.references.find((reference) => reference.start <= offset && offset < reference.end);
841
+ /** Returns the selections of the declarations whose key equals the reference key, in declaration order. */
842
+ const definitions = (reference, analysis) => analysis.declarations.filter((declaration) => declaration.key === reference.key).map((declaration) => declaration.selection);
843
+ // src/codegen.ts
844
+ var CodegenError = class extends effect.Data.TaggedError("CodegenError") {};
845
+ const generatedFileHeader = "// Generated by UncutSQL. Do not edit.";
846
+ // src/codegen-validation.ts
847
+ const identifier = effect.Schema.Trimmed.check(effect.Schema.isNonEmpty());
848
+ const version = effect.Schema.Int.check(effect.Schema.isGreaterThan(0));
849
+ const applicationContract = effect.Schema.Struct({
850
+ id: identifier,
851
+ version
852
+ });
853
+ const generatorInput = effect.Schema.Struct({
854
+ id: identifier,
855
+ versions: effect.Schema.NonEmptyArray(version)
856
+ });
857
+ const mapperDescriptor = effect.Schema.Struct({
858
+ name: identifier,
859
+ output: applicationContract
860
+ });
861
+ const generatorDescriptor = effect.Schema.Struct({
862
+ input: generatorInput,
863
+ name: identifier
864
+ });
865
+ const relationIdentitySchema = effect.Schema.Struct({
866
+ catalog: effect.Schema.optionalKey(effect.Schema.String),
867
+ name: effect.Schema.String,
868
+ schema: effect.Schema.optionalKey(effect.Schema.String)
869
+ });
870
+ const codegenDiagnosticSchema = effect.Schema.Struct({
871
+ code: identifier,
872
+ message: effect.Schema.NonEmptyString,
873
+ severity: effect.Schema.Literals(["error", "warning"]),
874
+ subjects: effect.Schema.Array(effect.Schema.Union([effect.Schema.Struct({
875
+ identity: effect.Schema.Struct({
876
+ key: effect.Schema.String,
877
+ table: relationIdentitySchema
878
+ }),
879
+ kind: effect.Schema.Literal("column")
880
+ }), effect.Schema.Struct({
881
+ identity: relationIdentitySchema,
882
+ kind: effect.Schema.Literal("relation")
883
+ })]))
884
+ });
885
+ const diagnostics = effect.Schema.Array(codegenDiagnosticSchema);
886
+ const taggedCodegenError = effect.Schema.Struct({
887
+ _tag: effect.Schema.Literal("CodegenError"),
888
+ code: identifier,
889
+ diagnostics: effect.Schema.optionalKey(diagnostics),
890
+ message: effect.Schema.String,
891
+ path: effect.Schema.optionalKey(effect.Schema.String)
892
+ });
893
+ const artifactPathSchema = effect.Schema.String.check(effect.Schema.makeFilter((path) => !path.includes("\\") && !path.includes(":") && !path.includes("\0") && path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".."), { expected: "a slash-separated relative file path without traversal" }));
894
+ const artifact = effect.Schema.Struct({
895
+ content: effect.Schema.String,
896
+ path: artifactPathSchema
897
+ });
898
+ const generationResult = effect.Schema.Struct({
899
+ artifacts: effect.Schema.Array(artifact),
900
+ diagnostics
901
+ });
902
+ const mappingResult = effect.Schema.Struct({
903
+ diagnostics,
904
+ schema: effect.Schema.Unknown
905
+ });
906
+ const wrapError = (cause, code, path, fallback) => {
907
+ if (cause instanceof CodegenError) return cause;
908
+ const details = effect.Schema.decodeUnknownOption(taggedCodegenError)(cause);
909
+ if (effect.Option.isSome(details)) {
910
+ const { _tag, ...fields } = details.value;
911
+ return new CodegenError({
912
+ ...fields,
913
+ cause
914
+ });
915
+ }
916
+ return new CodegenError({
917
+ cause,
918
+ code,
919
+ message: cause instanceof Error ? cause.message : fallback,
920
+ path
921
+ });
922
+ };
923
+ const validate = (decode, code, path) => effect.Effect.try({
924
+ catch: (cause) => wrapError(cause, code, path, "Invalid codegen value"),
925
+ try: decode
926
+ });
927
+ /** Check the exact application contract ID and an explicitly accepted version. */
928
+ const validateApplicationCompatibility = (output, input) => effect.Effect.gen(function* () {
929
+ const contract = yield* validate(() => effect.Schema.decodeUnknownSync(applicationContract)(output), "invalid-contract", "output");
930
+ const accepted = yield* validate(() => effect.Schema.decodeUnknownSync(generatorInput)(input), "invalid-contract", "input");
931
+ if (contract.id !== accepted.id || !accepted.versions.includes(contract.version)) return yield* new CodegenError({
932
+ code: "incompatible-contract",
933
+ message: `Received application contract ${contract.id}@${contract.version}. Expected ${accepted.id} at one of versions ${accepted.versions.join(", ")}.`,
934
+ path: "input"
935
+ });
936
+ return contract;
937
+ });
938
+ /** Validate the text artifact and diagnostic envelopes before handing results to a consumer. */
939
+ const decodeGenerationResult = (value) => validate(() => effect.Schema.decodeUnknownSync(generationResult)(value), "invalid-result", "generation");
940
+ const readExport = (value, kind) => {
941
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`Expected a ${kind} plugin object`);
942
+ return value;
943
+ };
944
+ const method = (plugin, name) => {
945
+ const callback = plugin[name];
946
+ if (typeof callback !== "function") throw new CodegenError({
947
+ code: "invalid-plugin",
948
+ message: `Plugin requires a ${name}() method`,
949
+ path: name
950
+ });
951
+ return (...args) => Reflect.apply(callback, plugin, args);
952
+ };
953
+ const invoke = (callback, code, path) => effect.Effect.flatMap(validate(() => {
954
+ const result = callback();
955
+ if (!effect.Effect.isEffect(result)) throw new CodegenError({
956
+ code: "invalid-plugin",
957
+ message: `${path}() must return an Effect`,
958
+ path
959
+ });
960
+ return result;
961
+ }, "invalid-plugin", path), (effect$1) => effect.Effect.mapError(effect$1, (cause) => wrapError(cause, code, path, `Plugin ${path}() failed`)));
962
+ /** Validate the mapper value selected from a module by the consumer. */
963
+ const decodeMapperPlugin = (value) => validate(() => {
964
+ const plugin = readExport(value, "mapper");
965
+ const descriptor = effect.Schema.decodeUnknownSync(mapperDescriptor)(plugin.descriptor);
966
+ const decodeInput = method(plugin, "decodeInput");
967
+ const decodeOptions = method(plugin, "decodeOptions");
968
+ const map = method(plugin, "map");
969
+ return {
970
+ descriptor,
971
+ map: (schema, options) => effect.Effect.gen(function* () {
972
+ const input = yield* invoke(() => decodeInput(schema), "invalid-input", "decodeInput");
973
+ const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
974
+ const result = yield* invoke(() => map(input, settings), "mapping-failed", "map");
975
+ return yield* validate(() => effect.Schema.decodeUnknownSync(mappingResult)(result), "invalid-result", "mapping");
976
+ })
977
+ };
978
+ }, "invalid-plugin", "mapper");
979
+ /** Validate the generator value selected from a module by the consumer. */
980
+ const decodeGeneratorPlugin = (value) => validate(() => {
981
+ const plugin = readExport(value, "generator");
982
+ const descriptor = effect.Schema.decodeUnknownSync(generatorDescriptor)(plugin.descriptor);
983
+ const decodeInput = method(plugin, "decodeInput");
984
+ const decodeOptions = method(plugin, "decodeOptions");
985
+ const generate = method(plugin, "generate");
986
+ return {
987
+ descriptor,
988
+ generate: (contract, schema, options) => effect.Effect.gen(function* () {
989
+ const compatible = yield* validateApplicationCompatibility(contract, descriptor.input);
990
+ const input = yield* invoke(() => decodeInput(schema, compatible), "invalid-input", "decodeInput");
991
+ const settings = yield* invoke(() => decodeOptions(options), "invalid-options", "decodeOptions");
992
+ const result = yield* invoke(() => generate(input, settings), "generation-failed", "generate");
993
+ return yield* decodeGenerationResult(result);
994
+ })
995
+ };
996
+ }, "invalid-plugin", "generator");
997
+ exports.CodegenError = CodegenError;
728
998
  exports.MigrationDecisionError = MigrationDecisionError;
729
999
  exports.SchemaDiffError = SchemaDiffError;
730
1000
  exports.SchemaModelError = SchemaModelError;
1001
+ exports.artifactPathSchema = artifactPathSchema;
1002
+ exports.codegenDiagnosticSchema = codegenDiagnosticSchema;
731
1003
  exports.compareTable = compareTable;
1004
+ exports.continuesRun = continuesRun;
732
1005
  exports.decodeDatabaseSchema = decodeDatabaseSchema;
1006
+ exports.decodeGenerationResult = decodeGenerationResult;
1007
+ exports.decodeGeneratorPlugin = decodeGeneratorPlugin;
1008
+ exports.decodeMapperPlugin = decodeMapperPlugin;
1009
+ exports.definitions = definitions;
733
1010
  exports.diffDatabases = diffDatabases;
1011
+ exports.generatedFileHeader = generatedFileHeader;
734
1012
  exports.mergeMigrationDecisions = mergeMigrationDecisions;
1013
+ exports.migrationRun = migrationRun;
1014
+ exports.namespaceKey = namespaceKey;
1015
+ exports.namespaceOf = namespaceOf;
1016
+ exports.nextMigration = nextMigration;
735
1017
  exports.planDatabaseMigration = planDatabaseMigration;
736
1018
  exports.planDownMigration = planDownMigration;
737
1019
  exports.prepareMigrationDecisions = prepareMigrationDecisions;
1020
+ exports.referenceAt = referenceAt;
1021
+ exports.relationIdentitySchema = relationIdentitySchema;
738
1022
  exports.resolveMigrationDecisions = resolveMigrationDecisions;
739
1023
  exports.schemaValueEqual = schemaValueEqual;
740
1024
  exports.tableKey = tableKey;
1025
+ exports.validateApplicationCompatibility = validateApplicationCompatibility;
741
1026
  exports.validateDatabase = validateDatabase;