monorise 1.4.0 → 1.5.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.
@@ -1,5 +1,29 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ type WhereOperator = {
4
+ $eq: string | number | boolean;
5
+ } | {
6
+ $ne: string | number | boolean;
7
+ } | {
8
+ $gt: number;
9
+ } | {
10
+ $lt: number;
11
+ } | {
12
+ $gte: number;
13
+ } | {
14
+ $lte: number;
15
+ } | {
16
+ $exists: boolean;
17
+ } | {
18
+ $beginsWith: string;
19
+ };
20
+ type WhereClause = WhereOperator | string | number | boolean;
21
+ type WhereConditions = Record<string, WhereClause>;
22
+ type AdjustmentConditionFn<B extends z.ZodRawShape = z.ZodRawShape> = (data: Partial<z.infer<z.ZodObject<B>>>, adjustments: Record<string, number>) => WhereConditions;
23
+ type AdjustmentCondition<B extends z.ZodRawShape = z.ZodRawShape> = WhereConditions | AdjustmentConditionFn<B>;
24
+ type UpdateConditionFn<B extends z.ZodRawShape = z.ZodRawShape> = (data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions;
25
+ type UpdateCondition<B extends z.ZodRawShape = z.ZodRawShape> = WhereConditions | UpdateConditionFn<B>;
26
+
3
27
  declare enum Entity {
4
28
  }
5
29
  interface EntitySchemaMap {
@@ -284,6 +308,8 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
284
308
  * When adjusting numeric fields, these constraints are enforced at the database level.
285
309
  * If an adjustment would violate a constraint, the operation is rejected.
286
310
  *
311
+ * @deprecated Use `conditions` instead. Will be removed in a future version.
312
+ *
287
313
  * @example
288
314
  * ```ts
289
315
  * {
@@ -319,6 +345,67 @@ interface MonoriseEntityConfig<T extends Entity = Entity, B extends z.ZodRawShap
319
345
  };
320
346
  };
321
347
  };
348
+ /**
349
+ * @description Named conditions for adjustEntity operations.
350
+ * Each condition is either a static `WhereConditions` object or a function
351
+ * `(data, adjustments) => WhereConditions` that receives the entity's current data
352
+ * and the adjustment deltas.
353
+ *
354
+ * When defined, `$condition` is **required** in the adjustEntity request body.
355
+ * The client sends a condition name (string), the server resolves it to a
356
+ * DynamoDB ConditionExpression.
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * {
361
+ * adjustmentConditions: {
362
+ * withdraw: (data, adjustments) => ({
363
+ * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },
364
+ * }),
365
+ * deposit: (data, adjustments) => ({
366
+ * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },
367
+ * }),
368
+ * }
369
+ * }
370
+ * ```
371
+ */
372
+ adjustmentConditions?: {
373
+ [conditionName: string]: WhereConditions | ((data: Partial<z.infer<z.ZodObject<B>>>, adjustments: Record<string, number>) => WhereConditions);
374
+ };
375
+ /**
376
+ * @description Named conditions for updateEntity operations.
377
+ * Each condition is either a static `WhereConditions` object or a function
378
+ * `(data) => WhereConditions` that receives the entity's current data.
379
+ *
380
+ * `$condition` is always **optional** for updateEntity.
381
+ * The client sends a condition name (string), the server resolves it to a
382
+ * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).
383
+ *
384
+ * @example
385
+ * ```ts
386
+ * {
387
+ * updateConditions: {
388
+ * publish: { status: { $eq: 'draft' } },
389
+ * archive: (data) => ({ status: { $ne: 'archived' } }),
390
+ * }
391
+ * }
392
+ * ```
393
+ */
394
+ updateConditions?: {
395
+ [conditionName: string]: WhereConditions | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);
396
+ };
397
+ /**
398
+ * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.
399
+ * Disabled by default: raw DynamoDB condition operators must never be
400
+ * client-facing — an authenticated client could otherwise probe field
401
+ * existence or guess values via the 200-vs-409 response status.
402
+ *
403
+ * Only enable this if you trust the caller (e.g. server-to-server) or have
404
+ * your own validation in front of it. Prefer `updateConditions` instead.
405
+ *
406
+ * @default false
407
+ */
408
+ allowLegacyWhere?: boolean;
322
409
  }
323
410
 
324
411
  declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C extends z.ZodRawShape, M extends z.ZodRawShape, CO extends z.ZodObject<C> | undefined = undefined, MO extends z.ZodObject<M> | undefined = undefined>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) => {
@@ -388,7 +475,14 @@ declare const createEntityConfig: <T extends Entity, B extends z.ZodRawShape, C
388
475
  maxField?: (keyof { [K_2 in keyof B as B[K_2] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K_2 : never]: K_2; } extends never ? string : keyof { [K_3 in keyof B as B[K_3] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K_3 : never]: K_3; }) | undefined;
389
476
  };
390
477
  } | undefined;
478
+ adjustmentConditions?: {
479
+ [conditionName: string]: undefined | ((data: Partial<z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_27 ? { [k_4 in keyof T_27]: T_27[k_4]; } : never>, adjustments: Record<string, number>) => undefined);
480
+ } | undefined;
481
+ updateConditions?: {
482
+ [conditionName: string]: undefined | ((data: Partial<z.objectUtil.addQuestionMarks<z.baseObjectOutputType<B>, any> extends infer T_27 ? { [k_4 in keyof T_27]: T_27[k_4]; } : never>) => undefined);
483
+ } | undefined;
484
+ allowLegacyWhere?: boolean;
391
485
  };
392
486
  declare const createMutualConfig: <MD extends z.ZodRawShape>(config: MutualConfig<MD>) => MutualConfig<MD>;
393
487
 
394
- export { type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type NumericFields, createEntityConfig, createMutualConfig };
488
+ export { type AdjustmentCondition, type AdjustmentConditionFn, type CreatedEntity, type DraftEntity, Entity, type EntitySchemaMap, type MonoriseEntityConfig, type MutualConfig, type NumericFields, type UpdateCondition, type UpdateConditionFn, type WhereClause, type WhereConditions, type WhereOperator, createEntityConfig, createMutualConfig };
@@ -1 +1 @@
1
- {"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts"],"sourcesContent":["import type { z } from 'zod';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\nexport interface MutualConfig<\n MD extends z.ZodRawShape = z.ZodRawShape,\n> {\n entities: [Entity, Entity];\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n searchableFields?: (keyof B)[];\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database\n */\n mutualSchema: MO;\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: { entityId: string; entityType: string; data: Record<string, any>; createdAt: string; updatedAt: string }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n };\n };\n}\n","import type { Entity, MonoriseEntityConfig, MutualConfig } from '../types/monorise.type';\nimport { z } from 'zod';\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) {\n const { baseSchema, createSchema, mutual, effect } = config;\n const { mutualSchema } = mutual || {};\n\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & CO['shape']>\n : CO\n : MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & B>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...mutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO>,\n) => ({\n ...config,\n finalSchema: makeSchema(config),\n});\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfig<MD>,\n) => config;\n\nexport { createEntityConfig, createMutualConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAEO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACDZ,SAAS,SAAS;AAElB,SAAS,WAOP,QAAkD;AAClD,QAAM,EAAE,YAAY,cAAc,QAAQ,OAAO,IAAI;AACrD,QAAM,EAAE,aAAa,IAAI,UAAU,CAAC;AAUpC,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,6CAAc,MAClB;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CAQzB,WACI,iCACD,SADC;AAAA,EAEJ,aAAa,WAAW,MAAM;AAChC;AAEA,IAAM,qBAAqB,CACzB,WACG;","names":["Entity"]}
1
+ {"version":3,"sources":["../types/monorise.type.ts","../utils/index.ts"],"sourcesContent":["import type { z } from 'zod';\nimport type { WhereConditions } from './conditions.type';\n\nexport enum Entity {}\n\nexport interface EntitySchemaMap {\n [key: string]: Record<string, any>;\n}\n\n/**\n * @description Configuration for a mutual relationship between two entities.\n * Defines the schema for mutualData validation. Define once, reference from both entity configs.\n *\n * @example\n * ```ts\n * const enrollmentMutual = createMutualConfig({\n * entities: [Entity.STUDENT, Entity.COURSE],\n * mutualDataSchema: z.object({\n * role: z.enum(['student', 'auditor']),\n * enrolledAt: z.string().datetime(),\n * }),\n * });\n * ```\n */\nexport interface MutualConfig<\n MD extends z.ZodRawShape = z.ZodRawShape,\n> {\n entities: [Entity, Entity];\n mutualDataSchema: z.ZodObject<MD>;\n}\n\nexport type DraftEntity<T extends Entity = Entity> =\n T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n\nexport type NumericFields<T> = {\n [K in keyof T as T[K] extends number ? K : never]?: number;\n};\n\nexport type CreatedEntity<T extends Entity = Entity> = {\n entityId: string;\n entityType: string;\n data: T extends keyof EntitySchemaMap ? EntitySchemaMap[T] : never;\n createdAt: string;\n updatedAt: string;\n};\n\n/**\n * @description Configuration for a monorise entity, a shared configuration that is used across frontend and backend.\n * This can be served as a single source of truth for the entity configuration.\n * It is used to define the schema, and mutual relationships between this entity and other entities.\n *\n * @example\n * ```ts\n * const baseSchema = z.object({\n * title: z.string(),\n * }).partial();\n *\n * const createSchema = baseSchema.extend({\n * title: z.string(),\n * })\n *\n * const config = createEntityConfig({\n * name: 'learner',\n * displayName: 'Learner',\n * baseSchema,\n * createSchema,\n * });\n * ```\n */\nexport interface MonoriseEntityConfig<\n T extends Entity = Entity,\n B extends z.ZodRawShape = z.ZodRawShape,\n C extends z.ZodRawShape = z.ZodRawShape,\n M extends z.ZodRawShape = z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n> {\n /**\n * @description Name of the entity. Must be in **lower-kebab-case** and **unique** across all entities\n *\n * @example `learner`, `learning-activity`\n */\n name: string | T;\n\n /**\n * @description Display name of the entity. It is not required to be unique\n */\n displayName: string;\n\n /**\n * @description (DEPRECATED) Use `uniqueFields` instead, Monorise should not handle auth mechanism\n * @description (Optional) Specify the authentication method to be used for the entity\n */\n authMethod?: {\n /**\n * @description Authentication method using email\n *\n * Note: The email used for authentication is unique per entity.\n * For example, if `johndoe@mail.com` is used for `learner` entity,\n * it can be reused again on `admin` entity. However, the same email\n * address cannot be repeated for the same entity.\n */\n email: {\n /**\n * @description Number of milliseconds before the token expires\n */\n tokenExpiresIn: number;\n };\n };\n\n /**\n * @description Base schema for the entity\n */\n baseSchema: z.ZodObject<B>;\n\n /**\n * @description Minimal schema required to create an entity\n */\n createSchema?: CO;\n searchableFields?: (keyof B)[];\n uniqueFields?: (keyof B)[];\n\n /**\n * @description Define mutual relationship of this entity with other entities\n */\n mutual?: {\n /**\n * @description Subscribes to update events from specified entities in the array.\n * These events will be used to run prejoin processor.\n */\n subscribes?: { entityType: Entity }[];\n /**\n * @description Virtual schema for mutual relationship. The schema is only used for validation purpose, but these fields are not stored in the database\n */\n mutualSchema: MO;\n\n /**\n * @description Keys of `mutualFields` are fields defined in `mutualSchema`.\n * Each field is a mutual relationship between this entity and another entity.\n */\n mutualFields: {\n [key: string]: {\n entityType: Entity;\n toMutualIds?: (context: any) => string[];\n /**\n * @description (Optional) Custom function to process `mutualData`. If not provided, `mutualData` will be empty.\n *\n * @returns the final state of `mutualData` to be stored in the mutual record. Must be an object.\n */\n mutualDataProcessor?: (\n mutualIds: string[],\n currentMutual: any,\n customContext?: Record<string, any>,\n ) => Record<string, any>;\n /**\n * @description (Optional) Reference to a mutual config created by `createMutualConfig`.\n * Provides mutualData schema validation for create/update operations on this mutual relationship.\n */\n mutual?: MutualConfig;\n };\n };\n\n /**\n * @description (Optional) Better known as tree processor\n * This is used to prejoin entities that are not directly related as mutual.\n * For example, if `learner` entity is related to `course` entity, and `course` entity is related to `module` entity,\n * prejoins can be used to join `learner` and `module` entities.\n * With this, the `learner` entity can access the `module` entity without having to go through the `course` entity,\n * hence reducing the number of queries.\n *\n * DynamoDB best practices: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-normalization.html\n *\n */\n prejoins?: {\n mutualField: string;\n targetEntityType: Entity;\n entityPaths: {\n skipCache?: boolean;\n entityType: Entity;\n processor?: (items: any[], context: Record<string, any>) => any;\n }[];\n }[];\n };\n /**\n * Use this function to perform side effects on the final schema for example refine/superRefine the schema\n *\n * @param schema The final schema of the entity (the combination of `baseSchema`/`createSchema` and `mutualSchema` if specified)\n * @returns void\n *\n * @example\n * ```ts\n * effect: (schema) => {\n * schema.refine(\n * // refinement logic here\n * )\n * }\n */\n effect?: (\n schema: z.ZodObject<z.ZodRawShape>,\n ) => z.ZodEffects<z.ZodObject<z.ZodRawShape>>;\n\n /**\n * @description (Optional) Use tags to create additional access patterns for the entity.\n * Time complexity for retrieving tagged entities is O(1).\n *\n * The following configuration will create a tag named `region` for the `organization` entity grouped by `region`.\n * You would then be able to retrieve all organizations in a specific region by:\n * GET `/core/tag/organization/region?group={region_name}`\n *\n * @example\n *\n * ```ts\n * {\n * name: 'organization',\n * tags: [\n * {\n * name: 'region',\n * processor: (entity) => {\n * return [\n * {\n * group: entity.data.region\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n *\n * @description\n *\n * The following configuration will create a tag named `dob` for the `user` entity sorted by `dob`.\n * You would then be able to retrieve all users sorted by `dob` by:\n * GET `/core/tag/user/dob?start=2000-01-01&end=2020-12-31`\n *\n * @example\n * ```ts\n * {\n * name: 'user',\n * tags: [\n * {\n * name: 'dob',\n * processor: (entity) => {\n * return [\n * {\n * sortValue: entity.data.dob\n * }\n * ]\n * },\n * }\n * ]\n * }\n * ```\n */\n tags?: {\n name: string;\n processor: (entity: { entityId: string; entityType: string; data: Record<string, any>; createdAt: string; updatedAt: string }) => {\n group?: string;\n sortValue?: string;\n }[];\n }[];\n\n /**\n * @description (Optional) Configure a DynamoDB TTL for this entity. When set, `expiresAt`\n * is computed via `processor` on create, and recomputed on every update/upsert. Once past,\n * DynamoDB automatically deletes the item (and its derived index rows, since they all carry\n * the same `expiresAt`).\n *\n * `processor` returning `undefined` means \"no TTL\" for that record. On updates, an `undefined`\n * result leaves any existing `expiresAt` untouched rather than clearing it.\n *\n * @example\n * ```ts\n * // fixed 30-day TTL from creation/each update\n * ttl: {\n * processor: () => Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,\n * }\n * ```\n *\n * @example\n * ```ts\n * // data-driven TTL, eg. expire when a subscription ends\n * ttl: {\n * processor: (entity) => {\n * return entity.data.subscriptionEndsAt\n * ? new Date(entity.data.subscriptionEndsAt)\n * : undefined;\n * },\n * }\n * ```\n */\n ttl?: {\n /**\n * @description Returns the expiry as epoch seconds (absolute) or a `Date`.\n * Return `undefined` for no expiry.\n */\n processor: (entity: {\n entityId: string;\n entityType: string;\n data: Record<string, any>;\n createdAt: string;\n updatedAt: string;\n }) => number | Date | undefined;\n };\n\n /**\n * @description (Optional) Constraints for `adjustEntity` operations.\n * When adjusting numeric fields, these constraints are enforced at the database level.\n * If an adjustment would violate a constraint, the operation is rejected.\n *\n * @deprecated Use `conditions` instead. Will be removed in a future version.\n *\n * @example\n * ```ts\n * {\n * adjustmentConstraints: {\n * // Static: same for all entities of this type\n * balance: { min: 0 },\n * credits: { min: 0, max: 10000 },\n *\n * // Dynamic: reads constraint value from entity's own data\n * balance: { minField: 'minBalance' },\n * credits: { min: 0, maxField: 'creditLimit' },\n * }\n * }\n * ```\n */\n adjustmentConstraints?: {\n [fieldName: string]: {\n /** Static minimum value */\n min?: number;\n /** Static maximum value */\n max?: number;\n /** Field name on the entity whose value is used as the minimum (must be a numeric field) */\n minField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n /** Field name on the entity whose value is used as the maximum (must be a numeric field) */\n maxField?: keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n } extends never ? string : keyof {\n [K in keyof B as B[K] extends z.ZodNumber | z.ZodOptional<z.ZodNumber> ? K : never]: K;\n };\n };\n };\n\n /**\n * @description Named conditions for adjustEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data, adjustments) => WhereConditions` that receives the entity's current data\n * and the adjustment deltas.\n *\n * When defined, `$condition` is **required** in the adjustEntity request body.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression.\n *\n * @example\n * ```ts\n * {\n * adjustmentConditions: {\n * withdraw: (data, adjustments) => ({\n * balance: { $gte: (data.minBalance ?? 0) + Math.abs(adjustments?.balance ?? 0) },\n * }),\n * deposit: (data, adjustments) => ({\n * balance: { $lte: 1000000 - (adjustments.balance ?? 0) },\n * }),\n * }\n * }\n * ```\n */\n adjustmentConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((\n data: Partial<z.infer<z.ZodObject<B>>>,\n adjustments: Record<string, number>,\n ) => WhereConditions);\n };\n\n /**\n * @description Named conditions for updateEntity operations.\n * Each condition is either a static `WhereConditions` object or a function\n * `(data) => WhereConditions` that receives the entity's current data.\n *\n * `$condition` is always **optional** for updateEntity.\n * The client sends a condition name (string), the server resolves it to a\n * DynamoDB ConditionExpression. Replaces raw `$where` (deprecated).\n *\n * @example\n * ```ts\n * {\n * updateConditions: {\n * publish: { status: { $eq: 'draft' } },\n * archive: (data) => ({ status: { $ne: 'archived' } }),\n * }\n * }\n * ```\n */\n updateConditions?: {\n [conditionName: string]:\n | WhereConditions\n | ((data: Partial<z.infer<z.ZodObject<B>>>) => WhereConditions);\n };\n\n /**\n * @description (Optional) Opt in to accepting legacy raw `$where` on updateEntity.\n * Disabled by default: raw DynamoDB condition operators must never be\n * client-facing — an authenticated client could otherwise probe field\n * existence or guess values via the 200-vs-409 response status.\n *\n * Only enable this if you trust the caller (e.g. server-to-server) or have\n * your own validation in front of it. Prefer `updateConditions` instead.\n *\n * @default false\n */\n allowLegacyWhere?: boolean;\n}\n","import type { Entity, MonoriseEntityConfig, MutualConfig } from '../types/monorise.type';\nimport { z } from 'zod';\n\nfunction makeSchema<\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(config: MonoriseEntityConfig<T, B, C, M, CO, MO>) {\n const { baseSchema, createSchema, mutual, effect } = config;\n const { mutualSchema } = mutual || {};\n\n type FinalSchemaType = CO extends z.AnyZodObject\n ? MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & CO['shape']>\n : CO\n : MO extends z.AnyZodObject\n ? z.ZodObject<MO['shape'] & B>\n : z.ZodObject<B>;\n\n const finalSchema = z.object({\n ...baseSchema.shape,\n ...createSchema?.shape,\n ...mutualSchema?.shape,\n }) as FinalSchemaType;\n\n if (effect) {\n return effect(finalSchema) as z.ZodEffects<FinalSchemaType>;\n }\n\n return finalSchema;\n}\n\nconst createEntityConfig = <\n T extends Entity,\n B extends z.ZodRawShape,\n C extends z.ZodRawShape,\n M extends z.ZodRawShape,\n CO extends z.ZodObject<C> | undefined = undefined,\n MO extends z.ZodObject<M> | undefined = undefined,\n>(\n config: MonoriseEntityConfig<T, B, C, M, CO, MO>,\n) => ({\n ...config,\n finalSchema: makeSchema(config),\n});\n\nconst createMutualConfig = <MD extends z.ZodRawShape>(\n config: MutualConfig<MD>,\n) => config;\n\nexport { createEntityConfig, createMutualConfig };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,IAAK,SAAL,kBAAKA,YAAL;AAAK,SAAAA;AAAA,GAAA;;;ACFZ,SAAS,SAAS;AAElB,SAAS,WAOP,QAAkD;AAClD,QAAM,EAAE,YAAY,cAAc,QAAQ,OAAO,IAAI;AACrD,QAAM,EAAE,aAAa,IAAI,UAAU,CAAC;AAUpC,QAAM,cAAc,EAAE,OAAO,iDACxB,WAAW,QACX,6CAAc,QACd,6CAAc,MAClB;AAED,MAAI,QAAQ;AACV,WAAO,OAAO,WAAW;AAAA,EAC3B;AAEA,SAAO;AACT;AAEA,IAAM,qBAAqB,CAQzB,WACI,iCACD,SADC;AAAA,EAEJ,aAAa,WAAW,MAAM;AAChC;AAEA,IAAM,qBAAqB,CACzB,WACG;","names":["Entity"]}
@@ -1,4 +1,4 @@
1
- import { Entity as Entity$2, EntitySchemaMap, createEntityConfig } from '../base/index';
1
+ import { Entity as Entity$2, EntitySchemaMap, createEntityConfig, WhereConditions } from '../base/index';
2
2
  import * as hono from 'hono';
3
3
  import { Hono } from 'hono';
4
4
  import { DynamoDB, TransactWriteItemsInput, AttributeValue, TransactWriteItem, UpdateItemCommandInput } from '@aws-sdk/client-dynamodb';
@@ -141,11 +141,10 @@ declare class EntityRepository extends Repository {
141
141
  ExpressionAttributeNames?: Record<string, string>;
142
142
  ExpressionAttributeValues?: Record<string, AttributeValue>;
143
143
  }): Promise<Entity$1<T>>;
144
- adjustEntity<T extends Entity$2>(entityType: T, entityId: string, adjustments: Record<string, number>, constraints?: {
145
- [field: string]: {
146
- min?: number;
147
- max?: number;
148
- };
144
+ adjustEntity<T extends Entity$2>(entityType: T, entityId: string, adjustments: Record<string, number>, opts?: {
145
+ ConditionExpression?: string;
146
+ ExpressionAttributeNames?: Record<string, string>;
147
+ ExpressionAttributeValues?: Record<string, AttributeValue>;
149
148
  }): Promise<Entity$1<T>>;
150
149
  deleteEntity<T extends Entity$2>(entityType: T, entityId: string): Promise<void>;
151
150
  queryEntities<T extends Entity$2>(entityType: T, query: string): Promise<{
@@ -4462,26 +4461,6 @@ external_exports.object({
4462
4461
  lastKey: external_exports.string().optional()
4463
4462
  });
4464
4463
 
4465
- type WhereOperator = {
4466
- $eq: string | number | boolean;
4467
- } | {
4468
- $ne: string | number | boolean;
4469
- } | {
4470
- $gt: number;
4471
- } | {
4472
- $lt: number;
4473
- } | {
4474
- $gte: number;
4475
- } | {
4476
- $lte: number;
4477
- } | {
4478
- $exists: boolean;
4479
- } | {
4480
- $beginsWith: string;
4481
- };
4482
- type WhereClause = WhereOperator | string | number | boolean;
4483
- type WhereConditions = Record<string, WhereClause>;
4484
-
4485
4464
  declare class EntityServiceLifeCycle {
4486
4465
  private EntityConfig;
4487
4466
  private publishEvent;
@@ -4507,19 +4486,24 @@ declare class EntityService {
4507
4486
  mutualId?: string;
4508
4487
  };
4509
4488
  }) => Promise<Entity<T>>;
4510
- adjustEntity: <T extends Entity$2>({ entityType, entityId, adjustments, accountId, }: {
4489
+ adjustEntity: <T extends Entity$2>({ entityType, entityId, adjustments, accountId, condition, }: {
4511
4490
  entityType: T;
4512
4491
  entityId: string;
4513
4492
  adjustments: Record<string, number>;
4514
4493
  accountId?: string;
4494
+ condition?: string;
4515
4495
  }) => Promise<Entity<T>>;
4516
- updateEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, accountId, where, }: {
4496
+ updateEntity: <T extends Entity$2>({ entityType, entityId, entityPayload, accountId, condition, where, }: {
4517
4497
  entityType: T;
4518
4498
  entityId: string;
4519
4499
  entityPayload: Partial<EntitySchemaMap[T]>;
4520
4500
  accountId?: string | string[];
4501
+ condition?: string;
4502
+ /** @deprecated Use `condition` (named condition) instead of raw `where`. */
4521
4503
  where?: WhereConditions;
4522
4504
  }) => Promise<Entity<T>>;
4505
+ /** @deprecated Converts legacy adjustmentConstraints to condition expression opts. */
4506
+ private buildLegacyAdjustCondition;
4523
4507
  deleteEntity: <T extends Entity$2>({ entityType, entityId, accountId, }: {
4524
4508
  entityType: T;
4525
4509
  entityId: string;
@@ -4777,6 +4761,7 @@ declare const StandardErrorCode: {
4777
4761
  readonly ENTITY_ID_IS_UNDEFINED: "ENTITY_ID_IS_UNDEFINED";
4778
4762
  readonly ENTITY_IS_UNDEFINED: "ENTITY_IS_UNDEFINED";
4779
4763
  readonly ENTITY_NOT_FOUND: "ENTITY_NOT_FOUND";
4764
+ readonly INVALID_CONDITION: "INVALID_CONDITION";
4780
4765
  readonly INVALID_ENTITY_TYPE: "INVALID_ENTITY_TYPE";
4781
4766
  readonly INVALID_MUTUAL: "INVALID_MUTUAL";
4782
4767
  readonly INVALID_QUERY: "INVALID_QUERY";
@@ -175,6 +175,7 @@ var StandardErrorCode = {
175
175
  ENTITY_ID_IS_UNDEFINED: "ENTITY_ID_IS_UNDEFINED",
176
176
  ENTITY_IS_UNDEFINED: "ENTITY_IS_UNDEFINED",
177
177
  ENTITY_NOT_FOUND: "ENTITY_NOT_FOUND",
178
+ INVALID_CONDITION: "INVALID_CONDITION",
178
179
  INVALID_ENTITY_TYPE: "INVALID_ENTITY_TYPE",
179
180
  INVALID_MUTUAL: "INVALID_MUTUAL",
180
181
  INVALID_QUERY: "INVALID_QUERY",
@@ -947,22 +948,22 @@ var EntityRepository = class extends Repository {
947
948
  }
948
949
  });
949
950
  }
950
- adjustEntity(entityType, entityId, adjustments, constraints) {
951
+ adjustEntity(entityType, entityId, adjustments, opts) {
951
952
  return __async(this, null, function* () {
952
953
  const entity = new Entity(entityType, entityId);
953
- const { UpdateExpression, ConditionExpression, ExpressionAttributeNames, ExpressionAttributeValues } = this.toAdjustUpdate(adjustments, constraints);
954
+ const { UpdateExpression, ExpressionAttributeNames, ExpressionAttributeValues } = this.toAdjustUpdate(adjustments);
954
955
  const updatedAtExpression = ", #updatedAt = :updatedAt";
955
956
  ExpressionAttributeNames["#updatedAt"] = "updatedAt";
956
957
  ExpressionAttributeValues[":updatedAt"] = { S: (/* @__PURE__ */ new Date()).toISOString() };
957
- const resp = yield this.dynamodbClient.updateItem(__spreadProps(__spreadValues({
958
+ const resp = yield this.dynamodbClient.updateItem({
958
959
  TableName: this.TABLE_NAME,
959
960
  Key: entity.keys(),
960
- UpdateExpression: UpdateExpression + updatedAtExpression
961
- }, ConditionExpression && { ConditionExpression }), {
962
- ExpressionAttributeNames,
963
- ExpressionAttributeValues,
961
+ UpdateExpression: UpdateExpression + updatedAtExpression,
962
+ ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK)",
963
+ ExpressionAttributeNames: __spreadValues(__spreadValues({}, ExpressionAttributeNames), opts == null ? void 0 : opts.ExpressionAttributeNames),
964
+ ExpressionAttributeValues: __spreadValues(__spreadValues({}, ExpressionAttributeValues), opts == null ? void 0 : opts.ExpressionAttributeValues),
964
965
  ReturnValues: "ALL_NEW"
965
- }));
966
+ });
966
967
  return Entity.fromItem(resp.Attributes);
967
968
  });
968
969
  }
@@ -7301,7 +7302,16 @@ var UpdateEntityController = class {
7301
7302
  const accountId = c.req.header("account-id");
7302
7303
  const { entityType, entityId } = c.req.param();
7303
7304
  const body = yield c.req.json();
7304
- const _a = body, { $where: where } = _a, entityPayload = __objRest(_a, ["$where"]);
7305
+ const _a = body, { $condition: condition, $where: where } = _a, entityPayload = __objRest(_a, ["$condition", "$where"]);
7306
+ if (condition !== void 0) {
7307
+ if (typeof condition !== "string" || condition.trim().length === 0) {
7308
+ c.status(httpStatus8.BAD_REQUEST);
7309
+ return c.json({
7310
+ code: "API_VALIDATION_ERROR",
7311
+ message: "$condition must be a non-empty string"
7312
+ });
7313
+ }
7314
+ }
7305
7315
  const errorContext = {
7306
7316
  accountId,
7307
7317
  "req.params": c.req.param(),
@@ -7313,6 +7323,7 @@ var UpdateEntityController = class {
7313
7323
  entityId,
7314
7324
  entityPayload,
7315
7325
  accountId,
7326
+ condition,
7316
7327
  where
7317
7328
  });
7318
7329
  errorContext.entity = entity;
@@ -7331,6 +7342,10 @@ var UpdateEntityController = class {
7331
7342
  c.status(httpStatus8.NOT_FOUND);
7332
7343
  return c.json(__spreadValues({}, err.toJSON()));
7333
7344
  }
7345
+ if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7346
+ c.status(httpStatus8.BAD_REQUEST);
7347
+ return c.json(__spreadValues({}, err.toJSON()));
7348
+ }
7334
7349
  if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
7335
7350
  c.status(httpStatus8.BAD_REQUEST);
7336
7351
  return c.json(__spreadValues({}, err.toJSON()));
@@ -7357,11 +7372,21 @@ var AdjustEntityController = class {
7357
7372
  constructor(entityService) {
7358
7373
  this.entityService = entityService;
7359
7374
  this.controller = createMiddleware9((c) => __async(this, null, function* () {
7360
- var _a;
7375
+ var _b;
7361
7376
  const accountId = c.req.header("account-id") || "";
7362
7377
  const { entityType, entityId } = c.req.param();
7363
7378
  const body = yield c.req.json();
7364
- for (const [key, value] of Object.entries(body)) {
7379
+ const _a = body, { $condition: condition } = _a, adjustments = __objRest(_a, ["$condition"]);
7380
+ if (condition !== void 0) {
7381
+ if (typeof condition !== "string" || condition.trim().length === 0) {
7382
+ c.status(httpStatus9.BAD_REQUEST);
7383
+ return c.json({
7384
+ code: "API_VALIDATION_ERROR",
7385
+ message: "$condition must be a non-empty string"
7386
+ });
7387
+ }
7388
+ }
7389
+ for (const [key, value] of Object.entries(adjustments)) {
7365
7390
  if (typeof value !== "number") {
7366
7391
  c.status(httpStatus9.BAD_REQUEST);
7367
7392
  return c.json({
@@ -7374,8 +7399,9 @@ var AdjustEntityController = class {
7374
7399
  const entity = yield this.entityService.adjustEntity({
7375
7400
  entityType,
7376
7401
  entityId,
7377
- adjustments: body,
7378
- accountId
7402
+ adjustments,
7403
+ accountId,
7404
+ condition
7379
7405
  });
7380
7406
  c.status(httpStatus9.OK);
7381
7407
  return c.json(entity.toJSON());
@@ -7384,7 +7410,11 @@ var AdjustEntityController = class {
7384
7410
  c.status(httpStatus9.NOT_FOUND);
7385
7411
  return c.json(__spreadValues({}, err.toJSON()));
7386
7412
  }
7387
- if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_a = err == null ? void 0 : err.__type) == null ? void 0 : _a.includes("ConditionalCheckFailed"))) {
7413
+ if (err instanceof StandardError && err.code === StandardErrorCode.INVALID_CONDITION) {
7414
+ c.status(httpStatus9.BAD_REQUEST);
7415
+ return c.json(__spreadValues({}, err.toJSON()));
7416
+ }
7417
+ if ((err == null ? void 0 : err.name) === "ConditionalCheckFailedException" || ((_b = err == null ? void 0 : err.__type) == null ? void 0 : _b.includes("ConditionalCheckFailed"))) {
7388
7418
  c.status(httpStatus9.CONFLICT);
7389
7419
  return c.json({
7390
7420
  code: "ADJUSTMENT_CONSTRAINT_VIOLATED",
@@ -7689,6 +7719,9 @@ var UpdateMutualController = class {
7689
7719
  }
7690
7720
  };
7691
7721
 
7722
+ // services/entity.service.ts
7723
+ import { marshall as marshall6 } from "@aws-sdk/util-dynamodb";
7724
+
7692
7725
  // data/utils/build-condition-expression.ts
7693
7726
  import { marshall as marshall5 } from "@aws-sdk/util-dynamodb";
7694
7727
  function buildConditionExpression(where) {
@@ -7750,7 +7783,62 @@ function buildConditionExpression(where) {
7750
7783
  };
7751
7784
  }
7752
7785
 
7786
+ // services/resolve-condition.ts
7787
+ function resolveAdjustmentCondition(_0) {
7788
+ return __async(this, arguments, function* ({
7789
+ conditionName,
7790
+ conditions,
7791
+ adjustments,
7792
+ getEntityData
7793
+ }) {
7794
+ if (!Object.hasOwn(conditions, conditionName)) {
7795
+ throw new StandardError(
7796
+ StandardErrorCode.INVALID_CONDITION,
7797
+ `Unknown adjustment condition: '${conditionName}'`
7798
+ );
7799
+ }
7800
+ const condition = conditions[conditionName];
7801
+ let resolved;
7802
+ if (typeof condition === "function") {
7803
+ const data = yield getEntityData();
7804
+ resolved = condition(data, adjustments);
7805
+ } else {
7806
+ resolved = condition;
7807
+ }
7808
+ return buildConditionExpression(resolved);
7809
+ });
7810
+ }
7811
+ function resolveUpdateCondition(_0) {
7812
+ return __async(this, arguments, function* ({
7813
+ conditionName,
7814
+ conditions,
7815
+ getEntityData
7816
+ }) {
7817
+ if (!Object.hasOwn(conditions, conditionName)) {
7818
+ throw new StandardError(
7819
+ StandardErrorCode.INVALID_CONDITION,
7820
+ `Unknown update condition: '${conditionName}'`
7821
+ );
7822
+ }
7823
+ const condition = conditions[conditionName];
7824
+ let resolved;
7825
+ if (typeof condition === "function") {
7826
+ const data = yield getEntityData();
7827
+ resolved = condition(data);
7828
+ } else {
7829
+ resolved = condition;
7830
+ }
7831
+ return buildConditionExpression(resolved);
7832
+ });
7833
+ }
7834
+
7753
7835
  // services/entity.service.ts
7836
+ var warnedOnce = /* @__PURE__ */ new Set();
7837
+ var deprecationWarnOnce = (key, message) => {
7838
+ if (warnedOnce.has(key)) return;
7839
+ warnedOnce.add(key);
7840
+ console.warn(message);
7841
+ };
7754
7842
  var EntityService = class {
7755
7843
  constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, publishEvent2, entityServiceLifeCycle) {
7756
7844
  this.EntityConfig = EntityConfig;
@@ -7805,34 +7893,65 @@ var EntityService = class {
7805
7893
  entityType,
7806
7894
  entityId,
7807
7895
  adjustments,
7808
- accountId
7896
+ accountId,
7897
+ condition
7809
7898
  }) {
7810
- var _a, _b, _c, _d;
7811
- const rawConstraints = (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.adjustmentConstraints;
7812
- let resolvedConstraints = rawConstraints;
7813
- if (rawConstraints) {
7899
+ var _a, _b, _c;
7900
+ const entityConfig = this.EntityConfig[entityType];
7901
+ const adjustmentConditions = entityConfig == null ? void 0 : entityConfig.adjustmentConditions;
7902
+ const rawConstraints = entityConfig == null ? void 0 : entityConfig.adjustmentConstraints;
7903
+ let opts;
7904
+ if (adjustmentConditions) {
7905
+ if (!condition) {
7906
+ throw new StandardError(
7907
+ StandardErrorCode.INVALID_CONDITION,
7908
+ "Entity has adjustmentConditions defined; $condition is required for adjustEntity"
7909
+ );
7910
+ }
7911
+ opts = yield resolveAdjustmentCondition({
7912
+ conditionName: condition,
7913
+ conditions: adjustmentConditions,
7914
+ adjustments,
7915
+ getEntityData: () => __async(this, null, function* () {
7916
+ var _a2;
7917
+ const entity2 = yield this.entityRepository.getEntity(entityType, entityId);
7918
+ return (_a2 = entity2 == null ? void 0 : entity2.data) != null ? _a2 : {};
7919
+ })
7920
+ });
7921
+ } else if (condition) {
7922
+ throw new StandardError(
7923
+ StandardErrorCode.INVALID_CONDITION,
7924
+ `Entity '${entityType}' has no adjustmentConditions defined`
7925
+ );
7926
+ } else if (rawConstraints) {
7927
+ deprecationWarnOnce(
7928
+ "adjustmentConstraints",
7929
+ "[monorise] adjustmentConstraints is deprecated. Use adjustmentConditions instead."
7930
+ );
7931
+ let resolvedConstraints = rawConstraints;
7814
7932
  const hasDynamicFields = Object.values(rawConstraints).some(
7815
7933
  (c) => c.minField || c.maxField
7816
7934
  );
7817
7935
  if (hasDynamicFields) {
7818
7936
  const currentEntity = yield this.entityRepository.getEntity(entityType, entityId);
7819
- const data = (_b = currentEntity == null ? void 0 : currentEntity.data) != null ? _b : {};
7937
+ const data = (_a = currentEntity == null ? void 0 : currentEntity.data) != null ? _a : {};
7820
7938
  resolvedConstraints = {};
7821
7939
  for (const [field, constraint] of Object.entries(rawConstraints)) {
7822
7940
  const resolved = {};
7823
7941
  if (constraint.min !== void 0) resolved.min = constraint.min;
7824
7942
  if (constraint.max !== void 0) resolved.max = constraint.max;
7825
- if (constraint.minField) resolved.min = (_c = data[constraint.minField]) != null ? _c : 0;
7826
- if (constraint.maxField) resolved.max = (_d = data[constraint.maxField]) != null ? _d : Number.MAX_SAFE_INTEGER;
7943
+ if (constraint.minField) resolved.min = (_b = data[constraint.minField]) != null ? _b : 0;
7944
+ if (constraint.maxField) resolved.max = (_c = data[constraint.maxField]) != null ? _c : Number.MAX_SAFE_INTEGER;
7827
7945
  resolvedConstraints[field] = resolved;
7828
7946
  }
7829
7947
  }
7948
+ opts = this.buildLegacyAdjustCondition(adjustments, resolvedConstraints);
7830
7949
  }
7831
7950
  const entity = yield this.entityRepository.adjustEntity(
7832
7951
  entityType,
7833
7952
  entityId,
7834
7953
  adjustments,
7835
- resolvedConstraints
7954
+ opts
7836
7955
  );
7837
7956
  yield this.publishEvent({
7838
7957
  event: EVENT.CORE.ENTITY_UPDATED,
@@ -7851,9 +7970,10 @@ var EntityService = class {
7851
7970
  entityId,
7852
7971
  entityPayload,
7853
7972
  accountId,
7973
+ condition,
7854
7974
  where
7855
7975
  }) {
7856
- var _a, _b;
7976
+ var _a, _b, _c, _d;
7857
7977
  const errorContext = {};
7858
7978
  try {
7859
7979
  const entitySchema = this.EntityConfig[entityType].baseSchema;
@@ -7867,7 +7987,37 @@ var EntityService = class {
7867
7987
  const parsedEntityPayload = entitySchema.parse(entityPayload);
7868
7988
  const parsedMutualPayload = mutualSchema == null ? void 0 : mutualSchema.parse(entityPayload);
7869
7989
  errorContext.parsedMutualPayload = parsedMutualPayload;
7870
- const opts = where && Object.keys(where).length > 0 ? buildConditionExpression(where) : void 0;
7990
+ let opts;
7991
+ if (condition) {
7992
+ const updateConditions = (_b = this.EntityConfig[entityType]) == null ? void 0 : _b.updateConditions;
7993
+ if (!updateConditions) {
7994
+ throw new StandardError(
7995
+ StandardErrorCode.INVALID_CONDITION,
7996
+ `Entity '${entityType}' has no updateConditions defined`
7997
+ );
7998
+ }
7999
+ opts = yield resolveUpdateCondition({
8000
+ conditionName: condition,
8001
+ conditions: updateConditions,
8002
+ getEntityData: () => __async(this, null, function* () {
8003
+ var _a2;
8004
+ const entity2 = yield this.entityRepository.getEntity(entityType, entityId);
8005
+ return (_a2 = entity2 == null ? void 0 : entity2.data) != null ? _a2 : {};
8006
+ })
8007
+ });
8008
+ } else if (where && Object.keys(where).length > 0) {
8009
+ if (!((_c = this.EntityConfig[entityType]) == null ? void 0 : _c.allowLegacyWhere)) {
8010
+ throw new StandardError(
8011
+ StandardErrorCode.INVALID_CONDITION,
8012
+ `Entity '${entityType}' has legacy $where disabled by default. Use named conditions via $condition, or set allowLegacyWhere: true to opt in (not recommended \u2014 re-exposes condition operators to clients).`
8013
+ );
8014
+ }
8015
+ deprecationWarnOnce(
8016
+ "where",
8017
+ "[monorise] $where is deprecated. Use named conditions via $condition instead."
8018
+ );
8019
+ opts = buildConditionExpression(where);
8020
+ }
7871
8021
  const entity = yield this.entityRepository.updateEntity(
7872
8022
  entityType,
7873
8023
  entityId,
@@ -7880,7 +8030,7 @@ var EntityService = class {
7880
8030
  const byEntityId = entityId;
7881
8031
  const publishEventPromises = [];
7882
8032
  for (const [fieldKey, config] of Object.entries(
7883
- ((_b = this.EntityConfig[entityType].mutual) == null ? void 0 : _b.mutualFields) || {}
8033
+ ((_d = this.EntityConfig[entityType].mutual) == null ? void 0 : _d.mutualFields) || {}
7884
8034
  )) {
7885
8035
  const toMutualIds = config.toMutualIds;
7886
8036
  const mutualPayload = parsedMutualPayload[fieldKey];
@@ -7936,6 +8086,35 @@ var EntityService = class {
7936
8086
  });
7937
8087
  });
7938
8088
  }
8089
+ /** @deprecated Converts legacy adjustmentConstraints to condition expression opts. */
8090
+ buildLegacyAdjustCondition(adjustments, constraints) {
8091
+ const conditionParts = [];
8092
+ const names = { "#data": "data" };
8093
+ const values = {};
8094
+ for (const [field, constraint] of Object.entries(constraints)) {
8095
+ const delta = adjustments[field];
8096
+ if (delta === void 0) continue;
8097
+ const namePlaceholder = `#where_${field}`;
8098
+ names[namePlaceholder] = field;
8099
+ const fieldRef = `#data.${namePlaceholder}`;
8100
+ if (constraint.min !== void 0 && delta < 0) {
8101
+ const valKey = `:where_${field}_min_threshold`;
8102
+ conditionParts.push(`${fieldRef} >= ${valKey}`);
8103
+ values[valKey] = constraint.min - delta;
8104
+ }
8105
+ if (constraint.max !== void 0 && delta > 0) {
8106
+ const valKey = `:where_${field}_max_threshold`;
8107
+ conditionParts.push(`${fieldRef} <= ${valKey}`);
8108
+ values[valKey] = constraint.max - delta;
8109
+ }
8110
+ }
8111
+ if (conditionParts.length === 0) return void 0;
8112
+ return {
8113
+ ConditionExpression: conditionParts.join(" AND "),
8114
+ ExpressionAttributeNames: names,
8115
+ ExpressionAttributeValues: marshall6(values)
8116
+ };
8117
+ }
7939
8118
  };
7940
8119
 
7941
8120
  // services/mutual.service.ts