@exabugs/dynamodb-client 1.3.35 → 1.3.36

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.
Files changed (30) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/server/handler.cjs +706 -1639
  3. package/dist/server/handler.cjs.map +4 -4
  4. package/dist/server/operations/deleteOne.d.ts +4 -5
  5. package/dist/server/operations/deleteOne.d.ts.map +1 -1
  6. package/dist/server/operations/deleteOne.js +51 -71
  7. package/dist/server/operations/deleteOne.js.map +1 -1
  8. package/dist/server/operations/findMany.d.ts +4 -2
  9. package/dist/server/operations/findMany.d.ts.map +1 -1
  10. package/dist/server/operations/findMany.js +66 -39
  11. package/dist/server/operations/findMany.js.map +1 -1
  12. package/dist/server/operations/findOne.d.ts +4 -4
  13. package/dist/server/operations/findOne.d.ts.map +1 -1
  14. package/dist/server/operations/findOne.js +28 -41
  15. package/dist/server/operations/findOne.js.map +1 -1
  16. package/dist/server/operations/insertOne.d.ts +4 -5
  17. package/dist/server/operations/insertOne.d.ts.map +1 -1
  18. package/dist/server/operations/insertOne.js +33 -48
  19. package/dist/server/operations/insertOne.js.map +1 -1
  20. package/dist/server/operations/parameterConverter.d.ts +1 -0
  21. package/dist/server/operations/parameterConverter.d.ts.map +1 -1
  22. package/dist/server/operations/parameterConverter.js +13 -5
  23. package/dist/server/operations/parameterConverter.js.map +1 -1
  24. package/dist/server/operations/updateOne.d.ts +4 -6
  25. package/dist/server/operations/updateOne.d.ts.map +1 -1
  26. package/dist/server/operations/updateOne.js +53 -266
  27. package/dist/server/operations/updateOne.js.map +1 -1
  28. package/dist/server/types.d.ts +2 -10
  29. package/dist/server/types.d.ts.map +1 -1
  30. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- // @exabugs/dynamodb-client v1.3.35
2
- // Built: 2026-01-08T13:48:58.427Z
1
+ // @exabugs/dynamodb-client v1.3.36
2
+ // Built: 2026-01-09T00:36:32.014Z
3
3
  "use strict";
4
4
  var __create = Object.create;
5
5
  var __defProp = Object.defineProperty;
@@ -37,11 +37,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
 
39
39
  // src/shared/constants/http.ts
40
- var DEFAULT_HTTP_TIMEOUT_MS, HTTP_STATUS, HTTP_METHOD;
40
+ var HTTP_STATUS;
41
41
  var init_http = __esm({
42
42
  "src/shared/constants/http.ts"() {
43
43
  "use strict";
44
- DEFAULT_HTTP_TIMEOUT_MS = 3e4;
45
44
  HTTP_STATUS = {
46
45
  OK: 200,
47
46
  BAD_REQUEST: 400,
@@ -52,13 +51,6 @@ var init_http = __esm({
52
51
  INTERNAL_SERVER_ERROR: 500,
53
52
  NOT_IMPLEMENTED: 501
54
53
  };
55
- HTTP_METHOD = {
56
- GET: "GET",
57
- POST: "POST",
58
- PUT: "PUT",
59
- DELETE: "DELETE",
60
- OPTIONS: "OPTIONS"
61
- };
62
54
  }
63
55
  });
64
56
 
@@ -73,43 +65,10 @@ var init_types = __esm({
73
65
  function isAppError(error2) {
74
66
  return error2 instanceof AppError;
75
67
  }
76
- function getErrorClass(code) {
77
- switch (code) {
78
- case "AUTH_ERROR" /* AUTH_ERROR */:
79
- return AuthError;
80
- case "CONFIG_ERROR" /* CONFIG_ERROR */:
81
- return ConfigError;
82
- case "INVALID_FILTER" /* INVALID_FILTER */:
83
- return InvalidFilterError;
84
- case "INVALID_TOKEN" /* INVALID_TOKEN */:
85
- return InvalidTokenError;
86
- case "ITEM_NOT_FOUND" /* ITEM_NOT_FOUND */:
87
- return ItemNotFoundError;
88
- case "VERSION_CONFLICT" /* VERSION_CONFLICT */:
89
- return VersionConflictError;
90
- default:
91
- return AppError;
92
- }
93
- }
94
- var ErrorCode, AppError, AuthError, ConfigError, InvalidFilterError, InvalidTokenError, ItemNotFoundError, PartialFailureError, VersionConflictError;
68
+ var AppError, AuthError, ConfigError, InvalidTokenError, ItemNotFoundError;
95
69
  var init_errors = __esm({
96
70
  "src/shared/errors/index.ts"() {
97
71
  "use strict";
98
- ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
99
- ErrorCode2["AUTH_ERROR"] = "AUTH_ERROR";
100
- ErrorCode2["CONFIG_ERROR"] = "CONFIG_ERROR";
101
- ErrorCode2["INVALID_FILTER"] = "INVALID_FILTER";
102
- ErrorCode2["INVALID_TOKEN"] = "INVALID_TOKEN";
103
- ErrorCode2["ITEM_NOT_FOUND"] = "ITEM_NOT_FOUND";
104
- ErrorCode2["PARTIAL_FAILURE"] = "PARTIAL_FAILURE";
105
- ErrorCode2["VERSION_CONFLICT"] = "VERSION_CONFLICT";
106
- ErrorCode2["VALIDATION_ERROR"] = "VALIDATION_ERROR";
107
- ErrorCode2["INTERNAL_ERROR"] = "INTERNAL_ERROR";
108
- ErrorCode2["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
109
- ErrorCode2["INVALID_OPERATION"] = "INVALID_OPERATION";
110
- ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
111
- return ErrorCode2;
112
- })(ErrorCode || {});
113
72
  AppError = class extends Error {
114
73
  constructor(code, message, statusCode = 500, details) {
115
74
  super(message);
@@ -150,14 +109,6 @@ var init_errors = __esm({
150
109
  super("CONFIG_ERROR" /* CONFIG_ERROR */, message, 500, details);
151
110
  }
152
111
  };
153
- InvalidFilterError = class extends AppError {
154
- static {
155
- __name(this, "InvalidFilterError");
156
- }
157
- constructor(message, details) {
158
- super("INVALID_FILTER" /* INVALID_FILTER */, message, 400, details);
159
- }
160
- };
161
112
  InvalidTokenError = class extends AppError {
162
113
  static {
163
114
  __name(this, "InvalidTokenError");
@@ -174,30 +125,7 @@ var init_errors = __esm({
174
125
  super("ITEM_NOT_FOUND" /* ITEM_NOT_FOUND */, message, 404, details);
175
126
  }
176
127
  };
177
- PartialFailureError = class extends AppError {
178
- constructor(message, failedIds, errors, details) {
179
- super("PARTIAL_FAILURE" /* PARTIAL_FAILURE */, message, 207, {
180
- ...details,
181
- failedIds,
182
- errors
183
- });
184
- this.failedIds = failedIds;
185
- this.errors = errors;
186
- }
187
- static {
188
- __name(this, "PartialFailureError");
189
- }
190
- };
191
- VersionConflictError = class extends AppError {
192
- static {
193
- __name(this, "VersionConflictError");
194
- }
195
- constructor(message, details) {
196
- super("VERSION_CONFLICT" /* VERSION_CONFLICT */, message, 409, details);
197
- }
198
- };
199
128
  __name(isAppError, "isAppError");
200
- __name(getErrorClass, "getErrorClass");
201
129
  }
202
130
  });
203
131
 
@@ -377,102 +305,19 @@ var init_node = __esm({
377
305
  function ulid2() {
378
306
  return ulid();
379
307
  }
380
- function ulidWithTime(seedTime) {
381
- return ulid(seedTime);
382
- }
383
- function decodeTime(id) {
384
- const timeChars = id.substring(0, 10);
385
- const ENCODING2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
386
- let time2 = 0;
387
- for (let i4 = 0; i4 < timeChars.length; i4++) {
388
- const char = timeChars[i4];
389
- const value = ENCODING2.indexOf(char);
390
- if (value === -1) {
391
- throw new Error(`Invalid ULID character: ${char}`);
392
- }
393
- time2 = time2 * 32 + value;
394
- }
395
- return time2;
396
- }
397
308
  var init_ulid = __esm({
398
309
  "src/shared/utils/ulid.ts"() {
399
310
  "use strict";
400
311
  init_node();
401
312
  __name(ulid2, "ulid");
402
- __name(ulidWithTime, "ulidWithTime");
403
- __name(decodeTime, "decodeTime");
404
313
  }
405
314
  });
406
315
 
407
316
  // src/shared/utils/validation.ts
408
- function validateRequiredFields(obj, fields) {
409
- const missingFields = fields.filter((field) => obj[field] === void 0 || obj[field] === null);
410
- if (missingFields.length > 0) {
411
- throw new Error(`Missing required fields: ${missingFields.join(", ")}`);
412
- }
413
- }
414
- function validateNonEmptyString(value, fieldName) {
415
- if (typeof value !== "string" || value.trim() === "") {
416
- throw new Error(`${fieldName} must be a non-empty string`);
417
- }
418
- }
419
- function validateNumberRange(value, fieldName, min, max) {
420
- if (typeof value !== "number" || isNaN(value)) {
421
- throw new Error(`${fieldName} must be a valid number`);
422
- }
423
- if (min !== void 0 && value < min) {
424
- throw new Error(`${fieldName} must be at least ${min}`);
425
- }
426
- if (max !== void 0 && value > max) {
427
- throw new Error(`${fieldName} must be at most ${max}`);
428
- }
429
- }
430
- function validateNonEmptyArray(value, fieldName) {
431
- if (!Array.isArray(value) || value.length === 0) {
432
- throw new Error(`${fieldName} must be a non-empty array`);
433
- }
434
- }
435
- function validateSortField(sortField, validFields) {
436
- if (!validFields.includes(sortField)) {
437
- throw new InvalidFilterError(
438
- `Invalid sort field: ${sortField}. Valid fields are: ${validFields.join(", ")}`,
439
- { sortField, validFields }
440
- );
441
- }
442
- }
443
- function validateULID(value, fieldName) {
444
- if (typeof value !== "string") {
445
- throw new Error(`${fieldName} must be a string`);
446
- }
447
- const ulidPattern = /^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/;
448
- if (!ulidPattern.test(value)) {
449
- throw new Error(`${fieldName} must be a valid ULID format (26 characters, Crockford's Base32)`);
450
- }
451
- }
452
- function validateISO8601DateTime(value, fieldName) {
453
- if (typeof value !== "string") {
454
- throw new Error(`${fieldName} must be a string`);
455
- }
456
- const date2 = new Date(value);
457
- if (isNaN(date2.getTime())) {
458
- throw new Error(`${fieldName} must be a valid ISO 8601 datetime string`);
459
- }
460
- const iso8601Pattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/;
461
- if (!iso8601Pattern.test(value)) {
462
- throw new Error(`${fieldName} must be in ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ)`);
463
- }
464
- }
465
317
  var init_validation = __esm({
466
318
  "src/shared/utils/validation.ts"() {
467
319
  "use strict";
468
320
  init_errors();
469
- __name(validateRequiredFields, "validateRequiredFields");
470
- __name(validateNonEmptyString, "validateNonEmptyString");
471
- __name(validateNumberRange, "validateNumberRange");
472
- __name(validateNonEmptyArray, "validateNonEmptyArray");
473
- __name(validateSortField, "validateSortField");
474
- __name(validateULID, "validateULID");
475
- __name(validateISO8601DateTime, "validateISO8601DateTime");
476
321
  }
477
322
  });
478
323
 
@@ -28542,7 +28387,7 @@ var require_dist_cjs66 = __commonJS({
28542
28387
  return async () => handler2(this.clientCommand);
28543
28388
  }
28544
28389
  };
28545
- var GetCommand4 = class extends DynamoDBDocumentClientCommand {
28390
+ var GetCommand = class extends DynamoDBDocumentClientCommand {
28546
28391
  static {
28547
28392
  __name(this, "GetCommand");
28548
28393
  }
@@ -28568,7 +28413,7 @@ var require_dist_cjs66 = __commonJS({
28568
28413
  return async () => handler2(this.clientCommand);
28569
28414
  }
28570
28415
  };
28571
- var PutCommand2 = class extends DynamoDBDocumentClientCommand {
28416
+ var PutCommand = class extends DynamoDBDocumentClientCommand {
28572
28417
  static {
28573
28418
  __name(this, "PutCommand");
28574
28419
  }
@@ -28715,7 +28560,7 @@ var require_dist_cjs66 = __commonJS({
28715
28560
  return async () => handler2(this.clientCommand);
28716
28561
  }
28717
28562
  };
28718
- var TransactWriteCommand6 = class extends DynamoDBDocumentClientCommand {
28563
+ var TransactWriteCommand4 = class extends DynamoDBDocumentClientCommand {
28719
28564
  static {
28720
28565
  __name(this, "TransactWriteCommand");
28721
28566
  }
@@ -28913,7 +28758,7 @@ var require_dist_cjs66 = __commonJS({
28913
28758
  }
28914
28759
  }
28915
28760
  get(args, optionsOrCb, cb) {
28916
- const command = new GetCommand4(args);
28761
+ const command = new GetCommand(args);
28917
28762
  if (typeof optionsOrCb === "function") {
28918
28763
  this.send(command, optionsOrCb);
28919
28764
  } else if (typeof cb === "function") {
@@ -28926,7 +28771,7 @@ var require_dist_cjs66 = __commonJS({
28926
28771
  }
28927
28772
  }
28928
28773
  put(args, optionsOrCb, cb) {
28929
- const command = new PutCommand2(args);
28774
+ const command = new PutCommand(args);
28930
28775
  if (typeof optionsOrCb === "function") {
28931
28776
  this.send(command, optionsOrCb);
28932
28777
  } else if (typeof cb === "function") {
@@ -28978,7 +28823,7 @@ var require_dist_cjs66 = __commonJS({
28978
28823
  }
28979
28824
  }
28980
28825
  transactWrite(args, optionsOrCb, cb) {
28981
- const command = new TransactWriteCommand6(args);
28826
+ const command = new TransactWriteCommand4(args);
28982
28827
  if (typeof optionsOrCb === "function") {
28983
28828
  this.send(command, optionsOrCb);
28984
28829
  } else if (typeof cb === "function") {
@@ -29033,12 +28878,12 @@ var require_dist_cjs66 = __commonJS({
29033
28878
  exports2.DynamoDBDocumentClientCommand = DynamoDBDocumentClientCommand;
29034
28879
  exports2.ExecuteStatementCommand = ExecuteStatementCommand;
29035
28880
  exports2.ExecuteTransactionCommand = ExecuteTransactionCommand;
29036
- exports2.GetCommand = GetCommand4;
29037
- exports2.PutCommand = PutCommand2;
28881
+ exports2.GetCommand = GetCommand;
28882
+ exports2.PutCommand = PutCommand;
29038
28883
  exports2.QueryCommand = QueryCommand5;
29039
28884
  exports2.ScanCommand = ScanCommand;
29040
28885
  exports2.TransactGetCommand = TransactGetCommand;
29041
- exports2.TransactWriteCommand = TransactWriteCommand6;
28886
+ exports2.TransactWriteCommand = TransactWriteCommand4;
29042
28887
  exports2.UpdateCommand = UpdateCommand;
29043
28888
  exports2.paginateQuery = paginateQuery;
29044
28889
  exports2.paginateScan = paginateScan;
@@ -29085,591 +28930,13 @@ var init_utils2 = __esm({
29085
28930
  });
29086
28931
 
29087
28932
  // src/shared/constants/dynamodb.ts
29088
- var DYNAMODB_TRANSACT_WRITE_MAX_ITEMS, DYNAMODB_BATCH_GET_MAX_ITEMS, DYNAMODB_BATCH_WRITE_MAX_ITEMS, DYNAMODB_QUERY_MAX_SIZE_BYTES, DYNAMODB_SCAN_MAX_SIZE_BYTES, DYNAMODB_RESERVED_WORDS;
28933
+ var DYNAMODB_TRANSACT_WRITE_MAX_ITEMS, DYNAMODB_QUERY_MAX_SIZE_BYTES, DYNAMODB_SCAN_MAX_SIZE_BYTES;
29089
28934
  var init_dynamodb2 = __esm({
29090
28935
  "src/shared/constants/dynamodb.ts"() {
29091
28936
  "use strict";
29092
28937
  DYNAMODB_TRANSACT_WRITE_MAX_ITEMS = 100;
29093
- DYNAMODB_BATCH_GET_MAX_ITEMS = 100;
29094
- DYNAMODB_BATCH_WRITE_MAX_ITEMS = 25;
29095
28938
  DYNAMODB_QUERY_MAX_SIZE_BYTES = 1024 * 1024;
29096
28939
  DYNAMODB_SCAN_MAX_SIZE_BYTES = 1024 * 1024;
29097
- DYNAMODB_RESERVED_WORDS = [
29098
- "ABORT",
29099
- "ABSOLUTE",
29100
- "ACTION",
29101
- "ADD",
29102
- "AFTER",
29103
- "AGENT",
29104
- "AGGREGATE",
29105
- "ALL",
29106
- "ALLOCATE",
29107
- "ALTER",
29108
- "ANALYZE",
29109
- "AND",
29110
- "ANY",
29111
- "ARCHIVE",
29112
- "ARE",
29113
- "ARRAY",
29114
- "AS",
29115
- "ASC",
29116
- "ASCII",
29117
- "ASENSITIVE",
29118
- "ASSERTION",
29119
- "ASYMMETRIC",
29120
- "AT",
29121
- "ATOMIC",
29122
- "ATTACH",
29123
- "ATTRIBUTE",
29124
- "AUTH",
29125
- "AUTHORIZATION",
29126
- "AUTHORIZE",
29127
- "AUTO",
29128
- "AVG",
29129
- "BACK",
29130
- "BACKUP",
29131
- "BASE",
29132
- "BATCH",
29133
- "BEFORE",
29134
- "BEGIN",
29135
- "BETWEEN",
29136
- "BIGINT",
29137
- "BINARY",
29138
- "BIT",
29139
- "BLOB",
29140
- "BLOCK",
29141
- "BOOLEAN",
29142
- "BOTH",
29143
- "BREADTH",
29144
- "BUCKET",
29145
- "BULK",
29146
- "BY",
29147
- "BYTE",
29148
- "CALL",
29149
- "CALLED",
29150
- "CALLING",
29151
- "CAPACITY",
29152
- "CASCADE",
29153
- "CASCADED",
29154
- "CASE",
29155
- "CAST",
29156
- "CATALOG",
29157
- "CHAR",
29158
- "CHARACTER",
29159
- "CHECK",
29160
- "CLASS",
29161
- "CLOB",
29162
- "CLOSE",
29163
- "CLUSTER",
29164
- "CLUSTERED",
29165
- "CLUSTERING",
29166
- "CLUSTERS",
29167
- "COALESCE",
29168
- "COLLATE",
29169
- "COLLATION",
29170
- "COLLECTION",
29171
- "COLUMN",
29172
- "COLUMNS",
29173
- "COMBINE",
29174
- "COMMENT",
29175
- "COMMIT",
29176
- "COMPACT",
29177
- "COMPILE",
29178
- "COMPRESS",
29179
- "CONDITION",
29180
- "CONFLICT",
29181
- "CONNECT",
29182
- "CONNECTION",
29183
- "CONSISTENCY",
29184
- "CONSISTENT",
29185
- "CONSTRAINT",
29186
- "CONSTRAINTS",
29187
- "CONSTRUCTOR",
29188
- "CONSUMED",
29189
- "CONTAINS",
29190
- "CONTINUE",
29191
- "CONVERT",
29192
- "COPY",
29193
- "CORRESPONDING",
29194
- "COUNT",
29195
- "COUNTER",
29196
- "CREATE",
29197
- "CROSS",
29198
- "CUBE",
29199
- "CURRENT",
29200
- "CURSOR",
29201
- "CYCLE",
29202
- "DATA",
29203
- "DATABASE",
29204
- "DATE",
29205
- "DATETIME",
29206
- "DAY",
29207
- "DEALLOCATE",
29208
- "DEC",
29209
- "DECIMAL",
29210
- "DECLARE",
29211
- "DEFAULT",
29212
- "DEFERRABLE",
29213
- "DEFERRED",
29214
- "DEFINE",
29215
- "DEFINED",
29216
- "DEFINITION",
29217
- "DELETE",
29218
- "DELIMITED",
29219
- "DEPTH",
29220
- "DEREF",
29221
- "DESC",
29222
- "DESCRIBE",
29223
- "DESCRIPTOR",
29224
- "DETACH",
29225
- "DETERMINISTIC",
29226
- "DIAGNOSTICS",
29227
- "DIRECTORIES",
29228
- "DISABLE",
29229
- "DISCONNECT",
29230
- "DISTINCT",
29231
- "DISTRIBUTE",
29232
- "DO",
29233
- "DOMAIN",
29234
- "DOUBLE",
29235
- "DROP",
29236
- "DUMP",
29237
- "DURATION",
29238
- "DYNAMIC",
29239
- "EACH",
29240
- "ELEMENT",
29241
- "ELSE",
29242
- "ELSEIF",
29243
- "EMPTY",
29244
- "ENABLE",
29245
- "END",
29246
- "EQUAL",
29247
- "EQUALS",
29248
- "ERROR",
29249
- "ESCAPE",
29250
- "ESCAPED",
29251
- "EVAL",
29252
- "EVALUATE",
29253
- "EXCEEDED",
29254
- "EXCEPT",
29255
- "EXCEPTION",
29256
- "EXCEPTIONS",
29257
- "EXCLUSIVE",
29258
- "EXEC",
29259
- "EXECUTE",
29260
- "EXISTS",
29261
- "EXIT",
29262
- "EXPLAIN",
29263
- "EXPLODE",
29264
- "EXPORT",
29265
- "EXPRESSION",
29266
- "EXPRESSIONS",
29267
- "EXTERNAL",
29268
- "EXTRACT",
29269
- "FAIL",
29270
- "FALSE",
29271
- "FAMILY",
29272
- "FETCH",
29273
- "FIELDS",
29274
- "FILE",
29275
- "FILTER",
29276
- "FILTERING",
29277
- "FINAL",
29278
- "FINISH",
29279
- "FIRST",
29280
- "FIXED",
29281
- "FLATTERN",
29282
- "FLOAT",
29283
- "FOR",
29284
- "FORCE",
29285
- "FOREIGN",
29286
- "FORMAT",
29287
- "FORWARD",
29288
- "FOUND",
29289
- "FREE",
29290
- "FROM",
29291
- "FULL",
29292
- "FUNCTION",
29293
- "FUNCTIONS",
29294
- "GENERAL",
29295
- "GENERATE",
29296
- "GET",
29297
- "GLOB",
29298
- "GLOBAL",
29299
- "GO",
29300
- "GOTO",
29301
- "GRANT",
29302
- "GREATER",
29303
- "GROUP",
29304
- "GROUPING",
29305
- "HANDLER",
29306
- "HASH",
29307
- "HAVE",
29308
- "HAVING",
29309
- "HEAP",
29310
- "HIDDEN",
29311
- "HOLD",
29312
- "HOUR",
29313
- "IDENTIFIED",
29314
- "IDENTITY",
29315
- "IF",
29316
- "IGNORE",
29317
- "IMMEDIATE",
29318
- "IMPORT",
29319
- "IN",
29320
- "INCLUDING",
29321
- "INCLUSIVE",
29322
- "INCREMENT",
29323
- "INCREMENTAL",
29324
- "INDEX",
29325
- "INDEXED",
29326
- "INDEXES",
29327
- "INDICATOR",
29328
- "INFINITE",
29329
- "INITIALLY",
29330
- "INLINE",
29331
- "INNER",
29332
- "INNTER",
29333
- "INOUT",
29334
- "INPUT",
29335
- "INSENSITIVE",
29336
- "INSERT",
29337
- "INSTEAD",
29338
- "INT",
29339
- "INTEGER",
29340
- "INTERSECT",
29341
- "INTERVAL",
29342
- "INTO",
29343
- "INVALIDATE",
29344
- "IS",
29345
- "ISOLATION",
29346
- "ITEM",
29347
- "ITEMS",
29348
- "ITERATE",
29349
- "JOIN",
29350
- "KEY",
29351
- "KEYS",
29352
- "LAG",
29353
- "LANGUAGE",
29354
- "LARGE",
29355
- "LAST",
29356
- "LATERAL",
29357
- "LEAD",
29358
- "LEADING",
29359
- "LEAVE",
29360
- "LEFT",
29361
- "LENGTH",
29362
- "LESS",
29363
- "LEVEL",
29364
- "LIKE",
29365
- "LIMIT",
29366
- "LIMITED",
29367
- "LINES",
29368
- "LIST",
29369
- "LOAD",
29370
- "LOCAL",
29371
- "LOCALTIME",
29372
- "LOCALTIMESTAMP",
29373
- "LOCATION",
29374
- "LOCATOR",
29375
- "LOCK",
29376
- "LOCKS",
29377
- "LOG",
29378
- "LOGED",
29379
- "LONG",
29380
- "LOOP",
29381
- "LOWER",
29382
- "MAP",
29383
- "MATCH",
29384
- "MATERIALIZED",
29385
- "MAX",
29386
- "MAXLEN",
29387
- "MEMBER",
29388
- "MERGE",
29389
- "METHOD",
29390
- "METRICS",
29391
- "MIN",
29392
- "MINUS",
29393
- "MINUTE",
29394
- "MISSING",
29395
- "MOD",
29396
- "MODE",
29397
- "MODIFIES",
29398
- "MODIFY",
29399
- "MODULE",
29400
- "MONTH",
29401
- "MULTI",
29402
- "MULTISET",
29403
- "NAME",
29404
- "NAMES",
29405
- "NATIONAL",
29406
- "NATURAL",
29407
- "NCHAR",
29408
- "NCLOB",
29409
- "NEW",
29410
- "NEXT",
29411
- "NO",
29412
- "NONE",
29413
- "NOT",
29414
- "NULL",
29415
- "NULLIF",
29416
- "NUMBER",
29417
- "NUMERIC",
29418
- "OBJECT",
29419
- "OF",
29420
- "OFFLINE",
29421
- "OFFSET",
29422
- "OLD",
29423
- "ON",
29424
- "ONLINE",
29425
- "ONLY",
29426
- "OPAQUE",
29427
- "OPEN",
29428
- "OPERATOR",
29429
- "OPTION",
29430
- "OR",
29431
- "ORDER",
29432
- "ORDINALITY",
29433
- "OTHER",
29434
- "OTHERS",
29435
- "OUT",
29436
- "OUTER",
29437
- "OUTPUT",
29438
- "OVER",
29439
- "OVERLAPS",
29440
- "OVERRIDE",
29441
- "OWNER",
29442
- "PAD",
29443
- "PARALLEL",
29444
- "PARAMETER",
29445
- "PARAMETERS",
29446
- "PARTIAL",
29447
- "PARTITION",
29448
- "PARTITIONED",
29449
- "PARTITIONS",
29450
- "PATH",
29451
- "PERCENT",
29452
- "PERCENTILE",
29453
- "PERMISSION",
29454
- "PERMISSIONS",
29455
- "PIPE",
29456
- "PIPELINED",
29457
- "PLAN",
29458
- "POOL",
29459
- "POSITION",
29460
- "PRECISION",
29461
- "PREPARE",
29462
- "PRESERVE",
29463
- "PRIMARY",
29464
- "PRIOR",
29465
- "PRIVATE",
29466
- "PRIVILEGES",
29467
- "PROCEDURE",
29468
- "PROCESSED",
29469
- "PROJECT",
29470
- "PROJECTION",
29471
- "PROPERTY",
29472
- "PROVISIONING",
29473
- "PUBLIC",
29474
- "PUT",
29475
- "QUERY",
29476
- "QUIT",
29477
- "QUORUM",
29478
- "RAISE",
29479
- "RANDOM",
29480
- "RANGE",
29481
- "RANK",
29482
- "RAW",
29483
- "READ",
29484
- "READS",
29485
- "REAL",
29486
- "REBUILD",
29487
- "RECORD",
29488
- "RECURSIVE",
29489
- "REDUCE",
29490
- "REF",
29491
- "REFERENCE",
29492
- "REFERENCES",
29493
- "REFERENCING",
29494
- "REGEXP",
29495
- "REGION",
29496
- "REINDEX",
29497
- "RELATIVE",
29498
- "RELEASE",
29499
- "REMAINDER",
29500
- "RENAME",
29501
- "REPEAT",
29502
- "REPLACE",
29503
- "REQUEST",
29504
- "RESET",
29505
- "RESIGNAL",
29506
- "RESOURCE",
29507
- "RESPONSE",
29508
- "RESTORE",
29509
- "RESTRICT",
29510
- "RESULT",
29511
- "RETURN",
29512
- "RETURNING",
29513
- "RETURNS",
29514
- "REVERSE",
29515
- "REVOKE",
29516
- "RIGHT",
29517
- "ROLE",
29518
- "ROLES",
29519
- "ROLLBACK",
29520
- "ROLLUP",
29521
- "ROUTINE",
29522
- "ROW",
29523
- "ROWS",
29524
- "RULE",
29525
- "RULES",
29526
- "SAMPLE",
29527
- "SATISFIES",
29528
- "SAVE",
29529
- "SAVEPOINT",
29530
- "SCAN",
29531
- "SCHEMA",
29532
- "SCOPE",
29533
- "SCROLL",
29534
- "SEARCH",
29535
- "SECOND",
29536
- "SECTION",
29537
- "SEGMENT",
29538
- "SEGMENTS",
29539
- "SELECT",
29540
- "SELF",
29541
- "SEMI",
29542
- "SENSITIVE",
29543
- "SEPARATE",
29544
- "SEQUENCE",
29545
- "SERIALIZABLE",
29546
- "SESSION",
29547
- "SET",
29548
- "SETS",
29549
- "SHARD",
29550
- "SHARE",
29551
- "SHARED",
29552
- "SHORT",
29553
- "SHOW",
29554
- "SIGNAL",
29555
- "SIMILAR",
29556
- "SIZE",
29557
- "SKEWED",
29558
- "SMALLINT",
29559
- "SNAPSHOT",
29560
- "SOME",
29561
- "SOURCE",
29562
- "SPACE",
29563
- "SPACES",
29564
- "SPARSE",
29565
- "SPECIFIC",
29566
- "SPECIFICTYPE",
29567
- "SPLIT",
29568
- "SQL",
29569
- "SQLCODE",
29570
- "SQLERROR",
29571
- "SQLEXCEPTION",
29572
- "SQLSTATE",
29573
- "SQLWARNING",
29574
- "START",
29575
- "STATE",
29576
- "STATIC",
29577
- "STATUS",
29578
- "STORAGE",
29579
- "STORE",
29580
- "STORED",
29581
- "STREAM",
29582
- "STRING",
29583
- "STRUCTURE",
29584
- "STYLE",
29585
- "SUB",
29586
- "SUBMULTISET",
29587
- "SUBPARTITION",
29588
- "SUBSTRING",
29589
- "SUBTYPE",
29590
- "SUM",
29591
- "SUPER",
29592
- "SYMMETRIC",
29593
- "SYNONYM",
29594
- "SYSTEM",
29595
- "TABLE",
29596
- "TABLESAMPLE",
29597
- "TEMP",
29598
- "TEMPORARY",
29599
- "TERMINATED",
29600
- "TEXT",
29601
- "THAN",
29602
- "THEN",
29603
- "THROUGHPUT",
29604
- "TIME",
29605
- "TIMESTAMP",
29606
- "TIMEZONE",
29607
- "TINYINT",
29608
- "TO",
29609
- "TOKEN",
29610
- "TOTAL",
29611
- "TOUCH",
29612
- "TRAILING",
29613
- "TRANSACTION",
29614
- "TRANSFORM",
29615
- "TRANSLATE",
29616
- "TRANSLATION",
29617
- "TREAT",
29618
- "TRIGGER",
29619
- "TRIM",
29620
- "TRUE",
29621
- "TRUNCATE",
29622
- "TTL",
29623
- "TUPLE",
29624
- "TYPE",
29625
- "UNDER",
29626
- "UNDO",
29627
- "UNION",
29628
- "UNIQUE",
29629
- "UNIT",
29630
- "UNKNOWN",
29631
- "UNLOGGED",
29632
- "UNNEST",
29633
- "UNPROCESSED",
29634
- "UNSIGNED",
29635
- "UNTIL",
29636
- "UPDATE",
29637
- "UPPER",
29638
- "URL",
29639
- "USAGE",
29640
- "USE",
29641
- "USER",
29642
- "USERS",
29643
- "USING",
29644
- "UUID",
29645
- "VACUUM",
29646
- "VALUE",
29647
- "VALUED",
29648
- "VALUES",
29649
- "VARCHAR",
29650
- "VARIABLE",
29651
- "VARIANCE",
29652
- "VARINT",
29653
- "VARYING",
29654
- "VIEW",
29655
- "VIEWS",
29656
- "VIRTUAL",
29657
- "VOID",
29658
- "WAIT",
29659
- "WHEN",
29660
- "WHENEVER",
29661
- "WHERE",
29662
- "WHILE",
29663
- "WINDOW",
29664
- "WITH",
29665
- "WITHIN",
29666
- "WITHOUT",
29667
- "WORK",
29668
- "WRAPPED",
29669
- "WRITE",
29670
- "YEAR",
29671
- "ZONE"
29672
- ];
29673
28940
  }
29674
28941
  });
29675
28942
 
@@ -29699,18 +28966,10 @@ var init_constants = __esm({
29699
28966
  });
29700
28967
 
29701
28968
  // src/shared/geohash/types.ts
29702
- var GEOHASH_PRECISION_TABLE, DEFAULT_GEOHASH_CONFIG;
28969
+ var DEFAULT_GEOHASH_CONFIG;
29703
28970
  var init_types2 = __esm({
29704
28971
  "src/shared/geohash/types.ts"() {
29705
28972
  "use strict";
29706
- GEOHASH_PRECISION_TABLE = {
29707
- 1: { error: 25e5, description: "\u5927\u9678\u30EC\u30D9\u30EB" },
29708
- 4: { error: 2e4, description: "\u5927\u90FD\u5E02\u30EC\u30D9\u30EB" },
29709
- 6: { error: 610, description: "\u8FD1\u96A3\u30EC\u30D9\u30EB" },
29710
- 7: { error: 76, description: "\u8857\u533A\u30EC\u30D9\u30EB" },
29711
- 8: { error: 19, description: "\u5EFA\u7269\u30EC\u30D9\u30EB" },
29712
- 10: { error: 0.6, description: "\u9AD8\u7CBE\u5EA6" }
29713
- };
29714
28973
  DEFAULT_GEOHASH_CONFIG = {
29715
28974
  shadowPrecision: 8,
29716
28975
  // ±19m(建物レベル)
@@ -30045,9 +29304,6 @@ function isGeoCoordinates(value) {
30045
29304
  function encodeGeoHash(latitude, longitude, precision = 6) {
30046
29305
  return import_ngeohash.default.encode(latitude, longitude, precision);
30047
29306
  }
30048
- function decodeGeoHash(geohash) {
30049
- return import_ngeohash.default.decode(geohash);
30050
- }
30051
29307
  function getNeighborGeoHashes(geohash) {
30052
29308
  const neighbors = [
30053
29309
  geohash,
@@ -30111,14 +29367,6 @@ function extractMinDistanceFromNearQuery(query) {
30111
29367
  return query.minDistance;
30112
29368
  }
30113
29369
  }
30114
- function validateLocation(latitude, longitude) {
30115
- if (latitude < -90 || latitude > 90) {
30116
- throw new Error("Latitude must be between -90 and 90");
30117
- }
30118
- if (longitude < -180 || longitude > 180) {
30119
- throw new Error("Longitude must be between -180 and 180");
30120
- }
30121
- }
30122
29370
  var import_ngeohash;
30123
29371
  var init_utils3 = __esm({
30124
29372
  "src/shared/geohash/utils.ts"() {
@@ -30126,14 +29374,12 @@ var init_utils3 = __esm({
30126
29374
  import_ngeohash = __toESM(require_main(), 1);
30127
29375
  __name(isGeoCoordinates, "isGeoCoordinates");
30128
29376
  __name(encodeGeoHash, "encodeGeoHash");
30129
- __name(decodeGeoHash, "decodeGeoHash");
30130
29377
  __name(getNeighborGeoHashes, "getNeighborGeoHashes");
30131
29378
  __name(calculateDistance, "calculateDistance");
30132
29379
  __name(isNearQueryGeoJSON, "isNearQueryGeoJSON");
30133
29380
  __name(extractCoordinatesFromNearQuery, "extractCoordinatesFromNearQuery");
30134
29381
  __name(extractMaxDistanceFromNearQuery, "extractMaxDistanceFromNearQuery");
30135
29382
  __name(extractMinDistanceFromNearQuery, "extractMinDistanceFromNearQuery");
30136
- __name(validateLocation, "validateLocation");
30137
29383
  }
30138
29384
  });
30139
29385
 
@@ -30147,60 +29393,6 @@ var init_geohash = __esm({
30147
29393
  });
30148
29394
 
30149
29395
  // src/shared/index.ts
30150
- var shared_exports = {};
30151
- __export(shared_exports, {
30152
- AppError: () => AppError,
30153
- AuthError: () => AuthError,
30154
- ConfigError: () => ConfigError,
30155
- DEFAULT_GEOHASH_CONFIG: () => DEFAULT_GEOHASH_CONFIG,
30156
- DEFAULT_HTTP_TIMEOUT_MS: () => DEFAULT_HTTP_TIMEOUT_MS,
30157
- DYNAMODB_BATCH_GET_MAX_ITEMS: () => DYNAMODB_BATCH_GET_MAX_ITEMS,
30158
- DYNAMODB_BATCH_WRITE_MAX_ITEMS: () => DYNAMODB_BATCH_WRITE_MAX_ITEMS,
30159
- DYNAMODB_QUERY_MAX_SIZE_BYTES: () => DYNAMODB_QUERY_MAX_SIZE_BYTES,
30160
- DYNAMODB_RESERVED_WORDS: () => DYNAMODB_RESERVED_WORDS,
30161
- DYNAMODB_SCAN_MAX_SIZE_BYTES: () => DYNAMODB_SCAN_MAX_SIZE_BYTES,
30162
- DYNAMODB_TRANSACT_WRITE_MAX_ITEMS: () => DYNAMODB_TRANSACT_WRITE_MAX_ITEMS,
30163
- ErrorCode: () => ErrorCode,
30164
- GEOHASH_PRECISION_TABLE: () => GEOHASH_PRECISION_TABLE,
30165
- HTTP_METHOD: () => HTTP_METHOD,
30166
- HTTP_STATUS: () => HTTP_STATUS,
30167
- InvalidFilterError: () => InvalidFilterError,
30168
- InvalidTokenError: () => InvalidTokenError,
30169
- ItemNotFoundError: () => ItemNotFoundError,
30170
- LAMBDA_MAX_ENV_VARS_SIZE: () => LAMBDA_MAX_ENV_VARS_SIZE,
30171
- LAMBDA_MAX_PAYLOAD_SIZE_ASYNC: () => LAMBDA_MAX_PAYLOAD_SIZE_ASYNC,
30172
- LAMBDA_MAX_PAYLOAD_SIZE_SYNC: () => LAMBDA_MAX_PAYLOAD_SIZE_SYNC,
30173
- LAMBDA_MAX_RESPONSE_SIZE: () => LAMBDA_MAX_RESPONSE_SIZE,
30174
- LAMBDA_TIMEOUT_MS: () => LAMBDA_TIMEOUT_MS,
30175
- LARGE_BATCH_WARNING_THRESHOLD: () => LARGE_BATCH_WARNING_THRESHOLD,
30176
- PartialFailureError: () => PartialFailureError,
30177
- TIMEOUT_RISK_THRESHOLD: () => TIMEOUT_RISK_THRESHOLD,
30178
- VersionConflictError: () => VersionConflictError,
30179
- calculateDistance: () => calculateDistance,
30180
- createDynamoDBClient: () => createDynamoDBClient,
30181
- createLogger: () => createLogger,
30182
- decodeGeoHash: () => decodeGeoHash,
30183
- decodeTime: () => decodeTime,
30184
- encodeGeoHash: () => encodeGeoHash,
30185
- extractCoordinatesFromNearQuery: () => extractCoordinatesFromNearQuery,
30186
- extractMaxDistanceFromNearQuery: () => extractMaxDistanceFromNearQuery,
30187
- extractMinDistanceFromNearQuery: () => extractMinDistanceFromNearQuery,
30188
- getErrorClass: () => getErrorClass,
30189
- getNeighborGeoHashes: () => getNeighborGeoHashes,
30190
- isAppError: () => isAppError,
30191
- isGeoCoordinates: () => isGeoCoordinates,
30192
- isNearQueryGeoJSON: () => isNearQueryGeoJSON,
30193
- ulid: () => ulid2,
30194
- ulidWithTime: () => ulidWithTime,
30195
- validateISO8601DateTime: () => validateISO8601DateTime,
30196
- validateLocation: () => validateLocation,
30197
- validateNonEmptyArray: () => validateNonEmptyArray,
30198
- validateNonEmptyString: () => validateNonEmptyString,
30199
- validateNumberRange: () => validateNumberRange,
30200
- validateRequiredFields: () => validateRequiredFields,
30201
- validateSortField: () => validateSortField,
30202
- validateULID: () => validateULID
30203
- });
30204
29396
  var init_shared = __esm({
30205
29397
  "src/shared/index.ts"() {
30206
29398
  "use strict";
@@ -30271,14 +29463,10 @@ function calculateShadowDiff(oldShadowKeys, newShadowKeys) {
30271
29463
  toAdd
30272
29464
  };
30273
29465
  }
30274
- function isDiffEmpty(diff) {
30275
- return diff.toDelete.length === 0 && diff.toAdd.length === 0;
30276
- }
30277
29466
  var init_differ = __esm({
30278
29467
  "src/shadows/differ.ts"() {
30279
29468
  "use strict";
30280
29469
  __name(calculateShadowDiff, "calculateShadowDiff");
30281
- __name(isDiffEmpty, "isDiffEmpty");
30282
29470
  }
30283
29471
  });
30284
29472
 
@@ -30507,6 +29695,238 @@ var init_shadow = __esm({
30507
29695
  }
30508
29696
  });
30509
29697
 
29698
+ // src/server/utils/bulkOperations.ts
29699
+ function logLargeBatchWarning(operation2, recordCount, requestId, resource) {
29700
+ if (recordCount > LARGE_BATCH_WARNING_THRESHOLD) {
29701
+ logger2.warn(`Large batch ${operation2} operation detected`, {
29702
+ requestId,
29703
+ resource,
29704
+ recordCount,
29705
+ warningThreshold: LARGE_BATCH_WARNING_THRESHOLD,
29706
+ estimatedTimeoutRisk: "high",
29707
+ recommendation: "Consider splitting the batch into smaller requests to avoid Lambda timeout (15 min limit)"
29708
+ });
29709
+ }
29710
+ }
29711
+ function calculateTimeoutRisk(startTime) {
29712
+ const elapsedMs = Date.now() - startTime;
29713
+ const remainingMs = LAMBDA_TIMEOUT_MS - elapsedMs;
29714
+ const utilizationPercent = Math.round(elapsedMs / LAMBDA_TIMEOUT_MS * 100);
29715
+ const risk = remainingMs < LAMBDA_TIMEOUT_MS * TIMEOUT_RISK_THRESHOLD ? "high" : "low";
29716
+ return {
29717
+ elapsedMs,
29718
+ remainingMs,
29719
+ risk,
29720
+ utilizationPercent
29721
+ };
29722
+ }
29723
+ function logPreparationTimeoutRisk(requestId, resource, totalRecords, chunkCount, riskInfo) {
29724
+ logger2.info("Records prepared for chunk execution", {
29725
+ requestId,
29726
+ resource,
29727
+ totalRecords,
29728
+ chunkCount,
29729
+ preparationTimeMs: riskInfo.elapsedMs,
29730
+ remainingTimeMs: riskInfo.remainingMs,
29731
+ timeoutRisk: riskInfo.risk
29732
+ });
29733
+ if (riskInfo.risk === "high") {
29734
+ logger2.warn("High timeout risk detected during preparation phase", {
29735
+ requestId,
29736
+ resource,
29737
+ preparationElapsedMs: riskInfo.elapsedMs,
29738
+ remainingTimeMs: riskInfo.remainingMs,
29739
+ lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
29740
+ recommendation: "Consider reducing batch size or optimizing preparation logic"
29741
+ });
29742
+ }
29743
+ }
29744
+ function logBulkOperationComplete(operation2, requestId, resource, requested, succeeded, failed, riskInfo, additionalInfo) {
29745
+ const totalElapsedSeconds = Math.round(riskInfo.elapsedMs / 1e3);
29746
+ logger2.info(`${operation2} completed`, {
29747
+ requestId,
29748
+ resource,
29749
+ requested,
29750
+ succeeded,
29751
+ totalFailed: failed,
29752
+ totalExecutionTimeMs: riskInfo.elapsedMs,
29753
+ totalExecutionTimeSeconds: totalElapsedSeconds,
29754
+ lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
29755
+ timeoutUtilization: `${riskInfo.utilizationPercent}%`,
29756
+ ...additionalInfo
29757
+ });
29758
+ }
29759
+ function logPartialFailure(operation2, requestId, resource, requested, succeeded, failed, errorCodes, additionalInfo) {
29760
+ const failureRate = Math.round(failed / requested * 100);
29761
+ logger2.warn(`Partial failure in ${operation2} operation`, {
29762
+ requestId,
29763
+ resource,
29764
+ totalRequested: requested,
29765
+ successCount: succeeded,
29766
+ failedCount: failed,
29767
+ failureRate: `${failureRate}%`,
29768
+ errorCodes: [...new Set(errorCodes)],
29769
+ ...additionalInfo
29770
+ });
29771
+ }
29772
+ var logger2;
29773
+ var init_bulkOperations = __esm({
29774
+ "src/server/utils/bulkOperations.ts"() {
29775
+ "use strict";
29776
+ init_shared();
29777
+ logger2 = createLogger({ service: "records-lambda" });
29778
+ __name(logLargeBatchWarning, "logLargeBatchWarning");
29779
+ __name(calculateTimeoutRisk, "calculateTimeoutRisk");
29780
+ __name(logPreparationTimeoutRisk, "logPreparationTimeoutRisk");
29781
+ __name(logBulkOperationComplete, "logBulkOperationComplete");
29782
+ __name(logPartialFailure, "logPartialFailure");
29783
+ }
29784
+ });
29785
+
29786
+ // src/server/utils/chunking.ts
29787
+ function calculateChunks(records, getItemCount) {
29788
+ const chunks = [];
29789
+ const itemCounts = [];
29790
+ let currentChunk = [];
29791
+ let currentItemCount = 0;
29792
+ for (const record of records) {
29793
+ const itemCount = getItemCount(record);
29794
+ if (itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
29795
+ const errorMsg = `Single record exceeds ${DYNAMODB_TRANSACT_WRITE_MAX_ITEMS} items limit: ${itemCount} items`;
29796
+ logger3.error("Chunk validation failed", {
29797
+ itemCount,
29798
+ limit: DYNAMODB_TRANSACT_WRITE_MAX_ITEMS
29799
+ });
29800
+ throw new Error(errorMsg);
29801
+ }
29802
+ if (currentItemCount + itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
29803
+ if (currentChunk.length > 0) {
29804
+ chunks.push(currentChunk);
29805
+ itemCounts.push(currentItemCount);
29806
+ }
29807
+ currentChunk = [record];
29808
+ currentItemCount = itemCount;
29809
+ } else {
29810
+ currentChunk.push(record);
29811
+ currentItemCount += itemCount;
29812
+ }
29813
+ }
29814
+ if (currentChunk.length > 0) {
29815
+ chunks.push(currentChunk);
29816
+ itemCounts.push(currentItemCount);
29817
+ }
29818
+ logger3.info("Chunk calculation completed", {
29819
+ totalRecords: records.length,
29820
+ chunkCount: chunks.length,
29821
+ itemCounts,
29822
+ minItemsPerChunk: itemCounts.length > 0 ? Math.min(...itemCounts) : 0,
29823
+ maxItemsPerChunk: itemCounts.length > 0 ? Math.max(...itemCounts) : 0,
29824
+ avgItemsPerChunk: itemCounts.length > 0 ? Math.round(itemCounts.reduce((sum, count) => sum + count, 0) / itemCounts.length) : 0
29825
+ });
29826
+ return { chunks, itemCounts };
29827
+ }
29828
+ async function executeChunks(chunks, executeChunk, getRecordId) {
29829
+ const successRecords = [];
29830
+ const failedIds = [];
29831
+ const errors = [];
29832
+ const totalRecords = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
29833
+ const executionStartTime = Date.now();
29834
+ logger3.info("Starting chunk execution", {
29835
+ totalChunks: chunks.length,
29836
+ totalRecords
29837
+ });
29838
+ for (let i4 = 0; i4 < chunks.length; i4++) {
29839
+ const chunk = chunks[i4];
29840
+ const chunkStartTime = Date.now();
29841
+ try {
29842
+ logger3.debug(`Executing chunk ${i4 + 1}/${chunks.length}`, {
29843
+ chunkIndex: i4,
29844
+ recordCount: chunk.length
29845
+ });
29846
+ const successfulRecords = await executeChunk(chunk);
29847
+ successRecords.push(...successfulRecords);
29848
+ const chunkDuration = Date.now() - chunkStartTime;
29849
+ logger3.info(`Chunk ${i4 + 1}/${chunks.length} succeeded`, {
29850
+ chunkIndex: i4,
29851
+ recordCount: chunk.length,
29852
+ durationMs: chunkDuration
29853
+ });
29854
+ } catch (error2) {
29855
+ const chunkDuration = Date.now() - chunkStartTime;
29856
+ const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
29857
+ const errorCode = getErrorCode(error2);
29858
+ logger3.error(`Chunk ${i4 + 1}/${chunks.length} failed`, {
29859
+ chunkIndex: i4,
29860
+ recordCount: chunk.length,
29861
+ durationMs: chunkDuration,
29862
+ error: errorMessage,
29863
+ errorCode
29864
+ });
29865
+ for (const record of chunk) {
29866
+ const recordId = getRecordId(record);
29867
+ failedIds.push(recordId);
29868
+ errors.push({
29869
+ id: recordId,
29870
+ code: errorCode,
29871
+ message: errorMessage
29872
+ });
29873
+ }
29874
+ }
29875
+ }
29876
+ const totalExecutionTime = Date.now() - executionStartTime;
29877
+ logger3.info("Chunk execution completed", {
29878
+ totalChunks: chunks.length,
29879
+ totalRecords,
29880
+ successCount: successRecords.length,
29881
+ failedCount: failedIds.length,
29882
+ totalExecutionTimeMs: totalExecutionTime,
29883
+ avgTimePerChunkMs: chunks.length > 0 ? Math.round(totalExecutionTime / chunks.length) : 0
29884
+ });
29885
+ if (failedIds.length > 0) {
29886
+ logger3.warn("Partial failure detected in chunk execution", {
29887
+ totalRecords,
29888
+ successCount: successRecords.length,
29889
+ failedCount: failedIds.length,
29890
+ failureRate: `${Math.round(failedIds.length / totalRecords * 100)}%`,
29891
+ failedIds: failedIds.slice(0, 10),
29892
+ // 最初の10件のみログ出力
29893
+ errorSummary: errors.slice(0, 5).map((e4) => ({
29894
+ id: e4.id,
29895
+ code: e4.code,
29896
+ message: e4.message.substring(0, 100)
29897
+ // メッセージを100文字に制限
29898
+ }))
29899
+ });
29900
+ }
29901
+ return {
29902
+ successRecords,
29903
+ failedIds,
29904
+ errors
29905
+ };
29906
+ }
29907
+ function getErrorCode(error2) {
29908
+ if (error2 && typeof error2 === "object") {
29909
+ if ("name" in error2 && typeof error2.name === "string") {
29910
+ return error2.name;
29911
+ }
29912
+ if ("code" in error2 && typeof error2.code === "string") {
29913
+ return error2.code;
29914
+ }
29915
+ }
29916
+ return "TRANSACTION_FAILED";
29917
+ }
29918
+ var logger3;
29919
+ var init_chunking = __esm({
29920
+ "src/server/utils/chunking.ts"() {
29921
+ "use strict";
29922
+ init_shared();
29923
+ logger3 = createLogger({ service: "records-lambda" });
29924
+ __name(calculateChunks, "calculateChunks");
29925
+ __name(executeChunks, "executeChunks");
29926
+ __name(getErrorCode, "getErrorCode");
29927
+ }
29928
+ });
29929
+
30510
29930
  // src/server/utils/dynamodb.ts
30511
29931
  function getDBClient() {
30512
29932
  if (!dbClient) {
@@ -30564,7 +29984,7 @@ var init_dynamodb3 = __esm({
30564
29984
  });
30565
29985
 
30566
29986
  // src/server/utils/validation.ts
30567
- function validateSortField2(_config, _resource, _sort) {
29987
+ function validateSortField(_config, _resource, _sort) {
30568
29988
  return;
30569
29989
  }
30570
29990
  function normalizePagination(pagination) {
@@ -30584,7 +30004,7 @@ function normalizeSort(config, _resource, sort) {
30584
30004
  var init_validation2 = __esm({
30585
30005
  "src/server/utils/validation.ts"() {
30586
30006
  "use strict";
30587
- __name(validateSortField2, "validateSortField");
30007
+ __name(validateSortField, "validateSortField");
30588
30008
  __name(normalizePagination, "normalizePagination");
30589
30009
  __name(normalizeSort, "normalizeSort");
30590
30010
  }
@@ -31503,7 +30923,7 @@ async function handleFind(resource, params, requestId) {
31503
30923
  }
31504
30924
  const config = initializeFindConfig();
31505
30925
  const normalizedParams = normalizeFindParams(config, resource, params);
31506
- validateSortField2(config, resource, normalizedParams.sort);
30926
+ validateSortField(config, resource, normalizedParams.sort);
31507
30927
  logger9.debug("Find parameters normalized", {
31508
30928
  requestId,
31509
30929
  resource,
@@ -31546,246 +30966,11 @@ var init_find = __esm({
31546
30966
  }
31547
30967
  });
31548
30968
 
31549
- // src/server/handler.ts
31550
- var handler_exports = {};
31551
- __export(handler_exports, {
31552
- handler: () => handler
31553
- });
31554
- module.exports = __toCommonJS(handler_exports);
31555
- init_http();
31556
- init_shared();
31557
-
31558
- // src/server/operations/operationDispatcher.ts
31559
- init_shared();
31560
-
31561
- // src/server/operations/deleteMany.ts
31562
- var import_lib_dynamodb5 = __toESM(require_dist_cjs66(), 1);
31563
- init_shared();
31564
- init_shadow();
31565
-
31566
- // src/server/utils/bulkOperations.ts
31567
- init_shared();
31568
- var logger2 = createLogger({ service: "records-lambda" });
31569
- function logLargeBatchWarning(operation2, recordCount, requestId, resource) {
31570
- if (recordCount > LARGE_BATCH_WARNING_THRESHOLD) {
31571
- logger2.warn(`Large batch ${operation2} operation detected`, {
31572
- requestId,
31573
- resource,
31574
- recordCount,
31575
- warningThreshold: LARGE_BATCH_WARNING_THRESHOLD,
31576
- estimatedTimeoutRisk: "high",
31577
- recommendation: "Consider splitting the batch into smaller requests to avoid Lambda timeout (15 min limit)"
31578
- });
31579
- }
31580
- }
31581
- __name(logLargeBatchWarning, "logLargeBatchWarning");
31582
- function calculateTimeoutRisk(startTime) {
31583
- const elapsedMs = Date.now() - startTime;
31584
- const remainingMs = LAMBDA_TIMEOUT_MS - elapsedMs;
31585
- const utilizationPercent = Math.round(elapsedMs / LAMBDA_TIMEOUT_MS * 100);
31586
- const risk = remainingMs < LAMBDA_TIMEOUT_MS * TIMEOUT_RISK_THRESHOLD ? "high" : "low";
31587
- return {
31588
- elapsedMs,
31589
- remainingMs,
31590
- risk,
31591
- utilizationPercent
31592
- };
31593
- }
31594
- __name(calculateTimeoutRisk, "calculateTimeoutRisk");
31595
- function logPreparationTimeoutRisk(requestId, resource, totalRecords, chunkCount, riskInfo) {
31596
- logger2.info("Records prepared for chunk execution", {
31597
- requestId,
31598
- resource,
31599
- totalRecords,
31600
- chunkCount,
31601
- preparationTimeMs: riskInfo.elapsedMs,
31602
- remainingTimeMs: riskInfo.remainingMs,
31603
- timeoutRisk: riskInfo.risk
31604
- });
31605
- if (riskInfo.risk === "high") {
31606
- logger2.warn("High timeout risk detected during preparation phase", {
31607
- requestId,
31608
- resource,
31609
- preparationElapsedMs: riskInfo.elapsedMs,
31610
- remainingTimeMs: riskInfo.remainingMs,
31611
- lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
31612
- recommendation: "Consider reducing batch size or optimizing preparation logic"
31613
- });
31614
- }
31615
- }
31616
- __name(logPreparationTimeoutRisk, "logPreparationTimeoutRisk");
31617
- function logBulkOperationComplete(operation2, requestId, resource, requested, succeeded, failed, riskInfo, additionalInfo) {
31618
- const totalElapsedSeconds = Math.round(riskInfo.elapsedMs / 1e3);
31619
- logger2.info(`${operation2} completed`, {
31620
- requestId,
31621
- resource,
31622
- requested,
31623
- succeeded,
31624
- totalFailed: failed,
31625
- totalExecutionTimeMs: riskInfo.elapsedMs,
31626
- totalExecutionTimeSeconds: totalElapsedSeconds,
31627
- lambdaTimeoutMs: LAMBDA_TIMEOUT_MS,
31628
- timeoutUtilization: `${riskInfo.utilizationPercent}%`,
31629
- ...additionalInfo
31630
- });
31631
- }
31632
- __name(logBulkOperationComplete, "logBulkOperationComplete");
31633
- function logPartialFailure(operation2, requestId, resource, requested, succeeded, failed, errorCodes, additionalInfo) {
31634
- const failureRate = Math.round(failed / requested * 100);
31635
- logger2.warn(`Partial failure in ${operation2} operation`, {
31636
- requestId,
31637
- resource,
31638
- totalRequested: requested,
31639
- successCount: succeeded,
31640
- failedCount: failed,
31641
- failureRate: `${failureRate}%`,
31642
- errorCodes: [...new Set(errorCodes)],
31643
- ...additionalInfo
31644
- });
31645
- }
31646
- __name(logPartialFailure, "logPartialFailure");
31647
-
31648
- // src/server/utils/chunking.ts
31649
- init_shared();
31650
- var logger3 = createLogger({ service: "records-lambda" });
31651
- function calculateChunks(records, getItemCount) {
31652
- const chunks = [];
31653
- const itemCounts = [];
31654
- let currentChunk = [];
31655
- let currentItemCount = 0;
31656
- for (const record of records) {
31657
- const itemCount = getItemCount(record);
31658
- if (itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
31659
- const errorMsg = `Single record exceeds ${DYNAMODB_TRANSACT_WRITE_MAX_ITEMS} items limit: ${itemCount} items`;
31660
- logger3.error("Chunk validation failed", {
31661
- itemCount,
31662
- limit: DYNAMODB_TRANSACT_WRITE_MAX_ITEMS
31663
- });
31664
- throw new Error(errorMsg);
31665
- }
31666
- if (currentItemCount + itemCount > DYNAMODB_TRANSACT_WRITE_MAX_ITEMS) {
31667
- if (currentChunk.length > 0) {
31668
- chunks.push(currentChunk);
31669
- itemCounts.push(currentItemCount);
31670
- }
31671
- currentChunk = [record];
31672
- currentItemCount = itemCount;
31673
- } else {
31674
- currentChunk.push(record);
31675
- currentItemCount += itemCount;
31676
- }
31677
- }
31678
- if (currentChunk.length > 0) {
31679
- chunks.push(currentChunk);
31680
- itemCounts.push(currentItemCount);
31681
- }
31682
- logger3.info("Chunk calculation completed", {
31683
- totalRecords: records.length,
31684
- chunkCount: chunks.length,
31685
- itemCounts,
31686
- minItemsPerChunk: itemCounts.length > 0 ? Math.min(...itemCounts) : 0,
31687
- maxItemsPerChunk: itemCounts.length > 0 ? Math.max(...itemCounts) : 0,
31688
- avgItemsPerChunk: itemCounts.length > 0 ? Math.round(itemCounts.reduce((sum, count) => sum + count, 0) / itemCounts.length) : 0
31689
- });
31690
- return { chunks, itemCounts };
31691
- }
31692
- __name(calculateChunks, "calculateChunks");
31693
- async function executeChunks(chunks, executeChunk, getRecordId) {
31694
- const successRecords = [];
31695
- const failedIds = [];
31696
- const errors = [];
31697
- const totalRecords = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
31698
- const executionStartTime = Date.now();
31699
- logger3.info("Starting chunk execution", {
31700
- totalChunks: chunks.length,
31701
- totalRecords
31702
- });
31703
- for (let i4 = 0; i4 < chunks.length; i4++) {
31704
- const chunk = chunks[i4];
31705
- const chunkStartTime = Date.now();
31706
- try {
31707
- logger3.debug(`Executing chunk ${i4 + 1}/${chunks.length}`, {
31708
- chunkIndex: i4,
31709
- recordCount: chunk.length
31710
- });
31711
- const successfulRecords = await executeChunk(chunk);
31712
- successRecords.push(...successfulRecords);
31713
- const chunkDuration = Date.now() - chunkStartTime;
31714
- logger3.info(`Chunk ${i4 + 1}/${chunks.length} succeeded`, {
31715
- chunkIndex: i4,
31716
- recordCount: chunk.length,
31717
- durationMs: chunkDuration
31718
- });
31719
- } catch (error2) {
31720
- const chunkDuration = Date.now() - chunkStartTime;
31721
- const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
31722
- const errorCode = getErrorCode(error2);
31723
- logger3.error(`Chunk ${i4 + 1}/${chunks.length} failed`, {
31724
- chunkIndex: i4,
31725
- recordCount: chunk.length,
31726
- durationMs: chunkDuration,
31727
- error: errorMessage,
31728
- errorCode
31729
- });
31730
- for (const record of chunk) {
31731
- const recordId = getRecordId(record);
31732
- failedIds.push(recordId);
31733
- errors.push({
31734
- id: recordId,
31735
- code: errorCode,
31736
- message: errorMessage
31737
- });
31738
- }
31739
- }
31740
- }
31741
- const totalExecutionTime = Date.now() - executionStartTime;
31742
- logger3.info("Chunk execution completed", {
31743
- totalChunks: chunks.length,
31744
- totalRecords,
31745
- successCount: successRecords.length,
31746
- failedCount: failedIds.length,
31747
- totalExecutionTimeMs: totalExecutionTime,
31748
- avgTimePerChunkMs: chunks.length > 0 ? Math.round(totalExecutionTime / chunks.length) : 0
31749
- });
31750
- if (failedIds.length > 0) {
31751
- logger3.warn("Partial failure detected in chunk execution", {
31752
- totalRecords,
31753
- successCount: successRecords.length,
31754
- failedCount: failedIds.length,
31755
- failureRate: `${Math.round(failedIds.length / totalRecords * 100)}%`,
31756
- failedIds: failedIds.slice(0, 10),
31757
- // 最初の10件のみログ出力
31758
- errorSummary: errors.slice(0, 5).map((e4) => ({
31759
- id: e4.id,
31760
- code: e4.code,
31761
- message: e4.message.substring(0, 100)
31762
- // メッセージを100文字に制限
31763
- }))
31764
- });
31765
- }
31766
- return {
31767
- successRecords,
31768
- failedIds,
31769
- errors
31770
- };
31771
- }
31772
- __name(executeChunks, "executeChunks");
31773
- function getErrorCode(error2) {
31774
- if (error2 && typeof error2 === "object") {
31775
- if ("name" in error2 && typeof error2.name === "string") {
31776
- return error2.name;
31777
- }
31778
- if ("code" in error2 && typeof error2.code === "string") {
31779
- return error2.code;
31780
- }
31781
- }
31782
- return "TRANSACTION_FAILED";
31783
- }
31784
- __name(getErrorCode, "getErrorCode");
31785
-
31786
30969
  // src/server/operations/deleteMany.ts
31787
- init_dynamodb3();
31788
- var logger10 = createLogger({ service: "records-lambda" });
30970
+ var deleteMany_exports = {};
30971
+ __export(deleteMany_exports, {
30972
+ handleDeleteMany: () => handleDeleteMany
30973
+ });
31789
30974
  async function handleDeleteMany(resource, params, requestId) {
31790
30975
  const startTime = Date.now();
31791
30976
  let ids;
@@ -32009,330 +31194,133 @@ async function handleDeleteMany(resource, params, requestId) {
32009
31194
  errors: errorsMap
32010
31195
  };
32011
31196
  }
32012
- __name(handleDeleteMany, "handleDeleteMany");
31197
+ var import_lib_dynamodb5, logger10;
31198
+ var init_deleteMany = __esm({
31199
+ "src/server/operations/deleteMany.ts"() {
31200
+ "use strict";
31201
+ import_lib_dynamodb5 = __toESM(require_dist_cjs66(), 1);
31202
+ init_shared();
31203
+ init_shadow();
31204
+ init_bulkOperations();
31205
+ init_chunking();
31206
+ init_dynamodb3();
31207
+ logger10 = createLogger({ service: "records-lambda" });
31208
+ __name(handleDeleteMany, "handleDeleteMany");
31209
+ }
31210
+ });
32013
31211
 
32014
- // src/server/operations/deleteOne.ts
32015
- var import_lib_dynamodb6 = __toESM(require_dist_cjs66(), 1);
32016
- init_shared();
32017
- init_shadow();
32018
- init_dynamodb3();
32019
- var logger11 = createLogger({ service: "records-lambda" });
32020
- async function handleDeleteOne(resource, params, requestId) {
32021
- let targetId;
32022
- if ("id" in params) {
32023
- targetId = params.id;
32024
- logger11.debug("Executing deleteOne with id", {
31212
+ // src/server/operations/findMany.ts
31213
+ async function handleFindMany(resource, params, requestId) {
31214
+ if ("ids" in params) {
31215
+ const { ids } = params;
31216
+ logger12.debug("Executing findMany by ids", {
32025
31217
  requestId,
32026
31218
  resource,
32027
- id: targetId
31219
+ count: ids.length
32028
31220
  });
32029
- } else {
32030
- logger11.debug("Executing deleteOne with filter", {
31221
+ if (ids.length === 0) {
31222
+ return [];
31223
+ }
31224
+ const dbClient2 = getDBClient();
31225
+ const tableName = getTableName();
31226
+ const keys = ids.map((id) => ({
31227
+ PK: resource,
31228
+ SK: generateMainRecordSK2(id)
31229
+ }));
31230
+ const result = await executeDynamoDBOperation(
31231
+ () => dbClient2.send(
31232
+ new import_lib_dynamodb6.BatchGetCommand({
31233
+ RequestItems: {
31234
+ [tableName]: {
31235
+ Keys: keys,
31236
+ ConsistentRead: true
31237
+ }
31238
+ }
31239
+ })
31240
+ ),
31241
+ "BatchGetItem"
31242
+ );
31243
+ const items = result.Responses?.[tableName] || [];
31244
+ const records = items.map((item) => extractCleanRecord(item));
31245
+ logger12.info("findMany by ids succeeded", {
32031
31246
  requestId,
32032
31247
  resource,
32033
- filter: params.filter
31248
+ requested: ids.length,
31249
+ found: records.length
32034
31250
  });
32035
- const { handleFind: handleFind2 } = await Promise.resolve().then(() => (init_find(), find_exports));
32036
- const findResult = await handleFind2(
31251
+ return records;
31252
+ }
31253
+ if ("filter" in params) {
31254
+ const { filter } = params;
31255
+ logger12.debug("Executing findMany by filter", {
31256
+ requestId,
31257
+ resource,
31258
+ filter
31259
+ });
31260
+ const findResult = await handleFind(
32037
31261
  resource,
32038
- { filter: params.filter, pagination: { perPage: 1 } },
31262
+ {
31263
+ filter
31264
+ },
32039
31265
  requestId
32040
31266
  );
32041
- if (findResult.items.length === 0) {
32042
- throw new ItemNotFoundError(`Record not found with filter`, {
32043
- resource,
32044
- filter: params.filter
32045
- });
32046
- }
32047
- const foundRecord = findResult.items[0];
32048
- targetId = foundRecord.id;
32049
- }
32050
- const dbClient2 = getDBClient();
32051
- const tableName = getTableName();
32052
- const mainSK = generateMainRecordSK2(targetId);
32053
- const getResult = await executeDynamoDBOperation(
32054
- () => dbClient2.send(
32055
- new import_lib_dynamodb6.GetCommand({
32056
- TableName: tableName,
32057
- Key: {
32058
- PK: resource,
32059
- SK: mainSK
32060
- },
32061
- ConsistentRead: true
32062
- })
32063
- ),
32064
- "GetItem"
32065
- );
32066
- if (!getResult.Item) {
32067
- throw new ItemNotFoundError(`Record not found: ${targetId}`, { resource, id: targetId });
32068
- }
32069
- const existingData = getResult.Item.data;
32070
- const shadowKeys = existingData.__shadowKeys || [];
32071
- const transactItems = [];
32072
- transactItems.push({
32073
- Delete: {
32074
- TableName: tableName,
32075
- Key: {
32076
- PK: resource,
32077
- SK: mainSK
32078
- }
32079
- }
32080
- });
32081
- for (const shadowSK of shadowKeys) {
32082
- transactItems.push({
32083
- Delete: {
32084
- TableName: tableName,
32085
- Key: {
32086
- PK: resource,
32087
- SK: shadowSK
32088
- }
32089
- }
31267
+ logger12.info("findMany by filter succeeded", {
31268
+ requestId,
31269
+ resource,
31270
+ filter,
31271
+ found: findResult.items.length
32090
31272
  });
31273
+ return findResult.items;
32091
31274
  }
32092
- await executeDynamoDBOperation(
32093
- () => dbClient2.send(
32094
- new import_lib_dynamodb6.TransactWriteCommand({
32095
- TransactItems: transactItems
32096
- })
32097
- ),
32098
- "TransactWriteItems"
32099
- );
32100
- logger11.info("deleteOne succeeded", {
32101
- requestId,
32102
- resource,
32103
- id: targetId,
32104
- shadowCount: shadowKeys.length
32105
- });
32106
- return { id: targetId };
31275
+ throw new Error("findMany requires either ids or filter");
32107
31276
  }
32108
- __name(handleDeleteOne, "handleDeleteOne");
32109
-
32110
- // src/server/operations/operationDispatcher.ts
32111
- init_find();
32112
-
32113
- // src/server/operations/findMany.ts
32114
- var import_lib_dynamodb7 = __toESM(require_dist_cjs66(), 1);
32115
- init_shared();
32116
- init_shadow();
32117
- init_dynamodb3();
32118
- var logger12 = createLogger({ service: "records-lambda" });
32119
- async function handleFindMany(resource, params, requestId) {
32120
- const { ids } = params;
32121
- logger12.debug("Executing findMany", {
32122
- requestId,
32123
- resource,
32124
- count: ids.length
32125
- });
32126
- if (ids.length === 0) {
32127
- return [];
32128
- }
32129
- const dbClient2 = getDBClient();
32130
- const tableName = getTableName();
32131
- const keys = ids.map((id) => ({
32132
- PK: resource,
32133
- SK: generateMainRecordSK2(id)
32134
- }));
32135
- const result = await executeDynamoDBOperation(
32136
- () => dbClient2.send(
32137
- new import_lib_dynamodb7.BatchGetCommand({
32138
- RequestItems: {
32139
- [tableName]: {
32140
- Keys: keys,
32141
- ConsistentRead: true
32142
- }
32143
- }
32144
- })
32145
- ),
32146
- "BatchGetItem"
32147
- );
32148
- const items = result.Responses?.[tableName] || [];
32149
- const records = items.map((item) => extractCleanRecord(item));
32150
- logger12.info("findMany succeeded", {
32151
- requestId,
32152
- resource,
32153
- requested: ids.length,
32154
- found: records.length
32155
- });
32156
- return records;
32157
- }
32158
- __name(handleFindMany, "handleFindMany");
32159
-
32160
- // src/server/operations/findManyReference.ts
32161
- var import_lib_dynamodb8 = __toESM(require_dist_cjs66(), 1);
32162
- init_shared();
32163
- init_shadow();
32164
- init_dynamodb3();
32165
- init_pagination();
32166
- init_validation2();
32167
- var logger13 = createLogger({ service: "records-lambda" });
32168
- async function handleFindManyReference(resource, params, requestId) {
32169
- const { target, id, filter, sort: sortParam, pagination } = params;
32170
- logger13.debug("Executing findManyReference", {
32171
- requestId,
32172
- resource,
32173
- target,
32174
- id
32175
- });
32176
- const shadowConfig = getShadowConfig();
32177
- const sort = normalizeSort(shadowConfig, resource, sortParam);
32178
- validateSortField2(shadowConfig, resource, sort);
32179
- const { perPage, nextToken } = normalizePagination(pagination);
32180
- const dbClient2 = getDBClient();
32181
- const tableName = getTableName();
32182
- const skPrefix = `${sort.field}#`;
32183
- let exclusiveStartKey;
32184
- if (nextToken) {
32185
- const decoded = decodeNextToken(nextToken);
32186
- exclusiveStartKey = {
32187
- PK: decoded.PK,
32188
- SK: decoded.SK
32189
- };
32190
- }
32191
- const queryResult = await executeDynamoDBOperation(
32192
- () => dbClient2.send(
32193
- new import_lib_dynamodb8.QueryCommand({
32194
- TableName: tableName,
32195
- KeyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
32196
- ExpressionAttributeValues: {
32197
- ":pk": resource,
32198
- ":skPrefix": skPrefix
32199
- },
32200
- ScanIndexForward: sort.order === "ASC",
32201
- Limit: perPage,
32202
- ExclusiveStartKey: exclusiveStartKey,
32203
- ConsistentRead: true
32204
- })
32205
- ),
32206
- "Query"
32207
- );
32208
- const shadowItems = queryResult.Items || [];
32209
- if (shadowItems.length === 0) {
32210
- return {
32211
- items: [],
32212
- pageInfo: {
32213
- hasNextPage: false,
32214
- hasPreviousPage: false
32215
- }
32216
- };
32217
- }
32218
- const recordIds = shadowItems.map((item) => {
32219
- const sk = item.SK;
32220
- const parts = sk.split("#id#");
32221
- return parts[parts.length - 1];
32222
- });
32223
- const batchGetResult = await executeDynamoDBOperation(
32224
- () => dbClient2.send(
32225
- new import_lib_dynamodb8.BatchGetCommand({
32226
- RequestItems: {
32227
- [tableName]: {
32228
- Keys: recordIds.map((recordId) => ({
32229
- PK: resource,
32230
- SK: `id#${recordId}`
32231
- })),
32232
- ConsistentRead: true
32233
- }
32234
- }
32235
- })
32236
- ),
32237
- "BatchGetItem"
32238
- );
32239
- const mainRecords = batchGetResult.Responses?.[tableName] || [];
32240
- const recordMap = new Map(
32241
- mainRecords.map((item) => {
32242
- const data2 = item.data;
32243
- return [data2.id, extractCleanRecord(item)];
32244
- })
32245
- );
32246
- let items = recordIds.map((recordId) => recordMap.get(recordId)).filter((record) => record !== void 0);
32247
- items = items.filter((record) => record[target] === id);
32248
- if (filter && Object.keys(filter).length > 0) {
32249
- items = items.filter((record) => {
32250
- return Object.entries(filter).every(([key, value]) => {
32251
- return record[key] === value;
32252
- });
32253
- });
31277
+ var import_lib_dynamodb6, logger12;
31278
+ var init_findMany = __esm({
31279
+ "src/server/operations/findMany.ts"() {
31280
+ "use strict";
31281
+ import_lib_dynamodb6 = __toESM(require_dist_cjs66(), 1);
31282
+ init_shared();
31283
+ init_shadow();
31284
+ init_dynamodb3();
31285
+ init_find();
31286
+ logger12 = createLogger({ service: "records-lambda" });
31287
+ __name(handleFindMany, "handleFindMany");
32254
31288
  }
32255
- const hasNextPage = queryResult.LastEvaluatedKey !== void 0;
32256
- const nextTokenValue = hasNextPage && queryResult.LastEvaluatedKey ? encodeNextToken(
32257
- queryResult.LastEvaluatedKey.PK,
32258
- queryResult.LastEvaluatedKey.SK
32259
- ) : void 0;
32260
- logger13.info("findManyReference succeeded", {
32261
- requestId,
32262
- resource,
32263
- target,
32264
- id,
32265
- count: items.length,
32266
- hasNextPage
32267
- });
32268
- return {
32269
- items,
32270
- pageInfo: {
32271
- hasNextPage,
32272
- hasPreviousPage: !!nextToken
32273
- },
32274
- ...nextTokenValue && { nextToken: nextTokenValue }
32275
- };
32276
- }
32277
- __name(handleFindManyReference, "handleFindManyReference");
31289
+ });
32278
31290
 
32279
31291
  // src/server/operations/findOne.ts
32280
- var import_lib_dynamodb9 = __toESM(require_dist_cjs66(), 1);
32281
- init_shared();
32282
- init_shadow();
32283
- init_dynamodb3();
32284
- init_find();
32285
- var logger14 = createLogger({ service: "records-lambda" });
31292
+ var findOne_exports = {};
31293
+ __export(findOne_exports, {
31294
+ handleFindOne: () => handleFindOne
31295
+ });
32286
31296
  async function handleFindOne(resource, params, requestId) {
32287
- const { id, filter } = params;
32288
- if (id) {
32289
- logger14.debug("Executing findOne by id", {
31297
+ if ("id" in params) {
31298
+ const { id } = params;
31299
+ logger14.debug("Executing findOne by id (using findMany)", {
32290
31300
  requestId,
32291
31301
  resource,
32292
31302
  id
32293
31303
  });
32294
- const dbClient2 = getDBClient();
32295
- const tableName = getTableName();
32296
- const sk = generateMainRecordSK2(id);
32297
- const result = await executeDynamoDBOperation(
32298
- () => dbClient2.send(
32299
- new import_lib_dynamodb9.GetCommand({
32300
- TableName: tableName,
32301
- Key: {
32302
- PK: resource,
32303
- SK: sk
32304
- },
32305
- ConsistentRead: true
32306
- })
32307
- ),
32308
- "GetItem"
32309
- );
32310
- if (!result.Item) {
31304
+ const results = await handleFindMany(resource, { ids: [id] }, requestId);
31305
+ if (results.length === 0) {
32311
31306
  throw new ItemNotFoundError(`Record not found: ${id}`, { resource, id });
32312
31307
  }
32313
- const record = extractCleanRecord(result.Item);
32314
31308
  logger14.info("findOne by id succeeded", {
32315
31309
  requestId,
32316
31310
  resource,
32317
31311
  id
32318
31312
  });
32319
- return record;
31313
+ return results[0];
32320
31314
  }
32321
- if (filter) {
32322
- logger14.debug("Executing findOne by filter", {
31315
+ if ("filter" in params) {
31316
+ const { filter } = params;
31317
+ logger14.debug("Executing findOne by filter (using findMany)", {
32323
31318
  requestId,
32324
31319
  resource,
32325
31320
  filter
32326
31321
  });
32327
- const findResult = await handleFind(
32328
- resource,
32329
- {
32330
- filter,
32331
- pagination: { perPage: 1 }
32332
- },
32333
- requestId
32334
- );
32335
- if (!findResult.items || findResult.items.length === 0) {
31322
+ const results = await handleFindMany(resource, { filter }, requestId);
31323
+ if (results.length === 0) {
32336
31324
  throw new ItemNotFoundError(`Record not found with filter`, { resource, filter });
32337
31325
  }
32338
31326
  logger14.info("findOne by filter succeeded", {
@@ -32340,21 +31328,22 @@ async function handleFindOne(resource, params, requestId) {
32340
31328
  resource,
32341
31329
  filter
32342
31330
  });
32343
- return findResult.items[0];
31331
+ return results[0];
32344
31332
  }
32345
31333
  throw new Error("findOne requires either id or filter");
32346
31334
  }
32347
- __name(handleFindOne, "handleFindOne");
32348
-
32349
- // src/server/operations/insertMany.ts
32350
- var import_lib_dynamodb10 = __toESM(require_dist_cjs66(), 1);
32351
- init_shared();
32352
- init_shadow();
32353
- init_shadow();
32354
- init_dynamodb3();
31335
+ var logger14;
31336
+ var init_findOne = __esm({
31337
+ "src/server/operations/findOne.ts"() {
31338
+ "use strict";
31339
+ init_shared();
31340
+ init_findMany();
31341
+ logger14 = createLogger({ service: "records-lambda" });
31342
+ __name(handleFindOne, "handleFindOne");
31343
+ }
31344
+ });
32355
31345
 
32356
31346
  // src/server/utils/timestamps.ts
32357
- init_index2();
32358
31347
  function getTimestampFields() {
32359
31348
  const shadowConfig = getShadowConfig();
32360
31349
  return {
@@ -32362,7 +31351,6 @@ function getTimestampFields() {
32362
31351
  updatedAt: shadowConfig.updatedAtField
32363
31352
  };
32364
31353
  }
32365
- __name(getTimestampFields, "getTimestampFields");
32366
31354
  function addCreateTimestamps(data2) {
32367
31355
  const timestampFields = getTimestampFields();
32368
31356
  if (!timestampFields) {
@@ -32375,7 +31363,6 @@ function addCreateTimestamps(data2) {
32375
31363
  [timestampFields.updatedAt]: now
32376
31364
  };
32377
31365
  }
32378
- __name(addCreateTimestamps, "addCreateTimestamps");
32379
31366
  function addUpdateTimestamp(data2) {
32380
31367
  const timestampFields = getTimestampFields();
32381
31368
  if (!timestampFields) {
@@ -32387,11 +31374,17 @@ function addUpdateTimestamp(data2) {
32387
31374
  [timestampFields.updatedAt]: now
32388
31375
  };
32389
31376
  }
32390
- __name(addUpdateTimestamp, "addUpdateTimestamp");
31377
+ var init_timestamps = __esm({
31378
+ "src/server/utils/timestamps.ts"() {
31379
+ "use strict";
31380
+ init_index2();
31381
+ __name(getTimestampFields, "getTimestampFields");
31382
+ __name(addCreateTimestamps, "addCreateTimestamps");
31383
+ __name(addUpdateTimestamp, "addUpdateTimestamp");
31384
+ }
31385
+ });
32391
31386
 
32392
31387
  // src/server/utils/ttl.ts
32393
- init_index2();
32394
- var logger15 = createLogger({ service: "records-lambda" });
32395
31388
  function calculateTTL(resource, createdAt) {
32396
31389
  const envKey = `${resource.toUpperCase()}_TTL_DAYS`;
32397
31390
  const ttlDaysStr = process.env[envKey];
@@ -32415,7 +31408,6 @@ function calculateTTL(resource, createdAt) {
32415
31408
  });
32416
31409
  return ttl;
32417
31410
  }
32418
- __name(calculateTTL, "calculateTTL");
32419
31411
  function addTTL(resource, recordData) {
32420
31412
  const createdAt = recordData.createdAt;
32421
31413
  if (!createdAt) {
@@ -32431,10 +31423,22 @@ function addTTL(resource, recordData) {
32431
31423
  ttl
32432
31424
  };
32433
31425
  }
32434
- __name(addTTL, "addTTL");
31426
+ var logger15;
31427
+ var init_ttl = __esm({
31428
+ "src/server/utils/ttl.ts"() {
31429
+ "use strict";
31430
+ init_index2();
31431
+ logger15 = createLogger({ service: "records-lambda" });
31432
+ __name(calculateTTL, "calculateTTL");
31433
+ __name(addTTL, "addTTL");
31434
+ }
31435
+ });
32435
31436
 
32436
31437
  // src/server/operations/insertMany.ts
32437
- var logger16 = createLogger({ service: "records-lambda" });
31438
+ var insertMany_exports = {};
31439
+ __export(insertMany_exports, {
31440
+ handleInsertMany: () => handleInsertMany
31441
+ });
32438
31442
  async function handleInsertMany(resource, params, requestId) {
32439
31443
  const { data: recordsData } = params;
32440
31444
  const startTime = Date.now();
@@ -32538,7 +31542,7 @@ async function handleInsertMany(resource, params, requestId) {
32538
31542
  }
32539
31543
  await executeDynamoDBOperation(
32540
31544
  () => dbClient2.send(
32541
- new import_lib_dynamodb10.TransactWriteCommand({
31545
+ new import_lib_dynamodb8.TransactWriteCommand({
32542
31546
  TransactItems: transactItems
32543
31547
  })
32544
31548
  ),
@@ -32625,7 +31629,6 @@ async function handleInsertMany(resource, params, requestId) {
32625
31629
  errors: errorsMap
32626
31630
  };
32627
31631
  }
32628
- __name(handleInsertMany, "handleInsertMany");
32629
31632
  function getPreparationErrorCode(error2) {
32630
31633
  if (error2 && typeof error2 === "object") {
32631
31634
  if ("code" in error2 && typeof error2.code === "string") {
@@ -32637,72 +31640,30 @@ function getPreparationErrorCode(error2) {
32637
31640
  }
32638
31641
  return "VALIDATION_ERROR" /* VALIDATION_ERROR */;
32639
31642
  }
32640
- __name(getPreparationErrorCode, "getPreparationErrorCode");
32641
-
32642
- // src/server/operations/insertOne.ts
32643
- var import_lib_dynamodb11 = __toESM(require_dist_cjs66(), 1);
32644
- init_shared();
32645
- init_shadow();
32646
- init_shadow();
32647
- init_dynamodb3();
32648
- var logger17 = createLogger({ service: "records-lambda" });
32649
- async function handleInsertOne(resource, params, requestId) {
32650
- logger17.debug("Executing insertOne", {
32651
- requestId,
32652
- resource
32653
- });
32654
- const dbClient2 = getDBClient();
32655
- const tableName = getTableName();
32656
- const id = params.data.id || ulid2();
32657
- let recordData = addCreateTimestamps({
32658
- ...params.data,
32659
- id
32660
- });
32661
- recordData = addTTL(resource, recordData);
32662
- const shadowConfig = getShadowConfig();
32663
- const shadowRecords = generateShadowRecords(recordData, resource, shadowConfig);
32664
- const mainSK = generateMainRecordSK2(id);
32665
- await executeDynamoDBOperation(
32666
- () => dbClient2.send(
32667
- new import_lib_dynamodb11.PutCommand({
32668
- TableName: tableName,
32669
- Item: {
32670
- PK: resource,
32671
- SK: mainSK,
32672
- data: recordData
32673
- }
32674
- })
32675
- ),
32676
- "PutItem"
32677
- );
32678
- for (const shadowRecord of shadowRecords) {
32679
- await executeDynamoDBOperation(
32680
- () => dbClient2.send(
32681
- new import_lib_dynamodb11.PutCommand({
32682
- TableName: tableName,
32683
- Item: shadowRecord
32684
- })
32685
- ),
32686
- "PutItem"
32687
- );
31643
+ var import_lib_dynamodb8, logger16;
31644
+ var init_insertMany = __esm({
31645
+ "src/server/operations/insertMany.ts"() {
31646
+ "use strict";
31647
+ import_lib_dynamodb8 = __toESM(require_dist_cjs66(), 1);
31648
+ init_shared();
31649
+ init_shadow();
31650
+ init_shadow();
31651
+ init_bulkOperations();
31652
+ init_chunking();
31653
+ init_dynamodb3();
31654
+ init_timestamps();
31655
+ init_ttl();
31656
+ logger16 = createLogger({ service: "records-lambda" });
31657
+ __name(handleInsertMany, "handleInsertMany");
31658
+ __name(getPreparationErrorCode, "getPreparationErrorCode");
32688
31659
  }
32689
- logger17.info("insertOne succeeded", {
32690
- requestId,
32691
- resource,
32692
- id,
32693
- shadowCount: shadowRecords.length
32694
- });
32695
- return recordData;
32696
- }
32697
- __name(handleInsertOne, "handleInsertOne");
31660
+ });
32698
31661
 
32699
31662
  // src/server/operations/updateMany.ts
32700
- var import_lib_dynamodb12 = __toESM(require_dist_cjs66(), 1);
32701
- init_shared();
32702
- init_shadow();
32703
- init_shadow();
32704
- init_dynamodb3();
32705
- var logger18 = createLogger({ service: "records-lambda" });
31663
+ var updateMany_exports = {};
31664
+ __export(updateMany_exports, {
31665
+ handleUpdateMany: () => handleUpdateMany
31666
+ });
32706
31667
  function applyJsonMergePatch(target, patch) {
32707
31668
  const result = { ...target };
32708
31669
  for (const [key, value] of Object.entries(patch)) {
@@ -32719,7 +31680,6 @@ function applyJsonMergePatch(target, patch) {
32719
31680
  }
32720
31681
  return result;
32721
31682
  }
32722
- __name(applyJsonMergePatch, "applyJsonMergePatch");
32723
31683
  async function handleUpdateMany(resource, params, requestId) {
32724
31684
  const { data: patchData } = params;
32725
31685
  const startTime = Date.now();
@@ -32763,7 +31723,7 @@ async function handleUpdateMany(resource, params, requestId) {
32763
31723
  }));
32764
31724
  const batchGetResult = await executeDynamoDBOperation(
32765
31725
  () => dbClient2.send(
32766
- new import_lib_dynamodb12.BatchGetCommand({
31726
+ new import_lib_dynamodb9.BatchGetCommand({
32767
31727
  RequestItems: {
32768
31728
  [tableName]: {
32769
31729
  Keys: keys,
@@ -32882,7 +31842,7 @@ async function handleUpdateMany(resource, params, requestId) {
32882
31842
  }
32883
31843
  await executeDynamoDBOperation(
32884
31844
  () => dbClient2.send(
32885
- new import_lib_dynamodb12.TransactWriteCommand({
31845
+ new import_lib_dynamodb9.TransactWriteCommand({
32886
31846
  TransactItems: transactItems
32887
31847
  })
32888
31848
  ),
@@ -32981,7 +31941,6 @@ async function handleUpdateMany(resource, params, requestId) {
32981
31941
  errors: errorsMap
32982
31942
  };
32983
31943
  }
32984
- __name(handleUpdateMany, "handleUpdateMany");
32985
31944
  function getPreparationErrorCode2(error2) {
32986
31945
  if (error2 && typeof error2 === "object") {
32987
31946
  if ("code" in error2 && typeof error2.code === "string") {
@@ -32993,236 +31952,338 @@ function getPreparationErrorCode2(error2) {
32993
31952
  }
32994
31953
  return "VALIDATION_ERROR" /* VALIDATION_ERROR */;
32995
31954
  }
32996
- __name(getPreparationErrorCode2, "getPreparationErrorCode");
31955
+ var import_lib_dynamodb9, logger18;
31956
+ var init_updateMany = __esm({
31957
+ "src/server/operations/updateMany.ts"() {
31958
+ "use strict";
31959
+ import_lib_dynamodb9 = __toESM(require_dist_cjs66(), 1);
31960
+ init_shared();
31961
+ init_shadow();
31962
+ init_shadow();
31963
+ init_bulkOperations();
31964
+ init_chunking();
31965
+ init_dynamodb3();
31966
+ init_timestamps();
31967
+ logger18 = createLogger({ service: "records-lambda" });
31968
+ __name(applyJsonMergePatch, "applyJsonMergePatch");
31969
+ __name(handleUpdateMany, "handleUpdateMany");
31970
+ __name(getPreparationErrorCode2, "getPreparationErrorCode");
31971
+ }
31972
+ });
32997
31973
 
32998
- // src/server/operations/updateOne.ts
32999
- var import_lib_dynamodb13 = __toESM(require_dist_cjs66(), 1);
31974
+ // src/server/handler.ts
31975
+ var handler_exports = {};
31976
+ __export(handler_exports, {
31977
+ handler: () => handler
31978
+ });
31979
+ module.exports = __toCommonJS(handler_exports);
31980
+ init_http();
33000
31981
  init_shared();
33001
- init_shadow();
33002
- init_shadow();
33003
- init_dynamodb3();
33004
- var logger19 = createLogger({ service: "records-lambda" });
33005
- function applyJsonMergePatch2(target, patch) {
33006
- const result = { ...target };
33007
- for (const [key, value] of Object.entries(patch)) {
33008
- if (value === null) {
33009
- delete result[key];
33010
- } else if (typeof value === "object" && !Array.isArray(value) && value !== null && typeof result[key] === "object" && !Array.isArray(result[key]) && result[key] !== null) {
33011
- result[key] = applyJsonMergePatch2(
33012
- result[key],
33013
- value
33014
- );
33015
- } else {
33016
- result[key] = value;
33017
- }
33018
- }
33019
- return result;
33020
- }
33021
- __name(applyJsonMergePatch2, "applyJsonMergePatch");
33022
- async function handleUpdateOne(resource, params, requestId) {
33023
- const { data: patchData, options } = params;
33024
- const upsert = options?.upsert ?? false;
31982
+
31983
+ // src/server/operations/operationDispatcher.ts
31984
+ init_shared();
31985
+ init_deleteMany();
31986
+
31987
+ // src/server/operations/deleteOne.ts
31988
+ init_shared();
31989
+ var logger11 = createLogger({ service: "records-lambda" });
31990
+ async function handleDeleteOne(resource, params, requestId) {
31991
+ const { handleDeleteMany: handleDeleteMany2 } = await Promise.resolve().then(() => (init_deleteMany(), deleteMany_exports));
33025
31992
  let targetId;
33026
- let existingItem;
33027
31993
  if ("id" in params) {
33028
31994
  targetId = params.id;
33029
- logger19.debug("Executing updateOne with id", {
31995
+ logger11.debug("Executing deleteOne with id", {
33030
31996
  requestId,
33031
31997
  resource,
33032
- id: targetId,
33033
- upsert
31998
+ id: targetId
33034
31999
  });
33035
- const dbClient2 = getDBClient();
33036
- const tableName = getTableName();
33037
- const mainSK = generateMainRecordSK2(targetId);
33038
- const getResult = await executeDynamoDBOperation(
33039
- () => dbClient2.send(
33040
- new import_lib_dynamodb13.GetCommand({
33041
- TableName: tableName,
33042
- Key: {
33043
- PK: resource,
33044
- SK: mainSK
33045
- },
33046
- ConsistentRead: true
33047
- })
33048
- ),
33049
- "GetItem"
32000
+ const deleteManyResult = await handleDeleteMany2(
32001
+ resource,
32002
+ {
32003
+ ids: [targetId]
32004
+ },
32005
+ requestId
33050
32006
  );
33051
- existingItem = getResult.Item;
32007
+ if (deleteManyResult.count === 0) {
32008
+ const error2 = Object.values(deleteManyResult.errors)[0];
32009
+ if (error2) {
32010
+ throw new Error(`Failed to delete record: ${error2.message}`);
32011
+ } else {
32012
+ throw new Error(`Failed to delete record: ${targetId}`);
32013
+ }
32014
+ }
32015
+ return { id: targetId };
33052
32016
  } else {
33053
- logger19.debug("Executing updateOne with filter", {
32017
+ logger11.debug("Executing deleteOne with filter", {
33054
32018
  requestId,
33055
32019
  resource,
33056
- filter: params.filter,
33057
- upsert
32020
+ filter: params.filter
33058
32021
  });
33059
- const { handleFind: handleFind2 } = await Promise.resolve().then(() => (init_find(), find_exports));
33060
- const findResult = await handleFind2(
32022
+ const deleteManyResult = await handleDeleteMany2(
33061
32023
  resource,
33062
- { filter: params.filter, pagination: { perPage: 1 } },
32024
+ {
32025
+ filter: params.filter
32026
+ },
33063
32027
  requestId
33064
32028
  );
33065
- if (findResult.items.length > 0) {
33066
- const foundRecord = findResult.items[0];
33067
- targetId = foundRecord.id;
33068
- const dbClient2 = getDBClient();
33069
- const tableName = getTableName();
33070
- const mainSK = generateMainRecordSK2(targetId);
33071
- const getResult = await executeDynamoDBOperation(
33072
- () => dbClient2.send(
33073
- new import_lib_dynamodb13.GetCommand({
33074
- TableName: tableName,
33075
- Key: {
33076
- PK: resource,
33077
- SK: mainSK
33078
- },
33079
- ConsistentRead: true
33080
- })
33081
- ),
33082
- "GetItem"
33083
- );
33084
- existingItem = getResult.Item;
33085
- } else {
33086
- if (!upsert) {
33087
- throw new ItemNotFoundError(`Record not found with filter`, {
33088
- resource,
33089
- filter: params.filter
33090
- });
32029
+ if (deleteManyResult.count === 0) {
32030
+ const error2 = Object.values(deleteManyResult.errors)[0];
32031
+ if (error2) {
32032
+ throw new Error(`Failed to delete record: ${error2.message}`);
32033
+ } else {
32034
+ throw new Error(`No records found matching filter`);
33091
32035
  }
33092
- const { ulid: ulid3 } = await Promise.resolve().then(() => (init_shared(), shared_exports));
33093
- targetId = ulid3();
33094
32036
  }
33095
- }
33096
- if (!existingItem) {
33097
- if (!upsert) {
33098
- throw new ItemNotFoundError(`Record not found: ${targetId}`, { resource, id: targetId });
32037
+ const deletedId = Object.values(deleteManyResult.successIds)[0];
32038
+ if (!deletedId) {
32039
+ throw new Error("Failed to get deleted record ID");
33099
32040
  }
33100
- return await handleUpsertCreate(resource, targetId, patchData, requestId);
32041
+ logger11.info("deleteOne succeeded", {
32042
+ requestId,
32043
+ resource,
32044
+ id: deletedId
32045
+ });
32046
+ return { id: deletedId };
33101
32047
  }
33102
- return await handleUpsertUpdate(resource, targetId, existingItem, patchData, requestId);
33103
32048
  }
33104
- __name(handleUpdateOne, "handleUpdateOne");
33105
- async function handleUpsertCreate(resource, id, data2, requestId) {
33106
- const $set = data2.$set || {};
33107
- const $setOnInsert = data2.$setOnInsert || {};
33108
- const mergedData = {
33109
- ...$setOnInsert,
33110
- ...$set
33111
- };
33112
- const recordData = addCreateTimestamps({ ...mergedData, id });
33113
- const shadowConfig = getShadowConfig();
33114
- const shadowRecords = generateShadowRecords(recordData, resource, shadowConfig);
33115
- const shadowKeys = shadowRecords.map((shadow) => shadow.SK);
33116
- const transactItems = [];
33117
- transactItems.push({
33118
- Put: {
33119
- TableName: getTableName(),
33120
- Item: {
33121
- PK: resource,
33122
- SK: generateMainRecordSK2(id),
33123
- data: {
33124
- ...recordData,
33125
- __shadowKeys: shadowKeys
33126
- }
33127
- }
33128
- }
32049
+ __name(handleDeleteOne, "handleDeleteOne");
32050
+
32051
+ // src/server/operations/operationDispatcher.ts
32052
+ init_find();
32053
+ init_findMany();
32054
+
32055
+ // src/server/operations/findManyReference.ts
32056
+ var import_lib_dynamodb7 = __toESM(require_dist_cjs66(), 1);
32057
+ init_shared();
32058
+ init_shadow();
32059
+ init_dynamodb3();
32060
+ init_pagination();
32061
+ init_validation2();
32062
+ var logger13 = createLogger({ service: "records-lambda" });
32063
+ async function handleFindManyReference(resource, params, requestId) {
32064
+ const { target, id, filter, sort: sortParam, pagination } = params;
32065
+ logger13.debug("Executing findManyReference", {
32066
+ requestId,
32067
+ resource,
32068
+ target,
32069
+ id
33129
32070
  });
33130
- for (const shadowRecord of shadowRecords) {
33131
- transactItems.push({
33132
- Put: {
33133
- TableName: getTableName(),
33134
- Item: shadowRecord
32071
+ const shadowConfig = getShadowConfig();
32072
+ const sort = normalizeSort(shadowConfig, resource, sortParam);
32073
+ validateSortField(shadowConfig, resource, sort);
32074
+ const { perPage, nextToken } = normalizePagination(pagination);
32075
+ const dbClient2 = getDBClient();
32076
+ const tableName = getTableName();
32077
+ const skPrefix = `${sort.field}#`;
32078
+ let exclusiveStartKey;
32079
+ if (nextToken) {
32080
+ const decoded = decodeNextToken(nextToken);
32081
+ exclusiveStartKey = {
32082
+ PK: decoded.PK,
32083
+ SK: decoded.SK
32084
+ };
32085
+ }
32086
+ const queryResult = await executeDynamoDBOperation(
32087
+ () => dbClient2.send(
32088
+ new import_lib_dynamodb7.QueryCommand({
32089
+ TableName: tableName,
32090
+ KeyConditionExpression: "PK = :pk AND begins_with(SK, :skPrefix)",
32091
+ ExpressionAttributeValues: {
32092
+ ":pk": resource,
32093
+ ":skPrefix": skPrefix
32094
+ },
32095
+ ScanIndexForward: sort.order === "ASC",
32096
+ Limit: perPage,
32097
+ ExclusiveStartKey: exclusiveStartKey,
32098
+ ConsistentRead: true
32099
+ })
32100
+ ),
32101
+ "Query"
32102
+ );
32103
+ const shadowItems = queryResult.Items || [];
32104
+ if (shadowItems.length === 0) {
32105
+ return {
32106
+ items: [],
32107
+ pageInfo: {
32108
+ hasNextPage: false,
32109
+ hasPreviousPage: false
33135
32110
  }
33136
- });
32111
+ };
33137
32112
  }
33138
- await executeDynamoDBOperation(
33139
- () => getDBClient().send(
33140
- new import_lib_dynamodb13.TransactWriteCommand({
33141
- TransactItems: transactItems
32113
+ const recordIds = shadowItems.map((item) => {
32114
+ const sk = item.SK;
32115
+ const parts = sk.split("#id#");
32116
+ return parts[parts.length - 1];
32117
+ });
32118
+ const batchGetResult = await executeDynamoDBOperation(
32119
+ () => dbClient2.send(
32120
+ new import_lib_dynamodb7.BatchGetCommand({
32121
+ RequestItems: {
32122
+ [tableName]: {
32123
+ Keys: recordIds.map((recordId) => ({
32124
+ PK: resource,
32125
+ SK: `id#${recordId}`
32126
+ })),
32127
+ ConsistentRead: true
32128
+ }
32129
+ }
33142
32130
  })
33143
32131
  ),
33144
- "TransactWriteItems"
32132
+ "BatchGetItem"
33145
32133
  );
33146
- logger19.info("updateOne upsert created", {
32134
+ const mainRecords = batchGetResult.Responses?.[tableName] || [];
32135
+ const recordMap = new Map(
32136
+ mainRecords.map((item) => {
32137
+ const data2 = item.data;
32138
+ return [data2.id, extractCleanRecord(item)];
32139
+ })
32140
+ );
32141
+ let items = recordIds.map((recordId) => recordMap.get(recordId)).filter((record) => record !== void 0);
32142
+ items = items.filter((record) => record[target] === id);
32143
+ if (filter && Object.keys(filter).length > 0) {
32144
+ items = items.filter((record) => {
32145
+ return Object.entries(filter).every(([key, value]) => {
32146
+ return record[key] === value;
32147
+ });
32148
+ });
32149
+ }
32150
+ const hasNextPage = queryResult.LastEvaluatedKey !== void 0;
32151
+ const nextTokenValue = hasNextPage && queryResult.LastEvaluatedKey ? encodeNextToken(
32152
+ queryResult.LastEvaluatedKey.PK,
32153
+ queryResult.LastEvaluatedKey.SK
32154
+ ) : void 0;
32155
+ logger13.info("findManyReference succeeded", {
33147
32156
  requestId,
33148
32157
  resource,
32158
+ target,
33149
32159
  id,
33150
- shadowsCreated: shadowKeys.length
32160
+ count: items.length,
32161
+ hasNextPage
33151
32162
  });
33152
32163
  return {
33153
- ...removeShadowKeys(recordData),
33154
- __upsertedId: id
32164
+ items,
32165
+ pageInfo: {
32166
+ hasNextPage,
32167
+ hasPreviousPage: !!nextToken
32168
+ },
32169
+ ...nextTokenValue && { nextToken: nextTokenValue }
33155
32170
  };
33156
32171
  }
33157
- __name(handleUpsertCreate, "handleUpsertCreate");
33158
- async function handleUpsertUpdate(resource, id, existingItem, patchData, requestId) {
33159
- const existingData = existingItem.data;
33160
- const oldShadowKeys = existingData.__shadowKeys || [];
33161
- const actualPatchData = patchData.$set ? patchData.$set : patchData;
33162
- const mergedData = applyJsonMergePatch2(removeShadowKeys(existingData), actualPatchData);
33163
- const updatedData = addUpdateTimestamp({
33164
- ...mergedData,
33165
- id
33166
- // IDは変更不可
32172
+ __name(handleFindManyReference, "handleFindManyReference");
32173
+
32174
+ // src/server/operations/operationDispatcher.ts
32175
+ init_findOne();
32176
+ init_insertMany();
32177
+
32178
+ // src/server/operations/insertOne.ts
32179
+ init_shared();
32180
+ var logger17 = createLogger({ service: "records-lambda" });
32181
+ async function handleInsertOne(resource, params, requestId) {
32182
+ logger17.debug("Executing insertOne", {
32183
+ requestId,
32184
+ resource
33167
32185
  });
33168
- const shadowConfig = getShadowConfig();
33169
- const newShadowRecords = generateShadowRecords(updatedData, resource, shadowConfig);
33170
- const newShadowKeys = newShadowRecords.map((shadow) => shadow.SK);
33171
- const shadowDiff = calculateShadowDiff(oldShadowKeys, newShadowKeys);
33172
- const transactItems = [];
33173
- transactItems.push({
33174
- Put: {
33175
- TableName: getTableName(),
33176
- Item: {
33177
- PK: resource,
33178
- SK: generateMainRecordSK2(id),
33179
- data: {
33180
- ...updatedData,
33181
- __shadowKeys: newShadowKeys
33182
- }
33183
- }
32186
+ const { handleInsertMany: handleInsertMany2 } = await Promise.resolve().then(() => (init_insertMany(), insertMany_exports));
32187
+ const insertManyResult = await handleInsertMany2(
32188
+ resource,
32189
+ {
32190
+ data: [params.data]
32191
+ },
32192
+ requestId
32193
+ );
32194
+ if (insertManyResult.count === 0) {
32195
+ const error2 = Object.values(insertManyResult.errors)[0];
32196
+ if (error2) {
32197
+ throw new Error(`Failed to create record: ${error2.message}`);
32198
+ } else {
32199
+ throw new Error("Failed to create record");
33184
32200
  }
33185
- });
33186
- for (const shadowSK of shadowDiff.toDelete) {
33187
- transactItems.push({
33188
- Delete: {
33189
- TableName: getTableName(),
33190
- Key: {
33191
- PK: resource,
33192
- SK: shadowSK
33193
- }
33194
- }
33195
- });
33196
32201
  }
33197
- for (const shadowRecord of newShadowRecords) {
33198
- if (shadowDiff.toAdd.includes(shadowRecord.SK)) {
33199
- transactItems.push({
33200
- Put: {
33201
- TableName: getTableName(),
33202
- Item: shadowRecord
33203
- }
33204
- });
33205
- }
32202
+ const createdId = Object.values(insertManyResult.successIds)[0];
32203
+ if (!createdId) {
32204
+ throw new Error("Failed to get created record ID");
33206
32205
  }
33207
- await executeDynamoDBOperation(
33208
- () => getDBClient().send(
33209
- new import_lib_dynamodb13.TransactWriteCommand({
33210
- TransactItems: transactItems
33211
- })
33212
- ),
33213
- "TransactWriteItems"
33214
- );
33215
- logger19.info("updateOne upsert updated", {
32206
+ const { handleFindOne: handleFindOne2 } = await Promise.resolve().then(() => (init_findOne(), findOne_exports));
32207
+ const createdRecord = await handleFindOne2(resource, { id: createdId }, requestId);
32208
+ logger17.info("insertOne succeeded", {
33216
32209
  requestId,
33217
32210
  resource,
33218
- id,
33219
- shadowDiffEmpty: isDiffEmpty(shadowDiff),
33220
- shadowsDeleted: shadowDiff.toDelete.length,
33221
- shadowsAdded: shadowDiff.toAdd.length
32211
+ id: createdId
33222
32212
  });
33223
- return removeShadowKeys(updatedData);
32213
+ return createdRecord;
33224
32214
  }
33225
- __name(handleUpsertUpdate, "handleUpsertUpdate");
32215
+ __name(handleInsertOne, "handleInsertOne");
32216
+
32217
+ // src/server/operations/operationDispatcher.ts
32218
+ init_updateMany();
32219
+
32220
+ // src/server/operations/updateOne.ts
32221
+ init_shared();
32222
+ var logger19 = createLogger({ service: "records-lambda" });
32223
+ async function handleUpdateOne(resource, params, requestId) {
32224
+ const { data: patchData, options } = params;
32225
+ const { handleUpdateMany: handleUpdateMany2 } = await Promise.resolve().then(() => (init_updateMany(), updateMany_exports));
32226
+ let targetId;
32227
+ if ("id" in params) {
32228
+ targetId = params.id;
32229
+ logger19.debug("Executing updateOne with id", {
32230
+ requestId,
32231
+ resource,
32232
+ id: targetId,
32233
+ upsert: options?.upsert
32234
+ });
32235
+ const updateManyResult = await handleUpdateMany2(
32236
+ resource,
32237
+ {
32238
+ ids: [targetId],
32239
+ data: patchData
32240
+ },
32241
+ requestId
32242
+ );
32243
+ if (updateManyResult.count === 0) {
32244
+ const error2 = Object.values(updateManyResult.errors)[0];
32245
+ if (error2) {
32246
+ throw new Error(`Failed to update record: ${error2.message}`);
32247
+ } else {
32248
+ throw new Error(`Failed to update record: ${targetId}`);
32249
+ }
32250
+ }
32251
+ const { handleFindOne: handleFindOne2 } = await Promise.resolve().then(() => (init_findOne(), findOne_exports));
32252
+ const updatedRecord = await handleFindOne2(resource, { id: targetId }, requestId);
32253
+ return updatedRecord;
32254
+ } else {
32255
+ logger19.debug("Executing updateOne with filter", {
32256
+ requestId,
32257
+ resource,
32258
+ filter: params.filter,
32259
+ upsert: options?.upsert
32260
+ });
32261
+ const updateManyResult = await handleUpdateMany2(
32262
+ resource,
32263
+ {
32264
+ filter: params.filter,
32265
+ data: patchData
32266
+ },
32267
+ requestId
32268
+ );
32269
+ if (updateManyResult.count === 0) {
32270
+ const error2 = Object.values(updateManyResult.errors)[0];
32271
+ if (error2) {
32272
+ throw new Error(`Failed to update record: ${error2.message}`);
32273
+ } else {
32274
+ throw new Error(`No records found matching filter`);
32275
+ }
32276
+ }
32277
+ const updatedId = Object.values(updateManyResult.successIds)[0];
32278
+ if (!updatedId) {
32279
+ throw new Error("Failed to get updated record ID");
32280
+ }
32281
+ const { handleFindOne: handleFindOne2 } = await Promise.resolve().then(() => (init_findOne(), findOne_exports));
32282
+ const updatedRecord = await handleFindOne2(resource, { id: updatedId }, requestId);
32283
+ return updatedRecord;
32284
+ }
32285
+ }
32286
+ __name(handleUpdateOne, "handleUpdateOne");
33226
32287
 
33227
32288
  // src/server/operations/parameterConverter.ts
33228
32289
  function convertFindParams(mongoParams) {
@@ -33258,9 +32319,15 @@ function convertFindOneParams(mongoParams) {
33258
32319
  }
33259
32320
  __name(convertFindOneParams, "convertFindOneParams");
33260
32321
  function convertFindManyParams(mongoParams) {
33261
- const idFilter = mongoParams.filter?.id;
33262
- const ids = typeof idFilter === "object" && idFilter !== null && "$in" in idFilter ? idFilter.$in || [] : [];
33263
- return { ids };
32322
+ if (!mongoParams.filter) {
32323
+ throw new Error("findMany requires filter");
32324
+ }
32325
+ const idFilter = mongoParams.filter.id;
32326
+ if (typeof idFilter === "object" && idFilter !== null && "$in" in idFilter) {
32327
+ const ids = idFilter.$in || [];
32328
+ return { ids };
32329
+ }
32330
+ return { filter: mongoParams.filter };
33264
32331
  }
33265
32332
  __name(convertFindManyParams, "convertFindManyParams");
33266
32333
  function convertInsertOneParams(mongoParams) {
@@ -34838,7 +33905,7 @@ async function handler(event) {
34838
33905
  return createCorsResponse(HTTP_STATUS.OK);
34839
33906
  }
34840
33907
  if (event.requestContext.http.method === "GET" && event.requestContext.http.path === "/version") {
34841
- const version = "1.3.35";
33908
+ const version = "1.3.36";
34842
33909
  return createSuccessResponse({ version, timestamp: (/* @__PURE__ */ new Date()).toISOString() }, requestId);
34843
33910
  }
34844
33911
  if (event.requestContext.http.method !== "POST") {