@zenstackhq/orm 3.10.0 → 3.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1006,17 +1006,22 @@ type FuzzyFilterOptions = {
1006
1006
  };
1007
1007
  //#endregion
1008
1008
  //#region src/client/crud/validator/validator.d.ts
1009
- type InputValidatorOptions = {
1009
+ type InputValidatorOptions<Schema extends SchemaDef> = {
1010
1010
  /**
1011
1011
  * Whether validation is enabled. Defaults to `true`.
1012
1012
  */
1013
1013
  enabled?: boolean;
1014
+ /**
1015
+ * Schema factory to validate with. Defaults to a new factory (and so a new schema cache) bound
1016
+ * to the client.
1017
+ */
1018
+ zodFactory?: ZodSchemaFactory<Schema>;
1014
1019
  };
1015
1020
  declare class InputValidator<Schema extends SchemaDef> {
1016
1021
  private readonly client;
1017
1022
  readonly zodFactory: ZodSchemaFactory<Schema>;
1018
1023
  private readonly enabled;
1019
- constructor(client: ClientContract<Schema>, options?: InputValidatorOptions);
1024
+ constructor(client: ClientContract<Schema>, options?: InputValidatorOptions<Schema>);
1020
1025
  validateFindArgs(model: GetModels<Schema>, args: unknown, operation: 'findFirst' | 'findUnique' | 'findMany'): FindArgs<Schema, GetModels<Schema>, any, true> | undefined;
1021
1026
  validateExistsArgs(model: GetModels<Schema>, args: unknown): ExistsArgs<Schema, GetModels<Schema>, any> | undefined;
1022
1027
  validateCreateArgs(model: GetModels<Schema>, args: unknown): CreateArgs<Schema, GetModels<Schema>, any>;
package/dist/index.d.mts CHANGED
@@ -1006,17 +1006,22 @@ type FuzzyFilterOptions = {
1006
1006
  };
1007
1007
  //#endregion
1008
1008
  //#region src/client/crud/validator/validator.d.ts
1009
- type InputValidatorOptions = {
1009
+ type InputValidatorOptions<Schema extends SchemaDef> = {
1010
1010
  /**
1011
1011
  * Whether validation is enabled. Defaults to `true`.
1012
1012
  */
1013
1013
  enabled?: boolean;
1014
+ /**
1015
+ * Schema factory to validate with. Defaults to a new factory (and so a new schema cache) bound
1016
+ * to the client.
1017
+ */
1018
+ zodFactory?: ZodSchemaFactory<Schema>;
1014
1019
  };
1015
1020
  declare class InputValidator<Schema extends SchemaDef> {
1016
1021
  private readonly client;
1017
1022
  readonly zodFactory: ZodSchemaFactory<Schema>;
1018
1023
  private readonly enabled;
1019
- constructor(client: ClientContract<Schema>, options?: InputValidatorOptions);
1024
+ constructor(client: ClientContract<Schema>, options?: InputValidatorOptions<Schema>);
1020
1025
  validateFindArgs(model: GetModels<Schema>, args: unknown, operation: 'findFirst' | 'findUnique' | 'findMany'): FindArgs<Schema, GetModels<Schema>, any, true> | undefined;
1021
1026
  validateExistsArgs(model: GetModels<Schema>, args: unknown): ExistsArgs<Schema, GetModels<Schema>, any> | undefined;
1022
1027
  validateCreateArgs(model: GetModels<Schema>, args: unknown): CreateArgs<Schema, GetModels<Schema>, any>;
package/dist/index.mjs CHANGED
@@ -2399,6 +2399,20 @@ function createQuerySchemaFactory(clientOrSchema, options) {
2399
2399
  return new ZodSchemaFactory(clientOrSchema, options);
2400
2400
  }
2401
2401
  /**
2402
+ * Whether two client options produce the same query-args schemas, i.e. a `ZodSchemaFactory`
2403
+ * built for one can serve the other. Only `omit`, `slicing`, `allowQueryTimeOmitOverride` and
2404
+ * the plugins that extend query args or results shape the schemas; dialect, auth, hooks and
2405
+ * validation flags do not.
2406
+ */
2407
+ function haveSameSchemaInputs(a, b) {
2408
+ if (a === b) return true;
2409
+ if (a.omit !== b.omit || a.slicing !== b.slicing || a.allowQueryTimeOmitOverride !== b.allowQueryTimeOmitOverride) return false;
2410
+ const shaping = (options) => (options.plugins ?? []).filter((plugin) => plugin.queryArgs || plugin.result);
2411
+ const pa = shaping(a);
2412
+ const pb = shaping(b);
2413
+ return pa.length === pb.length && pa.every((plugin, index) => plugin === pb[index]);
2414
+ }
2415
+ /**
2402
2416
  * Builds a `DateTime` value schema that accepts a `Date` object or any string
2403
2417
  * the JS `Date` constructor parses, and coerces it to a `Date`. ISO datetime,
2404
2418
  * ISO date, and time-only strings (e.g. `"09:00:00"` for `@db.Time` fields,
@@ -2623,12 +2637,13 @@ var ZodSchemaFactory = class {
2623
2637
  const schema = this.makeScalarSchema(typeDef.base, [...typeDef.fields["this"]?.attributes ?? [], ...fieldAttributes ?? []]);
2624
2638
  return this.extraValidationsEnabled ? ZodUtils.addCustomValidation(schema, typeDef.attributes) : schema;
2625
2639
  }
2626
- const schema = (typeDef.strict ? z.strictObject : z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2627
- let fieldSchema = isTypeDef(this.schema, def.type) ? z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type);
2628
- if (def.array) fieldSchema = fieldSchema.array();
2640
+ const objectSchema = (typeDef.strict ? z.strictObject : z.looseObject)(Object.fromEntries(Object.entries(typeDef.fields).map(([field, def]) => {
2641
+ let fieldSchema = isTypeDef(this.schema, def.type) && !isPrimitiveTypeDef(this.schema, def.type) ? z.lazy(() => this.makeTypeDefSchema(def.type)) : this.makeScalarSchema(def.type, this.getItemAttributes(def));
2642
+ if (def.array) fieldSchema = ZodUtils.addListValidation(fieldSchema.array(), def.attributes);
2629
2643
  if (def.optional) fieldSchema = fieldSchema.nullish();
2630
2644
  return [field, fieldSchema];
2631
2645
  })));
2646
+ const schema = this.extraValidationsEnabled ? ZodUtils.addCustomValidation(objectSchema, typeDef.attributes) : objectSchema;
2632
2647
  const finalSchema = z.any().superRefine((value, ctx) => {
2633
2648
  const parseResult = schema.safeParse(value);
2634
2649
  if (!parseResult.success) parseResult.error.issues.forEach((issue) => ctx.addIssue(issue));
@@ -4180,7 +4195,7 @@ var InputValidator = class {
4180
4195
  enabled;
4181
4196
  constructor(client, options) {
4182
4197
  this.client = client;
4183
- this.zodFactory = new ZodSchemaFactory(client);
4198
+ this.zodFactory = options?.zodFactory ?? new ZodSchemaFactory(client);
4184
4199
  this.enabled = options?.enabled !== false;
4185
4200
  }
4186
4201
  validateFindArgs(model, args, operation) {
@@ -4333,6 +4348,7 @@ var BaseOperationHandler = class {
4333
4348
  try {
4334
4349
  result = (await kysely.getExecutor().executeQuery(compiled)).rows;
4335
4350
  } catch (err) {
4351
+ if (err instanceof ORMError) throw err;
4336
4352
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
4337
4353
  }
4338
4354
  return !!result[0]?.$exists;
@@ -4352,6 +4368,7 @@ var BaseOperationHandler = class {
4352
4368
  try {
4353
4369
  result = (await kysely.getExecutor().executeQuery(compiled)).rows;
4354
4370
  } catch (err) {
4371
+ if (err instanceof ORMError) throw err;
4355
4372
  throw createDBQueryError(`Failed to execute query: ${err}`, err, compiled.sql, compiled.parameters);
4356
4373
  }
4357
4374
  return result;
@@ -6763,6 +6780,7 @@ var ZenStackQueryExecutor = class ZenStackQueryExecutor extends DefaultQueryExec
6763
6780
  if (this.dialect.supportsReturning) return queryResult.rows.map((row) => ({ ...row }));
6764
6781
  else {
6765
6782
  const mutatedIds = InsertQueryNode.is(queryNode) ? this.getInsertIds(mutationInfo.model, queryNode, queryResult) : preUpdateIds;
6783
+ if (mutatedIds && mutatedIds.length === 0) return [];
6766
6784
  if (mutatedIds) {
6767
6785
  const idFields = requireIdFields(this.client.$schema, mutationInfo.model);
6768
6786
  const eb = expressionBuilder();
@@ -7681,7 +7699,7 @@ var ClientImpl = class ClientImpl {
7681
7699
  plugins: newPlugins
7682
7700
  };
7683
7701
  const newClient = new ClientImpl(this.schema, newOptions, this);
7684
- newClient.inputValidator = new InputValidator(newClient, { enabled: newOptions.validateInput !== false });
7702
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7685
7703
  return newClient;
7686
7704
  }
7687
7705
  $unuse(pluginId) {
@@ -7692,7 +7710,7 @@ var ClientImpl = class ClientImpl {
7692
7710
  plugins: newPlugins
7693
7711
  };
7694
7712
  const newClient = new ClientImpl(this.schema, newOptions, this);
7695
- newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });
7713
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7696
7714
  return newClient;
7697
7715
  }
7698
7716
  $unuseAll() {
@@ -7701,9 +7719,22 @@ var ClientImpl = class ClientImpl {
7701
7719
  plugins: []
7702
7720
  };
7703
7721
  const newClient = new ClientImpl(this.schema, newOptions, this);
7704
- newClient.inputValidator = new InputValidator(newClient, { enabled: newOptions.validateInput !== false });
7722
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7705
7723
  return newClient;
7706
7724
  }
7725
+ /**
7726
+ * Validator for a client derived from this one. The derived client reuses this client's Zod
7727
+ * schema factory, and so its schema cache, whenever its options shape the same query-args
7728
+ * schemas; it only gets a fresh factory when a plugin that extends query args or results was
7729
+ * added or removed, or `omit`/`slicing` changed. The validator itself is always new because
7730
+ * `validateInput` may differ.
7731
+ */
7732
+ deriveInputValidator(newClient) {
7733
+ return new InputValidator(newClient, {
7734
+ enabled: newClient.$options.validateInput !== false,
7735
+ zodFactory: haveSameSchemaInputs(this.$options, newClient.$options) ? this.inputValidator.zodFactory : void 0
7736
+ });
7737
+ }
7707
7738
  $setAuth(auth) {
7708
7739
  if (auth !== void 0 && (typeof auth !== "object" || auth === null || Array.isArray(auth))) throw new Error("Invalid auth object");
7709
7740
  const newClient = new ClientImpl(this.schema, this.$options, this);
@@ -7725,7 +7756,7 @@ var ClientImpl = class ClientImpl {
7725
7756
  }
7726
7757
  $setOptions(options) {
7727
7758
  const newClient = new ClientImpl(this.schema, options, this);
7728
- newClient.inputValidator = new InputValidator(newClient, { enabled: newClient.$options.validateInput !== false });
7759
+ newClient.inputValidator = this.deriveInputValidator(newClient);
7729
7760
  return newClient;
7730
7761
  }
7731
7762
  $setInputValidation(enable) {