@zenstackhq/orm 3.9.0-beta.1 → 3.9.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.cjs CHANGED
@@ -61,26 +61,6 @@ function formatError(error) {
61
61
  return (0, zod_validation_error_v4.fromError)(error).toString();
62
62
  }
63
63
  //#endregion
64
- //#region src/utils/object-utils.ts
65
- /**
66
- * Extract fields from an object.
67
- */
68
- function extractFields(obj, fields) {
69
- return Object.fromEntries(Object.entries(obj).filter(([key]) => fields.includes(key)));
70
- }
71
- /**
72
- * Create an object with fields as keys and true values.
73
- */
74
- function fieldsToSelectObject(fields) {
75
- return Object.fromEntries(fields.map((f) => [f, true]));
76
- }
77
- /**
78
- * Checks if the given value is an empty plain object.
79
- */
80
- function isEmptyObject(x) {
81
- return (0, _zenstackhq_common_helpers.isPlainObject)(x) && Object.keys(x).length === 0;
82
- }
83
- //#endregion
84
64
  //#region src/client/executor/error-processor.ts
85
65
  /**
86
66
  * Extracts database error code from an error thrown by the database driver.
@@ -214,6 +194,26 @@ function createInternalError(message, model, options) {
214
194
  return error;
215
195
  }
216
196
  //#endregion
197
+ //#region src/utils/object-utils.ts
198
+ /**
199
+ * Extract fields from an object.
200
+ */
201
+ function extractFields(obj, fields) {
202
+ return Object.fromEntries(Object.entries(obj).filter(([key]) => fields.includes(key)));
203
+ }
204
+ /**
205
+ * Create an object with fields as keys and true values.
206
+ */
207
+ function fieldsToSelectObject(fields) {
208
+ return Object.fromEntries(fields.map((f) => [f, true]));
209
+ }
210
+ /**
211
+ * Checks if the given value is an empty plain object.
212
+ */
213
+ function isEmptyObject(x) {
214
+ return (0, _zenstackhq_common_helpers.isPlainObject)(x) && Object.keys(x).length === 0;
215
+ }
216
+ //#endregion
217
217
  //#region src/client/query-utils.ts
218
218
  var query_utils_exports = /* @__PURE__ */ __exportAll({
219
219
  TEMP_ALIAS_PREFIX: () => "$$_",
@@ -252,6 +252,7 @@ var query_utils_exports = /* @__PURE__ */ __exportAll({
252
252
  requireIdFields: () => requireIdFields,
253
253
  requireModel: () => requireModel,
254
254
  requireTypeDef: () => requireTypeDef,
255
+ schemaHasMappedNames: () => schemaHasMappedNames,
255
256
  stripAlias: () => stripAlias,
256
257
  tmpAlias: () => tmpAlias
257
258
  });
@@ -281,6 +282,22 @@ function getModel(schema, model) {
281
282
  function getTypeDef(schema, type) {
282
283
  return schema.typeDefs?.[type];
283
284
  }
285
+ /**
286
+ * Whether any model, type def, or field in the schema carries `@@map`/`@map`. Answering it walks
287
+ * every model and field, and it is asked once per query-executor construction, so the (immutable)
288
+ * answer is memoized per schema alongside the other structural lookups. See issue #2773.
289
+ */
290
+ function schemaHasMappedNames(schema) {
291
+ const cache = getSchemaLookupCache(schema);
292
+ if (cache.hasMappedNames === void 0) {
293
+ const hasMapAttr = (decl) => {
294
+ if (decl.attributes?.some((attr) => attr.name === "@@map")) return true;
295
+ return Object.values(decl.fields ?? {}).some((field) => field.attributes?.some((attr) => attr.name === "@map"));
296
+ };
297
+ cache.hasMappedNames = Object.values(schema.models).some(hasMapAttr) || Object.values(schema.typeDefs ?? {}).some(hasMapAttr) || Object.values(schema.enums ?? {}).some(hasMapAttr);
298
+ }
299
+ return cache.hasMappedNames;
300
+ }
284
301
  function requireModel(schema, model) {
285
302
  const modelDef = getModel(schema, model);
286
303
  if (!modelDef) throw createInternalError(`Model "${model}" not found in schema`, model);
@@ -672,9 +689,23 @@ const CRUD_EXT = [...CRUD, "post-update"];
672
689
  //#region src/client/crud/dialects/base-dialect.ts
673
690
  var BaseCrudDialect = class {
674
691
  eb = (0, kysely.expressionBuilder)();
675
- constructor(schema, options) {
676
- this.schema = schema;
677
- this.options = options;
692
+ schema;
693
+ options;
694
+ /**
695
+ * The client executing the query. Unset only when the dialect was constructed from a
696
+ * standalone schema/options pair, in which case it cannot evaluate computed fields.
697
+ */
698
+ client;
699
+ constructor(...args) {
700
+ if (args.length === 1) {
701
+ const [client] = args;
702
+ this.client = client;
703
+ this.schema = client.$schema;
704
+ this.options = client.$options;
705
+ } else {
706
+ [this.schema, this.options] = args;
707
+ this.client = void 0;
708
+ }
678
709
  }
679
710
  /**
680
711
  * Transforms input value before sending to database.
@@ -733,6 +764,8 @@ var BaseCrudDialect = class {
733
764
  if (typeof ob !== "object" || ob === null) return void 0;
734
765
  if ("_fuzzyRelevance" in ob) return "_fuzzyRelevance";
735
766
  if ("_ftsRelevance" in ob) return "_ftsRelevance";
767
+ const argsEntry = Object.entries(ob).find(([, v]) => v !== null && typeof v === "object" && "args" in v);
768
+ if (argsEntry) return argsEntry[0];
736
769
  }).find((k) => k !== void 0);
737
770
  if (offendingKey) throw createNotSupportedError(`cursor pagination cannot be combined with "${offendingKey}" ordering`);
738
771
  }
@@ -755,9 +788,16 @@ var BaseCrudDialect = class {
755
788
  const fieldDef = requireField(this.schema, model, key);
756
789
  if (fieldDef.relation) result = this.and(result, this.buildRelationFilter(model, modelAlias, key, fieldDef, payload));
757
790
  else {
758
- const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias);
759
- if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, payload));
760
- else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, payload));
791
+ let computedArgs;
792
+ let filterPayload = payload;
793
+ if (fieldDef.computed && fieldDef.params && payload && typeof payload === "object" && "args" in payload) {
794
+ computedArgs = payload.args;
795
+ const { args: _args, ...rest } = payload;
796
+ filterPayload = rest;
797
+ }
798
+ const fieldRef = this.fieldRef(fieldDef.originModel ?? model, key, fieldDef.originModel ?? modelAlias, true, computedArgs);
799
+ if (fieldDef.array) result = this.and(result, this.buildArrayFilter(fieldRef, fieldDef, filterPayload));
800
+ else result = this.and(result, this.buildPrimitiveFilter(fieldRef, fieldDef, filterPayload));
761
801
  }
762
802
  }
763
803
  if ("$expr" in _where && typeof _where["$expr"] === "function") result = this.and(result, _where["$expr"](this.eb));
@@ -815,7 +855,7 @@ var BaseCrudDialect = class {
815
855
  }
816
856
  const joinAlias = tmpAlias(`${modelAlias}$${field}`);
817
857
  const joinPairs = buildJoinPairs(this.schema, model, fieldDef.originModel ?? modelAlias, field, joinAlias);
818
- const baseJoin = this.eb.selectFrom(`${fieldDef.type} as ${joinAlias}`).select(this.eb.lit(1).as("_")).where(() => this.and(...joinPairs.map(([left, right]) => this.eb(this.eb.ref(left), "=", this.eb.ref(right)))));
858
+ 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)))));
819
859
  const existsSelect = (extraFilter) => {
820
860
  const q = extraFilter ? baseJoin.where(extraFilter) : baseJoin;
821
861
  return this.buildExistsExpression(q);
@@ -1016,7 +1056,7 @@ var BaseCrudDialect = class {
1016
1056
  else if (fieldDef.array) clauses.push(this.buildArrayFilter(fieldReceiver, fieldDef, value));
1017
1057
  else {
1018
1058
  let _receiver = fieldReceiver;
1019
- if (fieldDef.type === "String") _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
1059
+ if (fieldDef.type === "String" || isEnum(this.schema, fieldDef.type)) _receiver = this.trimTextQuotes(this.castText(fieldReceiver));
1020
1060
  clauses.push(this.buildPrimitiveFilter(_receiver, fieldDef, value));
1021
1061
  }
1022
1062
  }
@@ -1158,9 +1198,9 @@ var BaseCrudDialect = class {
1158
1198
  buildOrderBy(query, model, modelAlias, orderBy, negated, take) {
1159
1199
  if (!orderBy) return query;
1160
1200
  let result = query;
1161
- const buildFieldRef = (model, field, modelAlias) => {
1201
+ const buildFieldRef = (model, field, modelAlias, computedArgs) => {
1162
1202
  const fieldDef = requireField(this.schema, model, field);
1163
- return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel) : this.fieldRef(model, field, modelAlias);
1203
+ return fieldDef.originModel ? this.fieldRef(fieldDef.originModel, field, fieldDef.originModel, true, computedArgs) : this.fieldRef(model, field, modelAlias, true, computedArgs);
1164
1204
  };
1165
1205
  (0, _zenstackhq_common_helpers.enumerate)(orderBy).forEach((orderBy, index) => {
1166
1206
  for (const [field, value] of Object.entries(orderBy)) {
@@ -1216,7 +1256,7 @@ var BaseCrudDialect = class {
1216
1256
  return this.buildOrderBy(joined, relationModel, joinAlias, value, negated, take);
1217
1257
  }
1218
1258
  applyScalarOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
1219
- const fieldRef = buildFieldRef(model, field, modelAlias);
1259
+ const fieldRef = buildFieldRef(model, field, modelAlias, value && typeof value === "object" && "args" in value ? value.args : void 0);
1220
1260
  if (value === "asc" || value === "desc") return query.orderBy(fieldRef, this.negateSort(value, negated));
1221
1261
  if (typeof value === "object" && "sort" in value && (value.sort === "asc" || value.sort === "desc")) {
1222
1262
  const sort = this.negateSort(value.sort, negated);
@@ -1226,11 +1266,15 @@ var BaseCrudDialect = class {
1226
1266
  return query;
1227
1267
  }
1228
1268
  applyAggregationOrderBy(query, model, modelAlias, field, value, negated, buildFieldRef) {
1229
- (0, _zenstackhq_common_helpers.invariant)(typeof value === "object", `invalid orderBy value for field "${field}"`);
1269
+ if (!(0, _zenstackhq_common_helpers.isPlainObject)(value)) throw createInvalidInputError(`invalid orderBy value for field "${field}"`);
1230
1270
  let result = query;
1231
1271
  for (const [k, v] of Object.entries(value)) {
1232
- (0, _zenstackhq_common_helpers.invariant)(v === "asc" || v === "desc", `invalid orderBy value for field "${field}"`);
1233
- result = result.orderBy((eb) => aggregate(eb, buildFieldRef(model, k, modelAlias), field), this.negateSort(v, negated));
1272
+ const sort = (0, _zenstackhq_common_helpers.isPlainObject)(v) ? v["sort"] : v;
1273
+ if (sort !== "asc" && sort !== "desc") throw createInvalidInputError(`invalid orderBy value for field "${field}"`);
1274
+ const computedArgs = (0, _zenstackhq_common_helpers.isPlainObject)(v) && "args" in v ? v["args"] : void 0;
1275
+ const aggExpr = aggregate(this.eb, buildFieldRef(model, k, modelAlias, computedArgs), field);
1276
+ const nulls = (0, _zenstackhq_common_helpers.isPlainObject)(v) ? v["nulls"] : void 0;
1277
+ result = nulls === "first" || nulls === "last" ? this.buildOrderByField(result, aggExpr, this.negateSort(sort, negated), nulls) : result.orderBy(aggExpr, this.negateSort(sort, negated));
1234
1278
  }
1235
1279
  return result;
1236
1280
  }
@@ -1265,6 +1309,7 @@ var BaseCrudDialect = class {
1265
1309
  computed: true
1266
1310
  })) {
1267
1311
  if (this.shouldOmitField(omit, model, fieldDef.name)) continue;
1312
+ if (fieldDef.computed && fieldDef.params) continue;
1268
1313
  result = this.buildSelectField(result, model, modelAlias, fieldDef.name);
1269
1314
  }
1270
1315
  const descendants = getDelegateDescendantModels(this.schema, model);
@@ -1274,6 +1319,7 @@ var BaseCrudDialect = class {
1274
1319
  const jsonObject = {};
1275
1320
  for (const fieldDef of getModelFields(this.schema, subModel.name, { computed: true })) {
1276
1321
  if (this.shouldOmitField(omit, subModel.name, fieldDef.name)) continue;
1322
+ if (fieldDef.computed && fieldDef.params) continue;
1277
1323
  jsonObject[fieldDef.name] = this.fieldRef(subModel.name, fieldDef.name, subModel.name);
1278
1324
  }
1279
1325
  return this.buildJsonObject(jsonObject).as(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`);
@@ -1294,11 +1340,11 @@ var BaseCrudDialect = class {
1294
1340
  if (payload && typeof payload === "object") subQuery = this.buildFilterSortTake(model, payload, subQuery, subQueryAlias);
1295
1341
  return subQuery;
1296
1342
  }
1297
- buildSelectField(query, model, modelAlias, field) {
1343
+ buildSelectField(query, model, modelAlias, field, computedArgs) {
1298
1344
  const fieldDef = requireField(this.schema, model, field);
1299
1345
  const fieldModel = fieldDef.originModel ?? model;
1300
1346
  const alias = fieldDef.originModel ?? modelAlias;
1301
- return query.select(() => this.fieldRef(fieldModel, field, alias).as(field));
1347
+ return query.select(() => this.fieldRef(fieldModel, field, alias, true, computedArgs).as(field));
1302
1348
  }
1303
1349
  buildDelegateJoin(thisModel, thisModelAlias, otherModelAlias, query) {
1304
1350
  const idFields = requireIdFields(this.schema, thisModel);
@@ -1365,7 +1411,7 @@ var BaseCrudDialect = class {
1365
1411
  not(...args) {
1366
1412
  return this.eb.not(this.and(...args));
1367
1413
  }
1368
- fieldRef(model, field, modelAlias, inlineComputedField = true) {
1414
+ fieldRef(model, field, modelAlias, inlineComputedField = true, computedArgs) {
1369
1415
  const fieldDef = requireField(this.schema, model, field);
1370
1416
  if (!fieldDef.computed) return this.eb.ref(modelAlias ? `${modelAlias}.${field}` : field);
1371
1417
  else {
@@ -1377,7 +1423,11 @@ var BaseCrudDialect = class {
1377
1423
  computer = computedFields?.[(0, _zenstackhq_common_helpers.lowerCaseFirst)(computedModel)]?.[field] ?? computedFields?.[computedModel]?.[field];
1378
1424
  }
1379
1425
  if (!computer) throw createConfigError(`Computed field "${field}" implementation not provided for model "${model}"`);
1380
- return computer(this.eb, { modelAlias });
1426
+ (0, _zenstackhq_common_helpers.invariant)(this.client, `computed field "${field}" of model "${model}" needs a client to be evaluated`);
1427
+ return this.eb.parens(computer(this.eb, {
1428
+ modelAlias,
1429
+ client: this.client
1430
+ }, computedArgs));
1381
1431
  }
1382
1432
  }
1383
1433
  canJoinWithoutNestedSelect(modelDef, payload) {
@@ -1513,18 +1563,21 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1513
1563
  if (descendantModels.length > 0) Object.assign(objArgs, ...descendantModels.map((subModel) => ({ [`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`]: eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`) })));
1514
1564
  if (payload === true || !payload.select) {
1515
1565
  const omit = typeof payload === "object" ? payload.omit : void 0;
1516
- Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
1566
+ Object.assign(objArgs, ...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => ({ [field]: this.fieldRef(relationModel, field, relationModelAlias, false) })));
1517
1567
  } else if (payload.select) Object.assign(objArgs, ...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
1518
1568
  if (field === "_count") {
1519
1569
  const subJson = this.buildCountJson(relationModel, eb, relationModelAlias, value);
1520
1570
  return { [field]: subJson };
1521
1571
  } else {
1522
- const fieldValue = requireField(this.schema, relationModel, field).relation ? eb.ref(`${parentResultName}$${field}.$data`) : this.fieldRef(relationModel, field, relationModelAlias, false);
1572
+ const fieldDef = requireField(this.schema, relationModel, field);
1573
+ const fieldValue = fieldDef.relation ? eb.ref(`${parentResultName}$${field}.$data`) : fieldDef.computed && fieldDef.params ? this.fieldRef(relationModel, field, relationModelAlias, true, value.args) : this.fieldRef(relationModel, field, relationModelAlias, false);
1523
1574
  return { [field]: fieldValue };
1524
1575
  }
1525
1576
  }));
1526
1577
  if (typeof payload === "object" && payload.include && typeof payload.include === "object") Object.assign(objArgs, ...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
1527
1578
  if (field === "_count") return { [field]: this.buildCountJson(relationModel, eb, relationModelAlias, value) };
1579
+ const fieldDef = requireField(this.schema, relationModel, field);
1580
+ if (fieldDef.computed && fieldDef.params) return { [field]: this.fieldRef(relationModel, field, relationModelAlias, true, value.args) };
1528
1581
  return { [field]: eb.ref(`${parentResultName}$${field}.$data`) };
1529
1582
  }));
1530
1583
  return objArgs;
@@ -1543,9 +1596,6 @@ var LateralJoinDialectBase = class extends BaseCrudDialect {
1543
1596
  //#endregion
1544
1597
  //#region src/client/crud/dialects/mysql.ts
1545
1598
  var MySqlCrudDialect = class extends LateralJoinDialectBase {
1546
- constructor(schema, options) {
1547
- super(schema, options);
1548
- }
1549
1599
  get provider() {
1550
1600
  return "mysql";
1551
1601
  }
@@ -1773,8 +1823,8 @@ var PostgresCrudDialect = class PostgresCrudDialect extends LateralJoinDialectBa
1773
1823
  "@db.Decimal": "decimal",
1774
1824
  "@db.Boolean": "boolean"
1775
1825
  };
1776
- constructor(schema, options) {
1777
- super(schema, options);
1826
+ constructor(...args) {
1827
+ super(...args);
1778
1828
  this.overrideTypeParsers();
1779
1829
  }
1780
1830
  get provider() {
@@ -2190,21 +2240,27 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2190
2240
  if (descendantModels.length > 0) objArgs.push(...descendantModels.map((subModel) => [kysely.sql.lit(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`), eb.ref(`${DELEGATE_JOINED_FIELD_PREFIX}${subModel.name}`)]).flatMap((v) => v));
2191
2241
  if (payload === true || !payload.select) {
2192
2242
  const omit = typeof payload === "object" ? payload.omit : void 0;
2193
- objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
2243
+ objArgs.push(...Object.entries(relationModelDef.fields).filter(([, value]) => !value.relation).filter(([, value]) => !(value.computed && value.params)).filter(([name]) => !this.shouldOmitField(omit, relationModel, name)).map(([field]) => [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)]).flatMap((v) => v));
2194
2244
  } else if (payload.select) objArgs.push(...Object.entries(payload.select).filter(([, value]) => value).map(([field, value]) => {
2195
2245
  if (field === "_count") {
2196
2246
  const subJson = this.buildCountJson(relationModel, eb, tmpAlias(`${parentAlias}$${relationField}`), value);
2197
2247
  return [kysely.sql.lit(field), subJson];
2198
- } else if (requireField(this.schema, relationModel, field).relation) {
2199
- const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2200
- return [kysely.sql.lit(field), subJson];
2201
- } else return [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)];
2248
+ } else {
2249
+ const fieldDef = requireField(this.schema, relationModel, field);
2250
+ if (fieldDef.relation) {
2251
+ const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2252
+ return [kysely.sql.lit(field), subJson];
2253
+ } else if (fieldDef.computed && fieldDef.params) return [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, true, value.args)];
2254
+ else return [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, false)];
2255
+ }
2202
2256
  }).flatMap((v) => v));
2203
2257
  if (typeof payload === "object" && payload.include && typeof payload.include === "object") objArgs.push(...Object.entries(payload.include).filter(([, value]) => value).map(([field, value]) => {
2204
2258
  if (field === "_count") {
2205
2259
  const subJson = this.buildCountJson(relationModel, eb, tmpAlias(`${parentAlias}$${relationField}`), value);
2206
2260
  return [kysely.sql.lit(field), subJson];
2207
2261
  }
2262
+ const fieldDef = requireField(this.schema, relationModel, field);
2263
+ if (fieldDef.computed && fieldDef.params) return [kysely.sql.lit(field), this.fieldRef(relationModel, field, subQueryName, true, value.args)];
2208
2264
  const subJson = this.buildRelationJSON(relationModel, eb, field, tmpAlias(`${parentAlias}$${relationField}`), value);
2209
2265
  return [kysely.sql.lit(field), subJson];
2210
2266
  }).flatMap((v) => v));
@@ -2317,8 +2373,8 @@ var SqliteCrudDialect = class extends BaseCrudDialect {
2317
2373
  };
2318
2374
  //#endregion
2319
2375
  //#region src/client/crud/dialects/index.ts
2320
- function getCrudDialect(schema, options) {
2321
- return (0, ts_pattern.match)(schema.provider.type).with("sqlite", () => new SqliteCrudDialect(schema, options)).with("postgresql", () => new PostgresCrudDialect(schema, options)).with("mysql", () => new MySqlCrudDialect(schema, options)).exhaustive();
2376
+ function getCrudDialect(...args) {
2377
+ return (0, ts_pattern.match)((args.length === 1 ? args[0].$schema : args[0]).provider.type).with("sqlite", () => new SqliteCrudDialect(...args)).with("postgresql", () => new PostgresCrudDialect(...args)).with("mysql", () => new MySqlCrudDialect(...args)).exhaustive();
2322
2378
  }
2323
2379
  //#endregion
2324
2380
  //#region src/client/zod/cache-decorator.ts
@@ -2553,6 +2609,25 @@ var ZodSchemaFactory = class {
2553
2609
  ]);
2554
2610
  }).with("DateTime", () => this.makeDateTimeValueSchema()).with("Bytes", () => zod.z.instanceof(Uint8Array)).with("Json", () => this.makeJsonValueSchema()).otherwise(() => zod.z.unknown());
2555
2611
  }
2612
+ isParameterizedComputedField(fieldDef) {
2613
+ return !!(fieldDef.computed && fieldDef.params);
2614
+ }
2615
+ makeFieldArgsSchema(params) {
2616
+ return zod.z.strictObject(Object.fromEntries(Object.entries(params).map(([name, param]) => {
2617
+ let paramSchema = this.makeScalarSchema(param.type);
2618
+ if (param.array) paramSchema = paramSchema.array();
2619
+ if (param.optional) paramSchema = paramSchema.optional();
2620
+ return [name, paramSchema];
2621
+ })));
2622
+ }
2623
+ addComputedArgsToFilter(filterSchema, params) {
2624
+ const objectMembers = (filterSchema instanceof zod.z.ZodUnion ? filterSchema.options : [filterSchema]).filter((m) => m instanceof zod.z.ZodObject);
2625
+ const components = Object.assign({}, ...objectMembers.map((o) => o.shape));
2626
+ return zod.z.strictObject({
2627
+ args: this.makeFieldArgsSchema(params),
2628
+ ...components
2629
+ });
2630
+ }
2556
2631
  makeEnumSchema(_enum) {
2557
2632
  const enumDef = getEnum(this.schema, _enum);
2558
2633
  (0, _zenstackhq_common_helpers.invariant)(enumDef, `Enum "${_enum}" not found in schema`);
@@ -2610,6 +2685,7 @@ var ZodSchemaFactory = class {
2610
2685
  else if (this.isTypeDefType(fieldDef.type)) fieldSchema = this.makeTypedJsonFilterSchema(fieldDef.type, !!fieldDef.optional, !!fieldDef.array, allowedFilterKinds);
2611
2686
  else fieldSchema = this.makePrimitiveFilterSchema(fieldDef.type, !!fieldDef.optional, withAggregations, allowedFilterKinds, !!fieldDef.fuzzy, !!fieldDef.fullText);
2612
2687
  }
2688
+ if (fieldSchema && this.isParameterizedComputedField(fieldDef)) fieldSchema = this.addComputedArgsToFilter(fieldSchema, fieldDef.params);
2613
2689
  if (fieldSchema) fields[field] = fieldSchema.optional();
2614
2690
  }
2615
2691
  if (unique) {
@@ -2927,11 +3003,17 @@ var ZodSchemaFactory = class {
2927
3003
  }
2928
3004
  makeSelectSchema(model, options) {
2929
3005
  const fields = {};
2930
- for (const [field, fieldDef] of this.getModelFields(model)) if (fieldDef.relation) {
2931
- if (!this.shouldIncludeRelations(options)) continue;
2932
- if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
2933
- } else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = zod.z.literal(false).optional();
2934
- else fields[field] = zod.z.boolean().optional();
3006
+ for (const [field, fieldDef] of this.getModelFields(model)) {
3007
+ if (this.isParameterizedComputedField(fieldDef)) {
3008
+ fields[field] = zod.z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
3009
+ continue;
3010
+ }
3011
+ if (fieldDef.relation) {
3012
+ if (!this.shouldIncludeRelations(options)) continue;
3013
+ if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
3014
+ } else if (this.options.allowQueryTimeOmitOverride === false && this.isFieldOmittedByConfig(model, field)) fields[field] = zod.z.literal(false).optional();
3015
+ else fields[field] = zod.z.boolean().optional();
3016
+ }
2935
3017
  if (this.shouldIncludeRelations(options)) {
2936
3018
  const _countSchema = this.makeCountSelectionSchema(model, options);
2937
3019
  if (!(_countSchema instanceof zod.z.ZodNever)) fields["_count"] = _countSchema;
@@ -2988,8 +3070,11 @@ var ZodSchemaFactory = class {
2988
3070
  }
2989
3071
  makeOmitSchema(model) {
2990
3072
  const fields = {};
2991
- for (const [field, fieldDef] of this.getModelFields(model)) if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = zod.z.boolean().optional();
2992
- else fields[field] = zod.z.literal(true).optional();
3073
+ for (const [field, fieldDef] of this.getModelFields(model)) {
3074
+ if (this.isParameterizedComputedField(fieldDef)) continue;
3075
+ if (!fieldDef.relation) if (this.options.allowQueryTimeOmitOverride !== false) fields[field] = zod.z.boolean().optional();
3076
+ else fields[field] = zod.z.literal(true).optional();
3077
+ }
2993
3078
  this.addExtResultFields(model, fields);
2994
3079
  const result = zod.z.strictObject(fields);
2995
3080
  this.registerSchema(`${model}OmitInput`, result);
@@ -3012,7 +3097,7 @@ var ZodSchemaFactory = class {
3012
3097
  if (fieldDef.relation) {
3013
3098
  if (!this.shouldIncludeRelations(options)) continue;
3014
3099
  if (this.isModelAllowed(fieldDef.type)) fields[field] = this.makeRelationSelectIncludeSchema(model, field, options).optional();
3015
- }
3100
+ } else if (this.isParameterizedComputedField(fieldDef)) fields[field] = zod.z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional();
3016
3101
  }
3017
3102
  if (this.shouldIncludeRelations(options)) {
3018
3103
  const _countSchema = this.makeCountSelectionSchema(model, options);
@@ -3033,7 +3118,12 @@ var ZodSchemaFactory = class {
3033
3118
  if (fieldDef.array) relationOrderBy = refineAtMostOneKey(relationOrderBy.safeExtend({ _count: sort }));
3034
3119
  return relationOrderBy;
3035
3120
  }).optional();
3036
- } else if (fieldDef.optional) fields[field] = zod.z.union([sort, zod.z.strictObject({
3121
+ } else if (fieldDef.computed && fieldDef.params) fields[field] = zod.z.strictObject({
3122
+ args: this.makeFieldArgsSchema(fieldDef.params),
3123
+ sort,
3124
+ nulls: zod.z.union([zod.z.literal("first"), zod.z.literal("last")]).optional()
3125
+ }).optional();
3126
+ else if (fieldDef.optional) fields[field] = zod.z.union([sort, zod.z.strictObject({
3037
3127
  sort,
3038
3128
  nulls: zod.z.union([zod.z.literal("first"), zod.z.literal("last")]).optional()
3039
3129
  })]).optional();
@@ -3077,7 +3167,7 @@ var ZodSchemaFactory = class {
3077
3167
  return schema;
3078
3168
  }
3079
3169
  makeDistinctSchema(model) {
3080
- const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation).map(([name]) => name);
3170
+ const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
3081
3171
  const schema = nonRelationFields.length > 0 ? this.orArray(zod.z.enum(nonRelationFields), true) : zod.z.never();
3082
3172
  this.registerSchema(`${model}DistinctInput`, schema);
3083
3173
  return schema;
@@ -3398,8 +3488,8 @@ var ZodSchemaFactory = class {
3398
3488
  makeCountAggregateInputSchema(model) {
3399
3489
  const schema = zod.z.union([zod.z.literal(true), zod.z.strictObject({
3400
3490
  _all: zod.z.literal(true).optional(),
3401
- ...this.getModelFields(model).reduce((acc, [field]) => {
3402
- acc[field] = zod.z.literal(true).optional();
3491
+ ...this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3492
+ acc[field] = this.isParameterizedComputedField(fieldDef) ? zod.z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : zod.z.literal(true).optional();
3403
3493
  return acc;
3404
3494
  }, {})
3405
3495
  })]);
@@ -3423,7 +3513,7 @@ var ZodSchemaFactory = class {
3423
3513
  }
3424
3514
  makeSumAvgInputSchema(model) {
3425
3515
  const schema = zod.z.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3426
- if (this.isNumericField(fieldDef)) acc[field] = zod.z.literal(true).optional();
3516
+ if (this.isNumericField(fieldDef)) acc[field] = this.isParameterizedComputedField(fieldDef) ? zod.z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : zod.z.literal(true).optional();
3427
3517
  return acc;
3428
3518
  }, {}));
3429
3519
  this.registerSchema(`${model}SumAvgAggregateInput`, schema);
@@ -3431,15 +3521,22 @@ var ZodSchemaFactory = class {
3431
3521
  }
3432
3522
  makeMinMaxInputSchema(model) {
3433
3523
  const schema = zod.z.strictObject(this.getModelFields(model).reduce((acc, [field, fieldDef]) => {
3434
- if (!fieldDef.relation && !fieldDef.array) acc[field] = zod.z.literal(true).optional();
3524
+ if (!fieldDef.relation && !fieldDef.array) acc[field] = this.isParameterizedComputedField(fieldDef) ? zod.z.strictObject({ args: this.makeFieldArgsSchema(fieldDef.params) }).optional() : zod.z.literal(true).optional();
3435
3525
  return acc;
3436
3526
  }, {}));
3437
3527
  this.registerSchema(`${model}MinMaxAggregateInput`, schema);
3438
3528
  return schema;
3439
3529
  }
3440
3530
  makeGroupBySchema(model, options) {
3441
- const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation).map(([name]) => name);
3442
- const bySchema = nonRelationFields.length > 0 ? this.orArray(zod.z.enum(nonRelationFields), true) : zod.z.never();
3531
+ const nonRelationFields = this.getModelFields(model).filter(([, def]) => !def.relation && !this.isParameterizedComputedField(def)).map(([name]) => name);
3532
+ const byMembers = [];
3533
+ if (nonRelationFields.length > 0) byMembers.push(zod.z.enum(nonRelationFields));
3534
+ for (const [field, fieldDef] of this.getModelFields(model)) if (this.isParameterizedComputedField(fieldDef)) byMembers.push(zod.z.strictObject({
3535
+ field: zod.z.literal(field),
3536
+ args: this.makeFieldArgsSchema(fieldDef.params)
3537
+ }));
3538
+ const byElement = byMembers.length === 0 ? void 0 : byMembers.length === 1 ? byMembers[0] : zod.z.union(byMembers);
3539
+ const bySchema = byElement ? this.orArray(byElement, true) : zod.z.never();
3443
3540
  const baseSchema = zod.z.strictObject({
3444
3541
  where: this.makeWhereSchema(model, false, false, false, options).optional(),
3445
3542
  orderBy: this.orArray(this.makeOrderBySchema(model, false, true, options), true).optional(),
@@ -3455,7 +3552,7 @@ var ZodSchemaFactory = class {
3455
3552
  });
3456
3553
  let schema = this.mergePluginArgsSchema(baseSchema, "groupBy");
3457
3554
  schema = schema.refine((value) => {
3458
- const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by);
3555
+ const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3459
3556
  if (value.having && typeof value.having === "object") for (const [key, val] of Object.entries(value.having)) {
3460
3557
  if (AggregateOperators.includes(key)) continue;
3461
3558
  if (bys.includes(key)) continue;
@@ -3465,7 +3562,7 @@ var ZodSchemaFactory = class {
3465
3562
  return true;
3466
3563
  }, "fields in \"having\" must be in \"by\"");
3467
3564
  schema = schema.refine((value) => {
3468
- const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by);
3565
+ const bys = (0, _zenstackhq_common_helpers.enumerate)(value.by).map((b) => typeof b === "string" ? b : b?.field);
3469
3566
  for (const orderBy of (0, _zenstackhq_common_helpers.enumerate)(value.orderBy)) if (orderBy && Object.keys(orderBy).filter((f) => !AggregateOperators.includes(f)).some((key) => !bys.includes(key))) return false;
3470
3567
  return true;
3471
3568
  }, "fields in \"orderBy\" must be in \"by\"");
@@ -4283,7 +4380,7 @@ var BaseOperationHandler = class {
4283
4380
  this.client = client;
4284
4381
  this.model = model;
4285
4382
  this.inputValidator = inputValidator;
4286
- this.dialect = getCrudDialect(this.schema, this.client.$options);
4383
+ this.dialect = getCrudDialect(this.client);
4287
4384
  }
4288
4385
  get schema() {
4289
4386
  return this.client.$schema;
@@ -4366,8 +4463,10 @@ var BaseOperationHandler = class {
4366
4463
  continue;
4367
4464
  }
4368
4465
  const fieldDef = this.requireField(model, field);
4369
- if (!fieldDef.relation) result = this.dialect.buildSelectField(result, model, parentAlias, field);
4370
- else {
4466
+ if (!fieldDef.relation) {
4467
+ const computedArgs = fieldDef.computed && fieldDef.params && typeof payload === "object" && "args" in payload ? payload.args : void 0;
4468
+ result = this.dialect.buildSelectField(result, model, parentAlias, field, computedArgs);
4469
+ } else {
4371
4470
  if (!fieldDef.array && !fieldDef.optional && payload.where) throw createInternalError(`Field "${field}" does not support filtering`, model);
4372
4471
  if (fieldDef.originModel) result = this.dialect.buildRelationSelection(result, fieldDef.originModel, field, fieldDef.originModel, payload);
4373
4472
  else result = this.dialect.buildRelationSelection(result, model, field, parentAlias, payload);
@@ -5349,6 +5448,7 @@ var BaseOperationHandler = class {
5349
5448
  };
5350
5449
  //#endregion
5351
5450
  //#region src/client/crud/operations/aggregate.ts
5451
+ const argsKey = (v) => JSON.stringify(v, (_k, val) => typeof val === "bigint" ? `${val}n` : val);
5352
5452
  var AggregateOperationHandler = class extends BaseOperationHandler {
5353
5453
  async handle(_operation, args) {
5354
5454
  const normalizedArgs = this.normalizeArgs(args);
@@ -5356,10 +5456,18 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5356
5456
  let query = this.kysely.selectFrom((eb) => {
5357
5457
  let subQuery = this.dialect.buildSelectModel(this.model, this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5358
5458
  const selectedFields = [];
5359
- for (const [key, value] of Object.entries(parsedArgs)) if (key.startsWith("_") && value && typeof value === "object") Object.entries(value).filter(([field]) => field !== "_all").filter(([, val]) => val === true).forEach(([field]) => {
5459
+ const computedArgsByField = {};
5460
+ for (const [key, value] of Object.entries(parsedArgs)) if (key.startsWith("_") && value && typeof value === "object") Object.entries(value).filter(([field]) => field !== "_all").forEach(([field, val]) => {
5461
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5462
+ if (val !== true && args === void 0) return;
5360
5463
  if (!selectedFields.includes(field)) selectedFields.push(field);
5464
+ if (args !== void 0) {
5465
+ const prev = computedArgsByField[field];
5466
+ if (prev !== void 0 && argsKey(prev) !== argsKey(args)) throw createInvalidInputError(`computed field "${field}" is aggregated with conflicting "args"; the same field can only be aggregated with one set of arguments per query`);
5467
+ computedArgsByField[field] = args;
5468
+ }
5361
5469
  });
5362
- if (selectedFields.length > 0) for (const field of selectedFields) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, field);
5470
+ if (selectedFields.length > 0) for (const field of selectedFields) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, field, computedArgsByField[field]);
5363
5471
  else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5364
5472
  const skip = parsedArgs?.skip;
5365
5473
  let take = parsedArgs?.take;
@@ -5376,7 +5484,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5376
5484
  case "_count":
5377
5485
  if (value === true) query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
5378
5486
  else Object.entries(value).forEach(([field, val]) => {
5379
- if (val === true) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5487
+ if (val === true || val && typeof val === "object" && "args" in val) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5380
5488
  else query = query.select((eb) => this.dialect.castInt(eb.fn.count(eb.ref(`$sub.${field}`))).as(`${key}.${field}`));
5381
5489
  });
5382
5490
  break;
@@ -5385,7 +5493,7 @@ var AggregateOperationHandler = class extends BaseOperationHandler {
5385
5493
  case "_max":
5386
5494
  case "_min":
5387
5495
  Object.entries(value).forEach(([field, val]) => {
5388
- if (val === true) query = query.select((eb) => {
5496
+ if (val === true || val && typeof val === "object" && "args" in val) query = query.select((eb) => {
5389
5497
  return (0, ts_pattern.match)(key).with("_sum", () => eb.fn.sum).with("_avg", () => eb.fn.avg).with("_max", () => eb.fn.max).with("_min", () => eb.fn.min).exhaustive()(eb.ref(`$sub.${field}`)).as(`${key}.${field}`);
5390
5498
  });
5391
5499
  });
@@ -5428,9 +5536,12 @@ var CountOperationHandler = class extends BaseOperationHandler {
5428
5536
  const subQueryName = "$sub";
5429
5537
  let query = this.kysely.selectFrom((eb) => {
5430
5538
  let subQuery = this.dialect.buildSelectModel(this.model, this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5431
- if (parsedArgs?.select && typeof parsedArgs.select === "object") {
5432
- for (const [key, value] of Object.entries(parsedArgs.select)) if (key !== "_all" && value === true) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key);
5433
- } else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5539
+ if (parsedArgs?.select && typeof parsedArgs.select === "object") for (const [key, value] of Object.entries(parsedArgs.select)) {
5540
+ if (key === "_all") continue;
5541
+ if (value === true) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key);
5542
+ else if (value && typeof value === "object" && "args" in value) subQuery = this.dialect.buildSelectField(subQuery, this.model, this.model, key, value.args);
5543
+ }
5544
+ else subQuery = subQuery.select(() => eb.lit(1).as("_all"));
5434
5545
  subQuery = this.dialect.buildSkipTake(subQuery, parsedArgs?.skip, parsedArgs?.take);
5435
5546
  return subQuery.as(subQueryName);
5436
5547
  });
@@ -5571,9 +5682,17 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5571
5682
  const normalizedArgs = this.normalizeArgs(args);
5572
5683
  const parsedArgs = this.inputValidator.validateGroupByArgs(this.model, normalizedArgs);
5573
5684
  let query = this.kysely.selectFrom(this.model).where(() => this.dialect.buildFilter(this.model, this.model, parsedArgs?.where));
5574
- const fieldRef = (field) => this.dialect.fieldRef(this.model, field);
5575
- const bys = typeof parsedArgs.by === "string" ? [parsedArgs.by] : parsedArgs.by;
5576
- query = query.groupBy(bys.map((by) => fieldRef(by)));
5685
+ const fieldRef = (field, computedArgs) => this.dialect.fieldRef(this.model, field, this.model, true, computedArgs);
5686
+ const byEntries = (Array.isArray(parsedArgs.by) ? parsedArgs.by : [parsedArgs.by]).map((by) => typeof by === "string" ? {
5687
+ field: by,
5688
+ args: void 0
5689
+ } : {
5690
+ field: by.field,
5691
+ args: by.args
5692
+ });
5693
+ query = query.groupBy(byEntries.map((e) => {
5694
+ return getField(this.schema, this.model, e.field)?.computed ? kysely.sql.ref(e.field) : fieldRef(e.field);
5695
+ }));
5577
5696
  const skip = parsedArgs?.skip;
5578
5697
  let take = parsedArgs?.take;
5579
5698
  let negateOrderBy = false;
@@ -5584,13 +5703,14 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5584
5703
  query = this.dialect.buildSkipTake(query, skip, take);
5585
5704
  query = this.dialect.buildOrderBy(query, this.model, this.model, parsedArgs.orderBy, negateOrderBy, take);
5586
5705
  if (parsedArgs.having) query = query.having(() => this.dialect.buildFilter(this.model, this.model, parsedArgs.having));
5587
- for (const by of bys) query = query.select(() => fieldRef(by).as(by));
5706
+ for (const e of byEntries) query = query.select(() => fieldRef(e.field, e.args).as(e.field));
5588
5707
  for (const [key, value] of Object.entries(parsedArgs)) switch (key) {
5589
5708
  case "_count":
5590
5709
  if (value === true) query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as("_count"));
5591
5710
  else Object.entries(value).forEach(([field, val]) => {
5592
- if (val === true) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5593
- else query = query.select((eb) => this.dialect.castInt(eb.fn.count(fieldRef(field))).as(`${key}.${field}`));
5711
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5712
+ if (val === true || args !== void 0) if (field === "_all") query = query.select((eb) => this.dialect.castInt(eb.fn.countAll()).as(`_count._all`));
5713
+ else query = query.select((eb) => this.dialect.castInt(eb.fn.count(fieldRef(field, args))).as(`${key}.${field}`));
5594
5714
  });
5595
5715
  break;
5596
5716
  case "_sum":
@@ -5598,7 +5718,8 @@ var GroupByOperationHandler = class extends BaseOperationHandler {
5598
5718
  case "_max":
5599
5719
  case "_min":
5600
5720
  Object.entries(value).forEach(([field, val]) => {
5601
- if (val === true) query = query.select((eb) => aggregate(eb, fieldRef(field), key).as(`${key}.${field}`));
5721
+ const args = val && typeof val === "object" && "args" in val ? val.args : void 0;
5722
+ if (val === true || args !== void 0) query = query.select((eb) => aggregate(eb, fieldRef(field, args), key).as(`${key}.${field}`));
5602
5723
  });
5603
5724
  break;
5604
5725
  }
@@ -5892,7 +6013,7 @@ var QueryNameMapper = class extends kysely.OperationNodeTransformer {
5892
6013
  constructor(client) {
5893
6014
  super();
5894
6015
  this.client = client;
5895
- this.dialect = getCrudDialect(client.$schema, client.$options);
6016
+ this.dialect = getCrudDialect(client);
5896
6017
  for (const [modelName, modelDef] of Object.entries(client.$schema.models)) {
5897
6018
  const mappedName = this.getMappedName(modelDef);
5898
6019
  if (mappedName) this.modelToTableMap.set(modelName, mappedName);
@@ -6355,22 +6476,22 @@ const DEFAULT_MAX_SLOW_RECORDS = 100;
6355
6476
  var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQueryExecutor {
6356
6477
  nameMapper;
6357
6478
  dialect;
6358
- constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false) {
6479
+ constructor(client, driver, compiler, adapter, connectionProvider, plugins = [], suppressMutationHooks = false, nameMapper) {
6359
6480
  super(compiler, adapter, connectionProvider, plugins);
6360
6481
  this.client = client;
6361
6482
  this.driver = driver;
6362
6483
  this.compiler = compiler;
6363
6484
  this.connectionProvider = connectionProvider;
6364
6485
  this.suppressMutationHooks = suppressMutationHooks;
6365
- if (client.$schema.provider.type === "postgresql" || this.schemaHasMappedNames(client.$schema)) this.nameMapper = new QueryNameMapper(client);
6366
- this.dialect = getCrudDialect(client.$schema, client.$options);
6486
+ this.nameMapper = nameMapper ?? (client.$schema.provider.type === "postgresql" || schemaHasMappedNames(client.$schema) ? new QueryNameMapper(client.$contract) : void 0);
6487
+ this.dialect = getCrudDialect(client.$contract);
6367
6488
  }
6368
- schemaHasMappedNames(schema) {
6369
- const hasMapAttr = (decl) => {
6370
- if (decl.attributes?.some((attr) => attr.name === "@@map")) return true;
6371
- return Object.values(decl.fields).some((field) => field.attributes?.some((attr) => attr.name === "@map"));
6372
- };
6373
- return Object.values(schema.models).some(hasMapAttr) || Object.values(schema.typeDefs ?? []).some(hasMapAttr);
6489
+ /**
6490
+ * The name mapper built for this executor's schema, if the schema needs one. Exposed so that
6491
+ * derived clients built from the same schema and options can reuse it instead of rebuilding it.
6492
+ */
6493
+ getNameMapper() {
6494
+ return this.nameMapper;
6374
6495
  }
6375
6496
  get kysely() {
6376
6497
  return this.client.$qb;
@@ -6417,7 +6538,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends kysely.DefaultQu
6417
6538
  proceed = async (query) => {
6418
6539
  const _p = (q) => _proceed(q);
6419
6540
  return await hook({
6420
- client: this.client,
6541
+ client: this.client.$contract,
6421
6542
  schema: this.client.$schema,
6422
6543
  query,
6423
6544
  proceed: _p
@@ -6655,7 +6776,7 @@ In such cases, ZenStack cannot reliably determine the IDs of the mutated entitie
6655
6776
  innerExecutor.suppressMutationHooks = true;
6656
6777
  const innerClient = this.client.withExecutor(innerExecutor);
6657
6778
  if (inTx) innerClient.forceTransaction();
6658
- return innerClient;
6779
+ return innerClient.$contract;
6659
6780
  }
6660
6781
  andNodes(condition1, condition2) {
6661
6782
  if (condition1 && condition2) return kysely.WhereNode.create(kysely.AndNode.create(condition1, condition2));
@@ -6707,19 +6828,19 @@ In such cases, ZenStack cannot reliably determine the IDs of the mutated entitie
6707
6828
  return finalResult;
6708
6829
  }
6709
6830
  withPlugin(plugin) {
6710
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, plugin], this.suppressMutationHooks);
6831
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, plugin], this.suppressMutationHooks, this.nameMapper);
6711
6832
  }
6712
6833
  withPlugins(plugins) {
6713
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, ...plugins], this.suppressMutationHooks);
6834
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [...this.plugins, ...plugins], this.suppressMutationHooks, this.nameMapper);
6714
6835
  }
6715
6836
  withPluginAtFront(plugin) {
6716
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [plugin, ...this.plugins], this.suppressMutationHooks);
6837
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [plugin, ...this.plugins], this.suppressMutationHooks, this.nameMapper);
6717
6838
  }
6718
6839
  withoutPlugins() {
6719
- return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks);
6840
+ return new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, this.connectionProvider, [], this.suppressMutationHooks, this.nameMapper);
6720
6841
  }
6721
6842
  withConnectionProvider(connectionProvider) {
6722
- const newExecutor = new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks);
6843
+ const newExecutor = new ZenStackQueryExecutor(this.client, this.driver, this.compiler, this.adapter, connectionProvider, this.plugins, this.suppressMutationHooks, this.nameMapper);
6723
6844
  newExecutor.client = this.client.withExecutor(newExecutor);
6724
6845
  return newExecutor;
6725
6846
  }
@@ -7175,6 +7296,12 @@ var ResultProcessor = class {
7175
7296
  //#endregion
7176
7297
  //#region src/client/client-impl.ts
7177
7298
  /**
7299
+ * Returns the name mapper held by a ZenStack executor, or undefined for a plain kysely one.
7300
+ */
7301
+ function getExecutorNameMapper(executor) {
7302
+ return executor instanceof ZenStackQueryExecutor ? executor.getNameMapper() : void 0;
7303
+ }
7304
+ /**
7178
7305
  * ZenStack ORM client.
7179
7306
  */
7180
7307
  const ZenStackClient = function(schema, options) {
@@ -7202,7 +7329,7 @@ var ClientImpl = class ClientImpl {
7202
7329
  if (baseClient) {
7203
7330
  this.kyselyProps = {
7204
7331
  ...baseClient.kyselyProps,
7205
- executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new kysely.DefaultConnectionProvider(baseClient.kyselyProps.driver))
7332
+ executor: executor ?? new ZenStackQueryExecutor(this, baseClient.kyselyProps.driver, baseClient.kyselyProps.dialect.createQueryCompiler(), baseClient.kyselyProps.dialect.createAdapter(), new kysely.DefaultConnectionProvider(baseClient.kyselyProps.driver), [], false, baseClient.$schema === schema && baseClient.$options === options ? getExecutorNameMapper(baseClient.kyselyProps.executor) : void 0)
7206
7333
  };
7207
7334
  this.kyselyRaw = baseClient.kyselyRaw;
7208
7335
  this.auth = baseClient.auth;
@@ -7279,14 +7406,14 @@ var ClientImpl = class ClientImpl {
7279
7406
  if (!this.kysely.isTransaction) this.kysely = new kysely.Transaction(this.kyselyProps);
7280
7407
  }
7281
7408
  async interactiveTransaction(callback, options) {
7282
- if (this.kysely.isTransaction) return callback(this);
7409
+ if (this.kysely.isTransaction) return callback(this.$contract);
7283
7410
  else {
7284
7411
  let txBuilder = this.kysely.transaction();
7285
7412
  if (options?.isolationLevel) txBuilder = txBuilder.setIsolationLevel(options.isolationLevel);
7286
7413
  return txBuilder.execute((tx) => {
7287
7414
  const txClient = new ClientImpl(this.schema, this.$options, this);
7288
7415
  txClient.kysely = tx;
7289
- return callback(txClient);
7416
+ return callback(txClient.$contract);
7290
7417
  });
7291
7418
  }
7292
7419
  }
@@ -7303,7 +7430,7 @@ var ClientImpl = class ClientImpl {
7303
7430
  const result = [];
7304
7431
  for (const promise of arg) {
7305
7432
  const cb = this.getPromiseCallback(promise);
7306
- result.push(await cb(txClient));
7433
+ result.push(await cb(txClient.$contract));
7307
7434
  }
7308
7435
  return result;
7309
7436
  };
@@ -7404,6 +7531,16 @@ var ClientImpl = class ClientImpl {
7404
7531
  get $auth() {
7405
7532
  return this.auth;
7406
7533
  }
7534
+ /**
7535
+ * This client viewed through its public typed contract. `ClientImpl` is intentionally
7536
+ * untyped internally — the model accessors are added by the runtime proxy — so this
7537
+ * getter is the single sanctioned bridge to `ClientContract`. The proxy invokes it
7538
+ * with the proxy as `this` (`Reflect.get` with receiver), so the returned reference
7539
+ * keeps the model accessors.
7540
+ */
7541
+ get $contract() {
7542
+ return this;
7543
+ }
7407
7544
  $setOptions(options) {
7408
7545
  const newClient = new ClientImpl(this.schema, options, this);
7409
7546
  newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });