@zenstackhq/orm 3.9.8 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -207,6 +207,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
207
207
  isEnum: () => isEnum,
208
208
  isForeignKeyField: () => isForeignKeyField,
209
209
  isInheritedField: () => isInheritedField,
210
+ isPrimitiveTypeDef: () => isPrimitiveTypeDef,
210
211
  isRelationField: () => isRelationField,
211
212
  isScalarField: () => isScalarField,
212
213
  isTypeDef: () => isTypeDef,
@@ -387,6 +388,9 @@ function getEnum(schema, type) {
387
388
  function isTypeDef(schema, type) {
388
389
  return !!schema.typeDefs?.[type];
389
390
  }
391
+ function isPrimitiveTypeDef(schema, type) {
392
+ return !!schema.typeDefs?.[type]?.base;
393
+ }
390
394
  function buildJoinPairs(schema, model, modelAlias, relationField, relationModelAlias) {
391
395
  const { keyPairs, ownedByModel } = getRelationForeignKeyFieldPairs(schema, model, relationField);
392
396
  return keyPairs.map(({ fk, pk }) => {
@@ -690,12 +694,12 @@ var BaseCrudDialect = class {
690
694
  const { args: _args, ...rest } = payload;
691
695
  filterPayload = rest;
692
696
  }
693
- const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias, true, computedArgs);
697
+ const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, this.delegateFieldAlias(model, modelAlias, fieldDef), true, computedArgs);
694
698
  if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
695
699
  else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
696
700
  }
697
701
  }
698
- if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb));
702
+ if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb, { modelAlias }));
699
703
  return result;
700
704
  }
701
705
  buildCursorFilter(model, query, cursor, orderBy, negateOrderBy, modelAlias) {
@@ -710,8 +714,8 @@ var BaseCrudDialect = class {
710
714
  const [field, order] = orderByItems[j];
711
715
  const op = j === i ? (negateOrderBy ? order === "asc" ? "desc" : "asc" : order) === "asc" ? ">=" : "<=" : "=";
712
716
  const fieldDef = requireField(this.schema, model, field);
713
- const outerAlias = fieldDef.originModel ?? modelAlias;
714
- const subSelectAlias = fieldDef.originModel ?? subQueryAlias;
717
+ const outerAlias = this.delegateFieldAlias(model, modelAlias, fieldDef);
718
+ const subSelectAlias = this.delegateFieldAlias(model, subQueryAlias, fieldDef);
715
719
  andFilters.push(this.eb(this.eb.ref(`${outerAlias}.${field}`), op, this.buildSelectModel(model, subQueryAlias).select(`${subSelectAlias}.${field}`).where(cursorFilter)));
716
720
  }
717
721
  filters.push(this.eb.and(andFilters));
@@ -749,7 +753,7 @@ var BaseCrudDialect = class {
749
753
  else return this.buildToOneRelationFilter(model, modelAlias, field, fieldDef, { is: null });
750
754
  }
751
755
  const joinAlias = tmpAlias(`${modelAlias}$${field}`);
752
- const joinPairs = buildJoinPairs(this.schema, model, fieldDef.originModel ?? modelAlias, field, joinAlias);
756
+ const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
753
757
  const baseJoin = this.buildSelectModel(fieldDef.type, joinAlias).select(this.eb.lit(1).as("_")).where(() => this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), "=", this.eb.ref(right)))));
754
758
  const existsSelect = (extraFilter) => {
755
759
  const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
@@ -843,11 +847,13 @@ var BaseCrudDialect = class {
843
847
  buildPrimitiveFilter(fieldRef, fieldDef, payload) {
844
848
  if (payload === null) return this.eb(fieldRef, "is", null);
845
849
  if (isEnum(this.schema, fieldDef.type)) return this.buildEnumFilter(fieldRef, fieldDef, payload);
846
- if (isTypeDef(this.schema, fieldDef.type)) {
850
+ let type = fieldDef.type;
851
+ if (isTypeDef(this.schema, fieldDef.type)) if (isPrimitiveTypeDef(this.schema, fieldDef.type)) type = this.schema["typeDefs"][fieldDef.type]["base"];
852
+ else {
847
853
  if (payload instanceof DbNullClass || payload instanceof JsonNullClass || payload instanceof AnyNullClass) return this.buildJsonValueFilterClause(fieldRef, payload);
848
854
  return this.buildJsonFilter(fieldRef, payload, fieldDef);
849
855
  }
850
- return match(fieldDef.type).with("String", () => this.buildStringFilter(fieldRef, payload, fieldDef)).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", () => {
856
+ return match(type).with("String", () => this.buildStringFilter(fieldRef, payload, fieldDef)).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", () => {
851
857
  throw createInvalidInputError(`Unsupported field cannot be used in filters`);
852
858
  }).exhaustive();
853
859
  }
@@ -947,11 +953,12 @@ var BaseCrudDialect = class {
947
953
  const fieldDef = typeDef.fields[key];
948
954
  invariant(fieldDef, `Field "${key}" not found in type definition "${typeDefName}"`);
949
955
  const fieldReceiver = this.buildJsonPathSelection(receiver, `$.${key}`);
950
- if (isTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
956
+ if (isTypeDef(this.schema, fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) clauses.push(this.buildTypedJsonFilter(fieldReceiver, value, fieldDef.type, !!fieldDef.array));
951
957
  else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
952
958
  else {
959
+ const effectiveType = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
953
960
  let _receiver = fieldReceiver;
954
- if (fieldDef.type === "String" || isEnum(this.schema, fieldDef.type)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
961
+ if (effectiveType === "String" || isEnum(this.schema, effectiveType)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
955
962
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
956
963
  }
957
964
  }
@@ -1095,7 +1102,7 @@ var BaseCrudDialect = class {
1095
1102
  let result = query;
1096
1103
  const buildFieldRef = (model, field, modelAlias, computedArgs) => {
1097
1104
  const fieldDef = requireField(this.schema, model, field);
1098
- return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel, true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1105
+ return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, this.delegateJoinAlias(model, modelAlias, fieldDef.originModel), true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1099
1106
  };
1100
1107
  enumerate(orderBy).forEach((orderBy, index) => {
1101
1108
  for (const [field, value] of Object.entries(orderBy)) {
@@ -1144,10 +1151,15 @@ var BaseCrudDialect = class {
1144
1151
  return query;
1145
1152
  }
1146
1153
  const joinAlias = tmpAlias(`${modelAlias}$ob$${index}`);
1147
- const joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
1148
- const joinPairs = buildJoinPairs(this.schema, model, modelAlias, field, joinAlias);
1154
+ let joined = query.leftJoin(`${relationModel} as ${joinAlias}`, (join) => {
1155
+ const joinPairs = buildJoinPairs(this.schema, model, this.delegateFieldAlias(model, modelAlias, fieldDef), field, joinAlias);
1149
1156
  return join.on((eb) => this.and(...joinPairs.map(([left, right]) => eb(this.eb.ref(left), "=", this.eb.ref(right)))));
1150
1157
  });
1158
+ let joinBase = requireModel(this.schema, relationModel).baseModel;
1159
+ while (joinBase) {
1160
+ joined = this.buildDelegateJoin(relationModel, joinAlias, joinBase, joined);
1161
+ joinBase = requireModel(this.schema, joinBase).baseModel;
1162
+ }
1151
1163
  return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
1152
1164
  }
1153
1165
  applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
@@ -1211,12 +1223,13 @@ var BaseCrudDialect = class {
1211
1223
  const descendants = getDelegateDescendantModels(this.schema, model);
1212
1224
  for (const subModel of descendants) {
1213
1225
  result = this.buildDelegateJoin(model, modelAlias, subModel.name, result);
1226
+ const subModelAlias = this.delegateJoinAlias(model, modelAlias, subModel.name);
1214
1227
  result = result.select(() => {
1215
1228
  const jsonObject = {};
1216
1229
  for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
1217
1230
  if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
1218
1231
  if (fieldDef.computed && fieldDef.params) continue;
1219
- jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1232
+ jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModelAlias);
1220
1233
  }
1221
1234
  return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
1222
1235
  });
@@ -1239,17 +1252,35 @@ var BaseCrudDialect = class {
1239
1252
  buildSelectField(query, model, modelAlias, field, computedArgs) {
1240
1253
  const fieldDef = requireField(this.schema, model, field);
1241
1254
  const fieldModel = fieldDef.originModel ?? model;
1242
- const alias = fieldDef.originModel ?? modelAlias;
1255
+ const alias = this.delegateFieldAlias(model, modelAlias, fieldDef);
1243
1256
  return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
1244
1257
  }
1245
- buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1258
+ buildDelegateJoin(thisModel, thisModelAlias, otherModel, query) {
1246
1259
  const idFields = requireIdFields(this.schema, thisModel);
1247
- query = query.leftJoin(otherModelAlias, (qb) => {
1260
+ const otherModelAlias = this.delegateJoinAlias(thisModel, thisModelAlias, otherModel);
1261
+ const table = otherModelAlias === otherModel ? otherModel : `${otherModel} as ${otherModelAlias}`;
1262
+ query = query.leftJoin(table, (qb) => {
1248
1263
  for (const idField of idFields) qb = qb.onRef(`${thisModelAlias}.${idField}`, "=", `${otherModelAlias}.${idField}`);
1249
1264
  return qb;
1250
1265
  });
1251
1266
  return query;
1252
1267
  }
1268
+ /**
1269
+ * Gets the alias under which a delegate base or sub model is joined to a model selected as `modelAlias`.
1270
+ * A model selected under its own name (a top-level query) has them joined under their own model names.
1271
+ * A model selected under another alias (a relation subquery) has them joined under aliases derived from
1272
+ * it, so they never shadow a table of an enclosing query in the same delegate hierarchy.
1273
+ */
1274
+ delegateJoinAlias(model, modelAlias, joinedModel) {
1275
+ return modelAlias === model ? joinedModel : tmpAlias(`${modelAlias}$${joinedModel}`);
1276
+ }
1277
+ /**
1278
+ * Gets the alias of the table holding a field of a model selected as `modelAlias`: the joined base
1279
+ * table for a field inherited from a delegate base, otherwise the model's own table.
1280
+ */
1281
+ delegateFieldAlias(model, modelAlias, fieldDef) {
1282
+ return fieldDef.originModel ? this.delegateJoinAlias(model, modelAlias, fieldDef.originModel) : modelAlias;
1283
+ }
1253
1284
  buildCountJson(model, eb, parentAlias, payload) {
1254
1285
  const modelDef = requireModel(this.schema, model);
1255
1286
  const toManyRelations = Object.entries(modelDef.fields).filter(([, field]) => field.relation && field.array);
@@ -1521,9 +1552,10 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1521
1552
  if (value instanceof JsonNullClass) return this.eb.cast(sql.lit("null"), "json");
1522
1553
  else if (value instanceof DbNullClass) return null;
1523
1554
  else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
1524
- if (isTypeDef(this.schema, type)) if (typeof value !== "string") return this.transformInput(value, "Json", forArrayField);
1555
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
1556
+ else if (typeof value !== "string") return this.transformInput(value, "Json", forArrayField);
1525
1557
  else return value;
1526
- else if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1558
+ if (Array.isArray(value)) if (type === "Json") return JSON.stringify(value);
1527
1559
  else throw createNotSupportedError(`MySQL does not support array literals`);
1528
1560
  else switch (type) {
1529
1561
  case "Boolean": return value ? 1 : 0;
@@ -1538,6 +1570,7 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1538
1570
  }
1539
1571
  transformOutput(value, type, array) {
1540
1572
  if (value === null || value === void 0) return value;
1573
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
1541
1574
  switch (type) {
1542
1575
  case "Boolean": return this.transformOutputBoolean(value);
1543
1576
  case "DateTime": return this.transformOutputDate(value);
@@ -1566,7 +1599,12 @@ var MySqlCrudDialect = class extends LateralJoinDialectBase {
1566
1599
  return new Date(!anchored.endsWith("Z") ? anchored + "Z" : anchored);
1567
1600
  }
1568
1601
  transformOutputBytes(value) {
1569
- return Buffer.isBuffer(value) ? Uint8Array.from(value) : value;
1602
+ if (Buffer.isBuffer(value)) return Uint8Array.from(value);
1603
+ if (typeof value === "string") {
1604
+ const match = /^base64:type\d+:(.*)$/s.exec(value);
1605
+ if (match) return Uint8Array.from(Buffer.from(match[1], "base64"));
1606
+ }
1607
+ return value;
1570
1608
  }
1571
1609
  buildExistsExpression(innerQuery) {
1572
1610
  return this.eb.exists(this.eb.selectFrom(innerQuery.as("$exists_sub")).select(this.eb.lit(1).as("_")));
@@ -1778,9 +1816,10 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1778
1816
  if (value instanceof JsonNullClass) return "null";
1779
1817
  else if (value instanceof DbNullClass) return null;
1780
1818
  else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
1781
- if (isTypeDef(this.schema, type)) if (typeof value !== "string") return JSON.stringify(value);
1819
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema["typeDefs"][type]["base"];
1820
+ else if (typeof value !== "string") return JSON.stringify(value);
1782
1821
  else return value;
1783
- else if (Array.isArray(value)) if (type === "Json" && !forArrayField) return JSON.stringify(value);
1822
+ if (Array.isArray(value)) if (type === "Json" && !forArrayField) return JSON.stringify(value);
1784
1823
  else return value.map((v) => this.transformInput(v, type, false, fieldDef));
1785
1824
  else switch (type) {
1786
1825
  case "DateTime": {
@@ -1798,6 +1837,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1798
1837
  }
1799
1838
  transformOutput(value, type, array) {
1800
1839
  if (value === null || value === void 0) return value;
1840
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
1801
1841
  switch (type) {
1802
1842
  case "DateTime": return this.transformOutputDate(value);
1803
1843
  case "Bytes": return this.transformOutputBytes(value);
@@ -1910,6 +1950,7 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1910
1950
  const mapped = PostgresCrudDialect.dbAttributeToSqlTypeMap[attr.name];
1911
1951
  if (mapped) return mapped;
1912
1952
  }
1953
+ if (isPrimitiveTypeDef(this.schema, zmodelType)) zmodelType = this.schema.typeDefs[zmodelType].base;
1913
1954
  if (isEnum(this.schema, zmodelType)) return "text";
1914
1955
  else return this.zmodelToSqlTypeMap[zmodelType] ?? "text";
1915
1956
  }
@@ -2093,7 +2134,9 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2093
2134
  if (value instanceof JsonNullClass) return "null";
2094
2135
  else if (value instanceof DbNullClass) return null;
2095
2136
  else if (value instanceof AnyNullClass) invariant(false, "should not reach here: AnyNull is not a valid input value");
2096
- if (type === "Json" || this.schema.typeDefs && type in this.schema.typeDefs) return JSON.stringify(value);
2137
+ if (isTypeDef(this.schema, type)) if (isPrimitiveTypeDef(this.schema, type)) type = this.schema.typeDefs[type].base;
2138
+ else return JSON.stringify(value);
2139
+ if (type === "Json") return JSON.stringify(value);
2097
2140
  if (Array.isArray(value)) return value.map((v) => this.transformInput(v, type, false));
2098
2141
  else switch (type) {
2099
2142
  case "Boolean": return value ? 1 : 0;
@@ -2105,8 +2148,10 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2105
2148
  }
2106
2149
  transformOutput(value, type, array) {
2107
2150
  if (value === null || value === void 0) return value;
2108
- else if (this.schema.typeDefs && type in this.schema.typeDefs) return this.transformOutputJson(value);
2109
- else switch (type) {
2151
+ else if (this.schema.typeDefs && type in this.schema.typeDefs) {
2152
+ if (isPrimitiveTypeDef(this.schema, type)) return this.transformOutput(value, this.schema.typeDefs[type].base, array);
2153
+ return this.transformOutputJson(value);
2154
+ } else switch (type) {
2110
2155
  case "Boolean": return this.transformOutputBoolean(value);
2111
2156
  case "DateTime": return this.transformOutputDate(value);
2112
2157
  case "Bytes": return this.transformOutputBytes(value);
@@ -2528,7 +2573,7 @@ var ZodSchemaFactory = class {
2528
2573
  return result;
2529
2574
  }
2530
2575
  makeScalarSchema(type, attributes) {
2531
- if (this.schema.typeDefs && type in this.schema.typeDefs) return this.makeTypeDefSchema(type);
2576
+ if (this.schema.typeDefs && type in this.schema.typeDefs) return this.schema.typeDefs[type].base ? this.makeTypeDefSchema(type, attributes) : this.makeTypeDefSchema(type);
2532
2577
  else if (this.schema.enums && type in this.schema.enums) return this.makeEnumSchema(type);
2533
2578
  else return match(type).with("String", () => this.extraValidationsEnabled ? ZodUtils.addStringValidation(z.string(), attributes) : z.string()).with("Int", () => this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number().int(), attributes) : z.number().int()).with("Float", () => this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number(), attributes) : z.number()).with("Boolean", () => z.boolean()).with("BigInt", () => z.union([this.extraValidationsEnabled ? ZodUtils.addNumberValidation(z.number().int(), attributes) : z.number().int(), this.extraValidationsEnabled ? ZodUtils.addBigIntValidation(z.bigint(), attributes) : z.bigint()])).with("Decimal", () => {
2534
2579
  return z.union([
@@ -2564,9 +2609,20 @@ var ZodSchemaFactory = class {
2564
2609
  this.registerSchema(_enum, schema);
2565
2610
  return schema;
2566
2611
  }
2567
- makeTypeDefSchema(type) {
2612
+ /**
2613
+ * Attributes to validate each value of a scalar field against. For typedef list fields, the
2614
+ * field's own attributes (e.g. `@length`) validate the list rather than its items.
2615
+ */
2616
+ getItemAttributes(fieldDef) {
2617
+ return fieldDef.array && isTypeDef(this.schema, fieldDef.type) ? void 0 : fieldDef.attributes;
2618
+ }
2619
+ makeTypeDefSchema(type, fieldAttributes) {
2568
2620
  const typeDef = getTypeDef(this.schema, type);
2569
2621
  invariant(typeDef, `Type definition "${type}" not found in schema`);
2622
+ if (typeDef.base) {
2623
+ const schema = this.makeScalarSchema(typeDef.base, [...typeDef.fields["this"]?.attributes ?? [], ...fieldAttributes ?? []]);
2624
+ return this.extraValidationsEnabled ? ZodUtils.addCustomValidation(schema, typeDef.attributes) : schema;
2625
+ }
2570
2626
  const schema = (typeDef.strict ? z.strictObject : z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2571
2627
  let fieldSchema = isTypeDef(this.schema, def.type) ? z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
2572
2628
  if (def.array) fieldSchema = fieldSchema.array();
@@ -2611,8 +2667,8 @@ var ZodSchemaFactory = class {
2611
2667
  if (enumDef) {
2612
2668
  if (Object.keys(enumDef.values).length > 0) fieldSchema = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, withAggregations, allowedFilterKinds);
2613
2669
  } else if (fieldDef.array) fieldSchema = this.makeArrayFilterSchema(fieldDef.type, allowedFilterKinds);
2614
- else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2615
- else fieldSchema = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2670
+ else if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2671
+ else fieldSchema = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2616
2672
  }
2617
2673
  if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2618
2674
  if (fieldSchema) fields[field] = fieldSchema.optional();
@@ -2655,10 +2711,10 @@ var ZodSchemaFactory = class {
2655
2711
  const candidates = [];
2656
2712
  if (!array) {
2657
2713
  const fieldSchemas = {};
2658
- for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
2714
+ for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) if (this.isTypeDefType(fieldDef.type) && !isPrimitiveTypeDef(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, void 0).optional();
2659
2715
  else if (getEnum(this.schema, fieldDef.type)) fieldSchemas[fieldName] = this.makeEnumFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, false, void 0).optional();
2660
2716
  else if (fieldDef.array) fieldSchemas[fieldName] = this.makeArrayFilterSchema(fieldDef.type, void 0).optional();
2661
- else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, false, void 0).optional();
2717
+ else fieldSchemas[fieldName] = this.makePrimitiveFilterSchema(this.getEffectiveFieldType(fieldDef.type), !!fieldDef.optional, false, void 0).optional();
2662
2718
  candidates.push(z.strictObject(fieldSchemas));
2663
2719
  }
2664
2720
  const recursiveSchema = z.lazy(() => this.makeTypedJsonFilterSchema(type, optional, false, allowedFilterKinds)).optional();
@@ -2696,6 +2752,10 @@ var ZodSchemaFactory = class {
2696
2752
  isTypeDefType(type) {
2697
2753
  return this.schema.typeDefs && type in this.schema.typeDefs;
2698
2754
  }
2755
+ getEffectiveFieldType(type) {
2756
+ if (isPrimitiveTypeDef(this.schema, type)) return this.schema.typeDefs[type].base;
2757
+ return type;
2758
+ }
2699
2759
  makeEnumFilterSchema(enumName, optional, array, withAggregations, allowedFilterKinds) {
2700
2760
  const enumDef = getEnum(this.schema, enumName);
2701
2761
  invariant(enumDef, `Enum "${enumName}" not found in schema`);
@@ -3171,7 +3231,7 @@ var ZodSchemaFactory = class {
3171
3231
  checkedVariantFields[field] = fieldSchema;
3172
3232
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3173
3233
  } else {
3174
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3234
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3175
3235
  if (fieldDef.array) {
3176
3236
  fieldSchema = ZodUtils.addListValidation(fieldSchema.array(), fieldDef.attributes);
3177
3237
  fieldSchema = z.union([fieldSchema, z.strictObject({ set: fieldSchema })]).optional();
@@ -3349,7 +3409,7 @@ var ZodSchemaFactory = class {
3349
3409
  checkedVariantFields[field] = fieldSchema;
3350
3410
  if (fieldDef.array || !fieldDef.relation.references) uncheckedVariantFields[field] = fieldSchema;
3351
3411
  } else {
3352
- let fieldSchema = this.makeScalarSchema(fieldDef.type, fieldDef.attributes);
3412
+ let fieldSchema = this.makeScalarSchema(fieldDef.type, this.getItemAttributes(fieldDef));
3353
3413
  if (this.isNumericField(fieldDef)) fieldSchema = z.union([fieldSchema, z.object({
3354
3414
  set: this.nullableIf(z.number().optional(), !!fieldDef.optional).optional(),
3355
3415
  increment: z.number().optional(),
@@ -3590,7 +3650,7 @@ var ZodSchemaFactory = class {
3590
3650
  return canBeArray ? z.union([schema, z.array(schema)]) : schema;
3591
3651
  }
3592
3652
  isNumericField(fieldDef) {
3593
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
3653
+ return NUMERIC_FIELD_TYPES.includes(this.getEffectiveFieldType(fieldDef.type)) && !fieldDef.array;
3594
3654
  }
3595
3655
  get providerSupportsCaseSensitivity() {
3596
3656
  return this.schema.provider.type === "postgresql";
@@ -3710,7 +3770,7 @@ __decorate([
3710
3770
  __decorate([
3711
3771
  cache(),
3712
3772
  __decorateMetadata("design:type", Function),
3713
- __decorateMetadata("design:paramtypes", [String]),
3773
+ __decorateMetadata("design:paramtypes", [String, Array]),
3714
3774
  __decorateMetadata("design:returntype", typeof (_ref2 = typeof ZodType !== "undefined" && ZodType) === "function" ? _ref2 : Object)
3715
3775
  ], ZodSchemaFactory.prototype, "makeTypeDefSchema", null);
3716
3776
  __decorate([
@@ -4316,7 +4376,7 @@ var BaseOperationHandler = class {
4316
4376
  result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4317
4377
  } else {
4318
4378
  if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
4319
- if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, fieldDef.originModel, payload);
4379
+ if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, this.dialect.delegateJoinAlias(model, parentAlias, fieldDef.originModel), payload);
4320
4380
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
4321
4381
  }
4322
4382
  }
@@ -4678,16 +4738,9 @@ var BaseOperationHandler = class {
4678
4738
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4679
4739
  const origWhere = combinedWhere;
4680
4740
  const modelDef = this.requireModel(model);
4681
- let finalData = data;
4682
- const autoUpdatedFields = [];
4683
- for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && finalData[fieldName] === void 0) {
4684
- const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
4685
- if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
4686
- if (finalData === data) finalData = clone(data);
4687
- finalData[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
4688
- autoUpdatedFields.push(fieldName);
4689
- }
4690
- }
4741
+ const filled = this.fillUpdatedAtFields(modelDef, data);
4742
+ let finalData = filled.data;
4743
+ const autoUpdatedFields = filled.autoUpdatedFields;
4691
4744
  let thisEntity;
4692
4745
  const loadThisEntity = async () => {
4693
4746
  if (thisEntity === void 0) {
@@ -4836,7 +4889,8 @@ var BaseOperationHandler = class {
4836
4889
  });
4837
4890
  }
4838
4891
  isNumericField(fieldDef) {
4839
- return NUMERIC_FIELD_TYPES.includes(fieldDef.type) && !fieldDef.array;
4892
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
4893
+ return NUMERIC_FIELD_TYPES.includes(type) && !fieldDef.array;
4840
4894
  }
4841
4895
  makeContextComment(_context) {
4842
4896
  return sql``;
@@ -4849,11 +4903,13 @@ var BaseOperationHandler = class {
4849
4903
  const parentWhere = await this.buildUpdateParentRelationFilter(kysely, fromRelation);
4850
4904
  let combinedWhere = where ?? true;
4851
4905
  if (Object.keys(parentWhere).length > 0) combinedWhere = Object.keys(combinedWhere).length > 0 ? { AND: [parentWhere, combinedWhere] } : parentWhere;
4906
+ const { data: finalData } = this.fillUpdatedAtFields(modelDef, data);
4907
+ if (modelDef.baseModel && filterModel === void 0) return this.updateManyByIds(kysely, model, combinedWhere, finalData, returnData, fieldsToReturn);
4852
4908
  filterModel ??= model;
4853
4909
  let updateFields = {};
4854
- for (const field in data) {
4910
+ for (const field in finalData) {
4855
4911
  if (isRelationField(this.schema, model, field)) continue;
4856
- updateFields[field] = this.processScalarFieldUpdateData(model, field, data);
4912
+ updateFields[field] = this.processScalarFieldUpdateData(model, field, finalData);
4857
4913
  }
4858
4914
  let resultFromBaseModel = void 0;
4859
4915
  if (modelDef.baseModel) {
@@ -4904,6 +4960,50 @@ var BaseOperationHandler = class {
4904
4960
  }
4905
4961
  }
4906
4962
  }
4963
+ /**
4964
+ * Runs `updateMany` on a delegate sub model by id. Reads the ids of the rows that match
4965
+ * `where`, then updates them in batches with an id filter. Callers run this inside a
4966
+ * transaction (`needsNestedUpdate` is true for every model with a base model).
4967
+ */
4968
+ async updateManyByIds(kysely, model, where, data, returnData, fieldsToReturn) {
4969
+ const idFields = requireIdFields(this.schema, model);
4970
+ const rows = await this.read(kysely, model, {
4971
+ where,
4972
+ select: Object.fromEntries(idFields.map((f) => [f, true]))
4973
+ });
4974
+ const batchSize = idFields.length === 1 ? 1e3 : 100;
4975
+ let count = 0;
4976
+ const returned = [];
4977
+ for (let i = 0; i < rows.length; i += batchSize) {
4978
+ const batch = rows.slice(i, i + batchSize);
4979
+ const idWhere = idFields.length === 1 ? { [idFields[0]]: { in: batch.map((row) => row[idFields[0]]) } } : { OR: batch.map((row) => Object.fromEntries(idFields.map((f) => [f, row[f]]))) };
4980
+ const result = await this.updateMany(kysely, model, idWhere, data, void 0, returnData, model, void 0, fieldsToReturn);
4981
+ if (returnData) returned.push(...result);
4982
+ else count += result.count;
4983
+ }
4984
+ return returnData ? returned : { count };
4985
+ }
4986
+ /**
4987
+ * Sets `@updatedAt` fields to the current time when `data` changes a scalar or foreign key
4988
+ * field that is not in the field's `ignore` list. A value given explicitly in `data` is kept.
4989
+ * Returns the original `data` object when nothing is filled in, otherwise a clone.
4990
+ */
4991
+ fillUpdatedAtFields(modelDef, data) {
4992
+ let result = data;
4993
+ const autoUpdatedFields = [];
4994
+ for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.updatedAt && result[fieldName] === void 0) {
4995
+ const ignoredFields = new Set(typeof fieldDef.updatedAt === "boolean" ? [] : fieldDef.updatedAt.ignore);
4996
+ if (Object.keys(data).some((field) => (isScalarField(this.schema, modelDef.name, field) || isForeignKeyField(this.schema, modelDef.name, field)) && !ignoredFields.has(field))) {
4997
+ if (result === data) result = clone(data);
4998
+ result[fieldName] = this.dialect.transformInput(/* @__PURE__ */ new Date(), "DateTime", false, fieldDef);
4999
+ autoUpdatedFields.push(fieldName);
5000
+ }
5001
+ }
5002
+ return {
5003
+ data: result,
5004
+ autoUpdatedFields
5005
+ };
5006
+ }
4907
5007
  async processBaseModelUpdateMany(kysely, model, where, updateFields, filterModel) {
4908
5008
  const thisUpdateFields = {};
4909
5009
  const remainingFields = {};
@@ -4974,7 +5074,7 @@ var BaseOperationHandler = class {
4974
5074
  case "updateMany":
4975
5075
  for (const _item of enumerate(value)) {
4976
5076
  const item = _item;
4977
- await this.updateMany(kysely, fieldModel, item.where, item.data, item.limit, false, fieldModel, fromRelationContext);
5077
+ await this.updateMany(kysely, fieldModel, item.where, item.data, item.limit, false, void 0, fromRelationContext);
4978
5078
  }
4979
5079
  break;
4980
5080
  case "delete":
@@ -5166,17 +5266,12 @@ var BaseOperationHandler = class {
5166
5266
  }
5167
5267
  const cascadeRelations = this.getDelegateCascadeRelations(model, filterModel);
5168
5268
  if (cascadeRelations.length === 0) return this.executeDelete(kysely, model, where, limit, filterModel, fieldsToReturn);
5169
- if (!modelDef.isDelegate) {
5170
- if (limit !== void 0) throw createNotSupportedError("Deleting with a limit is not supported for polymorphic models");
5171
- for (const { fieldDef } of cascadeRelations) await this.delete(kysely, fieldDef.type, { [fieldDef.relation.opposite]: where }, void 0, void 0, void 0, visited);
5172
- return this.executeDelete(kysely, model, where, limit, filterModel, fieldsToReturn);
5173
- }
5174
5269
  const discriminator = getDiscriminatorField(this.schema, model);
5175
5270
  const deletedRows = await this.read(kysely, filterModel, {
5176
5271
  where,
5177
5272
  select: {
5178
5273
  ...this.makeIdSelect(filterModel),
5179
- [discriminator]: true
5274
+ ...discriminator ? { [discriminator]: true } : {}
5180
5275
  },
5181
5276
  ...limit !== void 0 ? { take: limit } : {}
5182
5277
  });
@@ -5455,7 +5550,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5455
5550
  if (typeof value === "string") {
5456
5551
  const fieldDef = getField(this.schema, this.model, field);
5457
5552
  if (fieldDef) {
5458
- const type = fieldDef.type;
5553
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5459
5554
  if (op === "_avg") val = parseFloat(val);
5460
5555
  else if (op === "_sum" || op === "_min" || op === "_max") val = match(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
5461
5556
  }
@@ -5678,7 +5773,7 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5678
5773
  if (typeof value === "string") {
5679
5774
  const fieldDef = getField(this.schema, this.model, field);
5680
5775
  if (fieldDef) {
5681
- const type = fieldDef.type;
5776
+ const type = isPrimitiveTypeDef(this.schema, fieldDef.type) ? this.schema.typeDefs[fieldDef.type].base : fieldDef.type;
5682
5777
  if (op === "_avg") val = parseFloat(val);
5683
5778
  else if (op === "_sum" || op === "_min" || op === "_max") val = match(type).with("Int", () => parseInt(value, 10)).with("BigInt", () => BigInt(value)).with("Float", () => parseFloat(value)).with("Decimal", () => parseFloat(value)).otherwise(() => value);
5684
5779
  }
@@ -6098,7 +6193,7 @@ var QueryNameMapper = class extends OperationNodeTransformer {
6098
6193
  return ColumnNode.create(mappedName);
6099
6194
  }
6100
6195
  transformBinaryOperation(node, queryId) {
6101
- if (ReferenceNode.is(node.leftOperand) && ColumnNode.is(node.leftOperand.column) && (ValueNode.is(node.rightOperand) || PrimitiveValueListNode.is(node.rightOperand))) {
6196
+ if (ReferenceNode.is(node.leftOperand) && ColumnNode.is(node.leftOperand.column) && (ValueNode.is(node.rightOperand) || PrimitiveValueListNode.is(node.rightOperand) || ValueListNode.is(node.rightOperand))) {
6102
6197
  const columnNode = node.leftOperand.column;
6103
6198
  const resolvedScope = this.resolveFieldFromScopes(columnNode.column.name, node.leftOperand.table?.table.identifier.name);
6104
6199
  if (resolvedScope?.model) {
@@ -6106,6 +6201,7 @@ var QueryNameMapper = class extends OperationNodeTransformer {
6106
6201
  let resultValue = valueNode;
6107
6202
  if (ValueNode.is(valueNode)) resultValue = this.processEnumMappingForValue(resolvedScope.model, columnNode, valueNode);
6108
6203
  else if (PrimitiveValueListNode.is(valueNode)) resultValue = PrimitiveValueListNode.create(this.processEnumMappingForValues(resolvedScope.model, valueNode.values.map(() => columnNode), valueNode.values));
6204
+ else if (ValueListNode.is(valueNode)) resultValue = ValueListNode.create(valueNode.values.map((v) => ValueNode.is(v) ? this.processEnumMappingForValue(resolvedScope.model, columnNode, v) : v));
6109
6205
  return super.transformBinaryOperation({
6110
6206
  ...node,
6111
6207
  rightOperand: resultValue
@@ -6506,7 +6602,11 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6506
6602
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation);
6507
6603
  }
6508
6604
  get hasEntityMutationPluginsWithAfterMutationHooks() {
6509
- return (this.client.$options.plugins ?? []).some((plugin) => plugin.onEntityMutation?.afterEntityMutation);
6605
+ return (this.client.$options.plugins ?? []).some((plugin) => {
6606
+ if (!plugin.onEntityMutation) return false;
6607
+ if (plugin.onEntityMutation["$all"]?.afterEntityMutation) return true;
6608
+ return Object.keys(this.client.$schema.models).some((model) => plugin.onEntityMutation?.[model]?.afterEntityMutation);
6609
+ });
6510
6610
  }
6511
6611
  get hasOnKyselyHooks() {
6512
6612
  return (this.client.$options.plugins ?? []).some((plugin) => plugin.onKyselyQuery);
@@ -6611,8 +6711,17 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6611
6711
  const { queryNode, mutationInfo, loadBeforeMutationEntities, client, queryId } = args;
6612
6712
  if (this.options.plugins) for (const plugin of this.options.plugins) {
6613
6713
  const onEntityMutation = plugin.onEntityMutation;
6614
- if (!onEntityMutation?.beforeEntityMutation) continue;
6615
- await onEntityMutation.beforeEntityMutation({
6714
+ if (!onEntityMutation) continue;
6715
+ if (onEntityMutation["$all"]?.beforeEntityMutation) await onEntityMutation["$all"].beforeEntityMutation({
6716
+ model: mutationInfo.model,
6717
+ action: mutationInfo.action,
6718
+ queryNode,
6719
+ loadBeforeMutationEntities,
6720
+ client,
6721
+ queryId
6722
+ });
6723
+ const modelHooks = onEntityMutation[mutationInfo.model];
6724
+ if (modelHooks?.beforeEntityMutation) await modelHooks.beforeEntityMutation({
6616
6725
  model: mutationInfo.model,
6617
6726
  action: mutationInfo.action,
6618
6727
  queryNode,
@@ -6627,10 +6736,16 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6627
6736
  const hooks = [];
6628
6737
  for (const plugin of this.options.plugins ?? []) {
6629
6738
  const onEntityMutation = plugin.onEntityMutation;
6630
- if (!onEntityMutation?.afterEntityMutation) continue;
6631
- if (filterFor === "inTx" && !onEntityMutation.runAfterMutationWithinTransaction) continue;
6632
- if (filterFor === "outTx" && onEntityMutation.runAfterMutationWithinTransaction) continue;
6633
- hooks.push(onEntityMutation.afterEntityMutation.bind(plugin));
6739
+ if (!onEntityMutation) continue;
6740
+ if (onEntityMutation["$all"]?.afterEntityMutation) {
6741
+ const runInTx = onEntityMutation["$all"].runAfterMutationWithinTransaction ?? false;
6742
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(onEntityMutation["$all"].afterEntityMutation.bind(plugin));
6743
+ }
6744
+ const modelHooks = onEntityMutation[mutationInfo.model];
6745
+ if (modelHooks?.afterEntityMutation) {
6746
+ const runInTx = modelHooks.runAfterMutationWithinTransaction ?? false;
6747
+ if (filterFor === "all" || filterFor === "inTx" && runInTx || filterFor === "outTx" && !runInTx) hooks.push(modelHooks.afterEntityMutation.bind(plugin));
6748
+ }
6634
6749
  }
6635
6750
  if (hooks.length === 0) return;
6636
6751
  for (const hook of hooks) await hook({
@@ -6645,7 +6760,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6645
6760
  }
6646
6761
  async loadAfterMutationEntities(mutationInfo, queryNode, queryResult, connection, preUpdateIds) {
6647
6762
  if (mutationInfo.action === "delete") return;
6648
- if (this.dialect.supportsReturning) return queryResult.rows;
6763
+ if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
6649
6764
  else {
6650
6765
  const mutatedIds = InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
6651
6766
  if (mutatedIds) {
@@ -7105,8 +7220,12 @@ var SchemaDbPusher = class {
7105
7220
  return sql.raw(`enum(${enumValues.map((v) => `'${v}'`).join(", ")})`);
7106
7221
  } else return "text";
7107
7222
  if (this.isAutoIncrement(fieldDef) && this.schema.provider.type === "postgresql") return "serial";
7108
- if (this.isCustomType(fieldDef.type)) return this.jsonType;
7109
- const type = fieldDef.type;
7223
+ let type = fieldDef.type;
7224
+ if (this.isCustomType(type)) {
7225
+ const typeDef = Object.values(this.schema.typeDefs).find((def) => def.name === type);
7226
+ if (typeDef.base) type = typeDef.base;
7227
+ else return this.jsonType;
7228
+ }
7110
7229
  const result = match(type).with("String", () => this.stringType).with("Boolean", () => this.booleanType).with("Int", () => this.intType).with("Float", () => this.floatType).with("BigInt", () => this.bigIntType).with("Decimal", () => this.decimalType).with("DateTime", () => this.dateTimeType).with("Bytes", () => this.bytesType).with("Json", () => this.jsonType).otherwise(() => {
7111
7230
  throw new Error(`Unsupported field type: ${type}`);
7112
7231
  });
@@ -7298,6 +7417,7 @@ var ResultProcessor = class {
7298
7417
  };
7299
7418
  //#endregion
7300
7419
  //#region src/client/client-impl.ts
7420
+ const warnedPlugins = /* @__PURE__ */ new WeakSet();
7301
7421
  /**
7302
7422
  * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7303
7423
  */
@@ -7328,6 +7448,7 @@ var ClientImpl = class ClientImpl {
7328
7448
  ...functions_exports,
7329
7449
  ...this.$options.functions
7330
7450
  };
7451
+ if (this.$options.plugins) this.$options.plugins = this.normalizePlugins(this.$options.plugins);
7331
7452
  this.validateOptions(baseClient, options);
7332
7453
  if (baseClient) {
7333
7454
  this.kyselyProps = {
@@ -7361,6 +7482,63 @@ var ClientImpl = class ClientImpl {
7361
7482
  this.inputValidator = baseClient?.inputValidator ?? new InputValidator(this, { enabled: this.$options.validateInput !== false });
7362
7483
  return createClientProxy(this);
7363
7484
  }
7485
+ /**
7486
+ * Normalizes plugin definitions for backward compatibility and validates
7487
+ * `onEntityMutation` keys. Legacy plugins that define hooks directly under
7488
+ * `onEntityMutation` (instead of under `$all`) are converted to the new shape
7489
+ * with a one-time warning.
7490
+ */
7491
+ normalizePlugins(plugins) {
7492
+ let changed = false;
7493
+ const result = plugins.map((plugin) => {
7494
+ const normalized = this.normalizeEntityMutationHooks(plugin);
7495
+ if (normalized !== plugin) changed = true;
7496
+ return normalized;
7497
+ });
7498
+ return changed ? result : plugins;
7499
+ }
7500
+ normalizeEntityMutationHooks(plugin) {
7501
+ const hooks = plugin.onEntityMutation;
7502
+ if (!hooks || typeof hooks !== "object") return plugin;
7503
+ const legacyKeys = [
7504
+ "beforeEntityMutation",
7505
+ "afterEntityMutation",
7506
+ "runAfterMutationWithinTransaction"
7507
+ ];
7508
+ const presentLegacyKeys = legacyKeys.filter((key) => key in hooks);
7509
+ const unknownKeys = Object.keys(hooks).filter((key) => key !== "$all" && !legacyKeys.includes(key) && !(key in this.$schema.models));
7510
+ const warnOnce = (message) => {
7511
+ if (!warnedPlugins.has(hooks)) console.warn(message);
7512
+ };
7513
+ if (unknownKeys.length > 0) warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks for unknown keys: ${unknownKeys.map((k) => `"${k}"`).join(", ")}. Valid keys are "$all" and model names. These hooks will never be invoked.`);
7514
+ if (presentLegacyKeys.length === 0) {
7515
+ warnedPlugins.add(hooks);
7516
+ return plugin;
7517
+ }
7518
+ warnOnce(`Plugin "${plugin.id}" defines "onEntityMutation" hooks in a deprecated shape. Hooks that apply to all models should be nested under "$all": { onEntityMutation: { $all: { beforeEntityMutation, afterEntityMutation, runAfterMutationWithinTransaction } } }. The legacy shape is still supported but will be removed in a future release.`);
7519
+ warnedPlugins.add(hooks);
7520
+ const legacy = {};
7521
+ const rest = {};
7522
+ for (const [key, value] of Object.entries(hooks)) if (legacyKeys.includes(key)) legacy[key] = value;
7523
+ else rest[key] = value;
7524
+ for (const key of ["beforeEntityMutation", "afterEntityMutation"]) if (typeof legacy[key] === "function") legacy[key] = legacy[key].bind(plugin);
7525
+ const normalizedHooks = {
7526
+ ...rest,
7527
+ $all: {
7528
+ ...legacy,
7529
+ ...rest["$all"]
7530
+ }
7531
+ };
7532
+ warnedPlugins.add(normalizedHooks);
7533
+ const copy = Object.create(Object.getPrototypeOf(plugin), Object.getOwnPropertyDescriptors(plugin));
7534
+ Object.defineProperty(copy, "onEntityMutation", {
7535
+ value: normalizedHooks,
7536
+ enumerable: true,
7537
+ configurable: true,
7538
+ writable: true
7539
+ });
7540
+ return copy;
7541
+ }
7364
7542
  validateOptions(baseClient, options) {
7365
7543
  if (!baseClient && !options.skipValidationForComputedFields) this.validateComputedFieldsConfig(options);
7366
7544
  if (options.diagnostics) {