monorise 2.0.0-dev.1 → 2.0.0-dev.3

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.
@@ -180,11 +180,13 @@ var createRouteGuards = (entityConfig) => {
180
180
  `adjust on these fields of '${entityType}'`
181
181
  );
182
182
  const checkSearch = (key, entityType) => {
183
- var _a, _b;
183
+ var _a;
184
+ const config = entityConfig[entityType];
185
+ const fields = (config == null ? void 0 : config.search) ? config.search.fields.map(({ field }) => field) : (_a = config == null ? void 0 : config.searchableFields) != null ? _a : [];
184
186
  return checkFields(
185
187
  key,
186
188
  key.access.entity(entityType).read,
187
- ((_b = (_a = entityConfig[entityType]) == null ? void 0 : _a.searchableFields) != null ? _b : []).map(String),
189
+ fields.map(String),
188
190
  `search on '${entityType}', which matches these fields it cannot read`
189
191
  );
190
192
  };
@@ -622,6 +624,7 @@ var StandardErrorCode = {
622
624
  REPLICATION_ERROR: "REPLICATION_ERROR",
623
625
  RETRYABLE_MUTUAL_LOCK_CONFLICT: "RETRYABLE_MUTUAL_LOCK_CONFLICT",
624
626
  TAG_IS_UNDEFINED: "TAG_IS_UNDEFINED",
627
+ TRANSACTION_CONFLICT: "TRANSACTION_CONFLICT",
625
628
  TRANSACTION_EMPTY: "TRANSACTION_EMPTY",
626
629
  TRANSACTION_FAILED: "TRANSACTION_FAILED",
627
630
  TRANSACTION_INVALID_OPERATION: "TRANSACTION_INVALID_OPERATION",
@@ -750,6 +753,16 @@ var Repository = class {
750
753
  };
751
754
 
752
755
  // data/Entity.ts
756
+ var transactionConflict = (err) => {
757
+ var _a;
758
+ return ((_a = err.CancellationReasons) == null ? void 0 : _a.some(
759
+ (reason) => reason.Code === "TransactionConflict"
760
+ )) ? new StandardError(
761
+ StandardErrorCode.TRANSACTION_CONFLICT,
762
+ "Another request wrote the same data at the same time; retry",
763
+ err
764
+ ) : void 0;
765
+ };
753
766
  var Entity = class _Entity extends Item {
754
767
  constructor(entityType, entityId, data = {}, _createdAt, _updatedAt, _expiresAt) {
755
768
  super();
@@ -1147,6 +1160,8 @@ var EntityRepository = class extends Repository {
1147
1160
  );
1148
1161
  }
1149
1162
  }
1163
+ const conflict = transactionConflict(err);
1164
+ if (conflict) throw conflict;
1150
1165
  }
1151
1166
  throw err;
1152
1167
  }
@@ -1351,6 +1366,8 @@ var EntityRepository = class extends Repository {
1351
1366
  );
1352
1367
  }
1353
1368
  }
1369
+ const conflict = transactionConflict(err);
1370
+ if (conflict) throw conflict;
1354
1371
  }
1355
1372
  throw err;
1356
1373
  }
@@ -1454,12 +1471,10 @@ var EntityRepository = class extends Repository {
1454
1471
  const filteredItems = [];
1455
1472
  const { searchableFields } = this.EntityConfig[entityType];
1456
1473
  for (const item of results.items) {
1457
- const searchTerm = (searchableFields != null ? searchableFields : []).map(
1458
- (field) => {
1459
- var _a;
1460
- return (_a = item.data[field]) == null ? void 0 : _a.toLowerCase();
1461
- }
1462
- ).join(" ");
1474
+ const searchTerm = (searchableFields != null ? searchableFields : []).map((field) => {
1475
+ const value = item.data[field];
1476
+ return (Array.isArray(value) ? value : [value]).filter((v) => typeof v === "string" || typeof v === "number").map((v) => String(v).toLowerCase()).join(" ");
1477
+ }).join(" ");
1463
1478
  const isMatched = queryRegex.test(searchTerm);
1464
1479
  if (isMatched) {
1465
1480
  filteredItems.push(item);
@@ -1491,6 +1506,14 @@ var PROJECTION_EXPRESSION = {
1491
1506
  MUTUAL_DATA_ONLY: "byEntityType, byEntityId, entityType, entityId, mutualId, mutualData"
1492
1507
  };
1493
1508
 
1509
+ // helpers/debug.ts
1510
+ var OFF = /* @__PURE__ */ new Set(["", "0", "false", "off", "no"]);
1511
+ var debugLog = (...args) => {
1512
+ var _a;
1513
+ const flag = (_a = process.env.MONORISE_DEBUG) == null ? void 0 : _a.trim().toLowerCase();
1514
+ if (flag !== void 0 && !OFF.has(flag)) console.log(...args);
1515
+ };
1516
+
1494
1517
  // data/Mutual.ts
1495
1518
  var Mutual = class _Mutual {
1496
1519
  constructor(byEntityType, byEntityId, byData, entityType, entityId, data, mutualData, mutualId, _createdAt, _updatedAt, _mutualUpdatedAt, _expiresAt) {
@@ -1670,7 +1693,7 @@ var MutualRepository = class extends Repository {
1670
1693
  getMutual(byEntityType, byEntityId, entityType, entityId, opts) {
1671
1694
  return __async(this, null, function* () {
1672
1695
  var _a, _b, _c, _d, _e, _f;
1673
- console.log("[MONORISE_DEBUG] getMutual start:", {
1696
+ debugLog("[MONORISE_DEBUG] getMutual start:", {
1674
1697
  byEntityType,
1675
1698
  byEntityId,
1676
1699
  entityType,
@@ -1686,7 +1709,7 @@ var MutualRepository = class extends Repository {
1686
1709
  {},
1687
1710
  {}
1688
1711
  );
1689
- console.log("[MONORISE_DEBUG] getMutual querying:", {
1712
+ debugLog("[MONORISE_DEBUG] getMutual querying:", {
1690
1713
  byFullEntityId: mutual.byFullEntityId,
1691
1714
  fullEntityId: mutual.fullEntityId,
1692
1715
  tableName: this.TABLE_NAME
@@ -1707,7 +1730,7 @@ var MutualRepository = class extends Repository {
1707
1730
  },
1708
1731
  Limit: 1
1709
1732
  });
1710
- console.log("[MONORISE_DEBUG] getMutual query result:", {
1733
+ debugLog("[MONORISE_DEBUG] getMutual query result:", {
1711
1734
  hasItems: !!((_a = resp.Items) == null ? void 0 : _a.length),
1712
1735
  itemCount: (_c = (_b = resp.Items) == null ? void 0 : _b.length) != null ? _c : 0,
1713
1736
  hasLastEvaluatedKey: !!resp.LastEvaluatedKey
@@ -1722,12 +1745,12 @@ var MutualRepository = class extends Repository {
1722
1745
  });
1723
1746
  mutualMetadata = Mutual.fromItem(respMetadataMutual.Item);
1724
1747
  }
1725
- console.log("[MONORISE_DEBUG] getMutual fromItem:", {
1748
+ debugLog("[MONORISE_DEBUG] getMutual fromItem:", {
1726
1749
  hasMutualMetadata: !!mutualMetadata,
1727
1750
  hasFirstItem: !!((_e = resp.Items) == null ? void 0 : _e[0])
1728
1751
  });
1729
1752
  const result = mutualMetadata || Mutual.fromItem((_f = resp.Items) == null ? void 0 : _f[0]);
1730
- console.log("[MONORISE_DEBUG] getMutual complete:", {
1753
+ debugLog("[MONORISE_DEBUG] getMutual complete:", {
1731
1754
  mutualId: result.mutualId,
1732
1755
  byEntityType: result.byEntityType,
1733
1756
  entityType: result.entityType
@@ -1738,7 +1761,7 @@ var MutualRepository = class extends Repository {
1738
1761
  checkMutualExist(byEntityType, byEntityId, entityType, entityId) {
1739
1762
  return __async(this, null, function* () {
1740
1763
  var _a, _b;
1741
- console.log("[MONORISE_DEBUG] checkMutualExist:", {
1764
+ debugLog("[MONORISE_DEBUG] checkMutualExist:", {
1742
1765
  byEntityType,
1743
1766
  byEntityId,
1744
1767
  entityType,
@@ -1758,7 +1781,7 @@ var MutualRepository = class extends Repository {
1758
1781
  Key: mutual.subKeys(),
1759
1782
  ProjectionExpression: "PK, SK, expiresAt"
1760
1783
  });
1761
- console.log("[MONORISE_DEBUG] checkMutualExist result:", {
1784
+ debugLog("[MONORISE_DEBUG] checkMutualExist result:", {
1762
1785
  hasItem: !!resp.Item,
1763
1786
  hasExpiresAt: !!((_a = resp.Item) == null ? void 0 : _a.expiresAt)
1764
1787
  });
@@ -1772,7 +1795,7 @@ var MutualRepository = class extends Repository {
1772
1795
  });
1773
1796
  }
1774
1797
  createMutualTransactItems(mutual, opts) {
1775
- console.log("[MONORISE_DEBUG] createMutualTransactItems:", {
1798
+ debugLog("[MONORISE_DEBUG] createMutualTransactItems:", {
1776
1799
  mutualId: mutual.mutualId,
1777
1800
  byEntityType: mutual.byEntityType,
1778
1801
  byEntityId: mutual.byEntityId,
@@ -1860,7 +1883,7 @@ var MutualRepository = class extends Repository {
1860
1883
  */
1861
1884
  prepareUpdateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1862
1885
  return __async(this, null, function* () {
1863
- console.log("[MONORISE_DEBUG] updateMutual fetching mutual...");
1886
+ debugLog("[MONORISE_DEBUG] updateMutual fetching mutual...");
1864
1887
  const mutual = yield this.getMutual(
1865
1888
  byEntityType,
1866
1889
  byEntityId,
@@ -1868,7 +1891,7 @@ var MutualRepository = class extends Repository {
1868
1891
  entityId,
1869
1892
  { ProjectionExpression: PROJECTION_EXPRESSION.NO_DATA }
1870
1893
  );
1871
- console.log("[MONORISE_DEBUG] updateMutual mutual found:", {
1894
+ debugLog("[MONORISE_DEBUG] updateMutual mutual found:", {
1872
1895
  mutualId: mutual.mutualId,
1873
1896
  mainPk: mutual.mainPk,
1874
1897
  byFullEntityId: mutual.byFullEntityId,
@@ -1881,7 +1904,7 @@ var MutualRepository = class extends Repository {
1881
1904
  }, toUpdate),
1882
1905
  { maxLevel: opts == null ? void 0 : opts.maxObjectUpdateLevel }
1883
1906
  );
1884
- console.log("[MONORISE_DEBUG] updateMutual update expression:", {
1907
+ debugLog("[MONORISE_DEBUG] updateMutual update expression:", {
1885
1908
  UpdateExpression: toUpdateExpressions.UpdateExpression,
1886
1909
  ExpressionAttributeNames: toUpdateExpressions.ExpressionAttributeNames,
1887
1910
  hasExpressionAttributeValues: !!toUpdateExpressions.ExpressionAttributeValues
@@ -1918,7 +1941,7 @@ var MutualRepository = class extends Repository {
1918
1941
  }, updateExpression)
1919
1942
  }
1920
1943
  ];
1921
- console.log("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1944
+ debugLog("[MONORISE_DEBUG] updateMutual transact items prepared:", {
1922
1945
  itemCount: TransactItems.length,
1923
1946
  tableName: this.TABLE_NAME
1924
1947
  });
@@ -1928,7 +1951,7 @@ var MutualRepository = class extends Repository {
1928
1951
  updateMutual(byEntityType, byEntityId, entityType, entityId, toUpdate, opts) {
1929
1952
  return __async(this, null, function* () {
1930
1953
  var _a, _b;
1931
- console.log("[MONORISE_DEBUG] updateMutual repository start:", {
1954
+ debugLog("[MONORISE_DEBUG] updateMutual repository start:", {
1932
1955
  byEntityType,
1933
1956
  byEntityId,
1934
1957
  entityType,
@@ -1948,24 +1971,24 @@ var MutualRepository = class extends Repository {
1948
1971
  opts
1949
1972
  );
1950
1973
  errorContext.TransactItems = TransactItems;
1951
- console.log("[MONORISE_DEBUG] updateMutual executing transaction...");
1974
+ debugLog("[MONORISE_DEBUG] updateMutual executing transaction...");
1952
1975
  yield this.ddbUtils.executeTransactWrite({ TransactItems });
1953
- console.log("[MONORISE_DEBUG] updateMutual transaction succeeded");
1976
+ debugLog("[MONORISE_DEBUG] updateMutual transaction succeeded");
1954
1977
  if (!returnUpdatedValue) {
1955
- console.log("[MONORISE_DEBUG] updateMutual returning (no value)");
1978
+ debugLog("[MONORISE_DEBUG] updateMutual returning (no value)");
1956
1979
  return;
1957
1980
  }
1958
- console.log("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1981
+ debugLog("[MONORISE_DEBUG] updateMutual fetching updated mutual...");
1959
1982
  const updatedMutual = yield this.getMutual(
1960
1983
  byEntityType,
1961
1984
  byEntityId,
1962
1985
  entityType,
1963
1986
  entityId
1964
1987
  );
1965
- console.log("[MONORISE_DEBUG] updateMutual repository complete");
1988
+ debugLog("[MONORISE_DEBUG] updateMutual repository complete");
1966
1989
  return updatedMutual;
1967
1990
  } catch (err) {
1968
- console.error("[MONORISE_DEBUG] updateMutual repository error:", {
1991
+ debugLog("[MONORISE_DEBUG] updateMutual repository error:", {
1969
1992
  errorName: (_b = err == null ? void 0 : err.constructor) == null ? void 0 : _b.name,
1970
1993
  errorMessage: err == null ? void 0 : err.message,
1971
1994
  errorCode: err == null ? void 0 : err.code,
@@ -2169,6 +2192,295 @@ var MutualRepository = class extends Repository {
2169
2192
  }
2170
2193
  };
2171
2194
 
2195
+ // data/Search.ts
2196
+ import {
2197
+ ConditionalCheckFailedException as ConditionalCheckFailedException2
2198
+ } from "@aws-sdk/client-dynamodb";
2199
+ import {
2200
+ indexedWords,
2201
+ matchesSearch,
2202
+ planSearch,
2203
+ resolveSearchConfig,
2204
+ searchConfigHash
2205
+ } from "../base/index.js";
2206
+ var INDEX_STATE_PK = "#SEARCH#";
2207
+ var BATCH_WRITE_LIMIT = 25;
2208
+ var SearchRepository = class {
2209
+ constructor(EntityConfig, TABLE_NAME, dynamodbClient, entityRepository, searchDefaults) {
2210
+ this.EntityConfig = EntityConfig;
2211
+ this.TABLE_NAME = TABLE_NAME;
2212
+ this.dynamodbClient = dynamodbClient;
2213
+ this.entityRepository = entityRepository;
2214
+ this.searchDefaults = searchDefaults;
2215
+ // Entity types whose index matched the config, once seen. The config is
2216
+ // fixed for the life of a Lambda instance, so this never goes stale.
2217
+ this.readyTypes = /* @__PURE__ */ new Set();
2218
+ }
2219
+ /** The resolved `search` config, or undefined if the type isn't indexed. */
2220
+ searchConfig(entityType) {
2221
+ var _a;
2222
+ const search = (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
2223
+ return search ? resolveSearchConfig(search, this.searchDefaults) : void 0;
2224
+ }
2225
+ indexedEntityTypes() {
2226
+ return Object.keys(this.EntityConfig).filter(
2227
+ (entityType) => {
2228
+ var _a;
2229
+ return (_a = this.EntityConfig[entityType]) == null ? void 0 : _a.search;
2230
+ }
2231
+ );
2232
+ }
2233
+ rowKeys(entityType, entityId, word) {
2234
+ return {
2235
+ PK: { S: `SEARCH#${entityType}` },
2236
+ SK: { S: `${word}#${entityId}` }
2237
+ };
2238
+ }
2239
+ searchRow(entity, word) {
2240
+ return __spreadProps(__spreadValues(__spreadValues({}, entity.toItem()), this.rowKeys(entity.entityType, entity.entityId, word)), {
2241
+ R1PK: entity.keys().PK,
2242
+ R1SK: { S: `SEARCH#${word}` }
2243
+ });
2244
+ }
2245
+ /** Puts a row for each word in `add` and deletes the rows in `remove`. */
2246
+ writeRows(entity, add, remove) {
2247
+ return __async(this, null, function* () {
2248
+ var _a, _b;
2249
+ const entityId = entity.entityId;
2250
+ const requests = [
2251
+ ...add.map((word) => ({
2252
+ PutRequest: { Item: this.searchRow(entity, word) }
2253
+ })),
2254
+ ...remove.map((word) => ({
2255
+ DeleteRequest: {
2256
+ Key: this.rowKeys(entity.entityType, entityId, word)
2257
+ }
2258
+ }))
2259
+ ];
2260
+ for (let i = 0; i < requests.length; i += BATCH_WRITE_LIMIT) {
2261
+ let batch = requests.slice(i, i + BATCH_WRITE_LIMIT);
2262
+ for (let attempt = 0; batch.length; attempt++) {
2263
+ if (attempt > 0) {
2264
+ yield new Promise(
2265
+ (resolve) => setTimeout(resolve, Math.min(1e3, 50 * 2 ** attempt))
2266
+ );
2267
+ }
2268
+ const resp = yield this.dynamodbClient.batchWriteItem({
2269
+ RequestItems: { [this.TABLE_NAME]: batch }
2270
+ });
2271
+ batch = (_b = (_a = resp.UnprocessedItems) == null ? void 0 : _a[this.TABLE_NAME]) != null ? _b : [];
2272
+ if (batch.length && attempt === 8) {
2273
+ throw new Error(
2274
+ `Search index: ${batch.length} writes still unprocessed for ${entity.entityType}#${entityId}`
2275
+ );
2276
+ }
2277
+ }
2278
+ }
2279
+ });
2280
+ }
2281
+ /** The words an entity currently has rows for, read from the GSI. */
2282
+ existingWords(entityType, entityId) {
2283
+ return __async(this, null, function* () {
2284
+ var _a, _b;
2285
+ const words = [];
2286
+ let lastKey;
2287
+ do {
2288
+ const resp = yield this.dynamodbClient.query({
2289
+ TableName: this.TABLE_NAME,
2290
+ IndexName: ENTITY_REPLICATION_INDEX,
2291
+ KeyConditionExpression: "#R1PK = :R1PK and begins_with(#R1SK, :R1SK)",
2292
+ ExpressionAttributeNames: { "#R1PK": "R1PK", "#R1SK": "R1SK" },
2293
+ ExpressionAttributeValues: {
2294
+ ":R1PK": { S: `${entityType}#${entityId}` },
2295
+ ":R1SK": { S: "SEARCH#" }
2296
+ },
2297
+ ExclusiveStartKey: lastKey
2298
+ });
2299
+ for (const item of (_a = resp.Items) != null ? _a : []) {
2300
+ const r1sk = (_b = item.R1SK) == null ? void 0 : _b.S;
2301
+ if (r1sk) words.push(r1sk.slice("SEARCH#".length));
2302
+ }
2303
+ lastKey = resp.LastEvaluatedKey;
2304
+ } while (lastKey);
2305
+ return words;
2306
+ });
2307
+ }
2308
+ getIndexState(entityType) {
2309
+ return __async(this, null, function* () {
2310
+ var _a, _b;
2311
+ const resp = yield this.dynamodbClient.getItem({
2312
+ TableName: this.TABLE_NAME,
2313
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
2314
+ });
2315
+ if (!resp.Item) return void 0;
2316
+ return {
2317
+ state: (_a = resp.Item.state) == null ? void 0 : _a.S,
2318
+ configHash: (_b = resp.Item.configHash) == null ? void 0 : _b.S
2319
+ };
2320
+ });
2321
+ }
2322
+ markIndexBuilding(entityType, configHash) {
2323
+ return __async(this, null, function* () {
2324
+ yield this.dynamodbClient.putItem({
2325
+ TableName: this.TABLE_NAME,
2326
+ Item: {
2327
+ PK: { S: INDEX_STATE_PK },
2328
+ SK: { S: `${entityType}` },
2329
+ state: { S: "building" },
2330
+ configHash: { S: configHash },
2331
+ updatedAt: { S: (/* @__PURE__ */ new Date()).toISOString() }
2332
+ }
2333
+ });
2334
+ });
2335
+ }
2336
+ /**
2337
+ * Marks the index ready, unless a newer reindex has taken over since: its
2338
+ * config hash replaces this one when it starts.
2339
+ */
2340
+ markIndexReady(entityType, configHash) {
2341
+ return __async(this, null, function* () {
2342
+ try {
2343
+ yield this.dynamodbClient.updateItem({
2344
+ TableName: this.TABLE_NAME,
2345
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } },
2346
+ UpdateExpression: "SET #state = :ready, #updatedAt = :now",
2347
+ ConditionExpression: "#configHash = :configHash",
2348
+ ExpressionAttributeNames: {
2349
+ "#state": "state",
2350
+ "#updatedAt": "updatedAt",
2351
+ "#configHash": "configHash"
2352
+ },
2353
+ ExpressionAttributeValues: {
2354
+ ":ready": { S: "ready" },
2355
+ ":now": { S: (/* @__PURE__ */ new Date()).toISOString() },
2356
+ ":configHash": { S: configHash }
2357
+ }
2358
+ });
2359
+ return true;
2360
+ } catch (err) {
2361
+ if (err instanceof ConditionalCheckFailedException2) return false;
2362
+ throw err;
2363
+ }
2364
+ });
2365
+ }
2366
+ /** Whether the index was fully built for the current config. */
2367
+ isIndexReady(entityType, config) {
2368
+ return __async(this, null, function* () {
2369
+ if (this.readyTypes.has(`${entityType}`)) return true;
2370
+ const state = yield this.getIndexState(entityType);
2371
+ const ready = (state == null ? void 0 : state.state) === "ready" && state.configHash === searchConfigHash(config);
2372
+ if (ready) this.readyTypes.add(`${entityType}`);
2373
+ return ready;
2374
+ });
2375
+ }
2376
+ /** Deletes the marker, so the next reindex rebuilds the type in full. */
2377
+ clearIndexState(entityType) {
2378
+ return __async(this, null, function* () {
2379
+ yield this.dynamodbClient.deleteItem({
2380
+ TableName: this.TABLE_NAME,
2381
+ Key: { PK: { S: INDEX_STATE_PK }, SK: { S: `${entityType}` } }
2382
+ });
2383
+ });
2384
+ }
2385
+ /**
2386
+ * Brings one entity's rows in line with its current data and config. It
2387
+ * runs alongside the stream, which may write a newer version of the same
2388
+ * rows, so each write only goes through over an older copy.
2389
+ */
2390
+ reindexEntity(entityType, entityId, config) {
2391
+ return __async(this, null, function* () {
2392
+ const resp = yield this.dynamodbClient.getItem({
2393
+ TableName: this.TABLE_NAME,
2394
+ Key: new Entity(entityType, entityId).keys(),
2395
+ ConsistentRead: true
2396
+ });
2397
+ if (!resp.Item) return;
2398
+ const entity = Entity.fromItem(resp.Item);
2399
+ const existing = yield this.existingWords(entityType, entityId);
2400
+ const words = indexedWords(entity.data, config);
2401
+ const notNewer = {
2402
+ ExpressionAttributeNames: { "#updatedAt": "updatedAt" },
2403
+ ExpressionAttributeValues: {
2404
+ ":updatedAt": { S: entity.updatedAt }
2405
+ }
2406
+ };
2407
+ const ignoreNewer = (err) => {
2408
+ if (!(err instanceof ConditionalCheckFailedException2)) throw err;
2409
+ };
2410
+ yield Promise.all([
2411
+ ...words.filter((word) => !existing.includes(word)).map(
2412
+ (word) => this.dynamodbClient.putItem(__spreadValues({
2413
+ TableName: this.TABLE_NAME,
2414
+ Item: this.searchRow(entity, word),
2415
+ ConditionExpression: "attribute_not_exists(PK) OR #updatedAt < :updatedAt"
2416
+ }, notNewer)).catch(ignoreNewer)
2417
+ ),
2418
+ ...existing.filter((word) => !words.includes(word)).map(
2419
+ (word) => this.dynamodbClient.deleteItem(__spreadValues({
2420
+ TableName: this.TABLE_NAME,
2421
+ Key: this.rowKeys(entityType, entityId, word),
2422
+ ConditionExpression: "#updatedAt <= :updatedAt"
2423
+ }, notNewer)).catch(ignoreNewer)
2424
+ )
2425
+ ]);
2426
+ });
2427
+ }
2428
+ lookUp(entityType, anchor) {
2429
+ return __async(this, null, function* () {
2430
+ var _a;
2431
+ const items = [];
2432
+ let lastKey;
2433
+ do {
2434
+ const resp = yield this.dynamodbClient.query({
2435
+ TableName: this.TABLE_NAME,
2436
+ KeyConditionExpression: "#PK = :PK and begins_with(#SK, :SK)",
2437
+ ExpressionAttributeNames: { "#PK": "PK", "#SK": "SK" },
2438
+ ExpressionAttributeValues: {
2439
+ ":PK": { S: `SEARCH#${entityType}` },
2440
+ ":SK": { S: anchor }
2441
+ },
2442
+ ExclusiveStartKey: lastKey
2443
+ });
2444
+ items.push(...(_a = resp.Items) != null ? _a : []);
2445
+ lastKey = resp.LastEvaluatedKey;
2446
+ } while (lastKey);
2447
+ return items.map(Entity.fromItem);
2448
+ });
2449
+ }
2450
+ /**
2451
+ * Every entity matching `query`, newest first. Reads the rows of the
2452
+ * query's longest word, or scans every entity while the index is still
2453
+ * being built for the current config. Both give the same matches.
2454
+ *
2455
+ * There's no `totalCount`: counting every entity of the type would take
2456
+ * the scan the index avoids. `filteredCount` is the number of matches.
2457
+ */
2458
+ searchEntities(entityType, query) {
2459
+ return __async(this, null, function* () {
2460
+ const config = this.searchConfig(entityType);
2461
+ const plan = config && planSearch(query, config.ignoreWords);
2462
+ if (!config || !(plan == null ? void 0 : plan.anchor)) {
2463
+ return { items: [], filteredCount: 0 };
2464
+ }
2465
+ const candidates = (yield this.isIndexReady(entityType, config)) ? yield this.lookUp(entityType, plan.anchor) : (yield this.entityRepository.listEntities({ entityType })).items;
2466
+ const seen = /* @__PURE__ */ new Set();
2467
+ const items = [];
2468
+ for (const entity of candidates) {
2469
+ const entityId = entity.entityId;
2470
+ if (seen.has(entityId)) continue;
2471
+ seen.add(entityId);
2472
+ if (matchesSearch(entity.data, plan, config)) {
2473
+ items.push(entity);
2474
+ }
2475
+ }
2476
+ items.sort(
2477
+ (a, b) => a.entityId < b.entityId ? 1 : -1
2478
+ );
2479
+ return { items, filteredCount: items.length };
2480
+ });
2481
+ }
2482
+ };
2483
+
2172
2484
  // data/Tag.ts
2173
2485
  import { marshall as marshall4, unmarshall as unmarshall3 } from "@aws-sdk/util-dynamodb";
2174
2486
  var TaggedEntity = class _TaggedEntity extends Entity {
@@ -8031,6 +8343,7 @@ function resolveAsEntity(mutualConfig, callOptions = {}) {
8031
8343
  var _a, _b;
8032
8344
  return (_b = callOptions.asEntity) != null ? _b : (_a = mutualConfig == null ? void 0 : mutualConfig.asEntity) == null ? void 0 : _a.name;
8033
8345
  }
8346
+ var entityInTransactionKey = (entityType, entityId) => `${entityType}#${entityId}`;
8034
8347
  var MutualService = class {
8035
8348
  constructor(EntityConfig, entityRepository, mutualRepository, publishEvent2, ddbUtils, entityServiceLifeCycle) {
8036
8349
  this.EntityConfig = EntityConfig;
@@ -8062,7 +8375,8 @@ var MutualService = class {
8062
8375
  skipMutualCreation = false,
8063
8376
  ConditionExpression,
8064
8377
  ExpressionAttributeNames,
8065
- ExpressionAttributeValues
8378
+ ExpressionAttributeValues,
8379
+ entitiesInTransaction
8066
8380
  } = options;
8067
8381
  const mutualFieldConfig = this.getMutualFieldConfig(byEntityType, entityType);
8068
8382
  const asEntity = resolveAsEntity(mutualFieldConfig, options);
@@ -8077,7 +8391,7 @@ var MutualService = class {
8077
8391
  options
8078
8392
  }
8079
8393
  };
8080
- console.log("[MONORISE_DEBUG] createMutual service start:", {
8394
+ debugLog("[MONORISE_DEBUG] createMutual service start:", {
8081
8395
  byEntityType,
8082
8396
  byEntityId,
8083
8397
  entityType,
@@ -8087,28 +8401,32 @@ var MutualService = class {
8087
8401
  });
8088
8402
  const mutualDataSchema = this.getMutualDataSchema(byEntityType, entityType);
8089
8403
  const schema = (_c = asEntityStorageSchema != null ? asEntityStorageSchema : mutualDataSchema) != null ? _c : external_exports.record(external_exports.string(), external_exports.any());
8090
- console.log("[MONORISE_DEBUG] createMutual schema resolved");
8404
+ debugLog("[MONORISE_DEBUG] createMutual schema resolved");
8091
8405
  const parsedMutualPayload = schema.parse(mutualPayload);
8092
- console.log("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
8093
- console.log("[MONORISE_DEBUG] createMutual fetching entities...");
8406
+ debugLog("[MONORISE_DEBUG] createMutual payload parsed:", parsedMutualPayload);
8407
+ debugLog("[MONORISE_DEBUG] createMutual fetching entities...");
8408
+ const readEntity = (type, id) => __async(this, null, function* () {
8409
+ const data = entitiesInTransaction == null ? void 0 : entitiesInTransaction.get(entityInTransactionKey(type, id));
8410
+ return data ? { data } : this.entityRepository.getEntity(type, id);
8411
+ });
8094
8412
  const [{ data: byEntityData }, { data: entityData }] = yield Promise.all([
8095
- this.entityRepository.getEntity(byEntityType, byEntityId),
8096
- this.entityRepository.getEntity(entityType, entityId)
8413
+ readEntity(byEntityType, byEntityId),
8414
+ readEntity(entityType, entityId)
8097
8415
  ]);
8098
- console.log("[MONORISE_DEBUG] createMutual entities fetched:", {
8416
+ debugLog("[MONORISE_DEBUG] createMutual entities fetched:", {
8099
8417
  hasByEntityData: !!byEntityData,
8100
8418
  hasEntityData: !!entityData
8101
8419
  });
8102
8420
  errorContext.byEntityData = byEntityData;
8103
8421
  errorContext.entityData = entityData;
8104
- console.log("[MONORISE_DEBUG] createMutual checking mutual exist...");
8422
+ debugLog("[MONORISE_DEBUG] createMutual checking mutual exist...");
8105
8423
  yield this.mutualRepository.checkMutualExist(
8106
8424
  byEntityType,
8107
8425
  byEntityId,
8108
8426
  entityType,
8109
8427
  entityId
8110
8428
  );
8111
- console.log("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
8429
+ debugLog("[MONORISE_DEBUG] createMutual mutual does not exist (ok)");
8112
8430
  const currentDatetime = createAndUpdateDatetime || /* @__PURE__ */ new Date();
8113
8431
  const mutual = new Mutual(
8114
8432
  byEntityType,
@@ -8123,7 +8441,7 @@ var MutualService = class {
8123
8441
  currentDatetime,
8124
8442
  currentDatetime
8125
8443
  );
8126
- console.log("[MONORISE_DEBUG] createMutual mutual object created:", {
8444
+ debugLog("[MONORISE_DEBUG] createMutual mutual object created:", {
8127
8445
  mutualId: mutual.mutualId
8128
8446
  });
8129
8447
  const mutualTransactions = skipMutualCreation ? [] : this.mutualRepository.createMutualTransactItems(mutual, {
@@ -8160,13 +8478,13 @@ var MutualService = class {
8160
8478
  mutualPayload
8161
8479
  } = params;
8162
8480
  const { mutual, entity, transactItems, parsedMutualPayload } = yield this.prepareCreateMutual(params);
8163
- console.log("[MONORISE_DEBUG] createMutual executing transaction:", {
8481
+ debugLog("[MONORISE_DEBUG] createMutual executing transaction:", {
8164
8482
  transactItemCount: transactItems.length
8165
8483
  });
8166
8484
  yield this.ddbUtils.executeTransactWrite({
8167
8485
  TransactItems: transactItems
8168
8486
  });
8169
- console.log("[MONORISE_DEBUG] createMutual transaction succeeded");
8487
+ debugLog("[MONORISE_DEBUG] createMutual transaction succeeded");
8170
8488
  if (entity) {
8171
8489
  yield this.entityServiceLifeCycle.afterCreateEntityHook(
8172
8490
  entity,
@@ -8188,7 +8506,7 @@ var MutualService = class {
8188
8506
  })
8189
8507
  ];
8190
8508
  yield Promise.all(eventPromises);
8191
- console.log("[MONORISE_DEBUG] createMutual service complete");
8509
+ debugLog("[MONORISE_DEBUG] createMutual service complete");
8192
8510
  return { mutual, eventPayload };
8193
8511
  });
8194
8512
  /**
@@ -8255,7 +8573,7 @@ var MutualService = class {
8255
8573
  mutualPayload,
8256
8574
  options
8257
8575
  }) {
8258
- console.log("[MONORISE_DEBUG] updateMutual service start:", {
8576
+ debugLog("[MONORISE_DEBUG] updateMutual service start:", {
8259
8577
  byEntityType,
8260
8578
  byEntityId,
8261
8579
  entityType,
@@ -8264,10 +8582,10 @@ var MutualService = class {
8264
8582
  options
8265
8583
  });
8266
8584
  const schema = this.getMutualUpdateSchema(byEntityType, entityType);
8267
- console.log("[MONORISE_DEBUG] updateMutual schema resolved");
8585
+ debugLog("[MONORISE_DEBUG] updateMutual schema resolved");
8268
8586
  const parsedMutualPayload = schema.parse(mutualPayload);
8269
- console.log("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
8270
- console.log("[MONORISE_DEBUG] updateMutual calling repository...");
8587
+ debugLog("[MONORISE_DEBUG] updateMutual payload parsed:", parsedMutualPayload);
8588
+ debugLog("[MONORISE_DEBUG] updateMutual calling repository...");
8271
8589
  const mutual = yield this.mutualRepository.updateMutual(
8272
8590
  byEntityType,
8273
8591
  byEntityId,
@@ -8276,7 +8594,7 @@ var MutualService = class {
8276
8594
  { mutualData: parsedMutualPayload },
8277
8595
  options
8278
8596
  );
8279
- console.log("[MONORISE_DEBUG] updateMutual repository result:", {
8597
+ debugLog("[MONORISE_DEBUG] updateMutual repository result:", {
8280
8598
  hasMutual: !!mutual,
8281
8599
  mutualId: mutual == null ? void 0 : mutual.mutualId
8282
8600
  });
@@ -8290,7 +8608,7 @@ var MutualService = class {
8290
8608
  parsedMutualPayload
8291
8609
  }
8292
8610
  });
8293
- console.log("[MONORISE_DEBUG] updateMutual service complete");
8611
+ debugLog("[MONORISE_DEBUG] updateMutual service complete");
8294
8612
  return mutual;
8295
8613
  });
8296
8614
  /**
@@ -8849,8 +9167,148 @@ var handler8 = (container) => (ev) => __async(null, null, function* () {
8849
9167
  });
8850
9168
 
8851
9169
  // processors/replication-processor.ts
8852
- import { ConditionalCheckFailedException as ConditionalCheckFailedException2 } from "@aws-sdk/client-dynamodb";
8853
- var handler9 = (container) => (event) => __async(null, null, function* () {
9170
+ import { ConditionalCheckFailedException as ConditionalCheckFailedException3 } from "@aws-sdk/client-dynamodb";
9171
+
9172
+ // processors/search-index-processor.ts
9173
+ import { InvokeCommand as InvokeCommand2, LambdaClient as LambdaClient2 } from "@aws-sdk/client-lambda";
9174
+ import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
9175
+ import {
9176
+ indexedWords as indexedWords2,
9177
+ searchConfigHash as searchConfigHash2
9178
+ } from "../base/index.js";
9179
+ function syncSearchIndex(container, record) {
9180
+ return __async(this, null, function* () {
9181
+ var _a, _b, _c, _d, _e, _f;
9182
+ if (record.eventName !== "INSERT" && record.eventName !== "MODIFY") return;
9183
+ const newImage = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
9184
+ if (!((_c = (_b = newImage == null ? void 0 : newImage.SK) == null ? void 0 : _b.S) == null ? void 0 : _c.startsWith("#METADATA#")) || ((_e = (_d = newImage.PK) == null ? void 0 : _d.S) == null ? void 0 : _e.startsWith("MUTUAL#"))) {
9185
+ return;
9186
+ }
9187
+ const entity = Entity.fromItem(newImage);
9188
+ const config = container.searchRepository.searchConfig(entity.entityType);
9189
+ if (!config) return;
9190
+ const oldImage = (_f = record.dynamodb) == null ? void 0 : _f.OldImage;
9191
+ const previous = oldImage ? indexedWords2(unmarshall6(oldImage).data, config) : [];
9192
+ const words = indexedWords2(entity.data, config);
9193
+ yield container.searchRepository.writeRows(
9194
+ entity,
9195
+ words.filter((word) => !previous.includes(word)),
9196
+ previous.filter((word) => !words.includes(word))
9197
+ );
9198
+ });
9199
+ }
9200
+ var HANDOVER_MS = 2 * 60 * 1e3;
9201
+ var PAGE_SIZE = 100;
9202
+ var CONCURRENCY = 25;
9203
+ var MAX_FAILURES = 3;
9204
+ var RETRY_WAIT_MS = 5e3;
9205
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9206
+ var lambdaClient;
9207
+ var invokeSelf = (event) => __async(null, null, function* () {
9208
+ lambdaClient != null ? lambdaClient : lambdaClient = new LambdaClient2();
9209
+ yield lambdaClient.send(
9210
+ new InvokeCommand2({
9211
+ FunctionName: process.env.AWS_LAMBDA_FUNCTION_NAME,
9212
+ InvocationType: "Event",
9213
+ Payload: Buffer.from(JSON.stringify(event))
9214
+ })
9215
+ );
9216
+ });
9217
+ var handler9 = (container, invoke = invokeSelf, pause = wait) => (event, context) => __async(null, null, function* () {
9218
+ var _a;
9219
+ const { searchRepository, entityRepository } = container;
9220
+ if (event.action === "start") {
9221
+ const indexed = searchRepository.indexedEntityTypes();
9222
+ const entityTypes = Object.keys(
9223
+ container.config.EntityConfig
9224
+ );
9225
+ for (const entityType2 of entityTypes) {
9226
+ if (!indexed.includes(entityType2)) {
9227
+ yield searchRepository.clearIndexState(entityType2);
9228
+ }
9229
+ }
9230
+ for (const entityType2 of indexed) {
9231
+ const config2 = searchRepository.searchConfig(entityType2);
9232
+ if (!config2) continue;
9233
+ const configHash2 = searchConfigHash2(config2);
9234
+ const state = yield searchRepository.getIndexState(entityType2);
9235
+ if (!event.force && (state == null ? void 0 : state.state) === "ready" && state.configHash === configHash2) {
9236
+ continue;
9237
+ }
9238
+ yield searchRepository.markIndexBuilding(entityType2, configHash2);
9239
+ yield invoke({ action: "reindex", entityType: entityType2, configHash: configHash2 });
9240
+ }
9241
+ return;
9242
+ }
9243
+ const { entityType, configHash } = event;
9244
+ const config = searchRepository.searchConfig(entityType);
9245
+ if (!config || searchConfigHash2(config) !== configHash) {
9246
+ console.log("[SEARCH_REINDEX] superseded, stopping", { entityType });
9247
+ return;
9248
+ }
9249
+ let lastKey = event.lastKey;
9250
+ let failures = (_a = event.failures) != null ? _a : 0;
9251
+ do {
9252
+ try {
9253
+ const page = yield entityRepository.listEntities({
9254
+ entityType,
9255
+ limit: PAGE_SIZE,
9256
+ options: { lastKey }
9257
+ });
9258
+ for (let i = 0; i < page.items.length; i += CONCURRENCY) {
9259
+ yield Promise.all(
9260
+ page.items.slice(i, i + CONCURRENCY).map(
9261
+ (entity) => searchRepository.reindexEntity(
9262
+ entityType,
9263
+ entity.entityId,
9264
+ config
9265
+ )
9266
+ )
9267
+ );
9268
+ }
9269
+ lastKey = page.lastKey;
9270
+ failures = 0;
9271
+ } catch (err) {
9272
+ failures++;
9273
+ if (failures >= MAX_FAILURES) {
9274
+ console.error(
9275
+ "[SEARCH_REINDEX] giving up: search scans until rebuilt",
9276
+ {
9277
+ entityType,
9278
+ lastKey,
9279
+ failures,
9280
+ err
9281
+ }
9282
+ );
9283
+ throw err;
9284
+ }
9285
+ console.warn("[SEARCH_REINDEX] page failed, retrying", {
9286
+ entityType,
9287
+ lastKey,
9288
+ failures,
9289
+ err
9290
+ });
9291
+ yield pause(RETRY_WAIT_MS * 2 ** (failures - 1));
9292
+ yield invoke({
9293
+ action: "reindex",
9294
+ entityType,
9295
+ configHash,
9296
+ lastKey,
9297
+ failures
9298
+ });
9299
+ return;
9300
+ }
9301
+ if (lastKey && context && context.getRemainingTimeInMillis() < HANDOVER_MS) {
9302
+ yield invoke({ action: "reindex", entityType, configHash, lastKey });
9303
+ return;
9304
+ }
9305
+ } while (lastKey);
9306
+ const ready = yield searchRepository.markIndexReady(entityType, configHash);
9307
+ console.log("[SEARCH_REINDEX] done", { entityType, ready });
9308
+ });
9309
+
9310
+ // processors/replication-processor.ts
9311
+ var handler10 = (container) => (event) => __async(null, null, function* () {
8854
9312
  var _a, _b, _c, _d, _e, _f, _g;
8855
9313
  const TableName = process.env.DDB_TABLE || container.coreTable;
8856
9314
  const batchItemFailures = [];
@@ -8859,6 +9317,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8859
9317
  const errorContext = {};
8860
9318
  errorContext.record = record;
8861
9319
  try {
9320
+ yield syncSearchIndex(container, record);
8862
9321
  if (record.eventName === "MODIFY") {
8863
9322
  const modifiedItem = (_a = record.dynamodb) == null ? void 0 : _a.NewImage;
8864
9323
  if (!modifiedItem) {
@@ -8949,7 +9408,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
8949
9408
  const results = yield Promise.allSettled(updatePromises);
8950
9409
  errorContext.results = results;
8951
9410
  if (results.some(
8952
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
9411
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
8953
9412
  )) {
8954
9413
  throw new StandardError(
8955
9414
  StandardErrorCode.REPLICATION_ERROR,
@@ -9020,7 +9479,7 @@ var handler9 = (container) => (event) => __async(null, null, function* () {
9020
9479
  );
9021
9480
  errorContext.deleteResults = deleteResults;
9022
9481
  if (deleteResults.some(
9023
- (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException2)
9482
+ (result) => result.status === "rejected" && !(result.reason instanceof ConditionalCheckFailedException3)
9024
9483
  )) {
9025
9484
  throw new StandardError(
9026
9485
  StandardErrorCode.REPLICATION_ERROR,
@@ -9114,7 +9573,7 @@ function batchUpdateTags(_0) {
9114
9573
  yield Promise.all(addPromises);
9115
9574
  });
9116
9575
  }
9117
- var handler10 = (container) => (ev) => __async(null, null, function* () {
9576
+ var handler11 = (container) => (ev) => __async(null, null, function* () {
9118
9577
  var _a;
9119
9578
  const batchItemFailures = [];
9120
9579
  for (const record of ev.Records) {
@@ -9179,7 +9638,7 @@ import {
9179
9638
  ApiGatewayManagementApiClient,
9180
9639
  PostToConnectionCommand
9181
9640
  } from "@aws-sdk/client-apigatewaymanagementapi";
9182
- import { unmarshall as unmarshall6 } from "@aws-sdk/util-dynamodb";
9641
+ import { unmarshall as unmarshall7 } from "@aws-sdk/util-dynamodb";
9183
9642
  import { ulid as ulid5 } from "ulid";
9184
9643
  var SUB_ENTITY_TYPE = "SUB#ENTITY#";
9185
9644
  var SUB_MUTUAL_TYPE = "SUB#MUTUAL#";
@@ -9481,7 +9940,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9481
9940
  byEntityId,
9482
9941
  mutualEntityType,
9483
9942
  entityId: skParts[1],
9484
- data: isRemove ? void 0 : unmarshall6(image)
9943
+ data: isRemove ? void 0 : unmarshall7(image)
9485
9944
  }
9486
9945
  };
9487
9946
  yield broadcastToSubscribers(
@@ -9505,7 +9964,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9505
9964
  payload: {
9506
9965
  entityType,
9507
9966
  entityId,
9508
- data: isRemove ? void 0 : unmarshall6(image)
9967
+ data: isRemove ? void 0 : unmarshall7(image)
9509
9968
  }
9510
9969
  };
9511
9970
  yield broadcastToSubscribers(
@@ -9531,7 +9990,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9531
9990
  byEntityId: entityId,
9532
9991
  mutualEntityType: sk.split("#")[0],
9533
9992
  entityId: sk.split("#")[1],
9534
- data: isRemove ? void 0 : unmarshall6(image)
9993
+ data: isRemove ? void 0 : unmarshall7(image)
9535
9994
  }
9536
9995
  } : {
9537
9996
  type: isInsert ? "entity.created" : isModify ? "entity.updated" : "entity.deleted",
@@ -9539,7 +9998,7 @@ var broadcast = (container) => (event) => __async(null, null, function* () {
9539
9998
  payload: {
9540
9999
  entityType,
9541
10000
  entityId,
9542
- data: isRemove ? void 0 : unmarshall6(image)
10001
+ data: isRemove ? void 0 : unmarshall7(image)
9543
10002
  }
9544
10003
  }
9545
10004
  );
@@ -9644,7 +10103,7 @@ var DbUtils = class {
9644
10103
  }
9645
10104
  executeTransactWrite(params) {
9646
10105
  return __async(this, null, function* () {
9647
- var _a;
10106
+ var _a, _b;
9648
10107
  try {
9649
10108
  yield this.ddbClient.transactWriteItems(params);
9650
10109
  } catch (err) {
@@ -9660,6 +10119,16 @@ var DbUtils = class {
9660
10119
  { params }
9661
10120
  );
9662
10121
  }
10122
+ if ((_b = err.CancellationReasons) == null ? void 0 : _b.some(
10123
+ (reason) => reason.Code === "TransactionConflict"
10124
+ )) {
10125
+ throw new StandardError(
10126
+ StandardErrorCode.TRANSACTION_CONFLICT,
10127
+ "Another request wrote the same data at the same time; retry",
10128
+ err,
10129
+ { params }
10130
+ );
10131
+ }
9663
10132
  }
9664
10133
  throw new StandardError(
9665
10134
  StandardErrorCode.TRANSACTION_FAILED,
@@ -9743,16 +10212,14 @@ var CreateEntityController = class {
9743
10212
  c.status(httpStatus6.BAD_REQUEST);
9744
10213
  return c.json(__spreadValues({}, err.toJSON()));
9745
10214
  }
9746
- if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9747
- c.status(httpStatus6.BAD_REQUEST);
10215
+ if (err instanceof StandardError && (err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS || err.code === StandardErrorCode.TRANSACTION_CONFLICT)) {
10216
+ c.status(httpStatus6.CONFLICT);
9748
10217
  return c.json(__spreadValues({}, err.toJSON()));
9749
10218
  }
9750
10219
  console.log("===create-entity error:", {
9751
10220
  err,
9752
- errorContext: JSON.stringify({
9753
- body,
9754
- headers: c.req.header()
9755
- })
10221
+ // Not the headers: they include the caller's x-api-key.
10222
+ errorContext: JSON.stringify({ body })
9756
10223
  });
9757
10224
  throw err;
9758
10225
  }
@@ -9853,8 +10320,9 @@ var querySchema = external_exports.object({
9853
10320
  end: external_exports.string().optional()
9854
10321
  });
9855
10322
  var ListEntitiesController = class {
9856
- constructor(entityRepository) {
10323
+ constructor(entityRepository, searchRepository) {
9857
10324
  this.entityRepository = entityRepository;
10325
+ this.searchRepository = searchRepository;
9858
10326
  this.controller = createMiddleware9((c) => __async(this, null, function* () {
9859
10327
  const errorContext = {};
9860
10328
  try {
@@ -9865,10 +10333,7 @@ var ListEntitiesController = class {
9865
10333
  const { entityType } = params;
9866
10334
  const { lastKey, query, limit, start, end } = querySchema.parse(queries2);
9867
10335
  if (query) {
9868
- const results2 = yield this.entityRepository.queryEntities(
9869
- entityType,
9870
- query
9871
- );
10336
+ const results2 = this.searchRepository.searchConfig(entityType) ? yield this.searchRepository.searchEntities(entityType, query) : yield this.entityRepository.queryEntities(entityType, query);
9872
10337
  return c.json({
9873
10338
  data: results2.items.map((item) => item.toJSON()),
9874
10339
  totalCount: results2.totalCount,
@@ -9948,8 +10413,8 @@ var UpdateEntityController = class {
9948
10413
  c.status(httpStatus10.BAD_REQUEST);
9949
10414
  return c.json(__spreadValues({}, err.toJSON()));
9950
10415
  }
9951
- if (err instanceof StandardError && err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS) {
9952
- c.status(httpStatus10.BAD_REQUEST);
10416
+ if (err instanceof StandardError && (err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS || err.code === StandardErrorCode.TRANSACTION_CONFLICT)) {
10417
+ c.status(httpStatus10.CONFLICT);
9953
10418
  return c.json(__spreadValues({}, err.toJSON()));
9954
10419
  }
9955
10420
  if (err instanceof StandardError && err.code === StandardErrorCode.CONDITIONAL_CHECK_FAILED) {
@@ -10110,6 +10575,10 @@ var UpsertEntityController = class {
10110
10575
  c.status(httpStatus12.BAD_REQUEST);
10111
10576
  return c.json(__spreadValues({}, err.toJSON()));
10112
10577
  }
10578
+ if (err instanceof StandardError && (err.code === StandardErrorCode.UNIQUE_VALUE_EXISTS || err.code === StandardErrorCode.TRANSACTION_CONFLICT)) {
10579
+ c.status(httpStatus12.CONFLICT);
10580
+ return c.json(__spreadValues({}, err.toJSON()));
10581
+ }
10113
10582
  throw err;
10114
10583
  }
10115
10584
  }));
@@ -10155,6 +10624,10 @@ var CreateMutualController = class {
10155
10624
  c.status(httpStatus13.BAD_REQUEST);
10156
10625
  return c.json(__spreadValues({}, err.toJSON()));
10157
10626
  }
10627
+ if (err instanceof StandardError && err.code === StandardErrorCode.TRANSACTION_CONFLICT) {
10628
+ c.status(httpStatus13.CONFLICT);
10629
+ return c.json(__spreadValues({}, err.toJSON()));
10630
+ }
10158
10631
  throw err;
10159
10632
  }
10160
10633
  }));
@@ -10182,6 +10655,10 @@ var DeleteMutualController = class {
10182
10655
  c.status(httpStatus14.BAD_REQUEST);
10183
10656
  return c.json(__spreadValues({}, err.toJSON()));
10184
10657
  }
10658
+ if (err instanceof StandardError && err.code === StandardErrorCode.TRANSACTION_CONFLICT) {
10659
+ c.status(httpStatus14.CONFLICT);
10660
+ return c.json(__spreadValues({}, err.toJSON()));
10661
+ }
10185
10662
  throw err;
10186
10663
  }
10187
10664
  }));
@@ -10314,6 +10791,10 @@ var UpdateMutualController = class {
10314
10791
  c.status(httpStatus16.BAD_REQUEST);
10315
10792
  return c.json(__spreadValues({}, err.toJSON()));
10316
10793
  }
10794
+ if (err instanceof StandardError && err.code === StandardErrorCode.TRANSACTION_CONFLICT) {
10795
+ c.status(httpStatus16.CONFLICT);
10796
+ return c.json(__spreadValues({}, err.toJSON()));
10797
+ }
10317
10798
  throw err;
10318
10799
  }
10319
10800
  }));
@@ -10972,8 +11453,31 @@ var TransactionService = class {
10972
11453
  const allTransactItems = [];
10973
11454
  const pendingEvents = [];
10974
11455
  const resultEntries = [];
10975
- const processed = yield Promise.all(
10976
- operations.map((op) => this.processOperation(op))
11456
+ const processed = new Array(operations.length);
11457
+ const isCreate = (op) => op.operation === "createEntity";
11458
+ yield Promise.all(
11459
+ operations.map((op, index) => __async(this, null, function* () {
11460
+ if (isCreate(op)) processed[index] = yield this.processOperation(op);
11461
+ }))
11462
+ );
11463
+ const entitiesInTransaction = /* @__PURE__ */ new Map();
11464
+ for (const { resultEntry } of processed.filter(Boolean)) {
11465
+ if (resultEntry.operation === "createEntity" && resultEntry.data) {
11466
+ entitiesInTransaction.set(
11467
+ entityInTransactionKey(resultEntry.entityType, resultEntry.entityId),
11468
+ resultEntry.data
11469
+ );
11470
+ }
11471
+ }
11472
+ yield Promise.all(
11473
+ operations.map((op, index) => __async(this, null, function* () {
11474
+ if (!isCreate(op)) {
11475
+ processed[index] = yield this.processOperation(
11476
+ op,
11477
+ entitiesInTransaction
11478
+ );
11479
+ }
11480
+ }))
10977
11481
  );
10978
11482
  const afterCommits = [];
10979
11483
  for (const { items, events, afterCommit, resultEntry } of processed) {
@@ -11092,7 +11596,7 @@ var TransactionService = class {
11092
11596
  return { results: resultEntries };
11093
11597
  });
11094
11598
  }
11095
- processOperation(op) {
11599
+ processOperation(op, entitiesInTransaction) {
11096
11600
  return __async(this, null, function* () {
11097
11601
  switch (op.operation) {
11098
11602
  case "createEntity": {
@@ -11166,7 +11670,7 @@ var TransactionService = class {
11166
11670
  };
11167
11671
  }
11168
11672
  case "createMutual":
11169
- return this.processCreateMutual(op);
11673
+ return this.processCreateMutual(op, entitiesInTransaction);
11170
11674
  case "updateMutual":
11171
11675
  return this.processUpdateMutual(op);
11172
11676
  case "deleteMutual":
@@ -11183,7 +11687,7 @@ var TransactionService = class {
11183
11687
  // the write is deferred into this transaction. A mutual created here
11184
11688
  // publishes the same MUTUAL_CREATED event, and an asEntity mutual's
11185
11689
  // projection is written in the same transaction.
11186
- processCreateMutual(op) {
11690
+ processCreateMutual(op, entitiesInTransaction) {
11187
11691
  return __async(this, null, function* () {
11188
11692
  var _a, _b;
11189
11693
  this.assertMutualOperation(op);
@@ -11193,7 +11697,8 @@ var TransactionService = class {
11193
11697
  byEntityId: op.byEntityId,
11194
11698
  entityType: op.entityType,
11195
11699
  entityId: op.entityId,
11196
- mutualPayload
11700
+ mutualPayload,
11701
+ options: { entitiesInTransaction }
11197
11702
  });
11198
11703
  return {
11199
11704
  items: transactItems,
@@ -11671,6 +12176,16 @@ var DependencyContainer = class {
11671
12176
  this.config.EmailAuthEnabledEntities
11672
12177
  );
11673
12178
  }
12179
+ get searchRepository() {
12180
+ return this.createCachedInstance(
12181
+ SearchRepository,
12182
+ this.config.EntityConfig,
12183
+ this.coreTable,
12184
+ this.dynamodbClient,
12185
+ this.entityRepository,
12186
+ this.config.SearchDefaults
12187
+ );
12188
+ }
11674
12189
  get mutualRepository() {
11675
12190
  return this.createCachedInstance(
11676
12191
  MutualRepository,
@@ -11737,7 +12252,8 @@ var DependencyContainer = class {
11737
12252
  get listEntitiesController() {
11738
12253
  return this.createCachedInstance(
11739
12254
  ListEntitiesController,
11740
- this.entityRepository
12255
+ this.entityRepository,
12256
+ this.searchRepository
11741
12257
  );
11742
12258
  }
11743
12259
  get createEntityController() {
@@ -11896,12 +12412,13 @@ var CoreFactory = class {
11896
12412
  this.dependencyContainer = dependencyContainer;
11897
12413
  this.setupCommonRoutes = setupCommonRoutes(dependencyContainer);
11898
12414
  this.mutualProcessor = handler7(dependencyContainer);
11899
- this.replicationProcessor = handler9(dependencyContainer);
12415
+ this.replicationProcessor = handler10(dependencyContainer);
12416
+ this.searchReindexProcessor = handler9(dependencyContainer);
11900
12417
  this.createEntityProcessor = handler(dependencyContainer);
11901
12418
  this.analyticsProcessor = handler2(this.config.EntityConfig);
11902
12419
  this.analyticsBackfillProcessor = handler3(this.config.EntityConfig);
11903
12420
  this.prejoinProcessor = handler8(dependencyContainer);
11904
- this.tagProcessor = handler10(dependencyContainer);
12421
+ this.tagProcessor = handler11(dependencyContainer);
11905
12422
  this.appHandler = appHandler(dependencyContainer);
11906
12423
  this.wsConnect = connect(dependencyContainer);
11907
12424
  this.wsDisconnect = disconnect(dependencyContainer);
@@ -11919,6 +12436,7 @@ export {
11919
12436
  MutualRepository,
11920
12437
  MutualService,
11921
12438
  PROJECTION_EXPRESSION,
12439
+ SearchRepository,
11922
12440
  StandardError,
11923
12441
  StandardErrorCode,
11924
12442
  TagRepository,
@@ -11935,11 +12453,12 @@ export {
11935
12453
  index_default as default,
11936
12454
  handler7 as mutualProcessor,
11937
12455
  handler8 as prejoinProcessor,
11938
- handler9 as replicationProcessor,
12456
+ handler10 as replicationProcessor,
11939
12457
  requires,
12458
+ handler9 as searchReindexProcessor,
11940
12459
  setupCommonRoutes,
11941
12460
  startBackfill as startAnalyticsBackfill,
11942
- handler10 as tagProcessor,
12461
+ handler11 as tagProcessor,
11943
12462
  transactional,
11944
12463
  broadcast as wsBroadcast,
11945
12464
  connect as wsConnect,