monorise 1.12.0 → 1.13.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.
@@ -1376,6 +1376,79 @@ var MutualRepository = class extends Repository {
1376
1376
  return mutual;
1377
1377
  });
1378
1378
  }
1379
+ /**
1380
+ * @description Resolves the live mutual and builds the TransactWriteItems that update its
1381
+ * `mutualData` on all three records, without writing them. `updateMutual` writes them on their
1382
+ * own; `TransactionService` folds them into a larger transaction. Throws `MUTUAL_IS_UNDEFINED`
1383
+ * when there is no live mutual for the pair.
1384
+ */
1385
+ prepareUpdateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1386
+ return __async(this, null, function* () {
1387
+ console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1388
+ const mutual = yield this.getMutual(
1389
+ byEntityType,
1390
+ byEntityId,
1391
+ entityType,
1392
+ entityId,
1393
+ { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1394
+ );
1395
+ console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1396
+ mutualId: mutual.mutualId,
1397
+ mainPk: mutual.mainPk,
1398
+ byFullEntityId: mutual.byFullEntityId,
1399
+ fullEntityId: mutual.fullEntityId
1400
+ });
1401
+ const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
1402
+ const toUpdateExpressions = this.toUpdate(
1403
+ __spreadValues({
1404
+ mutualUpdatedAt: currentDatetime
1405
+ }, toUpdate),
1406
+ { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1407
+ );
1408
+ console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1409
+ UpdateExpression: toUpdateExpressions.UpdateExpression,
1410
+ ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1411
+ hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
1412
+ });
1413
+ const updateExpression = {
1414
+ ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK)",
1415
+ UpdateExpression: toUpdateExpressions.UpdateExpression,
1416
+ ExpressionAttributeNames: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeNames), opts == null ? void 0 : opts.ExpressionAttributeNames),
1417
+ ExpressionAttributeValues: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeValues), opts == null ? void 0 : opts.ExpressionAttributeValues)
1418
+ };
1419
+ const TransactItems = [
1420
+ {
1421
+ Update: __spreadValues({
1422
+ TableName: this.TABLE_NAME,
1423
+ Key: mutual.mainKeys()
1424
+ }, updateExpression)
1425
+ },
1426
+ {
1427
+ Update: __spreadValues({
1428
+ TableName: this.TABLE_NAME,
1429
+ Key: {
1430
+ PK: { S: mutual.byFullEntityId },
1431
+ SK: { S: mutual.fullEntityId }
1432
+ }
1433
+ }, updateExpression)
1434
+ },
1435
+ {
1436
+ Update: __spreadValues({
1437
+ TableName: this.TABLE_NAME,
1438
+ Key: {
1439
+ PK: { S: mutual.fullEntityId },
1440
+ SK: { S: mutual.byFullEntityId }
1441
+ }
1442
+ }, updateExpression)
1443
+ }
1444
+ ];
1445
+ console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1446
+ itemCount: TransactItems.length,
1447
+ tableName: this.TABLE_NAME
1448
+ });
1449
+ return { mutual, TransactItems };
1450
+ });
1451
+ }
1379
1452
  updateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1380
1453
  return __async(this, null, function* () {
1381
1454
  var _a, _b;
@@ -1390,69 +1463,15 @@ var MutualRepository = class extends Repository {
1390
1463
  const returnUpdatedValue = (_a = opts == null ? void 0 : opts.returnUpdatedValue) != null ? _a : false;
1391
1464
  const errorContext = {};
1392
1465
  try {
1393
- console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1394
- const mutual = yield this.getMutual(
1466
+ const { TransactItems } = yield this.prepareUpdateMutual(
1395
1467
  byEntityType,
1396
1468
  byEntityId,
1397
1469
  entityType,
1398
1470
  entityId,
1399
- { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1400
- );
1401
- console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1402
- mutualId: mutual.mutualId,
1403
- mainPk: mutual.mainPk,
1404
- byFullEntityId: mutual.byFullEntityId,
1405
- fullEntityId: mutual.fullEntityId
1406
- });
1407
- const currentDatetime = (/* @__PURE__ */ new Date()).toISOString();
1408
- const toUpdateExpressions = this.toUpdate(
1409
- __spreadValues({
1410
- mutualUpdatedAt: currentDatetime
1411
- }, toUpdate),
1412
- { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1471
+ toUpdate,
1472
+ opts
1413
1473
  );
1414
- console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1415
- UpdateExpression: toUpdateExpressions.UpdateExpression,
1416
- ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1417
- hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
1418
- });
1419
- const updateExpression = {
1420
- ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK)",
1421
- UpdateExpression: toUpdateExpressions.UpdateExpression,
1422
- ExpressionAttributeNames: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeNames), opts == null ? void 0 : opts.ExpressionAttributeNames),
1423
- ExpressionAttributeValues: __spreadValues(__spreadValues({}, toUpdateExpressions.ExpressionAttributeValues), opts == null ? void 0 : opts.ExpressionAttributeValues)
1424
- };
1425
- const TransactItems = [
1426
- {
1427
- Update: __spreadValues({
1428
- TableName: this.TABLE_NAME,
1429
- Key: mutual.mainKeys()
1430
- }, updateExpression)
1431
- },
1432
- {
1433
- Update: __spreadValues({
1434
- TableName: this.TABLE_NAME,
1435
- Key: {
1436
- PK: { S: mutual.byFullEntityId },
1437
- SK: { S: mutual.fullEntityId }
1438
- }
1439
- }, updateExpression)
1440
- },
1441
- {
1442
- Update: __spreadValues({
1443
- TableName: this.TABLE_NAME,
1444
- Key: {
1445
- PK: { S: mutual.fullEntityId },
1446
- SK: { S: mutual.byFullEntityId }
1447
- }
1448
- }, updateExpression)
1449
- }
1450
- ];
1451
1474
  errorContext.TransactItems = TransactItems;
1452
- console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1453
- itemCount: TransactItems.length,
1454
- tableName: this.TABLE_NAME
1455
- });
1456
1475
  console.log("[MONORISE_DEBUG] updateMutual executing transaction...");
1457
1476
  yield this.ddbUtils.executeTransactWrite({ TransactItems });
1458
1477
  console.log("[MONORISE_DEBUG] updateMutual transaction succeeded");
@@ -1490,6 +1509,64 @@ var MutualRepository = class extends Repository {
1490
1509
  }
1491
1510
  });
1492
1511
  }
1512
+ /**
1513
+ * @description Resolves the live mutual and builds the TransactWriteItems that soft-delete it
1514
+ * (all three records get a 10-minute `expiresAt`), without writing them. `deleteMutual` writes
1515
+ * them on their own; `TransactionService` folds them into a larger transaction. Throws
1516
+ * `MUTUAL_IS_UNDEFINED` when there is no live mutual for the pair.
1517
+ */
1518
+ prepareDeleteMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1519
+ return __async(this, null, function* () {
1520
+ const mutual = yield this.getMutual(
1521
+ byEntityType,
1522
+ byEntityId,
1523
+ entityType,
1524
+ entityId,
1525
+ { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1526
+ );
1527
+ const tenMinsLater = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3 + 10 * 60);
1528
+ const expressions = {
1529
+ UpdateExpression: "SET #expiresAt = :expiresAt, #mutualUpdatedAt = :mutualUpdatedAt, #updatedAt = :mutualUpdatedAt",
1530
+ ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK) AND attribute_not_exists(#expiresAt)",
1531
+ ExpressionAttributeNames: __spreadValues({
1532
+ "#expiresAt": "expiresAt",
1533
+ "#mutualUpdatedAt": "mutualUpdatedAt",
1534
+ "#updatedAt": "updatedAt"
1535
+ }, opts == null ? void 0 : opts.ExpressionAttributeNames),
1536
+ ExpressionAttributeValues: __spreadValues({
1537
+ ":expiresAt": { N: String(tenMinsLater) },
1538
+ ":mutualUpdatedAt": { S: (/* @__PURE__ */ new Date()).toISOString() }
1539
+ }, opts == null ? void 0 : opts.ExpressionAttributeValues)
1540
+ };
1541
+ const TransactItems = [
1542
+ {
1543
+ Update: __spreadValues({
1544
+ TableName: this.TABLE_NAME,
1545
+ Key: mutual.mainKeys()
1546
+ }, expressions)
1547
+ },
1548
+ {
1549
+ Update: __spreadValues({
1550
+ TableName: this.TABLE_NAME,
1551
+ Key: {
1552
+ PK: { S: mutual.byFullEntityId },
1553
+ SK: { S: mutual.fullEntityId }
1554
+ }
1555
+ }, expressions)
1556
+ },
1557
+ {
1558
+ Update: __spreadValues({
1559
+ TableName: this.TABLE_NAME,
1560
+ Key: {
1561
+ PK: { S: mutual.fullEntityId },
1562
+ SK: { S: mutual.byFullEntityId }
1563
+ }
1564
+ }, expressions)
1565
+ }
1566
+ ];
1567
+ return { mutual, TransactItems };
1568
+ });
1569
+ }
1493
1570
  deleteMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1494
1571
  return __async(this, null, function* () {
1495
1572
  var _a;
@@ -1500,53 +1577,13 @@ var MutualRepository = class extends Repository {
1500
1577
  entityId
1501
1578
  };
1502
1579
  try {
1503
- const mutual = yield this.getMutual(
1580
+ const { mutual, TransactItems } = yield this.prepareDeleteMutual(
1504
1581
  byEntityType,
1505
1582
  byEntityId,
1506
1583
  entityType,
1507
1584
  entityId,
1508
- { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1585
+ opts
1509
1586
  );
1510
- const tenMinsLater = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3 + 10 * 60);
1511
- const expressions = {
1512
- UpdateExpression: "SET #expiresAt = :expiresAt, #mutualUpdatedAt = :mutualUpdatedAt, #updatedAt = :mutualUpdatedAt",
1513
- ConditionExpression: (opts == null ? void 0 : opts.ConditionExpression) || "attribute_exists(PK) AND attribute_not_exists(#expiresAt)",
1514
- ExpressionAttributeNames: __spreadValues({
1515
- "#expiresAt": "expiresAt",
1516
- "#mutualUpdatedAt": "mutualUpdatedAt",
1517
- "#updatedAt": "updatedAt"
1518
- }, opts == null ? void 0 : opts.ExpressionAttributeNames),
1519
- ExpressionAttributeValues: __spreadValues({
1520
- ":expiresAt": { N: String(tenMinsLater) },
1521
- ":mutualUpdatedAt": { S: (/* @__PURE__ */ new Date()).toISOString() }
1522
- }, opts == null ? void 0 : opts.ExpressionAttributeValues)
1523
- };
1524
- const TransactItems = [
1525
- {
1526
- Update: __spreadValues({
1527
- TableName: this.TABLE_NAME,
1528
- Key: mutual.mainKeys()
1529
- }, expressions)
1530
- },
1531
- {
1532
- Update: __spreadValues({
1533
- TableName: this.TABLE_NAME,
1534
- Key: {
1535
- PK: { S: mutual.byFullEntityId },
1536
- SK: { S: mutual.fullEntityId }
1537
- }
1538
- }, expressions)
1539
- },
1540
- {
1541
- Update: __spreadValues({
1542
- TableName: this.TABLE_NAME,
1543
- Key: {
1544
- PK: { S: mutual.fullEntityId },
1545
- SK: { S: mutual.byFullEntityId }
1546
- }
1547
- }, expressions)
1548
- }
1549
- ];
1550
1587
  errorContext.TransactItems = TransactItems;
1551
1588
  yield this.dynamodbClient.transactWriteItems({ TransactItems });
1552
1589
  return mutual;
@@ -7380,13 +7417,20 @@ var MutualService = class {
7380
7417
  this.publishEvent = publishEvent2;
7381
7418
  this.ddbUtils = ddbUtils;
7382
7419
  this.entityServiceLifeCycle = entityServiceLifeCycle;
7383
- this.createMutual = (_0) => __async(this, [_0], function* ({
7420
+ /**
7421
+ * @description Everything `createMutual` does before it writes: validates the payload, reads
7422
+ * both entities, checks no live mutual exists, and builds the TransactWriteItems (plus the
7423
+ * `asEntity` projection's items, when there is one). Nothing is written. `createMutual` commits
7424
+ * the items on their own; `TransactionService` folds them into a larger transaction. Either
7425
+ * caller then runs `afterCreateEntityHook` for `entity` (when set) and publishes MUTUAL_CREATED
7426
+ * once the write has committed.
7427
+ */
7428
+ this.prepareCreateMutual = (_0) => __async(this, [_0], function* ({
7384
7429
  byEntityType,
7385
7430
  byEntityId,
7386
7431
  entityType,
7387
7432
  entityId,
7388
7433
  mutualPayload,
7389
- accountId,
7390
7434
  options = {}
7391
7435
  }) {
7392
7436
  var _a, _b, _c;
@@ -7481,13 +7525,25 @@ var MutualService = class {
7481
7525
  })
7482
7526
  );
7483
7527
  }
7484
- const createTransactItems = [...mutualTransactions, ...entityTransactions];
7485
- errorContext.createTransactItems = createTransactItems;
7528
+ const transactItems = [...mutualTransactions, ...entityTransactions];
7529
+ errorContext.createTransactItems = transactItems;
7530
+ return { mutual, entity, transactItems, parsedMutualPayload };
7531
+ });
7532
+ this.createMutual = (params) => __async(this, null, function* () {
7533
+ const {
7534
+ byEntityType,
7535
+ byEntityId,
7536
+ entityType,
7537
+ entityId,
7538
+ mutualPayload,
7539
+ accountId
7540
+ } = params;
7541
+ const { mutual, entity, transactItems, parsedMutualPayload } = yield this.prepareCreateMutual(params);
7486
7542
  console.log("[MONORISE_DEBUG] createMutual executing transaction:", {
7487
- transactItemCount: createTransactItems.length
7543
+ transactItemCount: transactItems.length
7488
7544
  });
7489
7545
  yield this.ddbUtils.executeTransactWrite({
7490
- TransactItems: createTransactItems
7546
+ TransactItems: transactItems
7491
7547
  });
7492
7548
  console.log("[MONORISE_DEBUG] createMutual transaction succeeded");
7493
7549
  if (entity) {
@@ -7516,6 +7572,62 @@ var MutualService = class {
7516
7572
  console.log("[MONORISE_DEBUG] createMutual service complete");
7517
7573
  return { mutual, eventPayload };
7518
7574
  });
7575
+ /**
7576
+ * @description Reads the live mutual for a pair, with its stored `data` and `mutualData` —
7577
+ * the same read `updateMutual` returns with `returnUpdatedValue`. Throws `MUTUAL_IS_UNDEFINED`
7578
+ * when there is none.
7579
+ */
7580
+ this.getMutual = ({
7581
+ byEntityType,
7582
+ byEntityId,
7583
+ entityType,
7584
+ entityId
7585
+ }) => this.mutualRepository.getMutual(
7586
+ byEntityType,
7587
+ byEntityId,
7588
+ entityType,
7589
+ entityId
7590
+ );
7591
+ /**
7592
+ * @description Everything `updateMutual` does before it writes: validates the patch with the
7593
+ * same schema, resolves the live mutual and builds the TransactWriteItems. Nothing is written —
7594
+ * for `TransactionService`, which publishes the same MUTUAL_UPDATED event once its transaction
7595
+ * commits. Throws `MUTUAL_NOT_FOUND` when there is no live mutual for the pair.
7596
+ */
7597
+ this.prepareUpdateMutual = (_0) => __async(this, [_0], function* ({
7598
+ byEntityType,
7599
+ byEntityId,
7600
+ entityType,
7601
+ entityId,
7602
+ mutualPayload,
7603
+ options
7604
+ }) {
7605
+ const parsedMutualPayload = this.getMutualUpdateSchema(
7606
+ byEntityType,
7607
+ entityType
7608
+ ).parse(mutualPayload);
7609
+ try {
7610
+ const { mutual, TransactItems } = yield this.mutualRepository.prepareUpdateMutual(
7611
+ byEntityType,
7612
+ byEntityId,
7613
+ entityType,
7614
+ entityId,
7615
+ { mutualData: parsedMutualPayload },
7616
+ options
7617
+ );
7618
+ return { mutual, TransactItems, parsedMutualPayload };
7619
+ } catch (err) {
7620
+ if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
7621
+ throw new StandardError(
7622
+ StandardErrorCode.MUTUAL_NOT_FOUND,
7623
+ "Mutual not found",
7624
+ err,
7625
+ { byEntityType, byEntityId, entityType, entityId }
7626
+ );
7627
+ }
7628
+ throw err;
7629
+ }
7630
+ });
7519
7631
  this.updateMutual = (_0) => __async(this, [_0], function* ({
7520
7632
  byEntityType,
7521
7633
  byEntityId,
@@ -7525,7 +7637,6 @@ var MutualService = class {
7525
7637
  accountId,
7526
7638
  options
7527
7639
  }) {
7528
- var _a, _b;
7529
7640
  console.log("[MONORISE_DEBUG] updateMutual service start:", {
7530
7641
  byEntityType,
7531
7642
  byEntityId,
@@ -7534,9 +7645,7 @@ var MutualService = class {
7534
7645
  mutualPayload,
7535
7646
  options
7536
7647
  });
7537
- const mutualFieldConfig = this.getMutualFieldConfig(byEntityType, entityType);
7538
- const asEntityStorageSchema = (mutualFieldConfig == null ? void 0 : mutualFieldConfig.asEntity) ? (_a = mutualFieldConfig.asEntity.createSchema) != null ? _a : mutualFieldConfig.asEntity.baseSchema : void 0;
7539
- const schema = (_b = asEntityStorageSchema != null ? asEntityStorageSchema : mutualFieldConfig == null ? void 0 : mutualFieldConfig.mutualDataSchema) != null ? _b : external_exports.record(external_exports.string(), external_exports.any());
7648
+ const schema = this.getMutualUpdateSchema(byEntityType, entityType);
7540
7649
  console.log("[MONORISE_DEBUG] updateMutual schema resolved");
7541
7650
  const parsedMutualPayload = schema.parse(mutualPayload);
7542
7651
  console.log("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
@@ -7567,6 +7676,36 @@ var MutualService = class {
7567
7676
  console.log("[MONORISE_DEBUG] updateMutual service complete");
7568
7677
  return mutual;
7569
7678
  });
7679
+ /**
7680
+ * @description Resolves the live mutual and builds the TransactWriteItems that delete it,
7681
+ * without writing — for `TransactionService`. Throws `MUTUAL_NOT_FOUND` (same as
7682
+ * `deleteMutual`) when there is no live mutual for the pair.
7683
+ */
7684
+ this.prepareDeleteMutual = (_0) => __async(this, [_0], function* ({
7685
+ byEntityType,
7686
+ byEntityId,
7687
+ entityType,
7688
+ entityId
7689
+ }) {
7690
+ try {
7691
+ return yield this.mutualRepository.prepareDeleteMutual(
7692
+ byEntityType,
7693
+ byEntityId,
7694
+ entityType,
7695
+ entityId
7696
+ );
7697
+ } catch (err) {
7698
+ if (err instanceof StandardError && err.code === StandardErrorCode.MUTUAL_IS_UNDEFINED) {
7699
+ throw new StandardError(
7700
+ StandardErrorCode.MUTUAL_NOT_FOUND,
7701
+ "Mutual not found",
7702
+ err,
7703
+ { byEntityType, byEntityId, entityType, entityId }
7704
+ );
7705
+ }
7706
+ throw err;
7707
+ }
7708
+ });
7570
7709
  this.deleteMutual = (_0) => __async(this, [_0], function* ({
7571
7710
  byEntityType,
7572
7711
  byEntityId,
@@ -7627,6 +7766,19 @@ var MutualService = class {
7627
7766
  var _a;
7628
7767
  return (_a = this.getMutualFieldConfig(byEntityType, entityType)) == null ? void 0 : _a.mutualDataSchema;
7629
7768
  }
7769
+ // Same `asEntity`-aware narrowing as `createMutual` — an update to an `asEntity` mutual must
7770
+ // not re-introduce the target entity's own further `mutualFields` keys into stored
7771
+ // `mutualData` any more than the initial create does (see `createMutual`'s own comment).
7772
+ // Shared by `updateMutual` and `prepareUpdateMutual` so both validate a patch identically.
7773
+ getMutualUpdateSchema(byEntityType, entityType) {
7774
+ var _a, _b;
7775
+ const mutualFieldConfig = this.getMutualFieldConfig(
7776
+ byEntityType,
7777
+ entityType
7778
+ );
7779
+ const asEntityStorageSchema = (mutualFieldConfig == null ? void 0 : mutualFieldConfig.asEntity) ? (_a = mutualFieldConfig.asEntity.createSchema) != null ? _a : mutualFieldConfig.asEntity.baseSchema : void 0;
7780
+ return (_b = asEntityStorageSchema != null ? asEntityStorageSchema : mutualFieldConfig == null ? void 0 : mutualFieldConfig.mutualDataSchema) != null ? _b : external_exports.record(external_exports.string(), external_exports.any());
7781
+ }
7630
7782
  };
7631
7783
 
7632
7784
  // processors/mutual-processor.ts
@@ -10095,7 +10247,7 @@ var ExecuteTransactionController = class {
10095
10247
  }
10096
10248
  if (err instanceof StandardError) {
10097
10249
  const code = err.code;
10098
- if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND) {
10250
+ if (code === StandardErrorCode.ENTITY_IS_UNDEFINED || code === StandardErrorCode.ENTITY_NOT_FOUND || code === StandardErrorCode.MUTUAL_NOT_FOUND) {
10099
10251
  c.status(httpStatus16.NOT_FOUND);
10100
10252
  return c.json(__spreadValues({}, err.toJSON()));
10101
10253
  }
@@ -10103,7 +10255,7 @@ var ExecuteTransactionController = class {
10103
10255
  c.status(httpStatus16.BAD_REQUEST);
10104
10256
  return c.json(__spreadValues({}, err.toJSON()));
10105
10257
  }
10106
- if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
10258
+ if (code === StandardErrorCode.TRANSACTION_FAILED || code === StandardErrorCode.CONDITIONAL_CHECK_FAILED || code === StandardErrorCode.UNIQUE_VALUE_EXISTS || code === StandardErrorCode.MUTUAL_EXISTS) {
10107
10259
  c.status(httpStatus16.CONFLICT);
10108
10260
  return c.json(__spreadValues({}, err.toJSON()));
10109
10261
  }
@@ -10218,7 +10370,7 @@ import { TransactionCanceledException as TransactionCanceledException5 } from "@
10218
10370
  import { ulid as ulid7 } from "ulid";
10219
10371
  var MAX_TRANSACTION_ITEMS = 100;
10220
10372
  var TransactionService = class {
10221
- constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils) {
10373
+ constructor(EntityConfig, EmailAuthEnabledEntities, entityRepository, dynamodbClient, publishEvent2, entityServiceLifeCycle, eventUtils, mutualService) {
10222
10374
  this.EntityConfig = EntityConfig;
10223
10375
  this.EmailAuthEnabledEntities = EmailAuthEnabledEntities;
10224
10376
  this.entityRepository = entityRepository;
@@ -10226,6 +10378,7 @@ var TransactionService = class {
10226
10378
  this.publishEvent = publishEvent2;
10227
10379
  this.entityServiceLifeCycle = entityServiceLifeCycle;
10228
10380
  this.eventUtils = eventUtils;
10381
+ this.mutualService = mutualService;
10229
10382
  this.executeTransaction = (operations, accountId) => __async(this, null, function* () {
10230
10383
  var _a;
10231
10384
  if (!operations || operations.length === 0) {
@@ -10240,9 +10393,11 @@ var TransactionService = class {
10240
10393
  const processed = yield Promise.all(
10241
10394
  operations.map((op) => this.processOperation(op, accountId))
10242
10395
  );
10243
- for (const { items, events, resultEntry } of processed) {
10396
+ const afterCommits = [];
10397
+ for (const { items, events, afterCommit, resultEntry } of processed) {
10244
10398
  allTransactItems.push(...items);
10245
10399
  pendingEvents.push(...events);
10400
+ if (afterCommit) afterCommits.push(afterCommit);
10246
10401
  resultEntries.push(resultEntry);
10247
10402
  }
10248
10403
  if (allTransactItems.length > MAX_TRANSACTION_ITEMS) {
@@ -10290,8 +10445,53 @@ var TransactionService = class {
10290
10445
  } catch (e) {
10291
10446
  }
10292
10447
  }
10448
+ if (entry.operation === "updateMutual" && this.mutualService) {
10449
+ try {
10450
+ const mutual = yield this.mutualService.getMutual({
10451
+ byEntityType: entry.byEntityType,
10452
+ byEntityId: entry.byEntityId,
10453
+ entityType: entry.entityType,
10454
+ entityId: entry.entityId
10455
+ });
10456
+ entry.mutualId = mutual.mutualId;
10457
+ entry.data = mutual.data;
10458
+ entry.mutualData = mutual.mutualData;
10459
+ entry.createdAt = mutual.createdAt;
10460
+ entry.updatedAt = mutual.updatedAt;
10461
+ entry.mutualUpdatedAt = mutual.mutualUpdatedAt;
10462
+ } catch (e) {
10463
+ }
10464
+ }
10293
10465
  }));
10294
10466
  yield Promise.all(readPromises);
10467
+ const committedEntityData = /* @__PURE__ */ new Map();
10468
+ for (const entry of resultEntries) {
10469
+ if ((entry.operation === "updateEntity" || entry.operation === "adjustEntity") && entry.data) {
10470
+ committedEntityData.set(
10471
+ `${entry.entityType}#${entry.entityId}`,
10472
+ entry.data
10473
+ );
10474
+ }
10475
+ }
10476
+ for (const entry of resultEntries) {
10477
+ if (entry.operation === "createMutual" || entry.operation === "updateMutual") {
10478
+ const fresh = committedEntityData.get(
10479
+ `${entry.entityType}#${entry.entityId}`
10480
+ );
10481
+ if (fresh) entry.data = fresh;
10482
+ }
10483
+ }
10484
+ const afterCommitResults = yield Promise.allSettled(
10485
+ afterCommits.map((run) => run())
10486
+ );
10487
+ for (const result of afterCommitResults) {
10488
+ if (result.status === "rejected") {
10489
+ console.error(
10490
+ "[monorise] Post-commit hook failed after transaction commit:",
10491
+ { reason: result.reason }
10492
+ );
10493
+ }
10494
+ }
10295
10495
  const eventResults = yield Promise.allSettled(
10296
10496
  pendingEvents.map((ev) => this.publishEvent(ev))
10297
10497
  );
@@ -10385,6 +10585,12 @@ var TransactionService = class {
10385
10585
  }
10386
10586
  };
10387
10587
  }
10588
+ case "createMutual":
10589
+ return this.processCreateMutual(op, accountId);
10590
+ case "updateMutual":
10591
+ return this.processUpdateMutual(op, accountId);
10592
+ case "deleteMutual":
10593
+ return this.processDeleteMutual(op, accountId);
10388
10594
  default:
10389
10595
  throw new StandardError(
10390
10596
  StandardErrorCode.TRANSACTION_INVALID_OPERATION,
@@ -10393,6 +10599,171 @@ var TransactionService = class {
10393
10599
  }
10394
10600
  });
10395
10601
  }
10602
+ // Same validation, reads and records as MutualService.createMutual — only
10603
+ // the write is deferred into this transaction. A mutual created here
10604
+ // publishes the same MUTUAL_CREATED event, and an asEntity mutual's
10605
+ // projection is written in the same transaction.
10606
+ processCreateMutual(op, accountId) {
10607
+ return __async(this, null, function* () {
10608
+ var _a, _b;
10609
+ this.assertMutualOperation(op);
10610
+ const mutualPayload = (_a = op.payload) != null ? _a : {};
10611
+ const { mutual, entity, transactItems, parsedMutualPayload } = yield this.requireMutualService(op).prepareCreateMutual({
10612
+ byEntityType: op.byEntityType,
10613
+ byEntityId: op.byEntityId,
10614
+ entityType: op.entityType,
10615
+ entityId: op.entityId,
10616
+ mutualPayload
10617
+ });
10618
+ return {
10619
+ items: transactItems,
10620
+ events: [
10621
+ {
10622
+ event: EVENT.CORE.MUTUAL_CREATED(op.byEntityType, op.entityType),
10623
+ payload: {
10624
+ byEntityType: op.byEntityType,
10625
+ byEntityId: op.byEntityId,
10626
+ entityType: op.entityType,
10627
+ entityId: op.entityId,
10628
+ parsedMutualPayload,
10629
+ accountId,
10630
+ publishedAt: (_b = mutual.createdAt) != null ? _b : (/* @__PURE__ */ new Date()).toISOString()
10631
+ }
10632
+ }
10633
+ ],
10634
+ afterCommit: entity ? () => this.entityServiceLifeCycle.afterCreateEntityHook(
10635
+ entity,
10636
+ mutualPayload,
10637
+ accountId
10638
+ ) : void 0,
10639
+ resultEntry: {
10640
+ operation: "createMutual",
10641
+ byEntityType: op.byEntityType,
10642
+ byEntityId: op.byEntityId,
10643
+ entityType: op.entityType,
10644
+ entityId: op.entityId,
10645
+ mutualId: mutual.mutualId,
10646
+ data: mutual.data,
10647
+ mutualData: mutual.mutualData,
10648
+ createdAt: mutual.createdAt,
10649
+ updatedAt: mutual.updatedAt,
10650
+ mutualUpdatedAt: mutual.mutualUpdatedAt
10651
+ }
10652
+ };
10653
+ });
10654
+ }
10655
+ // Same validation and records as MutualService.updateMutual, and the same
10656
+ // MUTUAL_UPDATED event. The stored values are read back after the commit
10657
+ // (Phase 4), as a standalone PATCH /mutual/... returns them.
10658
+ processUpdateMutual(op, accountId) {
10659
+ return __async(this, null, function* () {
10660
+ this.assertMutualOperation(op);
10661
+ if (!op.payload || typeof op.payload !== "object") {
10662
+ throw new StandardError(
10663
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10664
+ "'updateMutual' requires a payload object"
10665
+ );
10666
+ }
10667
+ const { mutual, TransactItems, parsedMutualPayload } = yield this.requireMutualService(op).prepareUpdateMutual({
10668
+ byEntityType: op.byEntityType,
10669
+ byEntityId: op.byEntityId,
10670
+ entityType: op.entityType,
10671
+ entityId: op.entityId,
10672
+ mutualPayload: op.payload
10673
+ });
10674
+ return {
10675
+ items: TransactItems,
10676
+ events: [
10677
+ {
10678
+ event: EVENT.CORE.MUTUAL_UPDATED(op.byEntityType, op.entityType),
10679
+ payload: {
10680
+ byEntityType: op.byEntityType,
10681
+ byEntityId: op.byEntityId,
10682
+ entityType: op.entityType,
10683
+ entityId: op.entityId,
10684
+ parsedMutualPayload,
10685
+ updatedByAccountId: accountId
10686
+ }
10687
+ }
10688
+ ],
10689
+ resultEntry: {
10690
+ operation: "updateMutual",
10691
+ byEntityType: op.byEntityType,
10692
+ byEntityId: op.byEntityId,
10693
+ entityType: op.entityType,
10694
+ entityId: op.entityId,
10695
+ mutualId: mutual.mutualId
10696
+ }
10697
+ };
10698
+ });
10699
+ }
10700
+ // Same soft delete as MutualService.deleteMutual, and the same event.
10701
+ processDeleteMutual(op, accountId) {
10702
+ return __async(this, null, function* () {
10703
+ this.assertMutualOperation(op);
10704
+ const { mutual, TransactItems } = yield this.requireMutualService(
10705
+ op
10706
+ ).prepareDeleteMutual({
10707
+ byEntityType: op.byEntityType,
10708
+ byEntityId: op.byEntityId,
10709
+ entityType: op.entityType,
10710
+ entityId: op.entityId
10711
+ });
10712
+ return {
10713
+ items: TransactItems,
10714
+ events: [
10715
+ {
10716
+ event: EVENT.CORE.MUTUAL_UPDATED(op.byEntityType, op.entityType),
10717
+ payload: {
10718
+ byEntityType: op.byEntityType,
10719
+ byEntityId: op.byEntityId,
10720
+ entityType: op.entityType,
10721
+ entityId: op.entityId,
10722
+ deletedByAccountId: accountId
10723
+ }
10724
+ }
10725
+ ],
10726
+ resultEntry: {
10727
+ operation: "deleteMutual",
10728
+ byEntityType: op.byEntityType,
10729
+ byEntityId: op.byEntityId,
10730
+ entityType: op.entityType,
10731
+ entityId: op.entityId,
10732
+ mutualId: mutual.mutualId
10733
+ }
10734
+ };
10735
+ });
10736
+ }
10737
+ assertMutualOperation(op) {
10738
+ for (const type of [op.byEntityType, op.entityType]) {
10739
+ if (!this.EntityConfig[type]) {
10740
+ throw new StandardError(
10741
+ StandardErrorCode.INVALID_ENTITY_TYPE,
10742
+ `Unknown entity type: '${type}'`
10743
+ );
10744
+ }
10745
+ }
10746
+ for (const [field, id] of [
10747
+ ["byEntityId", op.byEntityId],
10748
+ ["entityId", op.entityId]
10749
+ ]) {
10750
+ if (typeof id !== "string" || id.length === 0) {
10751
+ throw new StandardError(
10752
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10753
+ `'${op.operation}' requires a non-empty ${field}`
10754
+ );
10755
+ }
10756
+ }
10757
+ }
10758
+ requireMutualService(op) {
10759
+ if (!this.mutualService) {
10760
+ throw new StandardError(
10761
+ StandardErrorCode.TRANSACTION_INVALID_OPERATION,
10762
+ `'${op.operation}' needs a TransactionService constructed with a MutualService`
10763
+ );
10764
+ }
10765
+ return this.mutualService;
10766
+ }
10396
10767
  buildCreateItems(op) {
10397
10768
  return __async(this, null, function* () {
10398
10769
  const config = this.EntityConfig[op.entityType];
@@ -10869,7 +11240,8 @@ var DependencyContainer = class {
10869
11240
  this.dynamodbClient,
10870
11241
  this.publishEvent,
10871
11242
  this.entityServiceLifeCycle,
10872
- this.eventUtils
11243
+ this.eventUtils,
11244
+ this.mutualService
10873
11245
  );
10874
11246
  }
10875
11247
  get executeTransactionController() {
@@ -10915,6 +11287,30 @@ var transactional = {
10915
11287
  operation: "deleteEntity",
10916
11288
  entityType,
10917
11289
  entityId
11290
+ }),
11291
+ // Same argument order as the client's standalone createMutual / editMutual
11292
+ // / deleteMutual.
11293
+ createMutual: (byEntityType, entityType, byEntityId, entityId, payload) => __spreadValues({
11294
+ operation: "createMutual",
11295
+ byEntityType,
11296
+ byEntityId,
11297
+ entityType,
11298
+ entityId
11299
+ }, payload && { payload }),
11300
+ updateMutual: (byEntityType, entityType, byEntityId, entityId, payload) => ({
11301
+ operation: "updateMutual",
11302
+ byEntityType,
11303
+ byEntityId,
11304
+ entityType,
11305
+ entityId,
11306
+ payload
11307
+ }),
11308
+ deleteMutual: (byEntityType, entityType, byEntityId, entityId) => ({
11309
+ operation: "deleteMutual",
11310
+ byEntityType,
11311
+ byEntityId,
11312
+ entityType,
11313
+ entityId
10918
11314
  })
10919
11315
  };
10920
11316