@zenstackhq/orm 3.5.4 → 3.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1431,7 +1431,7 @@ type JsonFilter<AllowedKinds extends FilterKind = FilterKind> = ('Equality' exte
1431
1431
  array_ends_with?: JsonValue;
1432
1432
  } : {});
1433
1433
  type TypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = XOR<JsonFilter<AllowedKinds>, TypedJsonTypedFilter<Schema, TypeDefName, Array, Optional, AllowedKinds>>;
1434
- type TypedJsonTypedFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? (Array extends true ? ArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds> : NonArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds>) | (Optional extends true ? null : never) : {};
1434
+ type TypedJsonTypedFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? (Array extends true ? ArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds> : NonArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds>) | (Optional extends true ? null | JsonNullValues : never) : {};
1435
1435
  type ArrayTypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, AllowedKinds extends FilterKind> = {
1436
1436
  some?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1437
1437
  every?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
@@ -1610,8 +1610,9 @@ type CreateScalarPayload<Schema extends SchemaDef, Model extends GetModels<Schem
1610
1610
  type ScalarCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends ScalarFields<Schema, Model, false>> = ScalarFieldMutationPayload<Schema, Model, Field> | (FieldIsArray<Schema, Model, Field> extends true ? {
1611
1611
  set?: MapModelFieldType<Schema, Model, Field>;
1612
1612
  } : never);
1613
- type ScalarFieldMutationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = IsJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : MapModelFieldType<Schema, Model, Field>;
1613
+ type ScalarFieldMutationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = IsJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : IsTypedJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? MapModelFieldType<Schema, Model, Field> | JsonNull | DbNull : MapModelFieldType<Schema, Model, Field> : MapModelFieldType<Schema, Model, Field>;
1614
1614
  type IsJsonField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends 'Json' ? true : false;
1615
+ type IsTypedJsonField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends GetTypeDefs<Schema> ? true : false;
1615
1616
  type CreateFKPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
1616
1617
  [Key in ForeignKeyFields<Schema, Model>]: MapModelFieldType<Schema, Model, Key>;
1617
1618
  }>;
@@ -3013,6 +3014,7 @@ declare class ZodSchemaFactory<Schema extends SchemaDef, Options extends ClientO
3013
3014
  private makeTypeDefSchema;
3014
3015
  makeWhereSchema(model: string, unique: boolean, withoutRelationFields?: boolean, withAggregations?: boolean, options?: CreateSchemaOptions): ZodType;
3015
3016
  private makeTypedJsonFilterSchema;
3017
+ private makeNullableTypedJsonMutationSchema;
3016
3018
  private isTypeDefType;
3017
3019
  private makeEnumFilterSchema;
3018
3020
  private makeArrayFilterSchema;
package/dist/index.d.ts CHANGED
@@ -1431,7 +1431,7 @@ type JsonFilter<AllowedKinds extends FilterKind = FilterKind> = ('Equality' exte
1431
1431
  array_ends_with?: JsonValue;
1432
1432
  } : {});
1433
1433
  type TypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = XOR<JsonFilter<AllowedKinds>, TypedJsonTypedFilter<Schema, TypeDefName, Array, Optional, AllowedKinds>>;
1434
- type TypedJsonTypedFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? (Array extends true ? ArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds> : NonArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds>) | (Optional extends true ? null : never) : {};
1434
+ type TypedJsonTypedFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? (Array extends true ? ArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds> : NonArrayTypedJsonFilter<Schema, TypeDefName, AllowedKinds>) | (Optional extends true ? null | JsonNullValues : never) : {};
1435
1435
  type ArrayTypedJsonFilter<Schema extends SchemaDef, TypeDefName extends GetTypeDefs<Schema>, AllowedKinds extends FilterKind> = {
1436
1436
  some?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
1437
1437
  every?: TypedJsonFieldsFilter<Schema, TypeDefName, AllowedKinds>;
@@ -1610,8 +1610,9 @@ type CreateScalarPayload<Schema extends SchemaDef, Model extends GetModels<Schem
1610
1610
  type ScalarCreatePayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends ScalarFields<Schema, Model, false>> = ScalarFieldMutationPayload<Schema, Model, Field> | (FieldIsArray<Schema, Model, Field> extends true ? {
1611
1611
  set?: MapModelFieldType<Schema, Model, Field>;
1612
1612
  } : never);
1613
- type ScalarFieldMutationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = IsJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : MapModelFieldType<Schema, Model, Field>;
1613
+ type ScalarFieldMutationPayload<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = IsJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : IsTypedJsonField<Schema, Model, Field> extends true ? ModelFieldIsOptional<Schema, Model, Field> extends true ? MapModelFieldType<Schema, Model, Field> | JsonNull | DbNull : MapModelFieldType<Schema, Model, Field> : MapModelFieldType<Schema, Model, Field>;
1614
1614
  type IsJsonField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends 'Json' ? true : false;
1615
+ type IsTypedJsonField<Schema extends SchemaDef, Model extends GetModels<Schema>, Field extends GetModelFields<Schema, Model>> = GetModelFieldType<Schema, Model, Field> extends GetTypeDefs<Schema> ? true : false;
1615
1616
  type CreateFKPayload<Schema extends SchemaDef, Model extends GetModels<Schema>> = OptionalWrap<Schema, Model, {
1616
1617
  [Key in ForeignKeyFields<Schema, Model>]: MapModelFieldType<Schema, Model, Key>;
1617
1618
  }>;
@@ -3013,6 +3014,7 @@ declare class ZodSchemaFactory<Schema extends SchemaDef, Options extends ClientO
3013
3014
  private makeTypeDefSchema;
3014
3015
  makeWhereSchema(model: string, unique: boolean, withoutRelationFields?: boolean, withAggregations?: boolean, options?: CreateSchemaOptions): ZodType;
3015
3016
  private makeTypedJsonFilterSchema;
3017
+ private makeNullableTypedJsonMutationSchema;
3016
3018
  private isTypeDefType;
3017
3019
  private makeEnumFilterSchema;
3018
3020
  private makeArrayFilterSchema;
package/dist/index.js CHANGED
@@ -787,17 +787,32 @@ var BaseCrudDialect = class {
787
787
  take = -take;
788
788
  }
789
789
  result = this.buildSkipTake(result, skip, take);
790
- result = this.buildOrderBy(result, model, modelAlias, args.orderBy, negateOrderBy, take);
790
+ let distinctFields = [];
791
791
  if ("distinct" in args && args.distinct) {
792
- const distinct = ensureArray(args.distinct);
792
+ distinctFields = ensureArray(args.distinct);
793
793
  if (this.supportsDistinctOn) {
794
- result = result.distinctOn(distinct.map((f) => this.eb.ref(`${modelAlias}.${f}`)));
794
+ result = result.distinctOn(distinctFields.map((f) => this.eb.ref(`${modelAlias}.${f}`)));
795
795
  } else {
796
796
  throw createNotSupportedError(`"distinct" is not supported by "${this.schema.provider.type}" provider`);
797
797
  }
798
798
  }
799
+ let effectiveOrderBy = args.orderBy;
800
+ if (distinctFields.length > 0 && this.supportsDistinctOn) {
801
+ const existingOrderBy = enumerate(args.orderBy).filter((o) => Object.keys(o).length > 0);
802
+ const alreadySatisfied = distinctFields.every((f, i) => i < existingOrderBy.length && Object.keys(existingOrderBy[i])[0] === f);
803
+ if (existingOrderBy.length > 0 && !alreadySatisfied) {
804
+ const prependedOrderBy = distinctFields.map((f) => ({
805
+ [f]: "asc"
806
+ }));
807
+ effectiveOrderBy = [
808
+ ...prependedOrderBy,
809
+ ...existingOrderBy
810
+ ];
811
+ }
812
+ }
813
+ result = this.buildOrderBy(result, model, modelAlias, effectiveOrderBy, negateOrderBy, take);
799
814
  if (args.cursor) {
800
- result = this.buildCursorFilter(model, result, args.cursor, args.orderBy, negateOrderBy, modelAlias);
815
+ result = this.buildCursorFilter(model, result, args.cursor, effectiveOrderBy, negateOrderBy, modelAlias);
801
816
  }
802
817
  return result;
803
818
  }
@@ -1050,6 +1065,9 @@ var BaseCrudDialect = class {
1050
1065
  return this.buildEnumFilter(fieldRef, fieldDef, payload);
1051
1066
  }
1052
1067
  if (isTypeDef(this.schema, fieldDef.type)) {
1068
+ if (payload instanceof DbNullClass || payload instanceof JsonNullClass || payload instanceof AnyNullClass) {
1069
+ return this.buildJsonValueFilterClause(fieldRef, payload);
1070
+ }
1053
1071
  return this.buildJsonFilter(fieldRef, payload, fieldDef);
1054
1072
  }
1055
1073
  return match2(fieldDef.type).with("String", () => this.buildStringFilter(fieldRef, payload)).with(P.union("Int", "Float", "Decimal", "BigInt"), (type) => this.buildNumberFilter(fieldRef, type, payload)).with("Boolean", () => this.buildBooleanFilter(fieldRef, payload)).with("DateTime", () => this.buildDateTimeFilter(fieldRef, payload)).with("Bytes", () => this.buildBytesFilter(fieldRef, payload)).with("Json", () => this.buildJsonFilter(fieldRef, payload, fieldDef)).with("Unsupported", () => {
@@ -1527,12 +1545,13 @@ var BaseCrudDialect = class {
1527
1545
  const fieldDef = requireField(this.schema, model, field);
1528
1546
  const fieldModel = fieldDef.type;
1529
1547
  let fieldCountQuery;
1548
+ const subQueryAlias = tmpAlias(`${parentAlias}$_${field}$count`);
1530
1549
  const m2m = getManyToManyRelation(this.schema, model, field);
1531
1550
  if (m2m) {
1532
- fieldCountQuery = this.buildModelSelect(fieldModel, fieldModel, value, false).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.joinTable}.${m2m.otherFkName}`, "=", `${fieldModel}.${m2m.otherPKName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${parentAlias}.${m2m.parentPKName}`)).select(eb.fn.countAll().as(`_count$${field}`));
1551
+ fieldCountQuery = this.buildModelSelect(fieldModel, subQueryAlias, value, false).innerJoin(m2m.joinTable, (join) => join.onRef(`${m2m.joinTable}.${m2m.otherFkName}`, "=", `${subQueryAlias}.${m2m.otherPKName}`).onRef(`${m2m.joinTable}.${m2m.parentFkName}`, "=", `${parentAlias}.${m2m.parentPKName}`)).select(eb.fn.countAll().as(`_count$${field}`));
1533
1552
  } else {
1534
- fieldCountQuery = this.buildModelSelect(fieldModel, fieldModel, value, false).select(eb.fn.countAll().as(`_count$${field}`));
1535
- const joinPairs = buildJoinPairs(this.schema, model, parentAlias, field, fieldModel);
1553
+ fieldCountQuery = this.buildModelSelect(fieldModel, subQueryAlias, value, false).select(eb.fn.countAll().as(`_count$${field}`));
1554
+ const joinPairs = buildJoinPairs(this.schema, model, parentAlias, field, subQueryAlias);
1536
1555
  for (const [left, right] of joinPairs) {
1537
1556
  fieldCountQuery = fieldCountQuery.whereRef(left, "=", right);
1538
1557
  }
@@ -2285,10 +2304,20 @@ var PostgresCrudDialect = class _PostgresCrudDialect extends LateralJoinDialectB
2285
2304
  return query;
2286
2305
  }
2287
2306
  buildJsonObject(value) {
2288
- return this.eb.fn("jsonb_build_object", Object.entries(value).flatMap(([key, value2]) => [
2289
- sql3.lit(key),
2290
- value2
2291
- ]));
2307
+ const entries = Object.entries(value);
2308
+ const MAX_PAIRS = 50;
2309
+ const buildChunk = /* @__PURE__ */ __name((chunk) => this.eb.fn("jsonb_build_object", chunk.flatMap(([k, v]) => [
2310
+ sql3.lit(k),
2311
+ v
2312
+ ])), "buildChunk");
2313
+ if (entries.length <= MAX_PAIRS) {
2314
+ return buildChunk(entries);
2315
+ }
2316
+ const chunks = [];
2317
+ for (let i = 0; i < entries.length; i += MAX_PAIRS) {
2318
+ chunks.push(buildChunk(entries.slice(i, i + MAX_PAIRS)));
2319
+ }
2320
+ return chunks.reduce((acc, chunk) => sql3`${acc} || ${chunk}`);
2292
2321
  }
2293
2322
  castInt(expression) {
2294
2323
  return this.eb.cast(expression, "integer");
@@ -5381,9 +5410,28 @@ var ZodSchemaFactory = class {
5381
5410
  candidates.push(this.makeJsonFilterSchema(contextModel, field, optional));
5382
5411
  if (optional) {
5383
5412
  candidates.push(z.null());
5413
+ candidates.push(z.instanceof(DbNullClass));
5414
+ candidates.push(z.instanceof(JsonNullClass));
5415
+ candidates.push(z.instanceof(AnyNullClass));
5384
5416
  }
5385
5417
  return z.union(candidates);
5386
5418
  }
5419
+ // For optional typed JSON fields, allow DbNull, JsonNull, and null.
5420
+ // z.union doesn't work here because `z.any()` (returned by `makeScalarSchema`)
5421
+ // always wins, so we create a wrapper superRefine instead.
5422
+ // The caller must pass the already-built fieldSchema so that array/list
5423
+ // mutation shapes (set, push, etc.) are preserved.
5424
+ makeNullableTypedJsonMutationSchema(fieldSchema) {
5425
+ return z.any().superRefine((value, ctx) => {
5426
+ if (value instanceof DbNullClass || value instanceof JsonNullClass || value === null || value === void 0) {
5427
+ return;
5428
+ }
5429
+ const parseResult = fieldSchema.safeParse(value);
5430
+ if (!parseResult.success) {
5431
+ parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
5432
+ }
5433
+ }).optional();
5434
+ }
5387
5435
  isTypeDefType(type) {
5388
5436
  return this.schema.typeDefs && type in this.schema.typeDefs;
5389
5437
  }
@@ -5722,6 +5770,9 @@ var ZodSchemaFactory = class {
5722
5770
  z.literal("asc"),
5723
5771
  z.literal("desc")
5724
5772
  ]);
5773
+ const refineAtMostOneKey = /* @__PURE__ */ __name((s) => s.refine((v) => Object.keys(v).length <= 1, {
5774
+ message: "Each orderBy element must have at most one key"
5775
+ }), "refineAtMostOneKey");
5725
5776
  const nextOpts = this.nextOptions(options);
5726
5777
  for (const [field, fieldDef] of this.getModelFields(model)) {
5727
5778
  if (fieldDef.relation) {
@@ -5729,9 +5780,9 @@ var ZodSchemaFactory = class {
5729
5780
  fields[field] = z.lazy(() => {
5730
5781
  let relationOrderBy = this.makeOrderBySchema(fieldDef.type, withRelation, WithAggregation, nextOpts);
5731
5782
  if (fieldDef.array) {
5732
- relationOrderBy = relationOrderBy.extend({
5783
+ relationOrderBy = refineAtMostOneKey(relationOrderBy.safeExtend({
5733
5784
  _count: sort
5734
- });
5785
+ }));
5735
5786
  }
5736
5787
  return relationOrderBy.optional();
5737
5788
  });
@@ -5765,7 +5816,7 @@ var ZodSchemaFactory = class {
5765
5816
  fields[agg] = z.lazy(() => this.makeOrderBySchema(model, true, false, options).optional());
5766
5817
  }
5767
5818
  }
5768
- return z.strictObject(fields);
5819
+ return refineAtMostOneKey(z.strictObject(fields));
5769
5820
  }
5770
5821
  makeDistinctSchema(model) {
5771
5822
  const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation).map(([name]) => name);
@@ -5875,6 +5926,8 @@ var ZodSchemaFactory = class {
5875
5926
  fieldSchema,
5876
5927
  z.instanceof(DbNullClass)
5877
5928
  ]);
5929
+ } else if (this.isTypeDefType(fieldDef.type)) {
5930
+ fieldSchema = this.makeNullableTypedJsonMutationSchema(fieldSchema);
5878
5931
  } else {
5879
5932
  fieldSchema = fieldSchema.nullable();
5880
5933
  }
@@ -6111,6 +6164,8 @@ var ZodSchemaFactory = class {
6111
6164
  fieldSchema,
6112
6165
  z.instanceof(DbNullClass)
6113
6166
  ]);
6167
+ } else if (this.isTypeDefType(fieldDef.type)) {
6168
+ fieldSchema = this.makeNullableTypedJsonMutationSchema(fieldSchema);
6114
6169
  } else {
6115
6170
  fieldSchema = fieldSchema.nullable();
6116
6171
  }