@aeye/query 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -82,6 +82,9 @@ var AID_REGISTRY = {
82
82
  Source: { label: "a query source", noun: "source" },
83
83
  // ── Scalars / literals ────────────────────────────────────────────────────
84
84
  ScalarValue: { label: "a literal value: string, number, boolean, or null" },
85
+ LiteralValue: {
86
+ label: "a literal value: string, number, boolean, null, or a whole JSON document (object / array) for a json / array field"
87
+ },
85
88
  TypeName: { label: "a registered Type name" },
86
89
  FieldName: { label: "a field name" },
87
90
  FunctionName: { label: "a registered function name" },
@@ -110,7 +113,7 @@ var AID_REGISTRY = {
110
113
  SourceName: { label: "a bound source name" },
111
114
  SelectField: { label: "a select field, an object of { expr, as? }" },
112
115
  FieldValue: { label: "a field assignment, an object of { field, value }" },
113
- WriteValue: { label: "a write value: a typed value or an expression (use JSON null / omit to skip a field)" },
116
+ WriteValue: { label: "a write value: a typed value, a JSON document (object / array) for a json / array field, or an expression (use JSON null / omit to skip a field)" },
114
117
  InsertRow: { label: "an INSERT row, a { field: value } object" },
115
118
  SetValue: { label: "a SET record, a { field: value } object" },
116
119
  OnConflict: { label: "an ON CONFLICT clause, an object of { fields, doNothing?, update? }" },
@@ -829,16 +832,16 @@ var NumberFieldType = class _NumberFieldType extends FieldType {
829
832
  /** This instance's discriminant kind. */
830
833
  kind = _NumberFieldType.NAME;
831
834
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
832
- static from(json) {
833
- if (json.kind !== "number") {
835
+ static from(json2) {
836
+ if (json2.kind !== "number") {
834
837
  throw new QueryTypeError({
835
838
  path: [],
836
839
  code: "field-type.mismatch",
837
840
  severity: "error",
838
- message: `NumberFieldType.from: expected kind 'number', got '${json.kind}'`
841
+ message: `NumberFieldType.from: expected kind 'number', got '${json2.kind}'`
839
842
  });
840
843
  }
841
- const { min: min2, max: max2, whole, minPlaces, maxPlaces, values } = json;
844
+ const { min: min2, max: max2, whole, minPlaces, maxPlaces, values } = json2;
842
845
  return new _NumberFieldType(compactNumberOptions({ min: min2, max: max2, whole, minPlaces, maxPlaces, values }));
843
846
  }
844
847
  /** The Zod schema for this field type's JSON def. */
@@ -912,16 +915,16 @@ var TextFieldType = class _TextFieldType extends FieldType {
912
915
  return this.options.sensitive === true;
913
916
  }
914
917
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
915
- static from(json) {
916
- if (json.kind !== "text") {
918
+ static from(json2) {
919
+ if (json2.kind !== "text") {
917
920
  throw new QueryTypeError({
918
921
  path: [],
919
922
  code: "field-type.mismatch",
920
923
  severity: "error",
921
- message: `TextFieldType.from: expected kind 'text', got '${json.kind}'`
924
+ message: `TextFieldType.from: expected kind 'text', got '${json2.kind}'`
922
925
  });
923
926
  }
924
- const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values } = json;
927
+ const { minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values } = json2;
925
928
  return new _TextFieldType(compact({ minLength, maxLength, pattern, semantic: semantic2, search, sensitive, values }));
926
929
  }
927
930
  /** The Zod schema for this field type's JSON def. */
@@ -996,16 +999,16 @@ var MoneyFieldType = class _MoneyFieldType extends FieldType {
996
999
  /** This instance's discriminant kind. */
997
1000
  kind = _MoneyFieldType.NAME;
998
1001
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
999
- static from(json) {
1000
- if (json.kind !== "money") {
1002
+ static from(json2) {
1003
+ if (json2.kind !== "money") {
1001
1004
  throw new QueryTypeError({
1002
1005
  path: [],
1003
1006
  code: "field-type.mismatch",
1004
1007
  severity: "error",
1005
- message: `MoneyFieldType.from: expected kind 'money', got '${json.kind}'`
1008
+ message: `MoneyFieldType.from: expected kind 'money', got '${json2.kind}'`
1006
1009
  });
1007
1010
  }
1008
- return new _MoneyFieldType(compact2({ number: json.number, currency: json.currency }));
1011
+ return new _MoneyFieldType(compact2({ number: json2.number, currency: json2.currency }));
1009
1012
  }
1010
1013
  /** The Zod schema for this field type's JSON def. */
1011
1014
  static toSchema() {
@@ -1052,13 +1055,13 @@ var BoolFieldType = class _BoolFieldType extends FieldType {
1052
1055
  /** This instance's discriminant kind. */
1053
1056
  kind = _BoolFieldType.NAME;
1054
1057
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1055
- static from(json) {
1056
- if (json.kind !== "bool") {
1058
+ static from(json2) {
1059
+ if (json2.kind !== "bool") {
1057
1060
  throw new QueryTypeError({
1058
1061
  path: [],
1059
1062
  code: "field-type.mismatch",
1060
1063
  severity: "error",
1061
- message: `BoolFieldType.from: expected kind 'bool', got '${json.kind}'`
1064
+ message: `BoolFieldType.from: expected kind 'bool', got '${json2.kind}'`
1062
1065
  });
1063
1066
  }
1064
1067
  return new _BoolFieldType();
@@ -1319,16 +1322,16 @@ var RelationFieldType = class _RelationFieldType extends FieldType {
1319
1322
  /** This instance's discriminant kind. */
1320
1323
  kind = _RelationFieldType.NAME;
1321
1324
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1322
- static from(json) {
1323
- if (json.kind !== "relation") {
1325
+ static from(json2) {
1326
+ if (json2.kind !== "relation") {
1324
1327
  throw new QueryTypeError({
1325
1328
  path: [],
1326
1329
  code: "field-type.mismatch",
1327
1330
  severity: "error",
1328
- message: `RelationFieldType.from: expected kind 'relation', got '${json.kind}'`
1331
+ message: `RelationFieldType.from: expected kind 'relation', got '${json2.kind}'`
1329
1332
  });
1330
1333
  }
1331
- return new _RelationFieldType(json.to, json.count, json.inverseRelation);
1334
+ return new _RelationFieldType(json2.to, json2.count, json2.inverseRelation);
1332
1335
  }
1333
1336
  /** The Zod schema for this field type's JSON def. */
1334
1337
  static toSchema() {
@@ -1498,16 +1501,16 @@ var TimestampFieldType = class _TimestampFieldType extends FieldType {
1498
1501
  /** This instance's discriminant kind. */
1499
1502
  kind = _TimestampFieldType.NAME;
1500
1503
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1501
- static from(json) {
1502
- if (json.kind !== "timestamp") {
1504
+ static from(json2) {
1505
+ if (json2.kind !== "timestamp") {
1503
1506
  throw new QueryTypeError({
1504
1507
  path: [],
1505
1508
  code: "field-type.mismatch",
1506
1509
  severity: "error",
1507
- message: `TimestampFieldType.from: expected kind 'timestamp', got '${json.kind}'`
1510
+ message: `TimestampFieldType.from: expected kind 'timestamp', got '${json2.kind}'`
1508
1511
  });
1509
1512
  }
1510
- return new _TimestampFieldType(json.timezone);
1513
+ return new _TimestampFieldType(json2.timezone);
1511
1514
  }
1512
1515
  /** The Zod schema for this field type's JSON def. */
1513
1516
  static toSchema() {
@@ -1555,16 +1558,16 @@ var DateFieldType = class _DateFieldType extends FieldType {
1555
1558
  /** This instance's discriminant kind. */
1556
1559
  kind = _DateFieldType.NAME;
1557
1560
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1558
- static from(json) {
1559
- if (json.kind !== "date") {
1561
+ static from(json2) {
1562
+ if (json2.kind !== "date") {
1560
1563
  throw new QueryTypeError({
1561
1564
  path: [],
1562
1565
  code: "field-type.mismatch",
1563
1566
  severity: "error",
1564
- message: `DateFieldType.from: expected kind 'date', got '${json.kind}'`
1567
+ message: `DateFieldType.from: expected kind 'date', got '${json2.kind}'`
1565
1568
  });
1566
1569
  }
1567
- return new _DateFieldType(json.timezone);
1570
+ return new _DateFieldType(json2.timezone);
1568
1571
  }
1569
1572
  /** The Zod schema for this field type's JSON def. */
1570
1573
  static toSchema() {
@@ -1625,16 +1628,16 @@ var JsonFieldType = class _JsonFieldType extends FieldType {
1625
1628
  /** This instance's discriminant kind. */
1626
1629
  kind = _JsonFieldType.NAME;
1627
1630
  /** Reconstruct from a JSON def (throws on a kind mismatch). */
1628
- static from(json) {
1629
- if (json.kind !== "json") {
1631
+ static from(json2) {
1632
+ if (json2.kind !== "json") {
1630
1633
  throw new QueryTypeError({
1631
1634
  path: [],
1632
1635
  code: "field-type.mismatch",
1633
1636
  severity: "error",
1634
- message: `JsonFieldType.from: expected kind 'json', got '${json.kind}'`
1637
+ message: `JsonFieldType.from: expected kind 'json', got '${json2.kind}'`
1635
1638
  });
1636
1639
  }
1637
- return new _JsonFieldType(json.schema);
1640
+ return new _JsonFieldType(json2.schema);
1638
1641
  }
1639
1642
  /** The Zod schema for this field type's JSON def. */
1640
1643
  static toSchema() {
@@ -1693,17 +1696,17 @@ var ArrayFieldType = class _ArrayFieldType extends FieldType {
1693
1696
  /** This instance's discriminant kind. */
1694
1697
  kind = _ArrayFieldType.NAME;
1695
1698
  /** Reconstruct from a JSON def, parsing the element type via the registry. */
1696
- static from(json, registry) {
1697
- if (json.kind !== "array") {
1699
+ static from(json2, registry) {
1700
+ if (json2.kind !== "array") {
1698
1701
  throw new QueryTypeError({
1699
1702
  path: [],
1700
1703
  code: "field-type.mismatch",
1701
1704
  severity: "error",
1702
- message: `ArrayFieldType.from: expected kind 'array', got '${json.kind}'`
1705
+ message: `ArrayFieldType.from: expected kind 'array', got '${json2.kind}'`
1703
1706
  });
1704
1707
  }
1705
- const item = json.item !== void 0 && registry ? registry.parseFieldType(json.item) : void 0;
1706
- return new _ArrayFieldType(item, json.minItems, json.maxItems);
1708
+ const item = json2.item !== void 0 && registry ? registry.parseFieldType(json2.item) : void 0;
1709
+ return new _ArrayFieldType(item, json2.minItems, json2.maxItems);
1707
1710
  }
1708
1711
  /** The Zod schema for this field type's JSON def. */
1709
1712
  static toSchema() {
@@ -1830,21 +1833,21 @@ var Field = class _Field {
1830
1833
  this.synthetic = spec.synthetic ?? false;
1831
1834
  }
1832
1835
  /** Build a Field from its JSON, parsing the field type via `registry`. */
1833
- static from(json, registry) {
1834
- const fieldType = registry.parseFieldType(json.type);
1836
+ static from(json2, registry) {
1837
+ const fieldType = registry.parseFieldType(json2.type);
1835
1838
  return new _Field({
1836
- name: json.name,
1837
- label: json.label,
1838
- description: json.description,
1839
+ name: json2.name,
1840
+ label: json2.label,
1841
+ description: json2.description,
1839
1842
  fieldType,
1840
1843
  // An explicit per-field `bytes` wins; otherwise a registry-level default for
1841
1844
  // this field type's kind may apply (else the field type's own avgBytes()).
1842
- bytes: json.bytes ?? registry.defaultFieldBytes(fieldType.kind),
1843
- changes: json.changes,
1844
- nullable: json.nullable ?? false,
1845
- insertable: json.insertable,
1846
- updatable: json.updatable,
1847
- exprs: json.exprs
1845
+ bytes: json2.bytes ?? registry.defaultFieldBytes(fieldType.kind),
1846
+ changes: json2.changes,
1847
+ nullable: json2.nullable ?? false,
1848
+ insertable: json2.insertable,
1849
+ updatable: json2.updatable,
1850
+ exprs: json2.exprs
1848
1851
  });
1849
1852
  }
1850
1853
  /**
@@ -1966,8 +1969,8 @@ function stableStringify(value2) {
1966
1969
  return JSON.stringify(value2);
1967
1970
  }
1968
1971
  function exprDigest(expr) {
1969
- const json = JSON.parse(JSON.stringify(expr));
1970
- return stableStringify(json);
1972
+ const json2 = JSON.parse(JSON.stringify(expr));
1973
+ return stableStringify(json2);
1971
1974
  }
1972
1975
  function renameJson(node, from, to) {
1973
1976
  if (Array.isArray(node)) return node.map((n) => renameJson(n, from, to));
@@ -2066,8 +2069,8 @@ var Index = class _Index {
2066
2069
  return reduction;
2067
2070
  }
2068
2071
  /** Build an Index from its `IndexDef` JSON. */
2069
- static from(json) {
2070
- return new _Index(json.exprs.map((p) => new IndexPart(p.expr, p.count)), json.bytes);
2072
+ static from(json2) {
2073
+ return new _Index(json2.exprs.map((p) => new IndexPart(p.expr, p.count)), json2.bytes);
2071
2074
  }
2072
2075
  /** Serialize to its `IndexDef` JSON shape (emitting `bytes` only when authored explicitly). */
2073
2076
  toJSON() {
@@ -2279,24 +2282,24 @@ var Type = class _Type {
2279
2282
  return this.search || this.fields.some((f) => this.isFieldSearchable(f));
2280
2283
  }
2281
2284
  /** Build a Type from its JSON, parsing fields/indexes via `registry`. */
2282
- static from(json, registry) {
2283
- const fields = json.fields.map((fd) => Field.from(fd, registry));
2284
- const indexes = (json.indexes ?? []).map((id) => Index.from(id));
2285
+ static from(json2, registry) {
2286
+ const fields = json2.fields.map((fd) => Field.from(fd, registry));
2287
+ const indexes = (json2.indexes ?? []).map((id) => Index.from(id));
2285
2288
  return new _Type({
2286
- name: json.name,
2287
- label: json.label,
2288
- description: json.description,
2289
+ name: json2.name,
2290
+ label: json2.label,
2291
+ description: json2.description,
2289
2292
  fields,
2290
2293
  indexes,
2291
- identity: json.identity,
2292
- count: json.count,
2293
- bytes: json.bytes,
2294
- changes: json.changes,
2295
- semantic: json.semantic,
2296
- search: json.search,
2297
- insertable: json.insertable,
2298
- updatable: json.updatable,
2299
- deletable: json.deletable
2294
+ identity: json2.identity,
2295
+ count: json2.count,
2296
+ bytes: json2.bytes,
2297
+ changes: json2.changes,
2298
+ semantic: json2.semantic,
2299
+ search: json2.search,
2300
+ insertable: json2.insertable,
2301
+ updatable: json2.updatable,
2302
+ deletable: json2.deletable
2300
2303
  });
2301
2304
  }
2302
2305
  /** Zod schema for the `TypeDef` JSON shape. */
@@ -2874,58 +2877,66 @@ var INVALID = /* @__PURE__ */ Symbol("invalid");
2874
2877
  function isRecord3(value2) {
2875
2878
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
2876
2879
  }
2877
- function gotTail(json) {
2878
- const got = describeInput(json);
2880
+ function gotTail(json2) {
2881
+ const got = describeInput(json2);
2879
2882
  return got !== void 0 ? `, got ${got}` : "";
2880
2883
  }
2881
- function expected(aid, json) {
2882
- return `expected ${aidInfo(aid).label}${gotTail(json)}`;
2884
+ function expected(aid, json2) {
2885
+ return `expected ${aidInfo(aid).label}${gotTail(json2)}`;
2883
2886
  }
2884
2887
  function lit(value2) {
2885
2888
  return {
2886
- check(json, ctx) {
2887
- if (json === value2) return value2;
2888
- ctx.problems.error("shape.literal", `expected ${JSON.stringify(value2)}${gotTail(json)}`);
2889
+ check(json2, ctx) {
2890
+ if (json2 === value2) return value2;
2891
+ ctx.problems.error("shape.literal", `expected ${JSON.stringify(value2)}${gotTail(json2)}`);
2889
2892
  return INVALID;
2890
2893
  }
2891
2894
  };
2892
2895
  }
2893
2896
  function str(aid) {
2894
2897
  return {
2895
- check(json, ctx) {
2896
- if (typeof json === "string") return json;
2897
- ctx.problems.error("shape.type", expected(aid, json));
2898
+ check(json2, ctx) {
2899
+ if (typeof json2 === "string") return json2;
2900
+ ctx.problems.error("shape.type", expected(aid, json2));
2898
2901
  return INVALID;
2899
2902
  }
2900
2903
  };
2901
2904
  }
2902
2905
  function bool(aid) {
2903
2906
  return {
2904
- check(json, ctx) {
2905
- if (typeof json === "boolean") return json;
2906
- ctx.problems.error("shape.type", expected(aid, json));
2907
+ check(json2, ctx) {
2908
+ if (typeof json2 === "boolean") return json2;
2909
+ ctx.problems.error("shape.type", expected(aid, json2));
2907
2910
  return INVALID;
2908
2911
  }
2909
2912
  };
2910
2913
  }
2911
- function scalar(aid) {
2914
+ function json(aid) {
2912
2915
  return {
2913
- check(json, ctx) {
2914
- if (json === null || typeof json === "string" || typeof json === "number" || typeof json === "boolean") {
2915
- return json;
2916
- }
2917
- ctx.problems.error("shape.type", expected(aid, json));
2916
+ check(value2, ctx) {
2917
+ if (isJsonValue(value2, JSON_MAX_DEPTH)) return value2;
2918
+ ctx.problems.error("shape.type", expected(aid, value2));
2918
2919
  return INVALID;
2919
2920
  }
2920
2921
  };
2921
2922
  }
2923
+ var JSON_MAX_DEPTH = 64;
2924
+ function isJsonValue(value2, depth) {
2925
+ if (value2 === null || typeof value2 === "string" || typeof value2 === "boolean") return true;
2926
+ if (typeof value2 === "number") return Number.isFinite(value2);
2927
+ if (depth <= 0 || typeof value2 !== "object") return false;
2928
+ if (Array.isArray(value2)) return value2.every((v) => isJsonValue(v, depth - 1));
2929
+ const proto = Object.getPrototypeOf(value2);
2930
+ if (proto !== Object.prototype && proto !== null) return false;
2931
+ return Object.values(value2).every((v) => isJsonValue(v, depth - 1));
2932
+ }
2922
2933
  function enumOf(values, aid) {
2923
2934
  return {
2924
- check(json, ctx) {
2925
- if (typeof json === "string") {
2926
- for (const v of values) if (v === json) return v;
2935
+ check(json2, ctx) {
2936
+ if (typeof json2 === "string") {
2937
+ for (const v of values) if (v === json2) return v;
2927
2938
  }
2928
- const suggestion = typeof json === "string" ? didYouMean(json, values) : "";
2939
+ const suggestion = typeof json2 === "string" ? didYouMean(json2, values) : "";
2929
2940
  ctx.problems.error("shape.enum", `expected ${aidInfo(aid).label}: ${values.join(", ")}${suggestion}`);
2930
2941
  return INVALID;
2931
2942
  }
@@ -2933,24 +2944,24 @@ function enumOf(values, aid) {
2933
2944
  }
2934
2945
  function list(shape, opts = {}) {
2935
2946
  return {
2936
- check(json, ctx) {
2937
- if (!Array.isArray(json)) {
2938
- ctx.problems.error("shape.array", `expected a list${gotTail(json)}`);
2947
+ check(json2, ctx) {
2948
+ if (!Array.isArray(json2)) {
2949
+ ctx.problems.error("shape.array", `expected a list${gotTail(json2)}`);
2939
2950
  return INVALID;
2940
2951
  }
2941
2952
  const out = [];
2942
2953
  let ok = true;
2943
- json.forEach((element, i) => {
2954
+ json2.forEach((element, i) => {
2944
2955
  const value2 = ctx.problems.at(i, () => shape.check(element, ctx));
2945
2956
  if (value2 === INVALID) ok = false;
2946
2957
  else out.push(value2);
2947
2958
  });
2948
- if (opts.min !== void 0 && json.length < opts.min) {
2949
- ctx.problems.error("shape.min", `expected at least ${opts.min} item${opts.min === 1 ? "" : "s"}, got ${json.length}`);
2959
+ if (opts.min !== void 0 && json2.length < opts.min) {
2960
+ ctx.problems.error("shape.min", `expected at least ${opts.min} item${opts.min === 1 ? "" : "s"}, got ${json2.length}`);
2950
2961
  ok = false;
2951
2962
  }
2952
- if (opts.max !== void 0 && json.length > opts.max) {
2953
- ctx.problems.error("shape.max", `expected at most ${opts.max} item${opts.max === 1 ? "" : "s"}, got ${json.length}`);
2963
+ if (opts.max !== void 0 && json2.length > opts.max) {
2964
+ ctx.problems.error("shape.max", `expected at most ${opts.max} item${opts.max === 1 ? "" : "s"}, got ${json2.length}`);
2954
2965
  ok = false;
2955
2966
  }
2956
2967
  return ok ? out : INVALID;
@@ -2959,15 +2970,15 @@ function list(shape, opts = {}) {
2959
2970
  }
2960
2971
  function record(shape, aid) {
2961
2972
  return {
2962
- check(json, ctx) {
2963
- if (!isRecord3(json)) {
2964
- ctx.problems.error("shape.not-object", expected(aid, json));
2973
+ check(json2, ctx) {
2974
+ if (!isRecord3(json2)) {
2975
+ ctx.problems.error("shape.not-object", expected(aid, json2));
2965
2976
  return INVALID;
2966
2977
  }
2967
2978
  const out = /* @__PURE__ */ new Map();
2968
2979
  let ok = true;
2969
- for (const key of Object.keys(json)) {
2970
- const value2 = ctx.problems.at(key, () => shape.check(json[key], ctx));
2980
+ for (const key of Object.keys(json2)) {
2981
+ const value2 = ctx.problems.at(key, () => shape.check(json2[key], ctx));
2971
2982
  if (value2 === INVALID) ok = false;
2972
2983
  else out.set(key, value2);
2973
2984
  }
@@ -2977,32 +2988,32 @@ function record(shape, aid) {
2977
2988
  }
2978
2989
  function exprRef() {
2979
2990
  return {
2980
- check(json, ctx) {
2981
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
2991
+ check(json2, ctx) {
2992
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
2982
2993
  return built === void 0 ? INVALID : built;
2983
2994
  }
2984
2995
  };
2985
2996
  }
2986
2997
  function queryRef() {
2987
2998
  return {
2988
- check(json, ctx) {
2989
- const built = ctx.registry.parseCheckedQuery(json, ctx.problems);
2999
+ check(json2, ctx) {
3000
+ const built = ctx.registry.parseCheckedQuery(json2, ctx.problems);
2990
3001
  return built === void 0 ? INVALID : built;
2991
3002
  }
2992
3003
  };
2993
3004
  }
2994
3005
  function queryDefRef() {
2995
3006
  return {
2996
- check(json, ctx) {
2997
- const built = ctx.registry.parseCheckedQuery(json, ctx.problems);
3007
+ check(json2, ctx) {
3008
+ const built = ctx.registry.parseCheckedQuery(json2, ctx.problems);
2998
3009
  return built === void 0 ? INVALID : built.toJSON();
2999
3010
  }
3000
3011
  };
3001
3012
  }
3002
3013
  function sourceRef() {
3003
3014
  return {
3004
- check(json, ctx) {
3005
- const built = ctx.registry.parseCheckedSource(json, ctx.problems);
3015
+ check(json2, ctx) {
3016
+ const built = ctx.registry.parseCheckedSource(json2, ctx.problems);
3006
3017
  return built === void 0 ? INVALID : built;
3007
3018
  }
3008
3019
  };
@@ -3015,22 +3026,22 @@ function obj(fields, build, opts = {}) {
3015
3026
  const keys = Object.keys(fields);
3016
3027
  const required = keys.filter((key) => !optionalKeys.has(key));
3017
3028
  return {
3018
- check(json, ctx) {
3019
- if (!isRecord3(json)) {
3020
- ctx.problems.error("shape.not-object", expected(opts.aid ?? "Expr", json));
3029
+ check(json2, ctx) {
3030
+ if (!isRecord3(json2)) {
3031
+ ctx.problems.error("shape.not-object", expected(opts.aid ?? "Expr", json2));
3021
3032
  return INVALID;
3022
3033
  }
3023
3034
  const acc = {};
3024
3035
  const checkKey = (key) => {
3025
3036
  const shape = fields[key];
3026
3037
  ctx.problems.at(key, () => {
3027
- if (!(key in json)) {
3038
+ if (!(key in json2)) {
3028
3039
  if (!optionalKeys.has(key)) {
3029
3040
  ctx.problems.error("shape.required", `missing required field \`${key}\``);
3030
3041
  }
3031
3042
  return;
3032
3043
  }
3033
- const value2 = shape.check(json[key], ctx);
3044
+ const value2 = shape.check(json2[key], ctx);
3034
3045
  if (value2 !== INVALID) acc[key] = value2;
3035
3046
  });
3036
3047
  };
@@ -3241,7 +3252,7 @@ var SqlContext = class _SqlContext {
3241
3252
 
3242
3253
  // src/exprs/literal.ts
3243
3254
  var LiteralExpr = class _LiteralExpr extends Expr {
3244
- /** Wrap a constant scalar value (`string | number | boolean | null`). */
3255
+ /** Wrap a constant value: a scalar, or a whole JSON document. */
3245
3256
  constructor(value2) {
3246
3257
  super();
3247
3258
  this.value = value2;
@@ -3249,14 +3260,14 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3249
3260
  value;
3250
3261
  static KIND = "literal";
3251
3262
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3252
- static INSTRUCTIONS = "A constant scalar value.";
3263
+ static INSTRUCTIONS = "A constant value: a scalar (string / number / boolean / null), or a whole JSON DOCUMENT (object / array) for a `json` / `array` field \u2014 which is how a write cell carries one. A document is bound as ONE parameter, never interpolated.";
3253
3264
  kind = _LiteralExpr.KIND;
3254
3265
  /** Reconstruct a LiteralExpr from its JSON def (validates the `kind` discriminant). */
3255
- static from(json, _registry) {
3256
- if (json.kind !== "literal") {
3257
- throw new Error(`LiteralExpr.from: expected 'literal', got '${json.kind}'`);
3266
+ static from(json2, _registry) {
3267
+ if (json2.kind !== "literal") {
3268
+ throw new Error(`LiteralExpr.from: expected 'literal', got '${json2.kind}'`);
3258
3269
  }
3259
- return new _LiteralExpr(json.value);
3270
+ return new _LiteralExpr(json2.value);
3260
3271
  }
3261
3272
  /**
3262
3273
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -3266,7 +3277,7 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3266
3277
  static SHAPE = obj(
3267
3278
  {
3268
3279
  kind: lit("literal"),
3269
- value: scalar("ScalarValue")
3280
+ value: json("LiteralValue")
3270
3281
  },
3271
3282
  (v) => new _LiteralExpr(v.value),
3272
3283
  { aid: "Expr_literal" }
@@ -3276,10 +3287,10 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3276
3287
  return withAid(
3277
3288
  z15.object({
3278
3289
  kind: z15.literal("literal"),
3279
- value: withAid(z15.union([z15.string(), z15.number(), z15.boolean(), z15.null()]), "ScalarValue")
3290
+ value: withAid(jsonValueSchema(), "LiteralValue")
3280
3291
  }),
3281
3292
  "Expr_literal"
3282
- ).describe("A constant scalar value.");
3293
+ ).describe("A constant value: a scalar, or a whole JSON document for a json / array field.");
3283
3294
  }
3284
3295
  /** Whether this is the SQL `NULL` literal. */
3285
3296
  isNullLiteral() {
@@ -3290,11 +3301,14 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3290
3301
  if (this.value === null) {
3291
3302
  return computed(new TextFieldType(), [], true, false);
3292
3303
  }
3304
+ if (Array.isArray(this.value)) return computed(new ArrayFieldType(), [], false, false);
3293
3305
  switch (typeof this.value) {
3294
3306
  case "number":
3295
3307
  return computed(new NumberFieldType(), [], false, false);
3296
3308
  case "boolean":
3297
3309
  return computed(new BoolFieldType(), [], false, false);
3310
+ case "object":
3311
+ return computed(new JsonFieldType(), [], false, false);
3298
3312
  default:
3299
3313
  return computed(new TextFieldType(), [], false, false);
3300
3314
  }
@@ -3312,9 +3326,20 @@ var LiteralExpr = class _LiteralExpr extends Expr {
3312
3326
  async evaluate() {
3313
3327
  return Value.of(this.value);
3314
3328
  }
3315
- /** Emit as a SqlText fragment — `NULL` keyword or a bound param. */
3316
- toSQL(_dialect, _ctx) {
3317
- return this.value === null ? SqlText.raw("NULL") : SqlText.param(this.value);
3329
+ /**
3330
+ * Emit as a SqlText fragment — `NULL` keyword, a bound scalar param, or a
3331
+ * bound DOCUMENT.
3332
+ *
3333
+ * A document has no target field type HERE (a bare literal in a WHERE knows
3334
+ * only its own shape), so it binds through the dialect's default json type.
3335
+ * The WRITE path emits its cells through `writeCellSql`, which supplies the
3336
+ * target COLUMN's field type — the difference between a Postgres `jsonb` cast
3337
+ * and the `ARRAY[…]::text[]` a native array column actually needs.
3338
+ */
3339
+ toSQL(dialect, _ctx) {
3340
+ if (this.value === null) return SqlText.raw("NULL");
3341
+ if (typeof this.value === "object") return dialect.jsonValue(this.value);
3342
+ return SqlText.param(this.value);
3318
3343
  }
3319
3344
  /** Serialize back to its JSON ExprDef. */
3320
3345
  toJSON() {
@@ -3344,11 +3369,11 @@ var OutputRefExpr = class _OutputRefExpr extends Expr {
3344
3369
  static INSTRUCTIONS = "References a projected SELECT output field by name (valid ONLY in groupBy/orderBy/having); expands to that item's expr.";
3345
3370
  kind = _OutputRefExpr.KIND;
3346
3371
  /** Reconstruct an OutputRefExpr from its JSON def (validates the `kind` discriminant). */
3347
- static from(json, _registry) {
3348
- if (json.kind !== "output") {
3349
- throw new Error(`OutputRefExpr.from: expected 'output', got '${json.kind}'`);
3372
+ static from(json2, _registry) {
3373
+ if (json2.kind !== "output") {
3374
+ throw new Error(`OutputRefExpr.from: expected 'output', got '${json2.kind}'`);
3350
3375
  }
3351
- return new _OutputRefExpr(json.name);
3376
+ return new _OutputRefExpr(json2.name);
3352
3377
  }
3353
3378
  /**
3354
3379
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -3928,14 +3953,14 @@ var FieldRefExpr = class _FieldRefExpr extends Expr {
3928
3953
  field;
3929
3954
  static KIND = "field-ref";
3930
3955
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
3931
- static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a RELATION field resolves to the whole related row, NOT a scalar: to READ a related scalar, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. To CORRELATE a subquery, join the relation and compare the joined key \u2014 do NOT compare a relation field-ref to an id/scalar. A relation field-ref may only be compared to ANOTHER relation of the same target.";
3956
+ static INSTRUCTIONS = "`<source>.<field>` \u2014 a SCALAR field\u2019s value from a bound source. A ref to a BELONGS-TO RELATION field IS a value: it projects the relation's IDENTITY \u2014 the target's key read off THIS row's own key column(s), as an object keyed by the target's identity field names (`{id:'u1'}`, `{tenantId:3,userId:1}`), NULL when unset \u2014 planning NO join and applying no target scope. Legal in `fields` / `RETURNING`, `order`, `groupBy`, `is null`, and an identity `=` / `<>` / `in`. To read any OTHER field of the target, cross the relation with a `relation` join (`joins:[{on:{kind:'relation',source,field,as}}]`) then field-ref the join alias. A HAS-MANY ref is REFUSED (`ref.relation-has-many`) \u2014 it has no key on this row and its value is a SET: join it, or test membership against a target key. A relation is still NOT a value as an arithmetic operand / `case` arm / function argument / aggregate; and to CORRELATE a subquery, join the relation and compare the joined key \u2014 never a relation field-ref against an id/scalar.";
3932
3957
  kind = _FieldRefExpr.KIND;
3933
3958
  /** Reconstruct a FieldRefExpr from its JSON def (validates the `kind` discriminant). */
3934
- static from(json, _registry) {
3935
- if (json.kind !== "field-ref") {
3936
- throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json.kind}'`);
3959
+ static from(json2, _registry) {
3960
+ if (json2.kind !== "field-ref") {
3961
+ throw new Error(`FieldRefExpr.from: expected 'field-ref', got '${json2.kind}'`);
3937
3962
  }
3938
- return new _FieldRefExpr(json.source, json.field);
3963
+ return new _FieldRefExpr(json2.source, json2.field);
3939
3964
  }
3940
3965
  /**
3941
3966
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -4415,11 +4440,11 @@ var ParamExpr = class _ParamExpr extends Expr {
4415
4440
  static INSTRUCTIONS = "A named bind parameter; type inferred from use, bound at run/emit time.";
4416
4441
  kind = _ParamExpr.KIND;
4417
4442
  /** Reconstruct a ParamExpr from its JSON def (validates the `kind` discriminant). */
4418
- static from(json, _registry) {
4419
- if (json.kind !== "param") {
4420
- throw new Error(`ParamExpr.from: expected 'param', got '${json.kind}'`);
4443
+ static from(json2, _registry) {
4444
+ if (json2.kind !== "param") {
4445
+ throw new Error(`ParamExpr.from: expected 'param', got '${json2.kind}'`);
4421
4446
  }
4422
- return new _ParamExpr(json.name);
4447
+ return new _ParamExpr(json2.name);
4423
4448
  }
4424
4449
  /**
4425
4450
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -4466,10 +4491,26 @@ var ParamExpr = class _ParamExpr extends Expr {
4466
4491
  async evaluate(ctx) {
4467
4492
  return ctx.param(this.name);
4468
4493
  }
4469
- /** Emit as a bound SqlText param slot (null until a value is supplied). */
4470
- toSQL(_dialect, ctx) {
4494
+ /**
4495
+ * Emit as a bound SqlText param slot (NULL until a value is supplied).
4496
+ *
4497
+ * A NON-SCALAR bound value — a JSON document, or a relation `{ pk }` object
4498
+ * that reached here undecomposed — binds through `Dialect.jsonValue`, NOT as
4499
+ * NULL. Binding NULL was the worst outcome available (A9): the statement
4500
+ * SUCCEEDED and the supplied value was silently dropped, so an INSERT of a
4501
+ * `json` column through a param appeared to work and lost the data. A
4502
+ * relation comparison still decomposes its `{ pk }` object into per-column
4503
+ * binds before reaching here, so that path is unchanged; anything that DOES
4504
+ * get here is a value the caller supplied, and is bound as one.
4505
+ *
4506
+ * A write CELL routes through `writeCellSql` first, which also knows the
4507
+ * target column's field type; this is the fallback for every other position,
4508
+ * which knows only the value's own shape.
4509
+ */
4510
+ toSQL(dialect, ctx) {
4471
4511
  const raw2 = Object.prototype.hasOwnProperty.call(ctx.params, this.name) ? ctx.params[this.name] : null;
4472
- const value2 = raw2 !== null && typeof raw2 === "object" ? null : raw2;
4512
+ if (raw2 !== null && raw2 !== void 0 && typeof raw2 === "object") return dialect.jsonValue(raw2);
4513
+ const value2 = raw2 ?? null;
4473
4514
  return SqlText.param(value2);
4474
4515
  }
4475
4516
  /** Serialize back to its JSON ExprDef. */
@@ -4804,15 +4845,15 @@ var SorterExpr = class _SorterExpr extends Expr {
4804
4845
  static INSTRUCTIONS = "A dynamic-sort catalog for a SELECT `order`: declare named `sorts` (+ optional `defaultSort`); the caller picks the sort at execution time.";
4805
4846
  kind = _SorterExpr.KIND;
4806
4847
  /** Reconstruct a SorterExpr from its JSON def (validates the `kind` discriminant). */
4807
- static from(json, registry) {
4808
- if (json.kind !== "sorter") {
4809
- throw new Error(`SorterExpr.from: expected 'sorter', got '${json.kind}'`);
4848
+ static from(json2, registry) {
4849
+ if (json2.kind !== "sorter") {
4850
+ throw new Error(`SorterExpr.from: expected 'sorter', got '${json2.kind}'`);
4810
4851
  }
4811
4852
  const sorts = /* @__PURE__ */ new Map();
4812
- for (const name of Object.keys(json.sorts)) {
4813
- sorts.set(name, registry.parseExpr(json.sorts[name]));
4853
+ for (const name of Object.keys(json2.sorts)) {
4854
+ sorts.set(name, registry.parseExpr(json2.sorts[name]));
4814
4855
  }
4815
- const defaultSort = json.defaultSort ? json.defaultSort.map((d) => ({ ...d })) : void 0;
4856
+ const defaultSort = json2.defaultSort ? json2.defaultSort.map((d) => ({ ...d })) : void 0;
4816
4857
  return new _SorterExpr(sorts, defaultSort);
4817
4858
  }
4818
4859
  /**
@@ -5010,14 +5051,14 @@ var BinaryExpr = class _BinaryExpr extends Expr {
5010
5051
  static INSTRUCTIONS = "Arithmetic `left <op> right` (`+ - * / %`).";
5011
5052
  kind = _BinaryExpr.KIND;
5012
5053
  /** Reconstruct a BinaryExpr from its JSON def (validates the `kind` discriminant). */
5013
- static from(json, registry) {
5014
- if (json.kind !== "binary") {
5015
- throw new Error(`BinaryExpr.from: expected 'binary', got '${json.kind}'`);
5054
+ static from(json2, registry) {
5055
+ if (json2.kind !== "binary") {
5056
+ throw new Error(`BinaryExpr.from: expected 'binary', got '${json2.kind}'`);
5016
5057
  }
5017
5058
  return new _BinaryExpr(
5018
- json.op,
5019
- registry.parseExpr(json.left),
5020
- registry.parseExpr(json.right)
5059
+ json2.op,
5060
+ registry.parseExpr(json2.left),
5061
+ registry.parseExpr(json2.right)
5021
5062
  );
5022
5063
  }
5023
5064
  /**
@@ -5178,11 +5219,11 @@ var UnaryExpr = class _UnaryExpr extends Expr {
5178
5219
  static INSTRUCTIONS = "`<op> operand` (`-` / `+`).";
5179
5220
  kind = _UnaryExpr.KIND;
5180
5221
  /** Reconstruct a UnaryExpr from its JSON def (validates the `kind` discriminant). */
5181
- static from(json, registry) {
5182
- if (json.kind !== "unary") {
5183
- throw new Error(`UnaryExpr.from: expected 'unary', got '${json.kind}'`);
5222
+ static from(json2, registry) {
5223
+ if (json2.kind !== "unary") {
5224
+ throw new Error(`UnaryExpr.from: expected 'unary', got '${json2.kind}'`);
5184
5225
  }
5185
- return new _UnaryExpr(json.op, registry.parseExpr(json.operand));
5226
+ return new _UnaryExpr(json2.op, registry.parseExpr(json2.operand));
5186
5227
  }
5187
5228
  /**
5188
5229
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -5346,14 +5387,14 @@ var ComparisonExpr = class _ComparisonExpr extends BoolExpr {
5346
5387
  static INSTRUCTIONS = "`left <op> right` \u2192 boolean (`= <> < <= > >=`, `like`, `notLike`, `ilike`). A RELATION field-ref compares by IDENTITY with `=`/`<>` ONLY (ordering / LIKE on a relation is rejected). Its RHS may be (a) another relation of the SAME target \u2014 compared by FK key (`order.customer = invoice.customer`); or (b) a `{ pk }` VALUE param keyed by the target's primary-key fields (`assignedUser = :u` with `:u = {id:5}`); a single-key relation also accepts a bare scalar param. A BELONGS-TO compares the FK columns; a HAS-MANY compares by MEMBERSHIP \u2014 `= value` is TRUE when the value's key is in the related set (correlated EXISTS), `<>` is NOT EXISTS; a has-many may not be compared to another relation. Do NOT compare a relation to a scalar id COLUMN/field-ref (the correlation bug) \u2014 JOIN the relation (`joins:[{on:{kind:'relation',source,field,as}}]`) and compare the joined key.";
5347
5388
  kind = _ComparisonExpr.KIND;
5348
5389
  /** Reconstruct a ComparisonExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
5349
- static from(json, registry) {
5350
- if (json.kind !== "comparison") {
5351
- throw new Error(`ComparisonExpr.from: expected 'comparison', got '${json.kind}'`);
5390
+ static from(json2, registry) {
5391
+ if (json2.kind !== "comparison") {
5392
+ throw new Error(`ComparisonExpr.from: expected 'comparison', got '${json2.kind}'`);
5352
5393
  }
5353
5394
  return new _ComparisonExpr(
5354
- json.op,
5355
- registry.parseExpr(json.left),
5356
- registry.parseExpr(json.right)
5395
+ json2.op,
5396
+ registry.parseExpr(json2.left),
5397
+ registry.parseExpr(json2.right)
5357
5398
  );
5358
5399
  }
5359
5400
  /**
@@ -5592,13 +5633,13 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5592
5633
  static INSTRUCTIONS = "Boolean connective `and` / `or` / `not` over operands.";
5593
5634
  kind = _LogicalExpr.KIND;
5594
5635
  /** Reconstruct a LogicalExpr from its JSON def (validates `kind`, recurses into operands via `registry.parseExpr`). */
5595
- static from(json, registry) {
5596
- if (json.kind !== "logical") {
5597
- throw new Error(`LogicalExpr.from: expected 'logical', got '${json.kind}'`);
5636
+ static from(json2, registry) {
5637
+ if (json2.kind !== "logical") {
5638
+ throw new Error(`LogicalExpr.from: expected 'logical', got '${json2.kind}'`);
5598
5639
  }
5599
5640
  return new _LogicalExpr(
5600
- json.op,
5601
- json.operands.map((o) => registry.parseExpr(o))
5641
+ json2.op,
5642
+ json2.operands.map((o) => registry.parseExpr(o))
5602
5643
  );
5603
5644
  }
5604
5645
  /**
@@ -5609,8 +5650,8 @@ var LogicalExpr = class _LogicalExpr extends BoolExpr {
5609
5650
  * builds an expr equal to `from`'s output on a valid def. See `shape/`.
5610
5651
  */
5611
5652
  static SHAPE = {
5612
- check(json, ctx) {
5613
- const built = _LogicalExpr.SHAPE_OBJECT.check(json, ctx);
5653
+ check(json2, ctx) {
5654
+ const built = _LogicalExpr.SHAPE_OBJECT.check(json2, ctx);
5614
5655
  if (built === INVALID) return INVALID;
5615
5656
  if (built.op === "not" && built.operands.length !== 1) {
5616
5657
  ctx.problems.at(
@@ -5780,7 +5821,7 @@ var InExpr = class _InExpr extends BoolExpr {
5780
5821
  not;
5781
5822
  static KIND = "in";
5782
5823
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
5783
- static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. To project a value across a relation in the SUBQUERY form, add a `relation` join and field-ref the joined alias \u2014 do NOT project/compare a relation field-ref as a scalar id. To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5824
+ static INSTRUCTIONS = "`value IN (list | subquery)` (negatable via `not`): membership test. `in` is EITHER an explicit array of value exprs OR a subquery projecting exactly ONE field (correlated or not). When `value` is a RELATION field-ref, the list holds `{ pk }` VALUE params (or bare scalars for a single-key relation): a belongs-to matches by FK key, a has-many by MEMBERSHIP (\u2208 the related set); `NOT IN` negates. A COMPOSITE-key relation may NOT use the subquery form (`in.relation-composite`) \u2014 one projected field cannot match a multi-column key, so list its `{ pk }` values instead. Inside the SUBQUERY, cross a relation with a `relation` join and field-ref the joined alias: projecting the relation field-ref itself yields its IDENTITY OBJECT, not a scalar id, and is refused here (`compare.relation-vs-value`). To correlate the subquery, JOIN the relation and compare the joined key to the outer scalar. Set `not:true` for NOT IN.";
5784
5825
  /**
5785
5826
  * Worked examples (see `ExprClass.EXAMPLES`) — the two `in` shapes: an explicit
5786
5827
  * value LIST, and a single-field SUBQUERY that crosses a relation via a
@@ -5830,15 +5871,15 @@ var InExpr = class _InExpr extends BoolExpr {
5830
5871
  ];
5831
5872
  kind = _InExpr.KIND;
5832
5873
  /** Reconstruct an InExpr from its JSON def (validates `kind`; recurses into the value and any list elements via `registry.parseExpr`). */
5833
- static from(json, registry) {
5834
- if (json.kind !== "in") {
5835
- throw new Error(`InExpr.from: expected 'in', got '${json.kind}'`);
5874
+ static from(json2, registry) {
5875
+ if (json2.kind !== "in") {
5876
+ throw new Error(`InExpr.from: expected 'in', got '${json2.kind}'`);
5836
5877
  }
5837
- const value2 = registry.parseExpr(json.value);
5838
- if (Array.isArray(json.in)) {
5839
- return new _InExpr(value2, json.in.map((e2) => registry.parseExpr(e2)), void 0, json.not ?? false);
5878
+ const value2 = registry.parseExpr(json2.value);
5879
+ if (Array.isArray(json2.in)) {
5880
+ return new _InExpr(value2, json2.in.map((e2) => registry.parseExpr(e2)), void 0, json2.not ?? false);
5840
5881
  }
5841
- return new _InExpr(value2, void 0, json.in, json.not ?? false);
5882
+ return new _InExpr(value2, void 0, json2.in, json2.not ?? false);
5842
5883
  }
5843
5884
  /**
5844
5885
  * Owned structural {@link Shape} — the zod-free parallel parser. Dispatches on
@@ -5848,11 +5889,11 @@ var InExpr = class _InExpr extends BoolExpr {
5848
5889
  * to `from`'s output on a valid def. Never throws; accumulates. See `shape/`.
5849
5890
  */
5850
5891
  static SHAPE = {
5851
- check(json, ctx) {
5852
- if (isRecord3(json) && isRecord3(json["in"])) {
5853
- return _InExpr.SHAPE_SUBQUERY.check(json, ctx);
5892
+ check(json2, ctx) {
5893
+ if (isRecord3(json2) && isRecord3(json2["in"])) {
5894
+ return _InExpr.SHAPE_SUBQUERY.check(json2, ctx);
5854
5895
  }
5855
- return _InExpr.SHAPE_LIST.check(json, ctx);
5896
+ return _InExpr.SHAPE_LIST.check(json2, ctx);
5856
5897
  }
5857
5898
  };
5858
5899
  /** The LIST-form object shape dispatched to by {@link SHAPE}. */
@@ -6080,15 +6121,15 @@ var BetweenExpr = class _BetweenExpr extends BoolExpr {
6080
6121
  static INSTRUCTIONS = "`value BETWEEN lower AND upper` (negatable).";
6081
6122
  kind = _BetweenExpr.KIND;
6082
6123
  /** Reconstruct a BetweenExpr from its JSON def (validates `kind`, recurses into value/lower/upper via `registry.parseExpr`). */
6083
- static from(json, registry) {
6084
- if (json.kind !== "between") {
6085
- throw new Error(`BetweenExpr.from: expected 'between', got '${json.kind}'`);
6124
+ static from(json2, registry) {
6125
+ if (json2.kind !== "between") {
6126
+ throw new Error(`BetweenExpr.from: expected 'between', got '${json2.kind}'`);
6086
6127
  }
6087
6128
  return new _BetweenExpr(
6088
- registry.parseExpr(json.value),
6089
- registry.parseExpr(json.lower),
6090
- registry.parseExpr(json.upper),
6091
- json.not ?? false
6129
+ registry.parseExpr(json2.value),
6130
+ registry.parseExpr(json2.lower),
6131
+ registry.parseExpr(json2.upper),
6132
+ json2.not ?? false
6092
6133
  );
6093
6134
  }
6094
6135
  /**
@@ -6229,14 +6270,14 @@ var IsNullExpr = class _IsNullExpr extends BoolExpr {
6229
6270
  not;
6230
6271
  static KIND = "is-null";
6231
6272
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
6232
- static INSTRUCTIONS = "`value IS [NOT] NULL`.";
6273
+ static INSTRUCTIONS = "`value IS [NOT] NULL`. On a BELONGS-TO relation field-ref it tests whether the relation is UNSET \u2014 the KEY COLUMNS, so it stays index-usable; a HAS-MANY there is refused (`ref.relation-has-many`) \u2014 use `[NOT] EXISTS` over the related rows instead.";
6233
6274
  kind = _IsNullExpr.KIND;
6234
6275
  /** Reconstruct an IsNullExpr from its JSON def (validates `kind`, recurses into the value via `registry.parseExpr`). */
6235
- static from(json, registry) {
6236
- if (json.kind !== "is-null") {
6237
- throw new Error(`IsNullExpr.from: expected 'is-null', got '${json.kind}'`);
6276
+ static from(json2, registry) {
6277
+ if (json2.kind !== "is-null") {
6278
+ throw new Error(`IsNullExpr.from: expected 'is-null', got '${json2.kind}'`);
6238
6279
  }
6239
- return new _IsNullExpr(registry.parseExpr(json.value), json.not ?? false);
6280
+ return new _IsNullExpr(registry.parseExpr(json2.value), json2.not ?? false);
6240
6281
  }
6241
6282
  /**
6242
6283
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -6405,11 +6446,11 @@ var ExistsExpr = class _ExistsExpr extends BoolExpr {
6405
6446
  ];
6406
6447
  kind = _ExistsExpr.KIND;
6407
6448
  /** Reconstruct an ExistsExpr from its JSON def (validates `kind`; the subquery is carried as-is). */
6408
- static from(json, _registry) {
6409
- if (json.kind !== "exists") {
6410
- throw new Error(`ExistsExpr.from: expected 'exists', got '${json.kind}'`);
6449
+ static from(json2, _registry) {
6450
+ if (json2.kind !== "exists") {
6451
+ throw new Error(`ExistsExpr.from: expected 'exists', got '${json2.kind}'`);
6411
6452
  }
6412
- return new _ExistsExpr(json.query, json.not ?? false);
6453
+ return new _ExistsExpr(json2.query, json2.not ?? false);
6413
6454
  }
6414
6455
  /**
6415
6456
  * Owned structural {@link Shape} — the zod-free parallel parser. Structurally
@@ -6490,9 +6531,9 @@ var ARRAY_OPS = [
6490
6531
  "notEmpty"
6491
6532
  ];
6492
6533
  var ARRAY_VALUE_SHAPE = {
6493
- check(json, ctx) {
6494
- if (Array.isArray(json)) return list(exprRef()).check(json, ctx);
6495
- const built = exprRef().check(json, ctx);
6534
+ check(json2, ctx) {
6535
+ if (Array.isArray(json2)) return list(exprRef()).check(json2, ctx);
6536
+ const built = exprRef().check(json2, ctx);
6496
6537
  return built === INVALID ? INVALID : [built];
6497
6538
  }
6498
6539
  };
@@ -6512,13 +6553,13 @@ var ArrayOpExpr = class _ArrayOpExpr extends BoolExpr {
6512
6553
  static INSTRUCTIONS = "Predicate over an array field: `contains` / `containsAny` / `containsAll` / `isEmpty` / `notEmpty`.";
6513
6554
  kind = _ArrayOpExpr.KIND;
6514
6555
  /** Reconstruct an ArrayOpExpr from its JSON def, recursing into target/values via the registry. */
6515
- static from(json, registry) {
6516
- if (json.kind !== "array-op") {
6517
- throw new Error(`ArrayOpExpr.from: expected 'array-op', got '${json.kind}'`);
6556
+ static from(json2, registry) {
6557
+ if (json2.kind !== "array-op") {
6558
+ throw new Error(`ArrayOpExpr.from: expected 'array-op', got '${json2.kind}'`);
6518
6559
  }
6519
- const target = registry.parseExpr(json.target);
6520
- const values = json.value === void 0 ? [] : Array.isArray(json.value) ? json.value.map((v) => registry.parseExpr(v)) : [registry.parseExpr(json.value)];
6521
- return new _ArrayOpExpr(json.op, target, values);
6560
+ const target = registry.parseExpr(json2.target);
6561
+ const values = json2.value === void 0 ? [] : Array.isArray(json2.value) ? json2.value.map((v) => registry.parseExpr(v)) : [registry.parseExpr(json2.value)];
6562
+ return new _ArrayOpExpr(json2.op, target, values);
6522
6563
  }
6523
6564
  /**
6524
6565
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -6733,15 +6774,15 @@ var CaseExpr = class _CaseExpr extends Expr {
6733
6774
  static INSTRUCTIONS = "`CASE WHEN \u2026 THEN \u2026 [ELSE \u2026] END`.";
6734
6775
  kind = _CaseExpr.KIND;
6735
6776
  /** Reconstruct a CaseExpr from its JSON def, recursing into each branch/else via the registry. */
6736
- static from(json, registry) {
6737
- if (json.kind !== "case") {
6738
- throw new Error(`CaseExpr.from: expected 'case', got '${json.kind}'`);
6777
+ static from(json2, registry) {
6778
+ if (json2.kind !== "case") {
6779
+ throw new Error(`CaseExpr.from: expected 'case', got '${json2.kind}'`);
6739
6780
  }
6740
- const branches = json.branches.map((b) => ({
6781
+ const branches = json2.branches.map((b) => ({
6741
6782
  when: registry.parseExpr(b.when),
6742
6783
  then: registry.parseExpr(b.then)
6743
6784
  }));
6744
- const els = json.else ? registry.parseExpr(json.else) : void 0;
6785
+ const els = json2.else ? registry.parseExpr(json2.else) : void 0;
6745
6786
  return new _CaseExpr(branches, els);
6746
6787
  }
6747
6788
  /**
@@ -6884,9 +6925,9 @@ import { z as z30 } from "zod";
6884
6925
 
6885
6926
  // src/exprs/_function-args.ts
6886
6927
  import { z as z29 } from "zod";
6887
- function parseNamedArgs(json, registry) {
6928
+ function parseNamedArgs(json2, registry) {
6888
6929
  const out = /* @__PURE__ */ new Map();
6889
- for (const [name, def] of Object.entries(json)) out.set(name, registry.parseExpr(def));
6930
+ for (const [name, def] of Object.entries(json2)) out.set(name, registry.parseExpr(def));
6890
6931
  return out;
6891
6932
  }
6892
6933
  function namedArgSchema(child) {
@@ -7023,7 +7064,7 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7023
7064
  distinct;
7024
7065
  static KIND = "aggregate";
7025
7066
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
7026
- static INSTRUCTIONS = "An aggregate function over a group (`count(*)` = empty args); optional `distinct`.";
7067
+ static INSTRUCTIONS = "An aggregate function over a group (`count(*)` = empty args); optional `distinct`. A RELATION field-ref is NOT aggregable (`ref.relation-aggregate`) \u2014 its value is an IDENTITY: group by it, or aggregate a scalar off a `relation`-joined alias.";
7027
7068
  kind = _AggregateExpr.KIND;
7028
7069
  /** The conventional single `value` argument (absent for `count(*)`). */
7029
7070
  valueArg() {
@@ -7048,11 +7089,11 @@ var AggregateExpr = class _AggregateExpr extends Expr {
7048
7089
  return substituted ? engine.registry.parseExpr(substituted) : void 0;
7049
7090
  }
7050
7091
  /** Reconstruct an AggregateExpr from its JSON def, parsing named args via the registry. */
7051
- static from(json, registry) {
7052
- if (json.kind !== "aggregate") {
7053
- throw new Error(`AggregateExpr.from: expected 'aggregate', got '${json.kind}'`);
7092
+ static from(json2, registry) {
7093
+ if (json2.kind !== "aggregate") {
7094
+ throw new Error(`AggregateExpr.from: expected 'aggregate', got '${json2.kind}'`);
7054
7095
  }
7055
- return new _AggregateExpr(json.function, parseNamedArgs(json.args, registry), json.distinct ?? false);
7096
+ return new _AggregateExpr(json2.function, parseNamedArgs(json2.args, registry), json2.distinct ?? false);
7056
7097
  }
7057
7098
  /**
7058
7099
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -7277,17 +7318,17 @@ var WindowExpr = class _WindowExpr extends Expr {
7277
7318
  ];
7278
7319
  kind = _WindowExpr.KIND;
7279
7320
  /** Reconstruct a WindowExpr from its JSON def, recursing into args/partition/order via the registry. */
7280
- static from(json, registry) {
7281
- if (json.kind !== "window") {
7282
- throw new Error(`WindowExpr.from: expected 'window', got '${json.kind}'`);
7321
+ static from(json2, registry) {
7322
+ if (json2.kind !== "window") {
7323
+ throw new Error(`WindowExpr.from: expected 'window', got '${json2.kind}'`);
7283
7324
  }
7284
- const partitionBy = (json.partitionBy ?? []).map((e2) => registry.parseExpr(e2));
7285
- const orderBy = (json.orderBy ?? []).map((o) => ({
7325
+ const partitionBy = (json2.partitionBy ?? []).map((e2) => registry.parseExpr(e2));
7326
+ const orderBy = (json2.orderBy ?? []).map((o) => ({
7286
7327
  expr: registry.parseExpr(o.expr),
7287
7328
  dir: o.dir,
7288
7329
  nulls: o.nulls
7289
7330
  }));
7290
- return new _WindowExpr(json.function, parseNamedArgs(json.args, registry), partitionBy, orderBy);
7331
+ return new _WindowExpr(json2.function, parseNamedArgs(json2.args, registry), partitionBy, orderBy);
7291
7332
  }
7292
7333
  /**
7293
7334
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7533,11 +7574,11 @@ var FunctionCallExpr = class _FunctionCallExpr extends Expr {
7533
7574
  ];
7534
7575
  kind = _FunctionCallExpr.KIND;
7535
7576
  /** Reconstruct a FunctionCallExpr from its JSON def, parsing named args via the registry. */
7536
- static from(json, registry) {
7537
- if (json.kind !== "function-call") {
7538
- throw new Error(`FunctionCallExpr.from: expected 'function-call', got '${json.kind}'`);
7577
+ static from(json2, registry) {
7578
+ if (json2.kind !== "function-call") {
7579
+ throw new Error(`FunctionCallExpr.from: expected 'function-call', got '${json2.kind}'`);
7539
7580
  }
7540
- return new _FunctionCallExpr(json.function, parseNamedArgs(json.args, registry));
7581
+ return new _FunctionCallExpr(json2.function, parseNamedArgs(json2.args, registry));
7541
7582
  }
7542
7583
  /**
7543
7584
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7662,11 +7703,11 @@ var TabularFunctionCallExpr = class _TabularFunctionCallExpr extends Expr {
7662
7703
  static INSTRUCTIONS = "A row-producing (table-valued) function call, usable as a source.";
7663
7704
  kind = _TabularFunctionCallExpr.KIND;
7664
7705
  /** Reconstruct a TabularFunctionCallExpr from its JSON def, parsing named args via the registry. */
7665
- static from(json, registry) {
7666
- if (json.kind !== "tabular-function-call") {
7667
- throw new Error(`TabularFunctionCallExpr.from: expected 'tabular-function-call', got '${json.kind}'`);
7706
+ static from(json2, registry) {
7707
+ if (json2.kind !== "tabular-function-call") {
7708
+ throw new Error(`TabularFunctionCallExpr.from: expected 'tabular-function-call', got '${json2.kind}'`);
7668
7709
  }
7669
- return new _TabularFunctionCallExpr(json.function, parseNamedArgs(json.args, registry));
7710
+ return new _TabularFunctionCallExpr(json2.function, parseNamedArgs(json2.args, registry));
7670
7711
  }
7671
7712
  /**
7672
7713
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -7864,18 +7905,18 @@ var SEMANTIC_TYPE_FIELD_SHAPE = obj(
7864
7905
  { aid: "SemanticQuery" }
7865
7906
  );
7866
7907
  var semanticQueryShape = {
7867
- check(json, ctx) {
7868
- if (typeof json === "string") return { kind: "text", text: json };
7869
- if (isRecord3(json)) {
7870
- if (json["kind"] === "param") {
7871
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
7908
+ check(json2, ctx) {
7909
+ if (typeof json2 === "string") return { kind: "text", text: json2 };
7910
+ if (isRecord3(json2)) {
7911
+ if (json2["kind"] === "param") {
7912
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
7872
7913
  if (built instanceof ParamExpr) return { kind: "param", param: built };
7873
7914
  return INVALID;
7874
7915
  }
7875
- if ("source" in json) return SEMANTIC_SOURCE_FIELD_SHAPE.check(json, ctx);
7876
- if ("type" in json) return SEMANTIC_TYPE_FIELD_SHAPE.check(json, ctx);
7916
+ if ("source" in json2) return SEMANTIC_SOURCE_FIELD_SHAPE.check(json2, ctx);
7917
+ if ("type" in json2) return SEMANTIC_TYPE_FIELD_SHAPE.check(json2, ctx);
7877
7918
  }
7878
- ctx.problems.error("shape.type", expected("SemanticQuery", json));
7919
+ ctx.problems.error("shape.type", expected("SemanticQuery", json2));
7879
7920
  return INVALID;
7880
7921
  }
7881
7922
  };
@@ -7910,11 +7951,11 @@ var SemanticExpr = class _SemanticExpr extends Expr {
7910
7951
  static INSTRUCTIONS = "Embedding-similarity score of a source\u2019s row vs a query (string / param / pairing ref) \u2192 number.";
7911
7952
  kind = _SemanticExpr.KIND;
7912
7953
  /** Reconstruct a SemanticExpr from its JSON def (validates the `kind` discriminant). */
7913
- static from(json, registry) {
7914
- if (json.kind !== "semantic") {
7915
- throw new Error(`SemanticExpr.from: expected 'semantic', got '${json.kind}'`);
7954
+ static from(json2, registry) {
7955
+ if (json2.kind !== "semantic") {
7956
+ throw new Error(`SemanticExpr.from: expected 'semantic', got '${json2.kind}'`);
7916
7957
  }
7917
- return new _SemanticExpr(json.source, json.field, parseQuery(json.query, registry));
7958
+ return new _SemanticExpr(json2.source, json2.field, parseQuery(json2.query, registry));
7918
7959
  }
7919
7960
  /**
7920
7961
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8298,9 +8339,9 @@ function parseTextQuery(def, registry) {
8298
8339
  }
8299
8340
  function textQueryShape() {
8300
8341
  return {
8301
- check(json, ctx) {
8302
- if (typeof json === "string") return { kind: "text", text: json };
8303
- const built = ParamExpr.SHAPE.check(json, ctx);
8342
+ check(json2, ctx) {
8343
+ if (typeof json2 === "string") return { kind: "text", text: json2 };
8344
+ const built = ParamExpr.SHAPE.check(json2, ctx);
8304
8345
  return built === INVALID ? INVALID : { kind: "param", param: built };
8305
8346
  }
8306
8347
  };
@@ -8383,14 +8424,14 @@ var TextSearchExpr = class _TextSearchExpr extends BoolExpr {
8383
8424
  query;
8384
8425
  static KIND = "text-search";
8385
8426
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
8386
- static INSTRUCTIONS = "Full-text predicate over a source (optionally one field) \u2192 boolean.";
8427
+ static INSTRUCTIONS = "Full-text predicate over a source (optionally one field) \u2192 boolean. NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source search is REFUSED (`text-search.unbacked`) rather than guessing a column.";
8387
8428
  kind = _TextSearchExpr.KIND;
8388
8429
  /** Reconstruct a TextSearchExpr from its JSON def (validates the `kind` discriminant). */
8389
- static from(json, registry) {
8390
- if (json.kind !== "text-search") {
8391
- throw new Error(`TextSearchExpr.from: expected 'text-search', got '${json.kind}'`);
8430
+ static from(json2, registry) {
8431
+ if (json2.kind !== "text-search") {
8432
+ throw new Error(`TextSearchExpr.from: expected 'text-search', got '${json2.kind}'`);
8392
8433
  }
8393
- return new _TextSearchExpr(json.source, json.field, parseTextQuery(json.query, registry));
8434
+ return new _TextSearchExpr(json2.source, json2.field, parseTextQuery(json2.query, registry));
8394
8435
  }
8395
8436
  /**
8396
8437
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8542,14 +8583,14 @@ var TextScoreExpr = class _TextScoreExpr extends Expr {
8542
8583
  query;
8543
8584
  static KIND = "text-score";
8544
8585
  /** Concise LLM-facing summary of this expr kind (see `ExprClass.INSTRUCTIONS`). */
8545
- static INSTRUCTIONS = "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`).";
8586
+ static INSTRUCTIONS = "Numeric full-text relevance score of a source (optionally one field) \u2192 number (`ts_rank`). NARROW it to a text `field` unless the Type declares a searchable whole-record DOCUMENT: an unbacked whole-source score is REFUSED (`text-score.unbacked`) rather than guessing a column.";
8546
8587
  kind = _TextScoreExpr.KIND;
8547
8588
  /** Reconstruct a TextScoreExpr from its JSON def (validates the `kind` discriminant). */
8548
- static from(json, registry) {
8549
- if (json.kind !== "text-score") {
8550
- throw new Error(`TextScoreExpr.from: expected 'text-score', got '${json.kind}'`);
8589
+ static from(json2, registry) {
8590
+ if (json2.kind !== "text-score") {
8591
+ throw new Error(`TextScoreExpr.from: expected 'text-score', got '${json2.kind}'`);
8551
8592
  }
8552
- return new _TextScoreExpr(json.source, json.field, parseTextQuery(json.query, registry));
8593
+ return new _TextScoreExpr(json2.source, json2.field, parseTextQuery(json2.query, registry));
8553
8594
  }
8554
8595
  /**
8555
8596
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8709,11 +8750,11 @@ var FiltersExpr = class _FiltersExpr extends BoolExpr {
8709
8750
  static INSTRUCTIONS = "An execution-time filter placeholder bound to a source (optional `fields` allowlist); predicate supplied at run time.";
8710
8751
  kind = _FiltersExpr.KIND;
8711
8752
  /** Reconstruct a FiltersExpr from its JSON def (validates the `kind` discriminant). */
8712
- static from(json, _registry) {
8713
- if (json.kind !== "filters") {
8714
- throw new Error(`FiltersExpr.from: expected 'filters', got '${json.kind}'`);
8753
+ static from(json2, _registry) {
8754
+ if (json2.kind !== "filters") {
8755
+ throw new Error(`FiltersExpr.from: expected 'filters', got '${json2.kind}'`);
8715
8756
  }
8716
- return new _FiltersExpr(json.source, json.fields ? [...json.fields] : void 0);
8757
+ return new _FiltersExpr(json2.source, json2.fields ? [...json2.fields] : void 0);
8717
8758
  }
8718
8759
  /**
8719
8760
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -8888,11 +8929,11 @@ var SubqueryExpr = class _SubqueryExpr extends Expr {
8888
8929
  ];
8889
8930
  kind = _SubqueryExpr.KIND;
8890
8931
  /** Reconstruct a SubqueryExpr from its JSON def (validates the `kind` discriminant). */
8891
- static from(json, _registry) {
8892
- if (json.kind !== "subquery") {
8893
- throw new Error(`SubqueryExpr.from: expected 'subquery', got '${json.kind}'`);
8932
+ static from(json2, _registry) {
8933
+ if (json2.kind !== "subquery") {
8934
+ throw new Error(`SubqueryExpr.from: expected 'subquery', got '${json2.kind}'`);
8894
8935
  }
8895
- return new _SubqueryExpr(json.query);
8936
+ return new _SubqueryExpr(json2.query);
8896
8937
  }
8897
8938
  /**
8898
8939
  * Owned structural {@link Shape} — the zod-free parallel parser. Structurally
@@ -8969,11 +9010,11 @@ var ExcludedExpr = class _ExcludedExpr extends Expr {
8969
9010
  static INSTRUCTIONS = '`EXCLUDED."field"` \u2014 the proposed row inside `INSERT \u2026 ON CONFLICT DO UPDATE`.';
8970
9011
  kind = _ExcludedExpr.KIND;
8971
9012
  /** Reconstruct an ExcludedExpr from its JSON def (validates the `kind` discriminant). */
8972
- static from(json, _registry) {
8973
- if (json.kind !== "excluded") {
8974
- throw new Error(`ExcludedExpr.from: expected 'excluded', got '${json.kind}'`);
9013
+ static from(json2, _registry) {
9014
+ if (json2.kind !== "excluded") {
9015
+ throw new Error(`ExcludedExpr.from: expected 'excluded', got '${json2.kind}'`);
8975
9016
  }
8976
- return new _ExcludedExpr(json.field);
9017
+ return new _ExcludedExpr(json2.field);
8977
9018
  }
8978
9019
  /**
8979
9020
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -9630,11 +9671,11 @@ var RELATION_ON_SHAPE = obj(
9630
9671
  { aid: "JoinOn" }
9631
9672
  );
9632
9673
  var JOIN_ON_SHAPE = {
9633
- check(json, ctx) {
9634
- if (isRecord3(json) && json["kind"] === "relation") {
9635
- return RELATION_ON_SHAPE.check(json, ctx);
9674
+ check(json2, ctx) {
9675
+ if (isRecord3(json2) && json2["kind"] === "relation") {
9676
+ return RELATION_ON_SHAPE.check(json2, ctx);
9636
9677
  }
9637
- const src = sourceRef().check(json, ctx);
9678
+ const src = sourceRef().check(json2, ctx);
9638
9679
  return src === INVALID ? INVALID : { kind: "source", source: src };
9639
9680
  }
9640
9681
  };
@@ -9911,20 +9952,24 @@ function reportDuplicateSources(p, sources) {
9911
9952
  }
9912
9953
 
9913
9954
  // src/queries/_write.ts
9914
- function isExprValue(v) {
9915
- return isRecord3(v) && typeof v["kind"] === "string";
9955
+ function isExprValue(v, registry) {
9956
+ if (!isRecord3(v) || typeof v["kind"] !== "string") return false;
9957
+ return registry === void 0 || registry.exprClass(v["kind"]) !== void 0;
9916
9958
  }
9917
9959
  function writeValueToExpr(v, registry) {
9918
9960
  if (v === null || v === void 0) return void 0;
9919
- if (isExprValue(v)) return registry.parseExpr(v);
9920
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") return new LiteralExpr(v);
9961
+ if (isExprValue(v, registry)) return registry.parseExpr(v);
9962
+ if (isJsonValue(v, JSON_MAX_DEPTH)) return new LiteralExpr(v);
9921
9963
  throw new QueryTypeError({
9922
9964
  path: [],
9923
9965
  code: "write.unsupported-value",
9924
9966
  severity: "error",
9925
- message: `Unsupported write value ${JSON.stringify(v)}; use a scalar or an expression.`
9967
+ message: `Unsupported write value ${describeUnsupported(v)}; use a JSON value or an expression.`
9926
9968
  });
9927
9969
  }
9970
+ function describeUnsupported(v) {
9971
+ return typeof v === "object" && v !== null ? Object.prototype.toString.call(v) : String(v);
9972
+ }
9928
9973
  function parseWriteRecord(record2, registry) {
9929
9974
  const out = /* @__PURE__ */ new Map();
9930
9975
  for (const key of Object.keys(record2)) {
@@ -9933,6 +9978,37 @@ function parseWriteRecord(record2, registry) {
9933
9978
  }
9934
9979
  return out;
9935
9980
  }
9981
+ function validateWriteValue(engine, scope, p, ctx, field, expr) {
9982
+ const resolved = expr.validateWalk(engine, scope, p, ctx);
9983
+ if (!field) return;
9984
+ if (expr instanceof ParamExpr) {
9985
+ scope.params.observe(expr.name, field.fieldType, p.here);
9986
+ return;
9987
+ }
9988
+ if (expr instanceof LiteralExpr && expr.isNullLiteral()) return;
9989
+ if (field.fieldType instanceof RelationFieldType) return;
9990
+ const valueType = asFieldType(resolved);
9991
+ if (valueType && !field.fieldType.comparableWith(valueType)) {
9992
+ p.error(
9993
+ "write.type",
9994
+ `Cannot write a ${valueType.resolve()} value to field '${field.name}' (${field.fieldType.resolve()}).`
9995
+ );
9996
+ }
9997
+ }
9998
+ function writeCellSql(expr, field, dialect, ctx) {
9999
+ const document = writeDocument(expr, ctx);
10000
+ return document !== void 0 ? dialect.jsonValue(document, field?.fieldType) : expr.toSQL(dialect, ctx);
10001
+ }
10002
+ function writeDocument(expr, ctx) {
10003
+ if (expr instanceof LiteralExpr) {
10004
+ return expr.value !== null && typeof expr.value === "object" ? expr.value : void 0;
10005
+ }
10006
+ if (expr instanceof ParamExpr && Object.prototype.hasOwnProperty.call(ctx.params, expr.name)) {
10007
+ const bound = ctx.params[expr.name];
10008
+ return bound !== null && bound !== void 0 && typeof bound === "object" ? bound : void 0;
10009
+ }
10010
+ return void 0;
10011
+ }
9936
10012
 
9937
10013
  // src/queries/_shape.ts
9938
10014
  function selectFieldShape() {
@@ -9944,16 +10020,14 @@ function selectFieldShape() {
9944
10020
  }
9945
10021
  function writeValueShape() {
9946
10022
  return {
9947
- check(json, ctx) {
9948
- if (json === null || json === void 0) return void 0;
9949
- if (isExprValue(json)) {
9950
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
10023
+ check(json2, ctx) {
10024
+ if (json2 === null || json2 === void 0) return void 0;
10025
+ if (isExprValue(json2, ctx.registry)) {
10026
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
9951
10027
  return built === void 0 ? INVALID : built;
9952
10028
  }
9953
- if (typeof json === "string" || typeof json === "number" || typeof json === "boolean") {
9954
- return new LiteralExpr(json);
9955
- }
9956
- ctx.problems.error("shape.type", expected("WriteValue", json));
10029
+ if (isJsonValue(json2, JSON_MAX_DEPTH)) return new LiteralExpr(json2);
10030
+ ctx.problems.error("shape.type", expected("WriteValue", json2));
9957
10031
  return INVALID;
9958
10032
  }
9959
10033
  };
@@ -9961,15 +10035,15 @@ function writeValueShape() {
9961
10035
  function writeRecordShape(aid) {
9962
10036
  const value2 = writeValueShape();
9963
10037
  return {
9964
- check(json, ctx) {
9965
- if (!isRecord3(json)) {
9966
- ctx.problems.error("shape.not-object", expected(aid, json));
10038
+ check(json2, ctx) {
10039
+ if (!isRecord3(json2)) {
10040
+ ctx.problems.error("shape.not-object", expected(aid, json2));
9967
10041
  return INVALID;
9968
10042
  }
9969
10043
  const out = /* @__PURE__ */ new Map();
9970
10044
  let ok = true;
9971
- for (const key of Object.keys(json)) {
9972
- const built = ctx.problems.at(key, () => value2.check(json[key], ctx));
10045
+ for (const key of Object.keys(json2)) {
10046
+ const built = ctx.problems.at(key, () => value2.check(json2[key], ctx));
9973
10047
  if (built === INVALID) ok = false;
9974
10048
  else if (built !== void 0) out.set(key, built);
9975
10049
  }
@@ -9979,14 +10053,14 @@ function writeRecordShape(aid) {
9979
10053
  }
9980
10054
  function boundShape() {
9981
10055
  return {
9982
- check(json, ctx) {
9983
- if (typeof json === "number") return json;
9984
- if (isRecord3(json) && json["kind"] === "param") {
9985
- const built = ctx.registry.parseCheckedExpr(json, ctx.problems);
10056
+ check(json2, ctx) {
10057
+ if (typeof json2 === "number") return json2;
10058
+ if (isRecord3(json2) && json2["kind"] === "param") {
10059
+ const built = ctx.registry.parseCheckedExpr(json2, ctx.problems);
9986
10060
  if (built instanceof ParamExpr) return built.toJSON();
9987
10061
  return INVALID;
9988
10062
  }
9989
- ctx.problems.error("shape.type", expected("Limit", json));
10063
+ ctx.problems.error("shape.type", expected("Limit", json2));
9990
10064
  return INVALID;
9991
10065
  }
9992
10066
  };
@@ -10669,8 +10743,8 @@ async function rowPassesDefaultConditions(active, row, ctx) {
10669
10743
 
10670
10744
  // src/queries/select.ts
10671
10745
  var orderItemShape = {
10672
- check(json, ctx) {
10673
- return isRecord3(json) && json["kind"] === "sorter" ? SorterExpr.SHAPE.check(json, ctx) : QueryOrder.SHAPE.check(json, ctx);
10746
+ check(json2, ctx) {
10747
+ return isRecord3(json2) && json2["kind"] === "sorter" ? SorterExpr.SHAPE.check(json2, ctx) : QueryOrder.SHAPE.check(json2, ctx);
10674
10748
  }
10675
10749
  };
10676
10750
  function parseOrderItem(def, registry) {
@@ -10806,19 +10880,19 @@ var SelectQuery = class _SelectQuery extends Query {
10806
10880
  /** This query's `kind` discriminant. */
10807
10881
  kind = _SelectQuery.KIND;
10808
10882
  /** Parse a `select` `QueryDef` into a `SelectQuery`. */
10809
- static from(json, registry) {
10810
- if (json.kind !== "select") throw new Error(`SelectQuery.from: expected 'select', got '${json.kind}'`);
10883
+ static from(json2, registry) {
10884
+ if (json2.kind !== "select") throw new Error(`SelectQuery.from: expected 'select', got '${json2.kind}'`);
10811
10885
  return new _SelectQuery(
10812
- json.distinct ?? false,
10813
- json.fields.map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as })),
10814
- QuerySource.from(json.from, registry),
10815
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
10816
- (json.where ?? []).map((w) => registry.parseExpr(w)),
10817
- (json.groupBy ?? []).map((g) => registry.parseExpr(g)),
10818
- (json.having ?? []).map((h) => registry.parseExpr(h)),
10819
- (json.order ?? []).map((o) => parseOrderItem(o, registry)),
10820
- json.limit,
10821
- json.offset
10886
+ json2.distinct ?? false,
10887
+ json2.fields.map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as })),
10888
+ QuerySource.from(json2.from, registry),
10889
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
10890
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
10891
+ (json2.groupBy ?? []).map((g) => registry.parseExpr(g)),
10892
+ (json2.having ?? []).map((h) => registry.parseExpr(h)),
10893
+ (json2.order ?? []).map((o) => parseOrderItem(o, registry)),
10894
+ json2.limit,
10895
+ json2.offset
10822
10896
  );
10823
10897
  }
10824
10898
  /**
@@ -11903,17 +11977,17 @@ var InsertQuery = class _InsertQuery extends Query {
11903
11977
  /** This query's `kind` discriminant. */
11904
11978
  kind = _InsertQuery.KIND;
11905
11979
  /** Parse an `insert` `QueryDef` into an `InsertQuery`. */
11906
- static from(json, registry) {
11907
- if (json.kind !== "insert") throw new Error(`InsertQuery.from: expected 'insert', got '${json.kind}'`);
11908
- const rows = json.rows?.map((r) => parseWriteRecord(r, registry));
11909
- const select = json.select ? registry.parseQuery(json.select) : void 0;
11910
- const returning = (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }));
11911
- const onConflict = json.onConflict ? {
11912
- fields: [...json.onConflict.fields],
11913
- doNothing: json.onConflict.doNothing ?? false,
11914
- update: toAssigns(parseWriteRecord(json.onConflict.update ?? {}, registry))
11980
+ static from(json2, registry) {
11981
+ if (json2.kind !== "insert") throw new Error(`InsertQuery.from: expected 'insert', got '${json2.kind}'`);
11982
+ const rows = json2.rows?.map((r) => parseWriteRecord(r, registry));
11983
+ const select = json2.select ? registry.parseQuery(json2.select) : void 0;
11984
+ const returning = (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }));
11985
+ const onConflict = json2.onConflict ? {
11986
+ fields: [...json2.onConflict.fields],
11987
+ doNothing: json2.onConflict.doNothing ?? false,
11988
+ update: toAssigns(parseWriteRecord(json2.onConflict.update ?? {}, registry))
11915
11989
  } : void 0;
11916
- return new _InsertQuery(json.into, rows, select, returning, onConflict);
11990
+ return new _InsertQuery(json2.into, rows, select, returning, onConflict);
11917
11991
  }
11918
11992
  /**
11919
11993
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -12012,6 +12086,21 @@ var InsertQuery = class _InsertQuery extends Query {
12012
12086
  }
12013
12087
  });
12014
12088
  });
12089
+ const valueScope = this.targetScope(engine, scope);
12090
+ const valueCtx = {
12091
+ inAggregate: false,
12092
+ inWindow: false,
12093
+ allowAggregate: false,
12094
+ groupKeys: [],
12095
+ inGroupBy: false
12096
+ };
12097
+ p.at("rows", () => {
12098
+ this.rows.forEach((row, i) => {
12099
+ for (const [column2, expr] of row) {
12100
+ p.at([i, column2], () => validateWriteValue(engine, valueScope, p, valueCtx, type.field(column2), expr));
12101
+ }
12102
+ });
12103
+ });
12015
12104
  const missing = type.fields.filter((f) => !canonical.has(f.name) && requiredOnInsert(f, engine.fieldBacking(this.into, f.name))).map((f) => f.name);
12016
12105
  if (missing.length) {
12017
12106
  p.at(
@@ -12035,7 +12124,7 @@ var InsertQuery = class _InsertQuery extends Query {
12035
12124
  if (type && !type.field(u.field)) {
12036
12125
  p.at(u.field, () => p.error("insert.unknown-field", `Type '${this.into}' has no field '${u.field}'.${didYouMean(u.field, type.fields.map((f) => f.name))}`));
12037
12126
  }
12038
- p.at(u.field, () => u.expr.validateWalk(engine, conflictScope, p, assignCtx));
12127
+ p.at(u.field, () => validateWriteValue(engine, conflictScope, p, assignCtx, type.field(u.field), u.expr));
12039
12128
  });
12040
12129
  });
12041
12130
  }
@@ -12180,8 +12269,12 @@ var InsertQuery = class _InsertQuery extends Query {
12180
12269
  SqlText.raw(")")
12181
12270
  ];
12182
12271
  if (this.rows) {
12272
+ const target = ctx.engine.type(this.into);
12183
12273
  const tuples = this.rows.map(
12184
- (row) => SqlText.join(columns.map((c) => row.get(c).toSQL(dialect, ctx)), ", ").parens()
12274
+ (row) => SqlText.join(
12275
+ columns.map((c) => writeCellSql(row.get(c), target?.field(c), dialect, ctx)),
12276
+ ", "
12277
+ ).parens()
12185
12278
  );
12186
12279
  parts.push(SqlText.raw(" VALUES "), SqlText.join(tuples, ", "));
12187
12280
  } else if (this.select) {
@@ -12197,8 +12290,13 @@ var InsertQuery = class _InsertQuery extends Query {
12197
12290
  parts.push(SqlText.raw(" DO NOTHING"));
12198
12291
  } else {
12199
12292
  const conflictCtx = ctx.withScope(this.conflictScope(ctx.engine, ctx.scope));
12293
+ const conflictType = ctx.engine.type(this.into);
12200
12294
  const sets = this.onConflict.update.map(
12201
- (u) => SqlText.concat([dialect.ident(u.field), SqlText.raw(" = "), u.expr.toSQL(dialect, conflictCtx)])
12295
+ (u) => SqlText.concat([
12296
+ dialect.ident(u.field),
12297
+ SqlText.raw(" = "),
12298
+ writeCellSql(u.expr, conflictType?.field(u.field), dialect, conflictCtx)
12299
+ ])
12202
12300
  );
12203
12301
  parts.push(SqlText.raw(" DO UPDATE SET "), SqlText.join(sets, ", "));
12204
12302
  }
@@ -12273,14 +12371,14 @@ var UpdateQuery = class _UpdateQuery extends Query {
12273
12371
  /** This query's `kind` discriminant. */
12274
12372
  kind = _UpdateQuery.KIND;
12275
12373
  /** Parse an `update` `QueryDef` into an `UpdateQuery`. */
12276
- static from(json, registry) {
12277
- if (json.kind !== "update") throw new Error(`UpdateQuery.from: expected 'update', got '${json.kind}'`);
12374
+ static from(json2, registry) {
12375
+ if (json2.kind !== "update") throw new Error(`UpdateQuery.from: expected 'update', got '${json2.kind}'`);
12278
12376
  return new _UpdateQuery(
12279
- json.type,
12280
- [...parseWriteRecord(json.set, registry)].map(([field, expr]) => ({ field, expr })),
12281
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12282
- (json.where ?? []).map((w) => registry.parseExpr(w)),
12283
- (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12377
+ json2.type,
12378
+ [...parseWriteRecord(json2.set, registry)].map(([field, expr]) => ({ field, expr })),
12379
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12380
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
12381
+ (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12284
12382
  );
12285
12383
  }
12286
12384
  /**
@@ -12384,7 +12482,7 @@ var UpdateQuery = class _UpdateQuery extends Query {
12384
12482
  } else if (!field.updatableFor(engine.fieldBacking(this.type, s.field))) {
12385
12483
  p.at([i, "field"], () => p.error("update.field-readonly", `Field '${s.field}' of '${this.type}' is not updatable.`));
12386
12484
  }
12387
- p.at([i, "value"], () => s.expr.validateWalk(engine, inner, p, ctx));
12485
+ p.at([i, "value"], () => validateWriteValue(engine, inner, p, ctx, field, s.expr));
12388
12486
  });
12389
12487
  });
12390
12488
  p.at("where", () => this.where.forEach((w, i) => p.at(i, () => {
@@ -12512,8 +12610,13 @@ var UpdateQuery = class _UpdateQuery extends Query {
12512
12610
  const planner = new JoinCtePlanner(dialect, engine, ctx.rls, ctx.params, true);
12513
12611
  const selCtx = ctx.withPlanner(inner, planner);
12514
12612
  this.registerJoins(dialect, engine, selCtx, planner, aliasTypes);
12613
+ const target = engine.type(this.type);
12515
12614
  const sets = this.set.map(
12516
- (s) => SqlText.concat([dialect.ident(s.field), SqlText.raw(" = "), s.expr.toSQL(dialect, selCtx)])
12615
+ (s) => SqlText.concat([
12616
+ dialect.ident(s.field),
12617
+ SqlText.raw(" = "),
12618
+ writeCellSql(s.expr, target?.field(s.field), dialect, selCtx)
12619
+ ])
12517
12620
  );
12518
12621
  const wherePreds = this.where.map((w) => w.toSQL(dialect, selCtx));
12519
12622
  const rls = rlsPredicate(ctx.rls, dialect, engine, planner, this.type, this.alias);
@@ -12582,13 +12685,13 @@ var DeleteQuery = class _DeleteQuery extends Query {
12582
12685
  /** This query's `kind` discriminant. */
12583
12686
  kind = _DeleteQuery.KIND;
12584
12687
  /** Parse a `delete` `QueryDef` into a `DeleteQuery`. */
12585
- static from(json, registry) {
12586
- if (json.kind !== "delete") throw new Error(`DeleteQuery.from: expected 'delete', got '${json.kind}'`);
12688
+ static from(json2, registry) {
12689
+ if (json2.kind !== "delete") throw new Error(`DeleteQuery.from: expected 'delete', got '${json2.kind}'`);
12587
12690
  return new _DeleteQuery(
12588
- json.from,
12589
- (json.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12590
- (json.where ?? []).map((w) => registry.parseExpr(w)),
12591
- (json.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12691
+ json2.from,
12692
+ (json2.joins ?? []).map((j) => QueryJoin.from(j, registry)),
12693
+ (json2.where ?? []).map((w) => registry.parseExpr(w)),
12694
+ (json2.returning ?? []).map((c) => ({ expr: registry.parseExpr(c.expr), as: c.as }))
12592
12695
  );
12593
12696
  }
12594
12697
  /**
@@ -12886,18 +12989,18 @@ var SetOperationQuery = class _SetOperationQuery extends Query {
12886
12989
  /** This instance's actual set operation (`union` / `intersect` / `except`). */
12887
12990
  kind;
12888
12991
  /** Parse a `union` / `intersect` / `except` `QueryDef` into a `SetOperationQuery`. */
12889
- static from(json, registry) {
12890
- if (json.kind !== "union" && json.kind !== "intersect" && json.kind !== "except") {
12891
- throw new Error(`SetOperationQuery.from: expected a set op, got '${json.kind}'`);
12992
+ static from(json2, registry) {
12993
+ if (json2.kind !== "union" && json2.kind !== "intersect" && json2.kind !== "except") {
12994
+ throw new Error(`SetOperationQuery.from: expected a set op, got '${json2.kind}'`);
12892
12995
  }
12893
12996
  return new _SetOperationQuery(
12894
- json.kind,
12895
- registry.parseQuery(json.left),
12896
- registry.parseQuery(json.right),
12897
- json.all ?? false,
12898
- (json.order ?? []).map((o) => QueryOrder.from(o, registry)),
12899
- json.limit,
12900
- json.offset
12997
+ json2.kind,
12998
+ registry.parseQuery(json2.left),
12999
+ registry.parseQuery(json2.right),
13000
+ json2.all ?? false,
13001
+ (json2.order ?? []).map((o) => QueryOrder.from(o, registry)),
13002
+ json2.limit,
13003
+ json2.offset
12901
13004
  );
12902
13005
  }
12903
13006
  /**
@@ -13251,11 +13354,11 @@ var RECURSIVE_ENTRY_SHAPE = obj(
13251
13354
  { aid: "CTEEntry" }
13252
13355
  );
13253
13356
  var cteEntryShape = {
13254
- check(json, ctx) {
13255
- if (isRecord3(json) && "base" in json && "recursive" in json) {
13256
- return RECURSIVE_ENTRY_SHAPE.check(json, ctx);
13357
+ check(json2, ctx) {
13358
+ if (isRecord3(json2) && "base" in json2 && "recursive" in json2) {
13359
+ return RECURSIVE_ENTRY_SHAPE.check(json2, ctx);
13257
13360
  }
13258
- return PLAIN_ENTRY_SHAPE.check(json, ctx);
13361
+ return PLAIN_ENTRY_SHAPE.check(json2, ctx);
13259
13362
  }
13260
13363
  };
13261
13364
  var CTEStatementQuery = class _CTEStatementQuery extends Query {
@@ -13361,10 +13464,10 @@ var CTEStatementQuery = class _CTEStatementQuery extends Query {
13361
13464
  /** This query's `kind` discriminant. */
13362
13465
  kind = _CTEStatementQuery.KIND;
13363
13466
  /** Parse a `cte` `QueryDef` into a `CTEStatementQuery`. */
13364
- static from(json, registry) {
13365
- if (json.kind !== "cte") throw new Error(`CTEStatementQuery.from: expected 'cte', got '${json.kind}'`);
13366
- const ctes = json.ctes.map((c) => parseEntry(c, registry));
13367
- return new _CTEStatementQuery(ctes, registry.parseQuery(json.final));
13467
+ static from(json2, registry) {
13468
+ if (json2.kind !== "cte") throw new Error(`CTEStatementQuery.from: expected 'cte', got '${json2.kind}'`);
13469
+ const ctes = json2.ctes.map((c) => parseEntry(c, registry));
13470
+ return new _CTEStatementQuery(ctes, registry.parseQuery(json2.final));
13368
13471
  }
13369
13472
  /**
13370
13473
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds a
@@ -13495,9 +13598,9 @@ var ExprQuery = class _ExprQuery extends Query {
13495
13598
  /** This query's `kind` discriminant. */
13496
13599
  kind = _ExprQuery.KIND;
13497
13600
  /** Parse an `expr` `QueryDef` into an `ExprQuery`. */
13498
- static from(json, registry) {
13499
- if (json.kind !== "expr") throw new Error(`ExprQuery.from: expected 'expr', got '${json.kind}'`);
13500
- return new _ExprQuery(registry.parseExpr(json.expr));
13601
+ static from(json2, registry) {
13602
+ if (json2.kind !== "expr") throw new Error(`ExprQuery.from: expected 'expr', got '${json2.kind}'`);
13603
+ return new _ExprQuery(registry.parseExpr(json2.expr));
13501
13604
  }
13502
13605
  /**
13503
13606
  * Owned structural {@link Shape} — the zod-free parallel parser. Builds an
@@ -13690,6 +13793,35 @@ var Dialect = class {
13690
13793
  SqlText.raw(")")
13691
13794
  ]);
13692
13795
  }
13796
+ /**
13797
+ * Bind a whole JSON DOCUMENT (an object / array) as ONE parameter, cast to the
13798
+ * column type it is destined for. The single binding path for a non-scalar
13799
+ * VALUE — a `json` cell, an `array` cell, a document literal in a predicate.
13800
+ *
13801
+ * WHY A CAST, AND WHY THE FIELD TYPE. The document travels as its JSON TEXT in
13802
+ * a normal parameter slot (so `SqlValue` stays scalar and nothing is ever
13803
+ * string-interpolated), which means the server must be told what to parse it
13804
+ * AS. Left to inference, the same text is a `jsonb` in one column and a syntax
13805
+ * error in another. `fieldType` — supplied by the WRITE path, which knows the
13806
+ * column — makes that explicit; without it (a bare literal in a `where`, which
13807
+ * knows only its own shape) the dialect's own JSON type is the default.
13808
+ *
13809
+ * The base dialect casts to whatever `sqlTypeFor` names, which is the portable
13810
+ * answer for a JSON-typed column. A dialect with a NATIVE array type (Postgres
13811
+ * `text[]`) must override — an array literal there is not JSON text.
13812
+ */
13813
+ jsonValue(value2, fieldType) {
13814
+ const target = fieldType ? this.sqlTypeFor(fieldType) : this.jsonSqlType();
13815
+ return SqlText.concat([
13816
+ SqlText.raw("CAST("),
13817
+ SqlText.param(JSON.stringify(value2)),
13818
+ SqlText.raw(` AS ${target})`)
13819
+ ]);
13820
+ }
13821
+ /** This dialect's JSON column type — the default cast target for a document. */
13822
+ jsonSqlType() {
13823
+ return "json";
13824
+ }
13693
13825
  /**
13694
13826
  * Render a builtin's INLINE-LITERAL argument (a `rawArgs` position — see
13695
13827
  * {@link import('../schema').FunctionDef.rawArgs}) as a dialect-appropriate SQL
@@ -13969,6 +14101,47 @@ var PostgresDialect = class extends BaseDialect {
13969
14101
  SqlText.raw(")")
13970
14102
  ]);
13971
14103
  }
14104
+ /** Postgres stores JSON as `jsonb` (it has the equality / ordering operators `json` lacks). */
14105
+ jsonSqlType() {
14106
+ return "jsonb";
14107
+ }
14108
+ /**
14109
+ * Bind a JSON DOCUMENT — with the one Postgres wrinkle that makes the base
14110
+ * implementation wrong here: a NATIVE array column (`text[]`, `integer[]`, …)
14111
+ * does NOT accept JSON text. `CAST('["a","b"]' AS text[])` is a syntax error,
14112
+ * because a Postgres array literal is `{a,b}`.
14113
+ *
14114
+ * So a document destined for a native array is CONSTRUCTED instead —
14115
+ * `ARRAY[$1, $2]::text[]` — with each element bound in its own slot. That
14116
+ * reuses the element-binding pattern the array containment operators already
14117
+ * use, needs no array-literal encoder (whose quoting / escaping / NULL rules
14118
+ * would be their own defect surface), and handles the empty array
14119
+ * (`ARRAY[]::text[]`, which Postgres accepts precisely because the cast names
14120
+ * the type). Elements recurse, so a `jsonb[]` column takes documents.
14121
+ *
14122
+ * Everything else — a `json` / `jsonb` column, a heterogeneous array (which
14123
+ * `sqlTypeFor` already stores as `jsonb`), or a bare document with no declared
14124
+ * target — casts the JSON text to `jsonb`.
14125
+ */
14126
+ jsonValue(value2, fieldType) {
14127
+ const array = fieldType instanceof ArrayFieldType ? fieldType : void 0;
14128
+ const item = array?.item;
14129
+ if (array !== void 0 && item !== void 0 && Array.isArray(value2)) {
14130
+ const elements2 = value2.map(
14131
+ (v) => v !== null && typeof v === "object" ? this.jsonValue(v, item) : SqlText.param(v)
14132
+ );
14133
+ return SqlText.concat([
14134
+ SqlText.raw("ARRAY["),
14135
+ SqlText.join(elements2, ", "),
14136
+ SqlText.raw(`]::${this.sqlTypeFor(array)}`)
14137
+ ]);
14138
+ }
14139
+ return SqlText.concat([
14140
+ SqlText.raw("CAST("),
14141
+ SqlText.param(JSON.stringify(value2)),
14142
+ SqlText.raw(` AS ${this.jsonSqlType()})`)
14143
+ ]);
14144
+ }
13972
14145
  /** Cast the query param to the pgvector type so `similarity` type-checks (`<param>::vector`). */
13973
14146
  queryVectorParam(param3) {
13974
14147
  return SqlText.concat([param3, SqlText.raw("::vector")]);
@@ -15271,12 +15444,12 @@ var Registry = class {
15271
15444
  return this.defaultFieldTypeBytes.get(kind);
15272
15445
  }
15273
15446
  /** Parse a `FieldTypeDef` into a `FieldType` instance by dispatching on kind. */
15274
- parseFieldType(json) {
15275
- const cls = this.fieldTypeClasses.get(json.kind);
15447
+ parseFieldType(json2) {
15448
+ const cls = this.fieldTypeClasses.get(json2.kind);
15276
15449
  if (!cls) {
15277
- throw new Error(`registry.parseFieldType: unknown field-type kind '${json.kind}'`);
15450
+ throw new Error(`registry.parseFieldType: unknown field-type kind '${json2.kind}'`);
15278
15451
  }
15279
- return cls.from(json, this);
15452
+ return cls.from(json2, this);
15280
15453
  }
15281
15454
  // ─── Named Type registration / dispatch ──────────────────────────────────
15282
15455
  /**
@@ -15351,8 +15524,8 @@ var Registry = class {
15351
15524
  return Array.from(this.namedTypes.values());
15352
15525
  }
15353
15526
  /** Parse a `TypeDef` into a `Type` instance (does NOT auto-register). */
15354
- parseType(json) {
15355
- return Type.from(json, this);
15527
+ parseType(json2) {
15528
+ return Type.from(json2, this);
15356
15529
  }
15357
15530
  // ─── Function registration (Phase 2/4) ────────────────────────────────────
15358
15531
  /**
@@ -15447,13 +15620,13 @@ var Registry = class {
15447
15620
  * PASS-THROUGH — returned as-is. This is a runtime-boundary widening only: the
15448
15621
  * JSON `ExprDef` types stay pure, but built and parsed exprs compose freely.
15449
15622
  */
15450
- parseExpr(json) {
15451
- if (json instanceof Expr) return json;
15452
- const cls = this.exprClasses.get(json.kind);
15623
+ parseExpr(json2) {
15624
+ if (json2 instanceof Expr) return json2;
15625
+ const cls = this.exprClasses.get(json2.kind);
15453
15626
  if (!cls) {
15454
- throw new Error(`registry.parseExpr: unknown expr kind '${json.kind}'`);
15627
+ throw new Error(`registry.parseExpr: unknown expr kind '${json2.kind}'`);
15455
15628
  }
15456
- return cls.from(json, this);
15629
+ return cls.from(json2, this);
15457
15630
  }
15458
15631
  /** The `kind → Shape<Expr>` map, built from every Expr class that owns a `SHAPE`. */
15459
15632
  checkedExprShapes() {
@@ -15474,17 +15647,17 @@ var Registry = class {
15474
15647
  * active gate (zod still gates `parseQueryInput`). Only kinds that declare a
15475
15648
  * `static SHAPE` participate — others surface as an unknown-kind problem.
15476
15649
  */
15477
- parseCheckedExpr(json, problems) {
15478
- if (json instanceof Expr) return json;
15479
- if (!isRecord3(json)) {
15480
- const got = describeInput(json);
15650
+ parseCheckedExpr(json2, problems) {
15651
+ if (json2 instanceof Expr) return json2;
15652
+ if (!isRecord3(json2)) {
15653
+ const got = describeInput(json2);
15481
15654
  problems.error(
15482
15655
  "shape.not-object",
15483
15656
  `expected ${aidInfo("Expr").label}${got !== void 0 ? `, got ${got}` : ""}`
15484
15657
  );
15485
15658
  return void 0;
15486
15659
  }
15487
- const kind = json["kind"];
15660
+ const kind = json2["kind"];
15488
15661
  if (typeof kind !== "string") {
15489
15662
  problems.error("shape.missing-kind", `expected ${aidInfo("Expr").label} with a string \`kind\` discriminant`);
15490
15663
  return void 0;
@@ -15499,7 +15672,7 @@ var Registry = class {
15499
15672
  );
15500
15673
  return void 0;
15501
15674
  }
15502
- const built = shape.check(json, { problems, registry: this });
15675
+ const built = shape.check(json2, { problems, registry: this });
15503
15676
  return built === INVALID ? void 0 : built;
15504
15677
  }
15505
15678
  /**
@@ -15507,12 +15680,12 @@ var Registry = class {
15507
15680
  * registered class's static `from`. Children (sub-selects, CTE arms, …) are
15508
15681
  * parsed recursively by the class's `from` calling back into this method.
15509
15682
  */
15510
- parseQuery(json) {
15511
- const cls = this.queryClasses.get(json.kind);
15683
+ parseQuery(json2) {
15684
+ const cls = this.queryClasses.get(json2.kind);
15512
15685
  if (!cls) {
15513
- throw new Error(`registry.parseQuery: unknown query kind '${json.kind}'`);
15686
+ throw new Error(`registry.parseQuery: unknown query kind '${json2.kind}'`);
15514
15687
  }
15515
- return cls.from(json, this);
15688
+ return cls.from(json2, this);
15516
15689
  }
15517
15690
  /** The `kind → Shape<Query>` map, built from every Query class that owns a `SHAPE`. */
15518
15691
  checkedQueryShapes() {
@@ -15530,16 +15703,16 @@ var Registry = class {
15530
15703
  * class's owned `SHAPE` (see `shape/`), accumulating every structural problem
15531
15704
  * in a single pass. Only query kinds that declare a `static SHAPE` participate.
15532
15705
  */
15533
- parseCheckedQuery(json, problems) {
15534
- if (!isRecord3(json)) {
15535
- const got = describeInput(json);
15706
+ parseCheckedQuery(json2, problems) {
15707
+ if (!isRecord3(json2)) {
15708
+ const got = describeInput(json2);
15536
15709
  problems.error(
15537
15710
  "shape.not-object",
15538
15711
  `expected ${aidInfo("Query").label}${got !== void 0 ? `, got ${got}` : ""}`
15539
15712
  );
15540
15713
  return void 0;
15541
15714
  }
15542
- const kind = json["kind"];
15715
+ const kind = json2["kind"];
15543
15716
  if (typeof kind !== "string") {
15544
15717
  problems.error("shape.missing-kind", `expected ${aidInfo("Query").label} with a string \`kind\` discriminant`);
15545
15718
  return void 0;
@@ -15554,7 +15727,7 @@ var Registry = class {
15554
15727
  );
15555
15728
  return void 0;
15556
15729
  }
15557
- const built = shape.check(json, { problems, registry: this });
15730
+ const built = shape.check(json2, { problems, registry: this });
15558
15731
  return built === INVALID ? void 0 : built;
15559
15732
  }
15560
15733
  /**
@@ -15563,16 +15736,16 @@ var Registry = class {
15563
15736
  * NEVER throws: records problems and returns the built `QuerySource` or
15564
15737
  * `undefined`. Dispatches on the source `kind` over `QuerySource.SHAPES`.
15565
15738
  */
15566
- parseCheckedSource(json, problems) {
15567
- if (!isRecord3(json)) {
15568
- const got = describeInput(json);
15739
+ parseCheckedSource(json2, problems) {
15740
+ if (!isRecord3(json2)) {
15741
+ const got = describeInput(json2);
15569
15742
  problems.error(
15570
15743
  "shape.not-object",
15571
15744
  `expected ${aidInfo("Source").label}${got !== void 0 ? `, got ${got}` : ""}`
15572
15745
  );
15573
15746
  return void 0;
15574
15747
  }
15575
- const kind = json["kind"];
15748
+ const kind = json2["kind"];
15576
15749
  if (typeof kind !== "string") {
15577
15750
  problems.error("shape.missing-kind", `expected ${aidInfo("Source").label} with a string \`kind\` discriminant`);
15578
15751
  return void 0;
@@ -15586,7 +15759,7 @@ var Registry = class {
15586
15759
  );
15587
15760
  return void 0;
15588
15761
  }
15589
- const built = shape.check(json, { problems, registry: this });
15762
+ const built = shape.check(json2, { problems, registry: this });
15590
15763
  return built === INVALID ? void 0 : built;
15591
15764
  }
15592
15765
  };
@@ -16097,41 +16270,41 @@ var QueryFunction = class _QueryFunction {
16097
16270
  this.references = spec.references ?? [];
16098
16271
  }
16099
16272
  /** Build a runtime function from its JSON, parsing field/Type references. */
16100
- static from(json, registry) {
16101
- const params = json.params.map((p) => ({
16273
+ static from(json2, registry) {
16274
+ const params = json2.params.map((p) => ({
16102
16275
  name: p.name,
16103
16276
  fieldType: p.type === "any" ? void 0 : registry.parseFieldType(p.type),
16104
16277
  optional: p.optional ?? false
16105
16278
  }));
16106
16279
  let output2;
16107
- if (json.output === "inferred") {
16280
+ if (json2.output === "inferred") {
16108
16281
  output2 = { tag: "inferred" };
16109
- } else if (isFieldTypeDef(json.output)) {
16110
- output2 = { tag: "field", fieldType: registry.parseFieldType(json.output) };
16282
+ } else if (isFieldTypeDef(json2.output)) {
16283
+ output2 = { tag: "field", fieldType: registry.parseFieldType(json2.output) };
16111
16284
  } else {
16112
- if (!isTypeRef(json.output)) return assertNever9(json.output);
16113
- const type = registry.type(json.output.type);
16285
+ if (!isTypeRef(json2.output)) return assertNever9(json2.output);
16286
+ const type = registry.type(json2.output.type);
16114
16287
  if (!type) {
16115
16288
  throw new Error(
16116
- `QueryFunction.from: function '${json.name}' output references unknown Type '${json.output.type}'`
16289
+ `QueryFunction.from: function '${json2.name}' output references unknown Type '${json2.output.type}'`
16117
16290
  );
16118
16291
  }
16119
16292
  output2 = { tag: "type", type };
16120
16293
  }
16121
16294
  return new _QueryFunction({
16122
- name: json.name,
16123
- shape: json.shape,
16295
+ name: json2.name,
16296
+ shape: json2.shape,
16124
16297
  params,
16125
16298
  output: output2,
16126
- sql: json.sql,
16127
- rawArgs: json.rawArgs,
16128
- instructions: json.instructions,
16129
- examples: json.examples,
16130
- unaggregate: json.unaggregate,
16131
- unaggregateEmpty: json.unaggregateEmpty,
16132
- cost: json.cost,
16133
- changes: json.changes,
16134
- references: json.references
16299
+ sql: json2.sql,
16300
+ rawArgs: json2.rawArgs,
16301
+ instructions: json2.instructions,
16302
+ examples: json2.examples,
16303
+ unaggregate: json2.unaggregate,
16304
+ unaggregateEmpty: json2.unaggregateEmpty,
16305
+ cost: json2.cost,
16306
+ changes: json2.changes,
16307
+ references: json2.references
16135
16308
  });
16136
16309
  }
16137
16310
  /**
@@ -17881,8 +18054,10 @@ function fieldTypeSentence(ft) {
17881
18054
  }
17882
18055
  case "bool":
17883
18056
  return "A true/false flag";
17884
- case "relation":
17885
- return def.count === 1 ? `Belongs to one ${def.to}` : `Has many ${def.to} (\u2248${def.count} per row)`;
18057
+ case "relation": {
18058
+ const belongsTo = ft instanceof RelationFieldType ? ft.isBelongsTo() : def.count === 1;
18059
+ return belongsTo ? `Belongs to one ${def.to}` : `Has many ${def.to} (\u2248${def.count} per row)`;
18060
+ }
17886
18061
  case "date":
17887
18062
  return "A calendar date";
17888
18063
  case "timestamp":